chore: lint and remove unused exports #806

This commit is contained in:
M Hassan Tariq
2021-12-07 15:43:11 +05:00
committed by GitHub
parent 352a054b71
commit fdbc548e28
42 changed files with 170 additions and 352 deletions

View File

@@ -65,6 +65,9 @@ jobs:
- name: Lint Prettier
run: npm run lint:prettier
- name: Lint Unused Exports
run: npm run lint:unused-exports
lint-docs:
runs-on: ubuntu-latest
defaults:

65
package-lock.json generated
View File

@@ -2486,8 +2486,7 @@
"@types/json5": {
"version": "0.0.29",
"resolved": "https://registry.npmjs.org/@types/json5/-/json5-0.0.29.tgz",
"integrity": "sha1-7ihweulOEdK4J7y+UnC86n8+ce4=",
"dev": true
"integrity": "sha1-7ihweulOEdK4J7y+UnC86n8+ce4="
},
"@types/lru-cache": {
"version": "5.1.1",
@@ -12169,7 +12168,6 @@
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/json5/-/json5-1.0.1.tgz",
"integrity": "sha512-aKS4WQjPenRxiQsC93MNfjx+nbF4PAdYzmd/1JIj8HYzqfbu86beTuNgXDzPknWk0n0uARlyewZo4s++ES36Ow==",
"dev": true,
"requires": {
"minimist": "^1.2.0"
}
@@ -12902,8 +12900,7 @@
"minimist": {
"version": "1.2.5",
"resolved": "https://registry.npmjs.org/minimist/-/minimist-1.2.5.tgz",
"integrity": "sha512-FM9nNUYrRBAELZQT3xeZQ7fmMOBg6nWNmJKTcgsJeaLstP/UODVpGsr5OhXhhXg6f+qtJ8uiZ+PUxkDWcgIXLw==",
"dev": true
"integrity": "sha512-FM9nNUYrRBAELZQT3xeZQ7fmMOBg6nWNmJKTcgsJeaLstP/UODVpGsr5OhXhhXg6f+qtJ8uiZ+PUxkDWcgIXLw=="
},
"minimist-options": {
"version": "4.1.0",
@@ -16485,8 +16482,7 @@
"strip-bom": {
"version": "3.0.0",
"resolved": "https://registry.npmjs.org/strip-bom/-/strip-bom-3.0.0.tgz",
"integrity": "sha1-IzTBjpx1n3vdVv3vfprj1YjmjtM=",
"dev": true
"integrity": "sha1-IzTBjpx1n3vdVv3vfprj1YjmjtM="
},
"strip-eof": {
"version": "1.0.0",
@@ -17153,11 +17149,64 @@
"yn": "3.1.1"
}
},
"ts-unused-exports": {
"version": "7.0.3",
"resolved": "https://registry.npmjs.org/ts-unused-exports/-/ts-unused-exports-7.0.3.tgz",
"integrity": "sha512-D0VdTiTfrmZM7tViQEMuzG0+giU5z5crn4vjK+f1dnxTKcNx23Vc2lpMgd1vP3lYrwnvJofZmCnvEuJ7XUeV2Q==",
"requires": {
"chalk": "^4.0.0",
"tsconfig-paths": "^3.9.0"
},
"dependencies": {
"ansi-styles": {
"version": "4.3.0",
"resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz",
"integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==",
"requires": {
"color-convert": "^2.0.1"
}
},
"chalk": {
"version": "4.1.2",
"resolved": "https://registry.npmjs.org/chalk/-/chalk-4.1.2.tgz",
"integrity": "sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA==",
"requires": {
"ansi-styles": "^4.1.0",
"supports-color": "^7.1.0"
}
},
"color-convert": {
"version": "2.0.1",
"resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz",
"integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==",
"requires": {
"color-name": "~1.1.4"
}
},
"color-name": {
"version": "1.1.4",
"resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz",
"integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA=="
},
"has-flag": {
"version": "4.0.0",
"resolved": "https://registry.npmjs.org/has-flag/-/has-flag-4.0.0.tgz",
"integrity": "sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ=="
},
"supports-color": {
"version": "7.2.0",
"resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz",
"integrity": "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==",
"requires": {
"has-flag": "^4.0.0"
}
}
}
},
"tsconfig-paths": {
"version": "3.9.0",
"resolved": "https://registry.npmjs.org/tsconfig-paths/-/tsconfig-paths-3.9.0.tgz",
"integrity": "sha512-dRcuzokWhajtZWkQsDVKbWyY+jgcLC5sqJhg2PSgf4ZkH2aHPvaOY8YWGhmjb68b5qqTfasSsDO9k7RUiEmZAw==",
"dev": true,
"requires": {
"@types/json5": "^0.0.29",
"json5": "^1.0.1",

View File

@@ -26,6 +26,7 @@
"build:docs": "npm i --prefix client && npm run generate:docs --prefix client && npm i --prefix docs && npm run generate:resolved-spec --prefix docs && npm run generate:docs --prefix docs",
"start": "node ./lib/index.js",
"lint": "npm run lint:eslint && npm run lint:prettier",
"lint:unused-exports": "ts-unused-exports tsconfig.json --ignoreFiles=src/migrations/*",
"lint:eslint": "eslint . --ext .js,.jsx,.ts,.tsx -f codeframe",
"lint:prettier": "prettier --check src/**/*.{ts,json}",
"lint:fix": "eslint . --ext .js,.jsx,.ts,.tsx -f codeframe --fix && prettier --write --check src/**/*.{ts,json}",
@@ -153,6 +154,7 @@
"source-map-support": "^0.5.19",
"split2": "^3.2.2",
"strict-event-emitter-types": "^2.0.0",
"ts-unused-exports": "^7.0.3",
"typescript": "^4.4.2",
"uuid": "^8.0.0",
"winston": "^3.2.1",

View File

@@ -106,7 +106,7 @@ export function getTxTypeString(typeId: DbTxTypeId): Transaction['tx_type'] {
}
}
export function getTxAnchorModeString(anchorMode: number): TransactionAnchorModeType {
function getTxAnchorModeString(anchorMode: number): TransactionAnchorModeType {
switch (anchorMode) {
case 0x01:
return 'on_chain_only';
@@ -448,7 +448,7 @@ export async function getBlockFromDataStore({
return { found: true, result: apiBlock };
}
export function parseDbBlock(
function parseDbBlock(
dbBlock: DbBlock,
txIds: string[],
microblocksAccepted: string[],
@@ -480,7 +480,7 @@ export function parseDbBlock(
return apiBlock;
}
export async function getRosettaBlockTransactionsFromDataStore(opts: {
async function getRosettaBlockTransactionsFromDataStore(opts: {
blockHash: string;
indexBlockHash: string;
db: DataStore;
@@ -566,26 +566,26 @@ export async function getRosettaTransactionFromDataStore(
return { found: true, result };
}
export interface GetTxArgs {
interface GetTxArgs {
txId: string;
includeUnanchored: boolean;
}
export interface GetTxFromDbTxArgs extends GetTxArgs {
interface GetTxFromDbTxArgs extends GetTxArgs {
dbTx: DbTx;
}
export interface GetTxsWithEventsArgs extends GetTxsArgs {
interface GetTxsWithEventsArgs extends GetTxsArgs {
eventLimit: number;
eventOffset: number;
}
export interface GetTxsArgs {
interface GetTxsArgs {
txIds: string[];
includeUnanchored: boolean;
}
export interface GetTxWithEventsArgs extends GetTxArgs {
interface GetTxWithEventsArgs extends GetTxArgs {
eventLimit: number;
eventOffset: number;
}
@@ -813,7 +813,7 @@ export async function getMempoolTxsFromDataStore(
return parsedMempoolTxs;
}
export async function getTxsFromDataStore(
async function getTxsFromDataStore(
db: DataStore,
args: GetTxsArgs | GetTxsWithEventsArgs
): Promise<Transaction[] | TransactionWithEvents[]> {

View File

@@ -11,7 +11,7 @@ import * as jsoncParser from 'jsonc-parser';
import fetch, { RequestInit } from 'node-fetch';
import { DataStore } from '../../datastore/common';
export function GetStacksNodeProxyEndpoint() {
function GetStacksNodeProxyEndpoint() {
// Use STACKS_CORE_PROXY env vars if available, otherwise fallback to `STACKS_CORE_RPC
const proxyHost =
process.env['STACKS_CORE_PROXY_HOST'] ?? process.env['STACKS_CORE_RPC_HOST'] ?? '';

View File

@@ -65,7 +65,7 @@ export const testnetKeys: { secretKey: string; stacksAddress: string }[] = [
},
];
export const testnetKeyMap: Record<
const testnetKeyMap: Record<
string,
{ address: string; secretKey: string; pubKey: string }
> = Object.fromEntries(

View File

@@ -16,7 +16,7 @@ import {
import { getTxTypeString } from '../controllers/db-controller';
import { address } from 'bitcoinjs-lib';
export const enum SearchResultType {
const enum SearchResultType {
TxId = 'tx_id',
MempoolTxId = 'mempool_tx_id',
BlockHash = 'block_hash',

View File

@@ -3,9 +3,9 @@ import * as WebSocket from 'ws';
import { Topic } from '@stacks/stacks-blockchain-api-types';
import { Socket } from 'socket.io';
export type WebSocketMetricsPrefix = 'socket_io' | 'websocket';
type WebSocketMetricsPrefix = 'socket_io' | 'websocket';
export type WebSocketSubscriber = Socket | WebSocket;
type WebSocketSubscriber = Socket | WebSocket;
interface WebSocketMetrics {
// Number of active subscriptions by topic.

View File

@@ -29,13 +29,7 @@ const assetPrincipalTypeMap = {
[PostConditionPrincipalTypeID.Contract]: 'principal_contract',
} as const;
export function serializeAssetPrincipalType(
type: PostConditionPrincipalTypeID
): PostConditionPrincipalType {
return assetPrincipalTypeMap[type];
}
export function serializePostConditionPrincipal(
function serializePostConditionPrincipal(
principal: TxPostConditionPrincipal
): PostConditionPrincipal {
if (principal.typeId === PostConditionPrincipalTypeID.Standard) {
@@ -60,7 +54,7 @@ type SerializedPostConditionAsset =
| PostConditionFungible['asset']
| PostConditionNonFungible['asset'];
export function serializePostConditionAsset(asset: AssetInfo): SerializedPostConditionAsset {
function serializePostConditionAsset(asset: AssetInfo): SerializedPostConditionAsset {
return {
contract_name: asset.contractName,
asset_name: asset.assetName,
@@ -77,10 +71,6 @@ const assetInfoTypeMap = {
[AssetInfoTypeID.NonfungibleAsset]: 'non_fungible',
} as const;
export function serializePostConditionType(type: AssetInfoTypeID) {
return assetInfoTypeMap[type];
}
export function serializePostCondition(pc: TransactionPostCondition): PostCondition {
switch (pc.assetInfoId) {
case AssetInfoTypeID.STX:
@@ -120,7 +110,7 @@ const fungibleConditionCodeMap = {
[FungibleConditionCode.SentLe]: 'sent_less_than_or_equal_to',
} as const;
export function serializeFungibleConditionCode(
function serializeFungibleConditionCode(
code: FungibleConditionCode
): PostConditionFungibleConditionCode {
return fungibleConditionCodeMap[code];
@@ -131,7 +121,7 @@ const fungibleNonConditionCodeMap = {
[NonfungibleConditionCode.Sent]: 'sent',
} as const;
export function serializeNonFungibleConditionCode(
function serializeNonFungibleConditionCode(
code: NonfungibleConditionCode
): PostConditionNonFungibleConditionCode {
return fungibleNonConditionCodeMap[code];

View File

@@ -26,7 +26,7 @@ import { URIType } from 'zone-file/dist/zoneFile';
import { BnsContractIdentifier } from './bns-constants';
import * as crypto from 'crypto';
export interface Attachment {
interface Attachment {
attachment: {
hash: string;
metadata: {
@@ -189,7 +189,7 @@ export function parseResolver(uri: URIType[]) {
return resolver;
}
export interface ZoneFileTXT {
interface ZoneFileTXT {
owner: string;
seqn: string;
parts: string;

View File

@@ -4,7 +4,7 @@ import * as Bluebird from 'bluebird';
import { parsePort, time, logger, logError } from './helpers';
import * as coinselect from 'coinselect';
export function getFaucetPk(): string {
function getFaucetPk(): string {
const { BTC_FAUCET_PK } = process.env;
if (!BTC_FAUCET_PK) {
throw new Error('BTC Faucet not fully configured.');

View File

@@ -3,7 +3,7 @@ import fetch, { RequestInit } from 'node-fetch';
import { parsePort, stopwatch, logError, timeout } from '../helpers';
import { CoreNodeFeeResponse } from '@stacks/stacks-blockchain-api-types';
export interface CoreRpcAccountInfo {
interface CoreRpcAccountInfo {
/** Hex-prefixed uint128. */
balance: string;
/** Hex-prefixed binary blob. */
@@ -14,7 +14,7 @@ export interface CoreRpcAccountInfo {
nonce_proof: string;
}
export interface CoreRpcInfo {
interface CoreRpcInfo {
burn_block_height: number;
burn_consensus: string;
exit_at_block_height: number | null;
@@ -30,7 +30,7 @@ export interface CoreRpcInfo {
unanchored_tip: string;
}
export interface CoreRpcPoxInfo {
interface CoreRpcPoxInfo {
contract_id: string;
first_burnchain_block_height: number;
min_amount_ustx: number;
@@ -49,7 +49,7 @@ export interface Neighbor {
authenticated: boolean;
}
export interface CoreRpcNeighbors {
interface CoreRpcNeighbors {
sample: Neighbor[];
inbound: Neighbor[];
outbound: Neighbor[];

View File

@@ -281,7 +281,7 @@ export enum DbAssetEventTypeId {
Burn = 3,
}
export interface DbAssetEvent extends DbEventBase {
interface DbAssetEvent extends DbEventBase {
asset_event_type_id: DbAssetEventTypeId;
sender?: string;
recipient?: string;
@@ -292,7 +292,7 @@ export interface DbStxEvent extends DbAssetEvent {
amount: bigint;
}
export interface DbContractAssetEvent extends DbAssetEvent {
interface DbContractAssetEvent extends DbAssetEvent {
asset_identifier: string;
}
@@ -868,14 +868,6 @@ export interface DataStore extends DataStoreEventEmitter {
close(): Promise<void>;
}
export function getAssetEventId(event_index: number, event_tx_id: string): string {
const buff = Buffer.alloc(4 + 32);
buff.writeUInt32BE(event_index, 0);
hexToBuffer(event_tx_id).copy(buff, 4);
const hashed = crypto.createHash('sha256').update(buff).digest().slice(16).toString('hex');
return '0x' + hashed;
}
export function getTxDbStatus(
txCoreStatus: CoreNodeTxStatus | CoreNodeDropMempoolTxReasonType
): DbTxStatus {

View File

@@ -32,7 +32,7 @@ export type PgTokensNotificationPayload = {
contractID: string;
};
export type PgNotificationPayload =
type PgNotificationPayload =
| PgBlockNotificationPayload
| PgMicroblockNotificationPayload
| PgTxNotificationPayload
@@ -41,12 +41,12 @@ export type PgNotificationPayload =
| PgNameNotificationPayload
| PgTokensNotificationPayload;
export type PgNotification = {
type PgNotification = {
type: string;
payload: PgNotificationPayload;
};
export type PgNotificationCallback = (notification: PgNotification) => void;
type PgNotificationCallback = (notification: PgNotification) => void;
/**
* Creates and connects to a channel between the API and the Postgres DB to receive table update notifications

View File

@@ -11,26 +11,26 @@ import {
} from '@stacks/transactions';
import { NotImplementedError } from '../errors';
export type ClarityAbiTypeBuffer = { buffer: { length: number } };
export type ClarityAbiTypeResponse = { response: { ok: ClarityAbiType; error: ClarityAbiType } };
export type ClarityAbiTypeOptional = { optional: ClarityAbiType };
export type ClarityAbiTypeTuple = { tuple: { name: string; type: ClarityAbiType }[] };
export type ClarityAbiTypeList = { list: { type: ClarityAbiType; length: number } };
type ClarityAbiTypeBuffer = { buffer: { length: number } };
type ClarityAbiTypeResponse = { response: { ok: ClarityAbiType; error: ClarityAbiType } };
type ClarityAbiTypeOptional = { optional: ClarityAbiType };
type ClarityAbiTypeTuple = { tuple: { name: string; type: ClarityAbiType }[] };
type ClarityAbiTypeList = { list: { type: ClarityAbiType; length: number } };
export type ClarityAbiTypeUInt128 = 'uint128';
export type ClarityAbiTypeInt128 = 'int128';
export type ClarityAbiTypeBool = 'bool';
export type ClarityAbiTypePrincipal = 'principal';
export type ClarityAbiTypeNone = 'none';
type ClarityAbiTypeUInt128 = 'uint128';
type ClarityAbiTypeInt128 = 'int128';
type ClarityAbiTypeBool = 'bool';
type ClarityAbiTypePrincipal = 'principal';
type ClarityAbiTypeNone = 'none';
export type ClarityAbiTypePrimitive =
type ClarityAbiTypePrimitive =
| ClarityAbiTypeUInt128
| ClarityAbiTypeInt128
| ClarityAbiTypeBool
| ClarityAbiTypePrincipal
| ClarityAbiTypeNone;
export type ClarityAbiType =
type ClarityAbiType =
| ClarityAbiTypePrimitive
| ClarityAbiTypeBuffer
| ClarityAbiTypeResponse
@@ -38,7 +38,7 @@ export type ClarityAbiType =
| ClarityAbiTypeTuple
| ClarityAbiTypeList;
export enum ClarityAbiTypeId {
enum ClarityAbiTypeId {
ClarityAbiTypeUInt128 = 1,
ClarityAbiTypeInt128 = 2,
ClarityAbiTypeBool = 3,
@@ -51,20 +51,20 @@ export enum ClarityAbiTypeId {
ClarityAbiTypeList = 10,
}
export const isClarityAbiPrimitive = (val: ClarityAbiType): val is ClarityAbiTypePrimitive =>
const isClarityAbiPrimitive = (val: ClarityAbiType): val is ClarityAbiTypePrimitive =>
typeof val === 'string';
export const isClarityAbiBuffer = (val: ClarityAbiType): val is ClarityAbiTypeBuffer =>
const isClarityAbiBuffer = (val: ClarityAbiType): val is ClarityAbiTypeBuffer =>
(val as ClarityAbiTypeBuffer).buffer !== undefined;
export const isClarityAbiResponse = (val: ClarityAbiType): val is ClarityAbiTypeResponse =>
const isClarityAbiResponse = (val: ClarityAbiType): val is ClarityAbiTypeResponse =>
(val as ClarityAbiTypeResponse).response !== undefined;
export const isClarityAbiOptional = (val: ClarityAbiType): val is ClarityAbiTypeOptional =>
const isClarityAbiOptional = (val: ClarityAbiType): val is ClarityAbiTypeOptional =>
(val as ClarityAbiTypeOptional).optional !== undefined;
export const isClarityAbiTuple = (val: ClarityAbiType): val is ClarityAbiTypeTuple =>
const isClarityAbiTuple = (val: ClarityAbiType): val is ClarityAbiTypeTuple =>
(val as ClarityAbiTypeTuple).tuple !== undefined;
export const isClarityAbiList = (val: ClarityAbiType): val is ClarityAbiTypeList =>
const isClarityAbiList = (val: ClarityAbiType): val is ClarityAbiTypeList =>
(val as ClarityAbiTypeList).list !== undefined;
export type ClarityAbiTypeUnion =
type ClarityAbiTypeUnion =
| { id: ClarityAbiTypeId.ClarityAbiTypeUInt128; type: ClarityAbiTypeUInt128 }
| { id: ClarityAbiTypeId.ClarityAbiTypeInt128; type: ClarityAbiTypeInt128 }
| { id: ClarityAbiTypeId.ClarityAbiTypeBool; type: ClarityAbiTypeBool }
@@ -76,7 +76,7 @@ export type ClarityAbiTypeUnion =
| { id: ClarityAbiTypeId.ClarityAbiTypeTuple; type: ClarityAbiTypeTuple }
| { id: ClarityAbiTypeId.ClarityAbiTypeList; type: ClarityAbiTypeList };
export function getTypeUnion(val: ClarityAbiType): ClarityAbiTypeUnion {
function getTypeUnion(val: ClarityAbiType): ClarityAbiTypeUnion {
if (isClarityAbiPrimitive(val)) {
if (val === 'uint128') {
return { id: ClarityAbiTypeId.ClarityAbiTypeUInt128, type: val };
@@ -172,7 +172,7 @@ export function getTypeString(val: ClarityAbiType): string {
}
}
export interface ClarityAbiFunction {
interface ClarityAbiFunction {
name: string;
access: 'private' | 'public' | 'read_only';
args: {
@@ -184,13 +184,13 @@ export interface ClarityAbiFunction {
};
}
export interface ClarityAbiVariable {
interface ClarityAbiVariable {
name: string;
access: 'variable' | 'constant';
type: ClarityAbiType;
}
export interface ClarityAbiMap {
interface ClarityAbiMap {
name: string;
key: {
name: string;
@@ -202,11 +202,11 @@ export interface ClarityAbiMap {
}[];
}
export interface ClarityAbiTypeFungibleToken {
interface ClarityAbiTypeFungibleToken {
name: string;
}
export interface ClarityAbiTypeNonFungibleToken {
interface ClarityAbiTypeNonFungibleToken {
name: string;
type: ClarityAbiType;
}

View File

@@ -16,16 +16,16 @@ export enum CoreNodeEventType {
}
// TODO: core-node should use a better encoding for this structure;
export type NonStandardClarityValue = unknown;
type NonStandardClarityValue = unknown;
export interface CoreNodeEventBase {
interface CoreNodeEventBase {
/** 0x-prefix transaction hash. */
txid: string;
event_index: number;
committed: boolean;
}
export interface SmartContractEvent extends CoreNodeEventBase {
interface SmartContractEvent extends CoreNodeEventBase {
type: CoreNodeEventType.ContractEvent;
contract_event: {
/** Fully qualified contract ID, e.g. "ST2ZRX0K27GW0SP3GJCEMHD95TQGJMKB7G9Y0X1MH.kv-store" */
@@ -46,7 +46,7 @@ export interface StxTransferEvent extends CoreNodeEventBase {
};
}
export interface StxMintEvent extends CoreNodeEventBase {
interface StxMintEvent extends CoreNodeEventBase {
type: CoreNodeEventType.StxMintEvent;
stx_mint_event: {
recipient: string;
@@ -54,7 +54,7 @@ export interface StxMintEvent extends CoreNodeEventBase {
};
}
export interface StxBurnEvent extends CoreNodeEventBase {
interface StxBurnEvent extends CoreNodeEventBase {
type: CoreNodeEventType.StxBurnEvent;
stx_burn_event: {
sender: string;
@@ -76,7 +76,7 @@ export interface StxLockEvent extends CoreNodeEventBase {
};
}
export interface NftTransferEvent extends CoreNodeEventBase {
interface NftTransferEvent extends CoreNodeEventBase {
type: CoreNodeEventType.NftTransferEvent;
nft_transfer_event: {
/** Fully qualified asset ID, e.g. "ST2ZRX0K27GW0SP3GJCEMHD95TQGJMKB7G9Y0X1MH.contract-name.asset-name" */
@@ -89,7 +89,7 @@ export interface NftTransferEvent extends CoreNodeEventBase {
};
}
export interface NftMintEvent extends CoreNodeEventBase {
interface NftMintEvent extends CoreNodeEventBase {
type: CoreNodeEventType.NftMintEvent;
nft_mint_event: {
/** Fully qualified asset ID, e.g. "ST2ZRX0K27GW0SP3GJCEMHD95TQGJMKB7G9Y0X1MH.contract-name.asset-name" */
@@ -101,7 +101,7 @@ export interface NftMintEvent extends CoreNodeEventBase {
};
}
export interface NftBurnEvent extends CoreNodeEventBase {
interface NftBurnEvent extends CoreNodeEventBase {
type: CoreNodeEventType.NftBurnEvent;
nft_burn_event: {
/** Fully qualified asset ID, e.g. "ST2ZRX0K27GW0SP3GJCEMHD95TQGJMKB7G9Y0X1MH.contract-name.asset-name" */
@@ -113,7 +113,7 @@ export interface NftBurnEvent extends CoreNodeEventBase {
};
}
export interface FtTransferEvent extends CoreNodeEventBase {
interface FtTransferEvent extends CoreNodeEventBase {
type: CoreNodeEventType.FtTransferEvent;
ft_transfer_event: {
/** Fully qualified asset ID, e.g. "ST2ZRX0K27GW0SP3GJCEMHD95TQGJMKB7G9Y0X1MH.contract-name.asset-name" */
@@ -124,7 +124,7 @@ export interface FtTransferEvent extends CoreNodeEventBase {
};
}
export interface FtMintEvent extends CoreNodeEventBase {
interface FtMintEvent extends CoreNodeEventBase {
type: CoreNodeEventType.FtMintEvent;
ft_mint_event: {
/** Fully qualified asset ID, e.g. "ST2ZRX0K27GW0SP3GJCEMHD95TQGJMKB7G9Y0X1MH.contract-name.asset-name" */
@@ -134,7 +134,7 @@ export interface FtMintEvent extends CoreNodeEventBase {
};
}
export interface FtBurnEvent extends CoreNodeEventBase {
interface FtBurnEvent extends CoreNodeEventBase {
type: CoreNodeEventType.FtBurnEvent;
ft_burn_event: {
/** Fully qualified asset ID, e.g. "ST2ZRX0K27GW0SP3GJCEMHD95TQGJMKB7G9Y0X1MH.contract-name.asset-name" */
@@ -289,7 +289,7 @@ export interface CoreNodeAttachmentMessage {
content: string;
}
export interface CoreNodeExecutionCostMessage {
interface CoreNodeExecutionCostMessage {
read_count: number;
read_length: number;
runtime: number;

View File

@@ -66,7 +66,7 @@ export function getTxSponsorAddress(tx: Transaction): string | undefined {
return sponsorAddress;
}
export function getAddressFromPublicKeyHash(
function getAddressFromPublicKeyHash(
publicKeyHash: Buffer,
hashMode: AddressHashMode,
transactionVersion: TransactionVersion
@@ -80,7 +80,7 @@ export function getAddressFromPublicKeyHash(
return addrString;
}
export function createTransactionFromCoreBtcStxLockEvent(
function createTransactionFromCoreBtcStxLockEvent(
chainId: ChainID,
event: StxLockEvent,
burnBlockHeight: number,
@@ -146,7 +146,7 @@ export function createTransactionFromCoreBtcStxLockEvent(
return tx;
}
export function createTransactionFromCoreBtcTxEvent(
function createTransactionFromCoreBtcTxEvent(
chainId: ChainID,
event: StxTransferEvent
): Transaction {

View File

@@ -197,7 +197,7 @@ interface FtTokenMetadata {
description: string;
}
export interface TokenHandlerArgs {
interface TokenHandlerArgs {
contractId: string;
smartContractAbi: ClarityAbi;
datastore: DataStore;
@@ -262,7 +262,7 @@ function findFunction(fun: ClarityAbiFunction, functionList: ClarityAbiFunction[
return found !== undefined;
}
export class TokensContractHandler {
class TokensContractHandler {
readonly contractAddress: string;
readonly contractName: string;
readonly contractId: string;

View File

@@ -30,7 +30,6 @@ export const isReadOnlyMode = parseArgBoolean(process.env['STACKS_READ_ONLY_MODE
export const APP_DIR = __dirname;
export const REPO_DIR = path.dirname(__dirname);
export const U32_MAX = 0xffffffff;
export const I32_MAX = 0x7fffffff;
export const EMPTY_HASH_256 = '0x0000000000000000000000000000000000000000000000000000000000000000';
@@ -66,7 +65,7 @@ const enumCheckFunctions = new Map<object, (value: number) => boolean>();
* }
* ```
*/
export function isEnum<T extends string, TEnumValue extends number>(
function isEnum<T extends string, TEnumValue extends number>(
enumVariable: { [key in T]: TEnumValue },
value: number
): value is TEnumValue {
@@ -149,7 +148,7 @@ type DisabledLogLevels = Exclude<
type LoggerInterface = Omit<winston.Logger, DisabledLogLevels> & { level: LogLevel };
const LOG_LEVELS: LogLevel[] = ['error', 'warn', 'info', 'http', 'verbose', 'debug', 'silly'];
export const defaultLogLevel: LogLevel = (() => {
const defaultLogLevel: LogLevel = (() => {
const STACKS_API_LOG_LEVEL_ENV_VAR = 'STACKS_API_LOG_LEVEL';
const logLevelEnvVar = process.env[
STACKS_API_LOG_LEVEL_ENV_VAR
@@ -213,7 +212,7 @@ export const TOTAL_STACKS = new BigNumber(1320000000)
.plus(322146 * 100 + 5 * 50000) // air drop
.toString();
export const MICROSTACKS_IN_STACKS = 1_000_000n;
const MICROSTACKS_IN_STACKS = 1_000_000n;
export const STACKS_DECIMAL_PLACES = 6;
export function stxToMicroStx(stx: bigint | number): bigint {
@@ -310,28 +309,12 @@ export function isValidPrincipal(
return false;
}
export type HttpClientResponse = http.IncomingMessage & {
type HttpClientResponse = http.IncomingMessage & {
statusCode: number;
statusMessage: string;
response: string;
};
export function httpPostJsonRequest(
opts: http.RequestOptions & {
/** Throw if the response was not successful (status outside the range 200-299). */
throwOnNotOK?: boolean;
body: any;
}
): Promise<HttpClientResponse> {
const bodyJsonString = JSON.stringify(opts.body);
const bodyBuffer = Buffer.from(bodyJsonString, 'utf8');
return httpPostRequest({
...opts,
body: bodyBuffer,
headers: { 'Content-Type': 'application/json', ...opts.headers },
});
}
export function httpPostRequest(
opts: http.RequestOptions & {
/** Throw if the response was not successful (status outside the range 200-299). */
@@ -513,19 +496,6 @@ export function getCurrentGitTag(): string {
}
}
/** JSON.stringify with support for bigint types. */
// eslint-disable-next-line @typescript-eslint/ban-types
export function jsonStringify(obj: object): string {
const stringified = JSON.stringify(obj, (_key, value) => {
if (typeof value === 'bigint') {
return '0x' + value.toString(16);
}
// eslint-disable-next-line @typescript-eslint/no-unsafe-return
return value;
});
return stringified;
}
/**
* Encodes a buffer as a `0x` prefixed lower-case hex string.
* Returns an empty string if the buffer is zero length.
@@ -809,8 +779,6 @@ export async function time<T>(
}
}
export type Json = string | number | boolean | null | { [property: string]: Json } | Json[];
/**
* Escape a string for use as a css selector name.
* From https://github.com/mathiasbynens/CSS.escape/blob/master/css.escape.js

View File

@@ -43,7 +43,7 @@ const readFile = util.promisify(fs.readFile);
const SUBDOMAIN_BATCH_SIZE = 2000;
const STX_VESTING_BATCH_SIZE = 2000;
export class LineReaderStream extends stream.Duplex {
class LineReaderStream extends stream.Duplex {
asyncGen: AsyncGenerator<string, void, unknown>;
readlineInstance: readline.Interface;
passthrough: stream.Duplex;

View File

@@ -29,7 +29,7 @@ function isInspectorNotConnectedError(error: unknown): boolean {
* Use VSCode or Chrome's 'DevTools for Node' (under chrome://inspect) to visualize the `.cpuprofile` file.
* @param samplingInterval - Optionally set sampling interval in microseconds, default is 1000 microseconds.
*/
export function initCpuProfiling(samplingInterval?: number): ProfilerInstance<CpuProfileResult> {
function initCpuProfiling(samplingInterval?: number): ProfilerInstance<CpuProfileResult> {
const sw = stopwatch();
const session = new inspector.Session();
session.connect();
@@ -164,7 +164,7 @@ export function initCpuProfiling(samplingInterval?: number): ProfilerInstance<Cp
* The result stream can be used to create a `.heapsnapshot` file.
* Use Chrome's 'DevTools for Node' (under chrome://inspect) to visualize the `.heapsnapshot` file.
*/
export function initHeapSnapshot(
function initHeapSnapshot(
outputStream: stream.Writable
): ProfilerInstance<{ totalSnapshotByteSize: number }> {
const session = new inspector.Session();

View File

@@ -1,69 +0,0 @@
import { BufferReader } from '@stacks/transactions';
/*
const blockHeaderSize =
1 + // version number
16 + // proof score
80 + // VRF proof
32 + // parent block hash
32 + // parent microblock hash
2 + // parent microblock sequence number
32 + // transaction merkle root
32 + // state merkle root
20; // microblock public key hash
*/
export interface BlockHeader {
/** Version number to describe how to validate the block. */
version: number;
/** How much work has gone into this chain so far. */
workScore: {
/** Number of burn tokens destroyed. */
burn: bigint;
/** In Stacks, "work" == the length of the fork. */
work: bigint;
};
/** RFC-compliant VRF. Must match the burn commitment transaction on the burn chain (in particular, it must hash to its VRF seed). */
vrfProof: {
/** Compressed Ed25519 point. */
gamma: Buffer;
/** Ed25519 scalar - unsigned integer */
c: Buffer;
/** Ed25519 scalar - unsigned integer */
s: Buffer;
};
/** The SHA512/256 hash of the last anchored block that precedes this block in the fork to which this block is to be appended. */
parentBlockHash: Buffer;
/** The SHA512/256 hash of the last streamed block that precedes this block in the fork to which this block is to be appended. */
parentMicroblockHash: Buffer;
/** The sequence number of the parent microblock to which this anchored block is attached. */
parentMicroblockSequence: number;
/** The SHA512/256 root hash of a binary Merkle tree calculated over the sequence of transactions in this block. */
txMerkleRootHash: Buffer;
/** The SHA512/256 root hash of a MARF index over the state of the blockchain. */
stateMerkleRootHash: Buffer;
/** The Hash160 of a compressed public key whose private key will be used to sign microblocks during the peer's tenure. */
microblockPubkeyHash: Buffer;
}
export function readBlockHeader(reader: BufferReader): BlockHeader {
const header: BlockHeader = {
version: reader.readUInt8(),
workScore: {
burn: reader.readBigUInt64BE(),
work: reader.readBigUInt64BE(),
},
vrfProof: {
gamma: reader.readBuffer(32),
c: reader.readBuffer(16),
s: reader.readBuffer(32),
},
parentBlockHash: reader.readBuffer(32),
parentMicroblockHash: reader.readBuffer(32),
parentMicroblockSequence: reader.readUInt16BE(),
txMerkleRootHash: reader.readBuffer(32),
stateMerkleRootHash: reader.readBuffer(32),
microblockPubkeyHash: reader.readBuffer(20),
};
return header;
}

View File

@@ -1,23 +0,0 @@
import { BufferReader } from '@stacks/transactions';
import { readBlockHeader, BlockHeader } from './block-header';
import { readTransactions, Transaction } from './tx';
export interface Block {
header: BlockHeader;
transactions: Transaction[];
}
export function readBlocks(reader: BufferReader): Block[] {
const blockCount = reader.readUInt32BE();
const blocks = new Array<Block>(blockCount);
for (let i = 0; i < blockCount; i++) {
const blockHeader = readBlockHeader(reader);
const txs = readTransactions(reader);
const block: Block = {
header: blockHeader,
transactions: txs,
};
blocks[i] = block;
}
return blocks;
}

View File

@@ -1,92 +0,0 @@
import { Block } from './block';
import { Transaction } from './tx';
import { BufferReader } from '@stacks/transactions';
export enum StacksMessageTypeID {
Handshake = 0,
HandshakeAccept = 1,
HandshakeReject = 2,
GetNeighbors = 3,
Neighbors = 4,
GetBlocksInv = 5,
BlocksInv = 6,
GetBlocks = 7,
Blocks = 8,
GetMicroblocks = 9,
Microblocks = 10,
Transaction = 11,
Nack = 12,
Ping = 13,
Pong = 14,
Reserved = 255,
}
export interface Preamble {
/** u32 - software version */
peerVersion: number;
/** u32 - mainnet, testnet, etc */
networkId: number;
/** u32 - message sequence number -- pairs this message to a request */
sequenceNumber: number;
/** u64 - last-seen block height (at chain tip) */
burnBlockHeight: bigint;
/** 20 bytes - consensus hash at block_height */
burnConsensusHash: Buffer;
/** u64 - latest stable block height (e.g. chain tip minus 7) */
burnStableBlockHeight: bigint;
/** 20 bytes - consensus hash for burn_stable_block_height */
burnStableConsensusHash: Buffer;
/** u32 - RESERVED; pointer to additional data (should be all 0's if not used) */
additionalData: number;
/** 65 bytes - signature from the peer that sent this */
signature: Buffer;
/** u32 - length of the following payload, including relayers vector */
payloadLength: number;
}
const CONSENSUS_HASH_ENCODED_SIZE = 20;
const MESSAGE_SIGNATURE_ENCODED_SIZE = 65;
export const PREAMBLE_ENCODED_SIZE =
4 + // peer_version
4 + // network_id
4 + // sequence number
8 + // burn_block_height
CONSENSUS_HASH_ENCODED_SIZE + // burn_consensus_hash
8 + // burn_stable_block_height
CONSENSUS_HASH_ENCODED_SIZE + // burn_stable_consensus_hash
4 + // additional_data
MESSAGE_SIGNATURE_ENCODED_SIZE + // signature
4; // payload_len
const RELAY_DATA_ENCODED_SIZE = 107;
function readRelayers(reader: BufferReader): Buffer {
const length = reader.readUInt32BE();
let relayersData: Buffer;
if (length === 0) {
relayersData = Buffer.alloc(0);
} else {
relayersData = reader.readBuffer(length * RELAY_DATA_ENCODED_SIZE);
}
return relayersData;
}
export interface StacksMessageBlocks {
messageTypeId: StacksMessageTypeID.Blocks;
blocks: Block[];
}
export function isStacksMessageBlocks(msg: StacksMessage): msg is StacksMessageBlocks {
return msg.messageTypeId === StacksMessageTypeID.Blocks;
}
export interface StacksMessageTransaction {
messageTypeId: StacksMessageTypeID.Transaction;
transaction: Transaction;
}
export function isStacksMessageTransaction(msg: StacksMessage): msg is StacksMessageTransaction {
return msg.messageTypeId === StacksMessageTypeID.Transaction;
}
type StacksMessage = StacksMessageBlocks | StacksMessageTransaction;

View File

@@ -2,7 +2,7 @@ import { getEnumDescription } from '../helpers';
import { StacksMessageParsingError, NotImplementedError } from '../errors';
import { ClarityValue, deserializeCV, BufferReader } from '@stacks/transactions';
export const MICROBLOCK_HEADER_SIZE =
const MICROBLOCK_HEADER_SIZE =
// 1-byte version number
1 +
// 2-byte sequence number
@@ -106,7 +106,7 @@ export enum TransactionPostConditionMode {
Deny = 0x02,
}
export enum TransactionVersion {
enum TransactionVersion {
Mainnet = 0x00,
Testnet = 0x80,
}
@@ -185,14 +185,14 @@ export interface AssetInfo {
assetName: string;
}
export interface TransactionPostConditionStx {
interface TransactionPostConditionStx {
assetInfoId: AssetInfoTypeID.STX; // u8
principal: PostConditionPrincipal;
conditionCode: FungibleConditionCode; // u8
amount: bigint; // u64
}
export interface TransactionPostConditionFungible {
interface TransactionPostConditionFungible {
assetInfoId: AssetInfoTypeID.FungibleAsset; // u8
principal: PostConditionPrincipal;
asset: AssetInfo;
@@ -200,7 +200,7 @@ export interface TransactionPostConditionFungible {
amount: bigint; // u64
}
export interface TransactionPostConditionNonfungible {
interface TransactionPostConditionNonfungible {
assetInfoId: AssetInfoTypeID.NonfungibleAsset; // u8
principal: PostConditionPrincipal;
asset: AssetInfo;
@@ -233,7 +233,7 @@ interface TransactionPayloadCoinbase {
payload: Buffer; // 32 bytes
}
export interface TransactionPayloadContractCall {
interface TransactionPayloadContractCall {
typeId: TransactionPayloadTypeID.ContractCall;
address: StacksAddress;
contractName: string;
@@ -334,16 +334,6 @@ export function readTransaction(reader: BufferReader): Transaction {
return tx;
}
export function readTransactions(reader: BufferReader): Transaction[] {
const txCount = reader.readUInt32BE();
const txs = new Array<Transaction>(txCount);
for (let i = 0; i < txCount; i++) {
const tx = readTransaction(reader);
txs[i] = tx;
}
return txs;
}
function readTransactionPayload(reader: BufferReader): TransactionPayload {
const txPayloadType = reader.readUInt8Enum(TransactionPayloadTypeID, n => {
throw new StacksMessageParsingError(`unexpected tx payload type: ${n}`);

View File

@@ -158,7 +158,7 @@ export function processUnlockingEvents(events: StxUnlockEvent[], operations: Ros
});
}
export function processEvents(events: DbEvent[], baseTx: BaseTx, operations: RosettaOperation[]) {
function processEvents(events: DbEvent[], baseTx: BaseTx, operations: RosettaOperation[]) {
events.forEach(event => {
const txEventType = event.event_type;
switch (txEventType) {
@@ -262,7 +262,7 @@ function makeStakeUnlockOperation(tx: StxUnlockEvent, index: number): RosettaOpe
return unlock;
}
export function getMinerOperations(minerRewards: DbMinerReward[], operations: RosettaOperation[]) {
function getMinerOperations(minerRewards: DbMinerReward[], operations: RosettaOperation[]) {
minerRewards.forEach(reward => {
operations.push(makeMinerRewardOperation(reward, operations.length));
});
@@ -760,7 +760,7 @@ export function isDecimalsSupported(operations: RosettaOperation[]): boolean {
return true;
}
export function getStxCurrencyMetadata(): RosettaCurrency {
function getStxCurrencyMetadata(): RosettaCurrency {
const currency: RosettaCurrency = {
decimals: RosettaConstants.decimals,
symbol: RosettaConstants.symbol,
@@ -912,7 +912,7 @@ export function getStacksTestnetNetwork() {
return stacksNetwork;
}
export function getStacksMainnetNetwork() {
function getStacksMainnetNetwork() {
const stacksNetwork = new StacksMainnet();
stacksNetwork.coreApiUrl = `http://${getCoreNodeEndpoint()}`;
return stacksNetwork;

View File

@@ -2,8 +2,8 @@ import { logError, logger, resolveOrTimeout } from './helpers';
const SHUTDOWN_SIGNALS = ['SIGINT', 'SIGTERM'] as const;
export type ShutdownHandler = () => void | PromiseLike<void>;
export type ShutdownConfig = {
type ShutdownHandler = () => void | PromiseLike<void>;
type ShutdownConfig = {
name: string;
handler: ShutdownHandler;
forceKillable: boolean;
@@ -12,7 +12,7 @@ export type ShutdownConfig = {
const shutdownConfigs: ShutdownConfig[] = [];
export let isShuttingDown = false;
let isShuttingDown = false;
async function startShutdown() {
if (isShuttingDown) {

View File

@@ -6,6 +6,7 @@ export interface GlobalServices {
db: PgDataStore;
}
// ts-unused-exports:disable-next-line
export default async (): Promise<void> => {
console.log('Jest - setup..');
if (!process.env.NODE_ENV) {

View File

@@ -1,5 +1,6 @@
import type { GlobalServices } from './setup';
// ts-unused-exports:disable-next-line
export default async (): Promise<void> => {
console.log('Jest - teardown..');
const globalServices = (global as unknown) as GlobalServices;

View File

@@ -5,7 +5,7 @@ import { PgDataStore } from '../datastore/postgres-store';
export interface GlobalServices {
db: PgDataStore;
}
// ts-unused-exports:disable-next-line
export default async (): Promise<void> => {
console.log('Jest - setup..');
if (!process.env.NODE_ENV) {

View File

@@ -1,5 +1,5 @@
import type { GlobalServices } from './setup';
// ts-unused-exports:disable-next-line
export default async (): Promise<void> => {
console.log('Jest - teardown..');
const globalServices = (global as unknown) as GlobalServices;

View File

@@ -148,7 +148,7 @@ async function sendCoreTx(
return Promise.resolve({ txId: '' });
}
export function GetStacksTestnetNetwork() {
function GetStacksTestnetNetwork() {
const stacksNetwork = new StacksTestnet();
stacksNetwork.coreApiUrl = getCoreNodeEndpoint({
host: `http://${HOST}`,

View File

@@ -5,7 +5,7 @@ import { PgDataStore } from '../datastore/postgres-store';
export interface GlobalServices {
db: PgDataStore;
}
// ts-unused-exports:disable-next-line
export default async (): Promise<void> => {
console.log('Jest - setup..');
if (!process.env.NODE_ENV) {

View File

@@ -1,5 +1,5 @@
import type { GlobalServices } from './setup';
// ts-unused-exports:disable-next-line
export default async (): Promise<void> => {
console.log('Jest - teardown..');
const globalServices = (global as unknown) as GlobalServices;

View File

@@ -306,7 +306,7 @@ async function sendCoreTx(
return Promise.resolve({ txId: '' });
}
export function getStacksTestnetNetwork() {
function getStacksTestnetNetwork() {
const stacksNetwork = new StacksTestnet();
stacksNetwork.coreApiUrl = getCoreNodeEndpoint({
host: `http://${HOST}`,

View File

@@ -6,6 +6,7 @@ export interface GlobalServices {
db: PgDataStore;
}
// ts-unused-exports:disable-next-line
export default async (): Promise<void> => {
console.log('Jest - setup..');
if (!process.env.NODE_ENV) {

View File

@@ -1,5 +1,6 @@
import type { GlobalServices } from './setup';
// ts-unused-exports:disable-next-line
export default async (): Promise<void> => {
console.log('Jest - teardown..');
const globalServices = (global as unknown) as GlobalServices;

View File

@@ -6,6 +6,7 @@ export interface GlobalServices {
db: PgDataStore;
}
// ts-unused-exports:disable-next-line
export default async (): Promise<void> => {
console.log('Jest - setup..');
if (!process.env.NODE_ENV) {

View File

@@ -1,5 +1,6 @@
import type { GlobalServices } from './setup';
// ts-unused-exports:disable-next-line
export default async (): Promise<void> => {
console.log('Jest - teardown..');
const globalServices = (global as unknown) as GlobalServices;

View File

@@ -5,6 +5,7 @@ import { startEventServer } from '../event-stream/event-server';
import { StacksCoreRpcClient } from '../core-rpc/client';
import { ChainID } from '@stacks/transactions';
// ts-unused-exports:disable-next-line
export default async (): Promise<void> => {
console.log('Jest - setup..');
if (!process.env.NODE_ENV) {

View File

@@ -1,3 +1,4 @@
// ts-unused-exports:disable-next-line
export default async (): Promise<void> => {
console.log('Jest - teardown..');
const eventSocketServer: import('net').Server = (global as any).server;

View File

@@ -38,7 +38,7 @@ export async function useWithCleanup<T extends [...Disposable<any>[]]>(
}
}
export type TestEnvVar = [EnvVarKey: string, EnvVarValue: string];
type TestEnvVar = [EnvVarKey: string, EnvVarValue: string];
/**
* Helper function for tests.