Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add /extended/v2/smart-contracts/status endpoint #1833

Merged
merged 8 commits into from
Jan 18, 2024
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 19 additions & 0 deletions docs/api/smart-contracts/get-smart-contracts-status.example.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
[
{
"contract_id": "SP3K8BC0PPEVCV7NZ6QSRWPQ2JE9E5B6N3PA0KBR9.swap-helper-bridged-v1-1",
"status": "success",
"tx_id": "0x8542d28e427256ea3c29dcd8793222891999ceff4ef1bb062e2f21cb6def6884",
"block_height": 111021
},
{
"contract_id": "SP1JTCR202ECC6333N7ZXD7MK7E3ZTEEE1MJ73C60.name-registrar",
"status": "success",
"tx_id": "0x6e1114cce8c6f2e9c8130f9acd75d67bb667ae584f882acdd2db6dd74e6cbe5e",
"block_height": 113010
},
{
"contract_id": "SP4SZE494VC2YC5JYG7AYFQ44F5Q4PYV7DVMDPBG.stacking-dao-core-v1",
"status": "pending",
"tx_id": "0x10bdcf10ffee72994f493ac36760f4e95a76c8471370182fd4705c2153dc173d"
}
]
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
{
"description": "GET request that returns the deployment status of multiple smart contracts",
"additionalProperties": false,
"title": "SmartContractsStatusResponse",
"type": "array",
"items": {
"$ref": "../../entities/smart-contracts/smart-contract-status.schema.json"
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
{
"contract_id": "SP3K8BC0PPEVCV7NZ6QSRWPQ2JE9E5B6N3PA0KBR9.swap-helper-bridged-v1-1",
"status": "success",
"tx_id": "0x8542d28e427256ea3c29dcd8793222891999ceff4ef1bb062e2f21cb6def6884",
"block_height": 111021
}
29 changes: 29 additions & 0 deletions docs/entities/smart-contracts/smart-contract-status.schema.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
{
"title": "SmartContractStatus",
"description": "Deployment status of a smart contract",
"type": "object",
"additionalProperties": false,
"required": [
"status",
"tx_id",
"contract_id"
],
"properties": {
"status": {
"type": "string",
"description": "Smart contract deployment transaction status"
},
"tx_id": {
"type": "string",
"description": "Deployment transaction ID"
},
"contract_id": {
"type": "string",
"description": "Smart contract ID"
},
"block_height": {
"type": "integer",
"description": "Height of the transaction confirmation block"
}
zone117x marked this conversation as resolved.
Show resolved Hide resolved
}
}
27 changes: 27 additions & 0 deletions docs/generated.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,7 @@ export type SchemaMergeRootStub =
| SearchSuccessResult
| TxSearchResult
| SearchResult
| SmartContractsStatusResponse
| PoolDelegationsResponse
| {
[k: string]: unknown | undefined;
Expand Down Expand Up @@ -177,6 +178,7 @@ export type SchemaMergeRootStub =
| RosettaSyncStatus
| TransactionIdentifier
| RosettaTransaction
| SmartContractStatus
| PoolDelegation
| NonFungibleTokenHistoryEventWithTxId
| NonFungibleTokenHistoryEventWithTxMetadata
Expand Down Expand Up @@ -689,6 +691,10 @@ export type SearchSuccessResult =
* complete search result for terms
*/
export type SearchResult = SearchErrorResult | SearchSuccessResult;
/**
* GET request that returns the deployment status of multiple smart contracts
*/
export type SmartContractsStatusResponse = SmartContractStatus[];
/**
* Describes an event from the history of a Non-Fungible Token
*/
Expand Down Expand Up @@ -3059,6 +3065,27 @@ export interface TxSearchResult {
metadata?: Transaction;
};
}
/**
* Deployment status of a smart contract
*/
export interface SmartContractStatus {
/**
* Smart contract deployment transaction status
*/
status: string;
/**
* Deployment transaction ID
*/
tx_id: string;
rafaelcr marked this conversation as resolved.
Show resolved Hide resolved
/**
* Smart contract ID
*/
contract_id: string;
/**
* Height of the transaction confirmation block
*/
block_height?: number;
}
/**
* GET request that returns stacking pool member details for a given pool (delegator) principal
*/
Expand Down
30 changes: 30 additions & 0 deletions docs/openapi.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -834,6 +834,36 @@ paths:
example:
$ref: ./api/transaction/get-transactions.example.json

/extended/v2/smart-contracts/status:
get:
summary: Get smart contracts status
description: |
Retrieves the deployment status of multiple smart contracts.
tags:
- Smart Contracts
operationId: get_smart_contracts_status
parameters:
- name: contract_id
in: query
description: contract ids to fetch status for
required: true
style: form
explode: true
schema:
type: array
example: "SPQZF23W7SEYBFG5JQ496NMY0G7379SRYEDREMSV.Candy"
items:
type: string
responses:
200:
description: List of smart contract status
content:
application/json:
schema:
$ref: ./api/blocks/get-blocks.schema.json
example:
$ref: ./api/blocks/get-blocks.example.json

/extended/v1/block:
get:
summary: Get recent blocks
Expand Down
2 changes: 2 additions & 0 deletions src/api/init.ts
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,7 @@ import { createV2BlocksRouter } from './routes/v2/blocks';
import { getReqQuery } from './query-helpers';
import { createV2BurnBlocksRouter } from './routes/v2/burn-blocks';
import { createMempoolRouter } from './routes/v2/mempool';
import { createV2SmartContractsRouter } from './routes/v2/smart-contracts';

export interface ApiServer {
expressApp: express.Express;
Expand Down Expand Up @@ -234,6 +235,7 @@ export async function startApiServer(opts: {
const v2 = express.Router();
v2.use('/blocks', createV2BlocksRouter(datastore));
v2.use('/burn-blocks', createV2BurnBlocksRouter(datastore));
v2.use('/smart-contracts', createV2SmartContractsRouter(datastore));
v2.use('/mempool', createMempoolRouter(datastore));
return v2;
})()
Expand Down
11 changes: 11 additions & 0 deletions src/api/routes/v2/schemas.ts
Original file line number Diff line number Diff line change
Expand Up @@ -125,3 +125,14 @@ const BlockParamsSchema = Type.Object(
);
export type BlockParams = Static<typeof BlockParamsSchema>;
export const CompiledBlockParams = ajv.compile(BlockParamsSchema);

const SmartContractStatusParamsSchema = Type.Object(
{
contract_id: Type.Array(
Type.RegExp(/^[0123456789ABCDEFGHJKMNPQRSTVWXYZ]{28,41}\.[a-zA-Z]([a-zA-Z0-9]|[-_]){0,39}$/)
),
},
{ additionalProperties: false }
);
export type SmartContractStatusParams = Static<typeof SmartContractStatusParamsSchema>;
export const CompiledSmartContractStatusParams = ajv.compile(SmartContractStatusParamsSchema);
30 changes: 30 additions & 0 deletions src/api/routes/v2/smart-contracts.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import * as express from 'express';
import { PgStore } from '../../../datastore/pg-store';
import { getETagCacheHandler, setETagCacheHeaders } from '../../controllers/cache-controller';
import { asyncHandler } from '../../async-handler';
import { SmartContractsStatusResponse } from 'docs/generated';
import {
validRequestQuery,
CompiledSmartContractStatusParams,
SmartContractStatusParams,
} from './schemas';

export function createV2SmartContractsRouter(db: PgStore): express.Router {
const router = express.Router();
const cacheHandler = getETagCacheHandler(db);

router.get(
'/status',
cacheHandler,
asyncHandler(async (req, res) => {
if (!validRequestQuery(req, res, CompiledSmartContractStatusParams)) return;
const query = req.query as SmartContractStatusParams;

const response = (await db.v2.getSmartContractStatus(query)) as SmartContractsStatusResponse;
setETagCacheHeaders(res);
res.json(response);
})
);

return router;
}
7 changes: 7 additions & 0 deletions src/datastore/common.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1554,3 +1554,10 @@ export enum IndexesState {
Off = 0,
On = 1,
}

export interface DbSmartContractStatus {
contract_id: string;
tx_id: string;
status: string;
block_height?: number;
}
37 changes: 37 additions & 0 deletions src/datastore/pg-store-v2.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import {
TransactionLimitParamSchema,
BlockParams,
BlockPaginationQueryParams,
SmartContractStatusParams,
} from '../api/routes/v2/schemas';
import { InvalidRequestError, InvalidRequestErrorType } from '../errors';
import { normalizeHashString } from '../helpers';
Expand All @@ -16,6 +17,8 @@ import {
DbTx,
TxQueryResult,
DbBurnBlock,
DbTxTypeId,
DbSmartContractStatus,
} from './common';
import { BLOCK_COLUMNS, parseBlockQueryResult, TX_COLUMNS, parseTxQueryResult } from './helpers';

Expand Down Expand Up @@ -230,4 +233,38 @@ export class PgStoreV2 extends BasePgStoreModule {
if (blockQuery.count > 0) return blockQuery[0];
});
}

async getSmartContractStatus(args: SmartContractStatusParams): Promise<DbSmartContractStatus[]> {
return await this.sqlTransaction(async sql => {
const statusArray: DbSmartContractStatus[] = [];

// Search confirmed txs.
const confirmed = await sql<DbSmartContractStatus[]>`
SELECT DISTINCT ON (smart_contract_contract_id) smart_contract_contract_id, tx_id, block_height, status
FROM txs
WHERE type_id IN ${sql([DbTxTypeId.SmartContract, DbTxTypeId.VersionedSmartContract])}
AND smart_contract_contract_id IN ${sql(args.contract_id)}
AND canonical = TRUE
AND microblock_canonical = TRUE
ORDER BY smart_contract_contract_id, block_height DESC, microblock_sequence DESC, tx_index DESC
`;
statusArray.push(...confirmed);
if (confirmed.count < args.contract_id.length) {
// Search mempool txs.
const confirmedIds = confirmed.map(c => c.contract_id);
const remainingIds = args.contract_id.filter(c => !confirmedIds.includes(c));
const mempool = await sql<DbSmartContractStatus[]>`
SELECT DISTINCT ON (smart_contract_contract_id) smart_contract_contract_id, tx_id, status
FROM mempool_txs
WHERE pruned = FALSE
AND type_id IN ${sql([DbTxTypeId.SmartContract, DbTxTypeId.VersionedSmartContract])}
AND smart_contract_contract_id IN ${sql(remainingIds)}
ORDER BY smart_contract_contract_id
`;
statusArray.push(...mempool);
}

return statusArray;
});
}
}
Loading