postchain-client
Advanced tools
Comparing version 1.15.2 to 1.16.0
@@ -15,2 +15,5 @@ export * as gtv from "./src/gtv/index"; | ||
export { createIccfProofTx, isBlockAnchored, getBlockAnchoringTransaction, getAnchoringClient, } from "./src/ICCF/IccfProofTxMaterialBuilder"; | ||
export { calculateTransactionRid } from "./src/utils/calculateTransactionRid"; | ||
export { encodeTransaction } from "./src/utils/encodeTransaction"; | ||
export { decodeTransactionToGtx } from "./src/utils/decodeTransactionToGtx"; | ||
export { Transaction, KeyPair, PubKey, PrivKey, QueryObject, NetworkSettings, TransactionReceipt, SignedTransaction, SignatureProvider, Operation, StatusObject, QueryCallback, ConfirmationProof, } from "./src/blockchainClient/types"; | ||
@@ -24,2 +27,3 @@ export { FailoverStrategy, ResponseStatus } from "./src/blockchainClient/enums"; | ||
export { Web3PromiEvent } from "./src/promiEvent/promiEvents"; | ||
export { CustomError } from "./src/customError"; | ||
export * from "./src/blockchainClient/errors"; | ||
@@ -26,0 +30,0 @@ export * from "./src/gtx/errors"; |
@@ -25,4 +25,8 @@ import * as gtv_1 from "./src/gtv/index"; | ||
export { createIccfProofTx, isBlockAnchored, getBlockAnchoringTransaction, getAnchoringClient, } from "./src/ICCF/IccfProofTxMaterialBuilder"; | ||
export { calculateTransactionRid } from "./src/utils/calculateTransactionRid"; | ||
export { encodeTransaction } from "./src/utils/encodeTransaction"; | ||
export { decodeTransactionToGtx } from "./src/utils/decodeTransactionToGtx"; | ||
export { FailoverStrategy, ResponseStatus } from "./src/blockchainClient/enums"; | ||
export { Web3PromiEvent } from "./src/promiEvent/promiEvents"; | ||
export { CustomError } from "./src/customError"; | ||
export * from "./src/blockchainClient/errors"; | ||
@@ -29,0 +33,0 @@ export * from "./src/gtx/errors"; |
@@ -22,3 +22,3 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { | ||
import { NumberOfSignersAndSignaturesException } from "../gtx/errors"; | ||
import { getTransactionRidException } from "./errors"; | ||
import { GetTransactionRidException } from "./errors"; | ||
import { Method } from "../restclient/enums"; | ||
@@ -76,5 +76,6 @@ import { ResponseStatus } from "./enums"; | ||
const promiEvent = new Web3PromiEvent((resolve, reject) => __awaiter(this, void 0, void 0, function* () { | ||
var _a; | ||
try { | ||
const gtx = getGTXFromBufferOrTransactionOrOperation(transaction, this.config.blockchainRid); | ||
if (gtx.signers.length !== gtx.signatures.length) { | ||
if (gtx.signers.length !== ((_a = gtx.signatures) === null || _a === void 0 ? void 0 : _a.length)) { | ||
reject(new NumberOfSignersAndSignaturesException()); | ||
@@ -114,2 +115,3 @@ } | ||
const awaitConfirmation = (txRID) => __awaiter(this, void 0, void 0, function* () { | ||
var _b; | ||
let lastKnownResult; | ||
@@ -122,6 +124,9 @@ for (let i = 0; i < this.config.statusPollCount; i++) { | ||
else if (lastKnownResult.status === ResponseStatus.Rejected) { | ||
throw new TxRejectedError(lastKnownResult.rejectReason); | ||
throw new TxRejectedError((_b = lastKnownResult.rejectReason) !== null && _b !== void 0 ? _b : ""); | ||
} | ||
yield sleep(this.config.statusPollInterval); | ||
} | ||
// TS issue. This could be fixed by inplementing new retry strategy | ||
// eslint-disable-next-line @typescript-eslint/ban-ts-comment | ||
//@ts-expect-error | ||
return lastKnownResult.status; | ||
@@ -216,3 +221,3 @@ }); | ||
catch (e) { | ||
throw new getTransactionRidException(e); | ||
throw new GetTransactionRidException(e); | ||
} | ||
@@ -225,7 +230,8 @@ }, | ||
: ""; | ||
const { error, statusCode, rspBody, } = yield requestWithRetry(Method.GET, `transactions/${this.config.blockchainRid}?limit=${limit}${beforeTimeQueryParam}`, this.config); | ||
const { error, statusCode, rspBody } = yield requestWithRetry(Method.GET, `transactions/${this.config.blockchainRid}?limit=${limit}${beforeTimeQueryParam}`, this.config); | ||
const body = statusCode === 200 | ||
? rspBody === null || rspBody === void 0 ? void 0 : rspBody.map(formatTransactionInfoResponse) | ||
: rspBody; | ||
return new Promise((resolve, reject) => { | ||
handleGetResponse(error, statusCode, statusCode === 200 | ||
? rspBody.map(formatTransactionInfoResponse) | ||
: rspBody, callbackPromiseBuilder(reject, resolve, callback)); | ||
handleGetResponse(error, statusCode, body, callbackPromiseBuilder(reject, resolve, callback)); | ||
}); | ||
@@ -243,5 +249,8 @@ }); | ||
} | ||
const { error, statusCode, rspBody, } = yield requestWithRetry(Method.GET, `transactions/${this.config.blockchainRid}/${toString(transactionRid)}`, this.config); | ||
const { error, statusCode, rspBody } = yield requestWithRetry(Method.GET, `transactions/${this.config.blockchainRid}/${toString(transactionRid)}`, this.config); | ||
const body = statusCode === 200 && rspBody | ||
? formatTransactionInfoResponse(rspBody) | ||
: rspBody; | ||
return new Promise((resolve, reject) => { | ||
handleGetResponse(error, statusCode, statusCode === 200 ? formatTransactionInfoResponse(rspBody) : rspBody, callbackPromiseBuilder(reject, resolve, callback)); | ||
handleGetResponse(error, statusCode, body, callbackPromiseBuilder(reject, resolve, callback)); | ||
}); | ||
@@ -252,3 +261,3 @@ }); | ||
return __awaiter(this, void 0, void 0, function* () { | ||
const { error, statusCode, rspBody, } = yield requestWithRetry(Method.GET, `transactions/${this.config.blockchainRid}/count`, this.config); | ||
const { error, statusCode, rspBody } = yield requestWithRetry(Method.GET, `transactions/${this.config.blockchainRid}/count`, this.config); | ||
return new Promise((resolve, reject) => { | ||
@@ -267,3 +276,3 @@ handleGetResponse(error, statusCode, statusCode === 200 ? rspBody.transactionsCount : rspBody, callbackPromiseBuilder(reject, resolve, callback)); | ||
return new Promise((resolve, reject) => { | ||
handleGetResponse(error, statusCode, statusCode === 200 && rspBody !== null | ||
handleGetResponse(error, statusCode, statusCode === 200 && rspBody !== null && rspBody | ||
? formatBlockInfoResponse(rspBody) | ||
@@ -274,2 +283,14 @@ : rspBody, callbackPromiseBuilder(reject, resolve, callback)); | ||
}, | ||
getLatestBlock(txs = false, callback) { | ||
return __awaiter(this, void 0, void 0, function* () { | ||
const shouldIncludeFullTransaction = txs ? `&txs=${txs}` : ""; | ||
const { error, statusCode, rspBody } = yield requestWithRetry(Method.GET, `blocks/${this.config.blockchainRid}?limit=1${shouldIncludeFullTransaction}`, this.config); | ||
const indexOfLatestBlock = 0; | ||
return new Promise((resolve, reject) => { | ||
handleGetResponse(error, statusCode, statusCode === 200 && rspBody !== null && rspBody | ||
? formatBlockInfoResponse(rspBody[indexOfLatestBlock]) | ||
: rspBody, callbackPromiseBuilder(reject, resolve, callback)); | ||
}); | ||
}); | ||
}, | ||
getBlocksInfo(limit = 25, beforeTime, beforeHeight, txs, callback) { | ||
@@ -287,3 +308,5 @@ return __awaiter(this, void 0, void 0, function* () { | ||
return new Promise((resolve, reject) => { | ||
handleGetResponse(error, statusCode, statusCode === 200 ? rspBody.map(formatBlockInfoResponse) : rspBody, callbackPromiseBuilder(reject, resolve, callback)); | ||
handleGetResponse(error, statusCode, statusCode === 200 && rspBody | ||
? rspBody.map(formatBlockInfoResponse) | ||
: rspBody, callbackPromiseBuilder(reject, resolve, callback)); | ||
}); | ||
@@ -340,5 +363,2 @@ }); | ||
const confirmationProof = { | ||
hash: undefined, | ||
blockHeader: undefined, | ||
witness: undefined, | ||
merkleProofTree: "", | ||
@@ -345,0 +365,0 @@ txIndex: 0, |
@@ -77,2 +77,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { | ||
}, | ||
getLatestBlock() { | ||
return __awaiter(this, void 0, void 0, function* () { | ||
return Promise.reject("getLatestBlock rejected"); | ||
}); | ||
}, | ||
getBlocksInfo() { | ||
@@ -79,0 +84,0 @@ return __awaiter(this, void 0, void 0, function* () { |
@@ -1,21 +0,22 @@ | ||
export declare class MissingPubKeyError extends Error { | ||
import { CustomError } from "../customError"; | ||
export declare class MissingPubKeyError extends CustomError { | ||
constructor(); | ||
} | ||
export declare class MissingBlockchainIdentifierError extends Error { | ||
export declare class MissingBlockchainIdentifierError extends CustomError { | ||
constructor(); | ||
} | ||
export declare class MissingNodeUrlError extends Error { | ||
export declare class MissingNodeUrlError extends CustomError { | ||
constructor(); | ||
} | ||
export declare class BlockchainUrlUndefinedException extends Error { | ||
export declare class BlockchainUrlUndefinedException extends CustomError { | ||
constructor(brid: string | number); | ||
} | ||
export declare class DirectoryNodeUrlPoolException extends Error { | ||
export declare class DirectoryNodeUrlPoolException extends CustomError { | ||
constructor(); | ||
} | ||
export declare class InvalidTransactionFormatException extends Error { | ||
export declare class InvalidTransactionFormatException extends CustomError { | ||
constructor(); | ||
} | ||
export declare class getTransactionRidException extends Error { | ||
export declare class GetTransactionRidException extends CustomError { | ||
constructor(error: Error); | ||
} |
@@ -1,37 +0,38 @@ | ||
export class MissingPubKeyError extends Error { | ||
import { CustomError } from "../customError"; | ||
export class MissingPubKeyError extends CustomError { | ||
constructor() { | ||
super(`No public key was provided`); | ||
super(`No public key was provided`, 400); | ||
} | ||
} | ||
export class MissingBlockchainIdentifierError extends Error { | ||
export class MissingBlockchainIdentifierError extends CustomError { | ||
constructor() { | ||
super(`No blockchain identifier was provided. Include either a blockchainRid (string) or a blockchainIid (number).`); | ||
super(`No blockchain identifier was provided. Include either a blockchainRid (string) or a blockchainIid (number).`, 400); | ||
} | ||
} | ||
export class MissingNodeUrlError extends Error { | ||
export class MissingNodeUrlError extends CustomError { | ||
constructor() { | ||
super(`No node url or directory node url was provided. Include either a nodeUrl (string) or a directory node url (number).`); | ||
super(`No node url or directory node url was provided. Include either a nodeUrl (string) or a directory node url (number).`, 400); | ||
} | ||
} | ||
export class BlockchainUrlUndefinedException extends Error { | ||
export class BlockchainUrlUndefinedException extends CustomError { | ||
constructor(brid) { | ||
const idType = typeof brid === "string" ? "BRID" : "IID"; | ||
super(`Cannot find nodes hosting the blockchain with ${idType} ${brid}`); | ||
super(`Cannot find nodes hosting the blockchain with ${idType} ${brid}`, 400); | ||
} | ||
} | ||
export class DirectoryNodeUrlPoolException extends Error { | ||
export class DirectoryNodeUrlPoolException extends CustomError { | ||
constructor() { | ||
super(`No directory node url was provided`); | ||
super(`No directory node url was provided`, 400); | ||
} | ||
} | ||
export class InvalidTransactionFormatException extends Error { | ||
export class InvalidTransactionFormatException extends CustomError { | ||
constructor() { | ||
super(`The transaction is not in the right format`); | ||
super(`The transaction is not in the right format`, 400); | ||
} | ||
} | ||
export class getTransactionRidException extends Error { | ||
export class GetTransactionRidException extends CustomError { | ||
constructor(error) { | ||
super(`"Error occurred while getting transaction RID:", ${error}`); | ||
super(`"Error occurred while getting transaction RID:", ${error}`, 400); | ||
} | ||
} | ||
//# sourceMappingURL=errors.js.map |
@@ -5,3 +5,3 @@ /// <reference types="node" /> | ||
import { Web3PromiEvent } from "../promiEvent/promiEvents"; | ||
import { StatusObject } from "../restclient/types"; | ||
import { RestClientCallback, StatusObject } from "../restclient/types"; | ||
import { ClientConfig, Operation, QueryCallback, QueryObject, SignatureProvider, SignedTransaction, Transaction, TransactionReceipt } from "./types"; | ||
@@ -34,3 +34,3 @@ import { GTX } from "../gtx/types"; | ||
*/ | ||
signTransaction(transaction: Transaction | SignedTransaction, signMethod: KeyPair | SignatureProvider, callback?: (error: Error, signedTx: Buffer) => void): Promise<SignedTransaction>; | ||
signTransaction(transaction: Transaction | SignedTransaction, signMethod: KeyPair | SignatureProvider, callback?: RestClientCallback<Buffer>): Promise<SignedTransaction>; | ||
/** | ||
@@ -44,3 +44,3 @@ * Sends a transaction to the blockchain. | ||
*/ | ||
sendTransaction(transaction: Transaction | SignedTransaction | Operation, doStatusPolling?: boolean, callback?: (error: Error, transactionReceipt: TransactionReceipt) => void): Web3PromiEvent<TransactionReceipt, { | ||
sendTransaction(transaction: Transaction | SignedTransaction | Operation, doStatusPolling?: boolean, callback?: RestClientCallback<TransactionReceipt>): Web3PromiEvent<TransactionReceipt, { | ||
sent: TransactionReceipt; | ||
@@ -58,3 +58,3 @@ }>; | ||
*/ | ||
signAndSendUniqueTransaction(transaction: Operation | Transaction, signMethod: KeyPair | SignatureProvider, doStatusPolling?: boolean, callback?: (error: Error, transactionReceipt: TransactionReceipt) => void): Web3PromiEvent<TransactionReceipt, { | ||
signAndSendUniqueTransaction(transaction: Operation | Transaction, signMethod: KeyPair | SignatureProvider, doStatusPolling?: boolean, callback?: RestClientCallback<TransactionReceipt>): Web3PromiEvent<TransactionReceipt, { | ||
sent: TransactionReceipt; | ||
@@ -73,3 +73,3 @@ }>; | ||
*/ | ||
getTransaction(transactionRid: Buffer, callback?: (error: Error, serializedMessage: Buffer) => void): Promise<Buffer>; | ||
getTransaction(transactionRid: Buffer, callback?: RestClientCallback<Buffer>): Promise<Buffer>; | ||
/** | ||
@@ -87,3 +87,3 @@ * Retrieves the status of a transaction given its transaction RID. | ||
*/ | ||
getTransactionStatus: (transactionRid: Buffer, callback?: (error: Error, responseBody: StatusObject) => void) => Promise<StatusObject>; | ||
getTransactionStatus: (transactionRid: Buffer, callback?: RestClientCallback<StatusObject>) => Promise<StatusObject>; | ||
/** | ||
@@ -96,2 +96,4 @@ * Adds an operation containing a nonce which makes the transaction unique. | ||
/** | ||
* @deprecated Use calculateTransactionRid util function instead. | ||
* | ||
* Calculates and returns the transaction RID, i.e., the merkle root hash of the transaction. | ||
@@ -113,3 +115,3 @@ * @param transaction The transaction to sign and send | ||
*/ | ||
getTransactionsInfo(limit?: number, beforeTime?: Date, callback?: (error: Error, responseBody: TransactionInfo[]) => void): Promise<TransactionInfo[]>; | ||
getTransactionsInfo(limit?: number, beforeTime?: Date, callback?: RestClientCallback<TransactionInfo[]>): Promise<TransactionInfo[]>; | ||
/** | ||
@@ -126,3 +128,3 @@ * Fetch info about a transaction from a chain. | ||
*/ | ||
getTransactionInfo(transactionRid: Buffer, callback?: (error: Error, responseBody: TransactionInfo) => void): Promise<TransactionInfo>; | ||
getTransactionInfo(transactionRid: Buffer, callback?: RestClientCallback<TransactionInfo>): Promise<TransactionInfo>; | ||
/** | ||
@@ -138,3 +140,3 @@ * Fetch number of successful transactions for a chain. | ||
*/ | ||
getTransactionCount(callback?: (error: Error, responseBody: number) => void): Promise<number>; | ||
getTransactionCount(callback?: RestClientCallback<number>): Promise<number>; | ||
/** | ||
@@ -152,4 +154,16 @@ * Fetch info about a block for a chain. | ||
*/ | ||
getBlockInfo(blockIdentifier?: number | string, txs?: boolean, callback?: (error: Error, responseBody: BlockInfo) => void): Promise<BlockInfo>; | ||
getBlockInfo(blockIdentifier: number | string, txs?: boolean, callback?: RestClientCallback<BlockInfo>): Promise<BlockInfo>; | ||
/** | ||
* Fetch info about the latest block for a chain. | ||
* | ||
* @param tsx - Boolean to decide whether or not to include full transaction data. Defaults to false. | ||
* @param callback - A callback function to handle the response body. Taking parameters (error, responseBody). If error is null | ||
* then responseBody is an object of type BlockInfo. | ||
* If error is not null, then responseBody | ||
* is an object with the string property 'error'. | ||
* @returns - A promise that resolves with the block info. | ||
* | ||
*/ | ||
getLatestBlock(txs?: boolean, callback?: RestClientCallback<BlockInfo>): Promise<BlockInfo>; | ||
/** | ||
* Fetch info about blocks for a chain. If both beforeTime and beforeHeight is provided, only beforeTime will be used. | ||
@@ -168,4 +182,6 @@ * | ||
*/ | ||
getBlocksInfo(limit?: number, beforeTime?: Date, beforeHeight?: number, txs?: boolean, callback?: (error: Error, responseBody: TransactionInfo[]) => void): Promise<BlockInfo[]>; | ||
getBlocksInfo(limit?: number, beforeTime?: Date, beforeHeight?: number, txs?: boolean, callback?: RestClientCallback<TransactionInfo[]>): Promise<BlockInfo[]>; | ||
/** | ||
* @deprecated Use encodeTransaction util function instead. | ||
* | ||
* Encodes the transaction using ASN.1. | ||
@@ -176,2 +192,4 @@ * @returns the transaction encoded | ||
/** | ||
* @deprecated Use decodeTransactionToGtx util function instead. | ||
* | ||
* Decodes the transaction using ASN.1. | ||
@@ -187,3 +205,3 @@ * @returns the transaction decoded in GTX format | ||
getClientNodeUrlPool(): string[]; | ||
getConfirmationProof(txRID: Buffer, callback?: (error: Error, responseObjectProof: ConfirmationProof) => void): Promise<ConfirmationProof>; | ||
getConfirmationProof(txRID: Buffer, callback?: RestClientCallback<ConfirmationProof>): Promise<ConfirmationProof>; | ||
} |
@@ -36,3 +36,3 @@ /// <reference types="node" /> | ||
status: ResponseStatus; | ||
statusCode: number; | ||
statusCode: number | null; | ||
transactionRid: Buffer; | ||
@@ -113,3 +113,3 @@ } | ||
height: number; | ||
transactions: transactionInfoInBlockResponse[]; | ||
transactions: TransactionInfoInBlockResponse[]; | ||
witness: string; | ||
@@ -119,3 +119,3 @@ witnesses: string[]; | ||
}; | ||
export type transactionInfoInBlockResponse = { | ||
export type TransactionInfoInBlockResponse = { | ||
rid: string; | ||
@@ -130,3 +130,3 @@ hash: string; | ||
height: number; | ||
transactions: transactionInfoInBlock[]; | ||
transactions: TransactionInfoInBlock[]; | ||
witness: Buffer; | ||
@@ -136,3 +136,3 @@ witnesses: Buffer[]; | ||
}; | ||
export type transactionInfoInBlock = { | ||
export type TransactionInfoInBlock = { | ||
rid: Buffer; | ||
@@ -139,0 +139,0 @@ hash: Buffer; |
@@ -6,2 +6,3 @@ /// <reference types="node" /> | ||
import { FailOverConfig } from "../restclient/types"; | ||
import { FailoverStrategy } from "./enums"; | ||
export declare function getClientConfigFromSettings(settings: NetworkSettings): Promise<ClientConfig>; | ||
@@ -14,8 +15,13 @@ export declare function validTxRid(txRID: Buffer): boolean; | ||
export declare const callbackPromiseBuilder: (reject: any, resolve: any, callback?: any) => (error: Error, result: any) => void; | ||
export declare const handlePostResponsePromisified: (error: Error, statusCode: number, rspBody: any) => Promise<void>; | ||
export declare const handlePostResponsePromisified: (error: Error | null, statusCode: number | null, rspBody: any) => Promise<void>; | ||
export declare const formatTransactionInfoResponse: (transactionInfoResponse: TransactionInfoResponse) => TransactionInfo; | ||
export declare const formatBlockInfoResponse: (blockInfoResponse: BlockInfoResponse) => BlockInfo; | ||
export declare const isKeyPair: (keypair: unknown) => keypair is KeyPair; | ||
export declare const defaultFailoverConfig: FailOverConfig; | ||
export declare const defaultFailoverConfig: { | ||
strategy: FailoverStrategy.AbortOnError; | ||
attemptsPerEndpoint: number; | ||
attemptInterval: number; | ||
unreachableDuration: number; | ||
}; | ||
export declare const createEndpointObjects: (endpointPoolUrls: readonly string[]) => Endpoint[]; | ||
export declare const getUrlsFromEndpoints: (endpointPool: Endpoint[]) => string[]; |
@@ -21,8 +21,19 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { | ||
export function getClientConfigFromSettings(settings) { | ||
var _a, _b, _c, _d; | ||
var _a, _b, _c, _d, _e, _f; | ||
return __awaiter(this, void 0, void 0, function* () { | ||
const nodeUrlPoolToUse = yield getNodeUrlsFromSettings(settings); | ||
if (nodeUrlPoolToUse.length === 0) { | ||
const id = (_b = (_a = settings.blockchainRid) !== null && _a !== void 0 ? _a : settings.blockchainIid) !== null && _b !== void 0 ? _b : "Unknown"; | ||
throw new BlockchainUrlUndefinedException(id); | ||
} | ||
const endpointPool = createEndpointObjects(nodeUrlPoolToUse); | ||
const blockchainRidToUse = settings.blockchainRid || | ||
(yield getBlockchainRidFromIid(endpointPool, settings.blockchainIid)); | ||
const blockchainRidToUse = yield (() => __awaiter(this, void 0, void 0, function* () { | ||
if (settings.blockchainRid) { | ||
return settings.blockchainRid; | ||
} | ||
if (settings.blockchainIid !== undefined) { | ||
return yield getBlockchainRidFromIid(endpointPool, settings.blockchainIid); | ||
} | ||
throw new MissingBlockchainIdentifierError(); | ||
}))(); | ||
return { | ||
@@ -33,8 +44,8 @@ endpointPool, | ||
statusPollCount: settings.statusPollCount || 20, | ||
failoverStrategy: ((_a = settings.failOverConfig) === null || _a === void 0 ? void 0 : _a.strategy) || defaultFailoverConfig.strategy, | ||
attemptsPerEndpoint: ((_b = settings.failOverConfig) === null || _b === void 0 ? void 0 : _b.attemptsPerEndpoint) || | ||
failoverStrategy: ((_c = settings.failOverConfig) === null || _c === void 0 ? void 0 : _c.strategy) || defaultFailoverConfig.strategy, | ||
attemptsPerEndpoint: ((_d = settings.failOverConfig) === null || _d === void 0 ? void 0 : _d.attemptsPerEndpoint) || | ||
defaultFailoverConfig.attemptsPerEndpoint, | ||
attemptInterval: ((_c = settings.failOverConfig) === null || _c === void 0 ? void 0 : _c.attemptInterval) || | ||
attemptInterval: ((_e = settings.failOverConfig) === null || _e === void 0 ? void 0 : _e.attemptInterval) || | ||
defaultFailoverConfig.attemptInterval, | ||
unreachableDuration: ((_d = settings.failOverConfig) === null || _d === void 0 ? void 0 : _d.unreachableDuration) || | ||
unreachableDuration: ((_f = settings.failOverConfig) === null || _f === void 0 ? void 0 : _f.unreachableDuration) || | ||
defaultFailoverConfig.unreachableDuration, | ||
@@ -57,3 +68,3 @@ }; | ||
} | ||
if (!(blockchainRid || blockchainIid != undefined)) { | ||
if (!blockchainRid && blockchainIid === undefined) { | ||
throw new MissingBlockchainIdentifierError(); | ||
@@ -63,4 +74,11 @@ } | ||
const directoryBRID = yield getBlockchainRidFromIid(directoryEndpointPool, directoryIid, failOverConfig); | ||
const blockchainRidToUse = blockchainRid || | ||
(yield getBlockchainRidFromIid(directoryEndpointPool, blockchainIid, failOverConfig)); | ||
const blockchainRidToUse = yield (() => __awaiter(this, void 0, void 0, function* () { | ||
if (blockchainRid) { | ||
return blockchainRid; | ||
} | ||
if (blockchainIid !== undefined) { | ||
return yield getBlockchainRidFromIid(directoryEndpointPool, blockchainIid, failOverConfig); | ||
} | ||
throw new MissingBlockchainIdentifierError(); | ||
}))(); | ||
const queryObject = { | ||
@@ -75,5 +93,2 @@ name: "cm_get_blockchain_api_urls", | ||
const baseUrls = yield D1Client.query(queryObject); | ||
if (!baseUrls.length) { | ||
throw new BlockchainUrlUndefinedException(blockchainRid !== null && blockchainRid !== void 0 ? blockchainRid : blockchainIid); | ||
} | ||
return baseUrls; | ||
@@ -80,0 +95,0 @@ }); |
/// <reference types="node" /> | ||
import { z } from "zod"; | ||
export declare const BufferSchema: z.ZodType<Buffer, z.ZodTypeDef, Buffer>; | ||
export declare const BufferSchema: z.ZodUnion<[z.ZodType<Uint8Array, z.ZodTypeDef, Uint8Array>, z.ZodType<Buffer, z.ZodTypeDef, Buffer>]>; |
import { z } from "zod"; | ||
export const BufferSchema = z.instanceof(Buffer); | ||
export const BufferSchema = z.union([ | ||
z.instanceof(Uint8Array), | ||
z.instanceof(Buffer), | ||
]); | ||
//# sourceMappingURL=bufferSchema.js.map |
@@ -6,6 +6,6 @@ import { z } from "zod"; | ||
error: z.ZodError<{ | ||
blockchainIid: number; | ||
blockchainRid?: undefined; | ||
blockchainIid?: number; | ||
} | { | ||
blockchainRid?: string; | ||
blockchainRid: string; | ||
blockchainIid?: undefined; | ||
@@ -12,0 +12,0 @@ }>; |
@@ -5,21 +5,21 @@ /// <reference types="node" /> | ||
export declare const SignMethodSchema: z.ZodUnion<[z.ZodObject<{ | ||
privKey: z.ZodType<Buffer, z.ZodTypeDef, Buffer>; | ||
pubKey: z.ZodType<Buffer, z.ZodTypeDef, Buffer>; | ||
privKey: z.ZodUnion<[z.ZodType<Uint8Array, z.ZodTypeDef, Uint8Array>, z.ZodType<Buffer, z.ZodTypeDef, Buffer>]>; | ||
pubKey: z.ZodUnion<[z.ZodType<Uint8Array, z.ZodTypeDef, Uint8Array>, z.ZodType<Buffer, z.ZodTypeDef, Buffer>]>; | ||
}, "strip", z.ZodTypeAny, { | ||
privKey?: Buffer; | ||
pubKey?: Buffer; | ||
pubKey: (Uint8Array | Buffer) & (Uint8Array | Buffer | undefined); | ||
privKey: (Uint8Array | Buffer) & (Uint8Array | Buffer | undefined); | ||
}, { | ||
privKey?: Buffer; | ||
pubKey?: Buffer; | ||
pubKey: (Uint8Array | Buffer) & (Uint8Array | Buffer | undefined); | ||
privKey: (Uint8Array | Buffer) & (Uint8Array | Buffer | undefined); | ||
}>, z.ZodObject<{ | ||
pubKey: z.ZodType<Buffer, z.ZodTypeDef, Buffer>; | ||
sign: z.ZodFunction<z.ZodTuple<[z.ZodType<Buffer, z.ZodTypeDef, Buffer>], z.ZodUnknown>, z.ZodPromise<z.ZodType<Buffer, z.ZodTypeDef, Buffer>>>; | ||
pubKey: z.ZodUnion<[z.ZodType<Uint8Array, z.ZodTypeDef, Uint8Array>, z.ZodType<Buffer, z.ZodTypeDef, Buffer>]>; | ||
sign: z.ZodFunction<z.ZodTuple<[z.ZodUnion<[z.ZodType<Uint8Array, z.ZodTypeDef, Uint8Array>, z.ZodType<Buffer, z.ZodTypeDef, Buffer>]>], z.ZodUnknown>, z.ZodPromise<z.ZodUnion<[z.ZodType<Uint8Array, z.ZodTypeDef, Uint8Array>, z.ZodType<Buffer, z.ZodTypeDef, Buffer>]>>>; | ||
}, "strip", z.ZodTypeAny, { | ||
pubKey?: Buffer; | ||
sign?: (args_0: Buffer, ...args_1: unknown[]) => Promise<Buffer>; | ||
sign: (args_0: Uint8Array | Buffer, ...args_1: unknown[]) => Promise<Uint8Array | Buffer>; | ||
pubKey: (Uint8Array | Buffer) & (Uint8Array | Buffer | undefined); | ||
}, { | ||
pubKey?: Buffer; | ||
sign?: (args_0: Buffer, ...args_1: unknown[]) => Promise<Buffer>; | ||
sign: (args_0: Uint8Array | Buffer, ...args_1: unknown[]) => Promise<Uint8Array | Buffer>; | ||
pubKey: (Uint8Array | Buffer) & (Uint8Array | Buffer | undefined); | ||
}>]>; | ||
export type SignMethod = z.infer<typeof SignMethodSchema>; | ||
export declare const isSignMethodValid: Validation; |
/// <reference types="node" /> | ||
import { Validation } from "./validation.types"; | ||
export declare const TxRidSchema: import("zod").ZodEffects<import("zod").ZodType<Buffer, import("zod").ZodTypeDef, Buffer>, Buffer, Buffer>; | ||
export declare const TxRidSchema: import("zod").ZodEffects<import("zod").ZodUnion<[import("zod").ZodType<Uint8Array, import("zod").ZodTypeDef, Uint8Array>, import("zod").ZodType<Buffer, import("zod").ZodTypeDef, Buffer>]>, Uint8Array | Buffer, Uint8Array | Buffer>; | ||
export declare const isTxRidValid: Validation; |
import type { RestClient } from "../restclient/interfaces"; | ||
import type { ChromiaClient } from "./interfaces"; | ||
/** | ||
* @deprecated Use the function createClient instead. | ||
* Provides postchain clients that can be used to communicate with dapps within the chromia network | ||
@@ -5,0 +6,0 @@ * @param chain0BRID brid of chain0 |
@@ -13,2 +13,3 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { | ||
/** | ||
* @deprecated Use the function createClient instead. | ||
* Provides postchain clients that can be used to communicate with dapps within the chromia network | ||
@@ -15,0 +16,0 @@ * @param chain0BRID brid of chain0 |
@@ -24,3 +24,3 @@ /// <reference types="node" /> | ||
*/ | ||
export declare function checkDigestSignature(digest: Buffer, pubKey: Buffer, signature: Buffer): boolean; | ||
export declare function checkDigestSignature(digest: Buffer, pubKey: Buffer, signature: Buffer | undefined): boolean; | ||
/** | ||
@@ -27,0 +27,0 @@ * @param content to sign. It will be digested before signing. |
@@ -40,2 +40,4 @@ "use strict"; | ||
export function checkDigestSignature(digest, pubKey, signature) { | ||
if (!signature) | ||
return false; | ||
return secp256k1.ecdsaVerify(signature, digest, pubKey); | ||
@@ -42,0 +44,0 @@ } |
/// <reference types="node" /> | ||
import { Buffer } from "buffer"; | ||
import { GTX, RawGtx } from "./gtx/types"; | ||
import { GTX, RawGtx, RawGtxBody } from "./gtx/types"; | ||
import { QueryObject, QueryObjectGTV } from "./restclient/types"; | ||
@@ -26,5 +26,10 @@ import { DictPair } from "./gtv/types"; | ||
export declare function rawGtxToGtx(rawGtx: RawGtx): GTX; | ||
export declare function rawGtxToRawGtxBody(rawGtx: RawGtx): RawGtxBody; | ||
export declare function checkGtxType(value: any): boolean; | ||
export declare function removeDuplicateSigners(signers: Buffer[]): Buffer[]; | ||
export declare function matchRellErrorString(rellError: string): { | ||
shortReason?: undefined; | ||
rellLine?: undefined; | ||
operation?: undefined; | ||
} | { | ||
shortReason: string; | ||
@@ -31,0 +36,0 @@ rellLine: string; |
@@ -0,1 +1,12 @@ | ||
var __rest = (this && this.__rest) || function (s, e) { | ||
var t = {}; | ||
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) | ||
t[p] = s[p]; | ||
if (s != null && typeof Object.getOwnPropertySymbols === "function") | ||
for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) { | ||
if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) | ||
t[p[i]] = s[p[i]]; | ||
} | ||
return t; | ||
}; | ||
import { Buffer } from "buffer"; | ||
@@ -6,3 +17,3 @@ export function pgBytes(buffer) { | ||
} | ||
return "\\x" + buffer.toString("hex"); | ||
return `\\x${buffer.toString("hex")}`; | ||
} | ||
@@ -33,5 +44,4 @@ /** | ||
const objectCopy = Object.assign({}, nameOrObject); | ||
name = objectCopy.type; | ||
delete objectCopy.type; | ||
return [name, objectCopy]; | ||
const { type } = objectCopy, restProps = __rest(objectCopy, ["type"]); | ||
return [type, restProps]; | ||
} | ||
@@ -106,2 +116,5 @@ } | ||
} | ||
export function rawGtxToRawGtxBody(rawGtx) { | ||
return rawGtx[0]; | ||
} | ||
export function checkGtxType(value) { | ||
@@ -131,14 +144,8 @@ try { | ||
export function matchRellErrorString(rellError) { | ||
let shortReason; | ||
let rellLine; | ||
let operation; | ||
const parsed = rellError.match(/\[([^\]]+)\]\sOperation\s'([^']+)'\sfailed:\s(.+)$/); | ||
if (parsed) { | ||
const [_rellLine, _operation, _errorMessage] = parsed.slice(1); | ||
shortReason = _errorMessage; | ||
rellLine = _rellLine; | ||
operation = _operation; | ||
} | ||
if (!parsed) | ||
return {}; | ||
const [rellLine, operation, shortReason] = parsed.slice(1); | ||
return { shortReason, rellLine, operation }; | ||
} | ||
//# sourceMappingURL=formatter.js.map |
@@ -1,15 +0,16 @@ | ||
export declare class UnexpectedArgumentTypeError extends Error { | ||
import { CustomError } from "../customError"; | ||
export declare class UnexpectedArgumentTypeError extends CustomError { | ||
constructor(typedArg: any); | ||
} | ||
export declare class MissingGtxException extends Error { | ||
export declare class MissingGtxException extends CustomError { | ||
constructor(); | ||
} | ||
export declare class AlreadySignedTransactionException extends Error { | ||
export declare class AlreadySignedTransactionException extends CustomError { | ||
constructor(operation: string); | ||
} | ||
export declare class NumberOfSignersAndSignaturesException extends Error { | ||
export declare class NumberOfSignersAndSignaturesException extends CustomError { | ||
constructor(); | ||
} | ||
export declare class MissingSignerException extends Error { | ||
export declare class MissingSignerException extends CustomError { | ||
constructor(); | ||
} |
@@ -1,26 +0,27 @@ | ||
export class UnexpectedArgumentTypeError extends Error { | ||
import { CustomError } from "../customError"; | ||
export class UnexpectedArgumentTypeError extends CustomError { | ||
constructor(typedArg) { | ||
super(`Cannot parse typedArg ${JSON.stringify(typedArg)}. Unknown type ${typedArg.type}`); | ||
super(`Cannot parse typedArg ${JSON.stringify(typedArg)}. Unknown type ${typedArg.type}`, 400); | ||
} | ||
} | ||
export class MissingGtxException extends Error { | ||
export class MissingGtxException extends CustomError { | ||
constructor() { | ||
super(`Missing instance of gtx protocol (used for communicating with postchain) to add operation to`); | ||
super(`Missing instance of gtx protocol (used for communicating with postchain) to add operation to`, 400); | ||
} | ||
} | ||
export class AlreadySignedTransactionException extends Error { | ||
export class AlreadySignedTransactionException extends CustomError { | ||
constructor(operation) { | ||
super(`Cannot add ${operation} calls to an already signed gtx`); | ||
super(`Cannot add ${operation} calls to an already signed gtx`, 400); | ||
} | ||
} | ||
export class NumberOfSignersAndSignaturesException extends Error { | ||
export class NumberOfSignersAndSignaturesException extends CustomError { | ||
constructor() { | ||
super(`Not matching number of signers and signatures`); | ||
super(`Not matching number of signers and signatures`, 400); | ||
} | ||
} | ||
export class MissingSignerException extends Error { | ||
export class MissingSignerException extends CustomError { | ||
constructor() { | ||
super(`No such signer, remember to add signer to transaction before adding a signature`); | ||
super(`No such signer, remember to add signer to transaction before adding a signature`, 400); | ||
} | ||
} | ||
//# sourceMappingURL=errors.js.map |
@@ -68,2 +68,3 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { | ||
export function gtxToRawGtx(gtx) { | ||
var _a; | ||
return [ | ||
@@ -75,3 +76,3 @@ [ | ||
], | ||
gtx.signatures, | ||
(_a = gtx.signatures) !== null && _a !== void 0 ? _a : [], | ||
]; | ||
@@ -144,4 +145,5 @@ } | ||
export function checkGTXSignatures(txHash, gtx) { | ||
var _a; | ||
for (const i in gtx.signers) { | ||
const signValid = checkDigestSignature(txHash, gtx.signers[i], gtx.signatures[i]); | ||
const signValid = checkDigestSignature(txHash, gtx.signers[i], (_a = gtx.signatures) === null || _a === void 0 ? void 0 : _a[i]); | ||
if (!signValid) | ||
@@ -153,4 +155,5 @@ return signValid; | ||
export function checkExistingGTXSignatures(txHash, gtx) { | ||
var _a; | ||
for (const i in gtx.signers) { | ||
if (gtx.signatures[i]) { | ||
if ((_a = gtx.signatures) === null || _a === void 0 ? void 0 : _a[i]) { | ||
const signValid = checkDigestSignature(txHash, gtx.signers[i], gtx.signatures[i]); | ||
@@ -157,0 +160,0 @@ if (!signValid) |
@@ -23,4 +23,4 @@ "use strict"; | ||
logger.debug(`signing transaction with ${privOrSigProv instanceof Buffer | ||
? "privkey: " + privOrSigProv.toString("hex") | ||
: "signature provider [pubKey: " + privOrSigProv.pubKey + "]"}`); | ||
? `privkey: ${privOrSigProv.toString("hex")}` | ||
: `signature provider [pubKey: ${privOrSigProv.pubKey}]`}`); | ||
if (privOrSigProv instanceof Buffer) { | ||
@@ -27,0 +27,0 @@ yield gtxTool.sign(this.gtx, privOrSigProv, pubKey); |
@@ -25,2 +25,3 @@ import { Buffer } from "buffer"; | ||
export function parseValue(typedArg) { | ||
var _a, _b; | ||
if (typedArg.type === "null") { | ||
@@ -43,3 +44,3 @@ return null; | ||
else if (typedArg.type === "bigInteger") { | ||
return BigInt(typedArg.value.toString()); | ||
return BigInt((_b = (_a = typedArg.value) === null || _a === void 0 ? void 0 : _a.toString()) !== null && _b !== void 0 ? _b : ""); | ||
} | ||
@@ -101,3 +102,4 @@ else if (typedArg.type === "dict") { | ||
catch (error) { | ||
throw new Error(`Failed to encode ${value.toString()}: ${error}`); | ||
const message = value ? value.toString() : "RawGtv"; | ||
throw new Error(`Failed to encode ${message}: ${error}`); | ||
} | ||
@@ -104,0 +106,0 @@ throw new Error(`value ${value} have unsupported type: ${typeof value}`); |
@@ -74,8 +74,8 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { | ||
return __awaiter(this, void 0, void 0, function* () { | ||
if (!(txRid || txProof)) { | ||
if (!txRid && !txProof) { | ||
throw Error("Missing a txRid or TxProof"); | ||
} | ||
const confirmationProof = txProof !== null && txProof !== void 0 ? txProof : (yield sourceClient.getConfirmationProof(txRid)); | ||
const confirmationProof = txProof !== null && txProof !== void 0 ? txProof : (txRid && (yield sourceClient.getConfirmationProof(txRid))); | ||
if (!confirmationProof) { | ||
return null; | ||
throw Error("Confirmation proof not found"); | ||
} | ||
@@ -115,6 +115,7 @@ const blockRid = calculateBlockRID(confirmationProof); | ||
return __awaiter(this, void 0, void 0, function* () { | ||
if (!(dappBlockchainRid || cluster)) { | ||
if (!dappBlockchainRid && !cluster) { | ||
throw Error("Missing a dapp blockchainRid or cluster name"); | ||
} | ||
const sourceCluster = cluster !== null && cluster !== void 0 ? cluster : (yield getClusterOfBlockchain(client, toBuffer(dappBlockchainRid))); | ||
const sourceCluster = cluster !== null && cluster !== void 0 ? cluster : (dappBlockchainRid && | ||
(yield getClusterOfBlockchain(client, toBuffer(dappBlockchainRid)))); | ||
if (!sourceCluster) { | ||
@@ -121,0 +122,0 @@ throw Error("No cluster could be found"); |
@@ -30,3 +30,3 @@ /// <reference types="node" /> | ||
iccfTx: Transaction; | ||
verifiedTx?: GTX; | ||
verifiedTx?: GTX | null; | ||
}; | ||
@@ -33,0 +33,0 @@ export type BlockHeader = { |
@@ -76,2 +76,3 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { | ||
export function fetchAndVerifyTransaction(sourceClient, txToProveRID, proofHash, txToProveSigners) { | ||
var _a, _b, _c; | ||
return __awaiter(this, void 0, void 0, function* () { | ||
@@ -87,4 +88,4 @@ const rawTx = yield sourceClient.getTransaction(txToProveRID); | ||
const fetchedTx = rawGtvToGtx(txGtv); | ||
if (txToProveSigners.length != fetchedTx.signatures.length) { | ||
throw new DifferentNumberOfSignersException(fetchedTx.signatures.length, txToProveSigners.length); | ||
if (txToProveSigners.length != ((_a = fetchedTx.signatures) === null || _a === void 0 ? void 0 : _a.length)) { | ||
throw new DifferentNumberOfSignersException((_c = (_b = fetchedTx.signatures) === null || _b === void 0 ? void 0 : _b.length) !== null && _c !== void 0 ? _c : 0, txToProveSigners.length); | ||
} | ||
@@ -118,5 +119,5 @@ const txRID = getDigestToSign(fetchedTx); | ||
if (isNetwork) { | ||
operationArgs = Object.assign(Object.assign({}, operationArgs), { transactionData: anchoringTx.txData, transactionIndex: anchoringTx.txOpIndex, anchoringProof: encodeValue(anchoringProof) }); | ||
operationArgs = Object.assign(Object.assign({}, operationArgs), { transactionData: anchoringTx === null || anchoringTx === void 0 ? void 0 : anchoringTx.txData, transactionIndex: anchoringTx === null || anchoringTx === void 0 ? void 0 : anchoringTx.txOpIndex, anchoringProof: anchoringProof && encodeValue(anchoringProof) }); | ||
} | ||
const proofTx = { | ||
return { | ||
operations: [ | ||
@@ -130,4 +131,3 @@ { | ||
}; | ||
return proofTx; | ||
} | ||
//# sourceMappingURL=utils.js.map |
@@ -106,3 +106,3 @@ /** | ||
*/ | ||
getPathLeafOrElseAnyCurrentPathElement(): any; | ||
getPathLeafOrElseAnyCurrentPathElement(): null; | ||
/** | ||
@@ -147,3 +147,3 @@ * Yeah, this might be a completely un-needed check (but it MIGHT save us later on if we forget this rule). | ||
*/ | ||
export function getTailIfFirstElementIsArrayOfThisIndex(index: number, path: Path): Path; | ||
export function getTailIfFirstElementIsArrayOfThisIndex(index: number, path: Path): Path | null; | ||
/** | ||
@@ -150,0 +150,0 @@ * |
/// <reference types="node" /> | ||
import { CustomError } from "../customError"; | ||
export declare class TxRejectedError extends Error { | ||
fullReason: string; | ||
shortReason: string; | ||
rellLine: string; | ||
operation: string; | ||
shortReason?: string; | ||
rellLine?: string; | ||
operation?: string; | ||
constructor(rejectReason: string); | ||
} | ||
export declare class UnexpectedStatusError extends Error { | ||
constructor(status: number, error?: any); | ||
export declare class UnexpectedStatusError extends CustomError { | ||
constructor(status: number | null, error?: any); | ||
} | ||
@@ -18,6 +19,6 @@ export declare class LostMessageError extends Error { | ||
} | ||
export declare class InvalidTxRidException extends Error { | ||
export declare class InvalidTxRidException extends CustomError { | ||
constructor(txRID: Buffer); | ||
} | ||
export declare class SerializedTransactionFormatException extends Error { | ||
export declare class SerializedTransactionFormatException extends CustomError { | ||
constructor(); | ||
@@ -28,7 +29,7 @@ } | ||
} | ||
export declare class EmptyListOfUrlsException extends Error { | ||
export declare class EmptyListOfUrlsException extends CustomError { | ||
constructor(); | ||
} | ||
export declare class InvalidBlockchainRIDException extends Error { | ||
export declare class InvalidBlockchainRIDException extends CustomError { | ||
constructor(); | ||
} |
@@ -0,1 +1,2 @@ | ||
import { CustomError } from "../customError"; | ||
import { matchRellErrorString } from "../formatter"; | ||
@@ -13,9 +14,14 @@ export class TxRejectedError extends Error { | ||
} | ||
export class UnexpectedStatusError extends Error { | ||
export class UnexpectedStatusError extends CustomError { | ||
constructor(status, error) { | ||
let errorMessage = `Unexpected status code from server. Code: ${status}.`; | ||
if (error) { | ||
errorMessage += ` Message: ${error}.`; | ||
if (status === null) { | ||
super(errorMessage, 500); // default status code | ||
} | ||
super(errorMessage); | ||
else { | ||
if (error) { | ||
errorMessage += ` Message: ${error}.`; | ||
} | ||
super(errorMessage, status); | ||
} | ||
} | ||
@@ -33,10 +39,10 @@ } | ||
} | ||
export class InvalidTxRidException extends Error { | ||
export class InvalidTxRidException extends CustomError { | ||
constructor(txRID) { | ||
super(`expected length 32 of txRID, but got ${txRID && txRID.length}`); | ||
super(`expected length 32 of txRID, but got ${txRID && txRID.length}`, 400); | ||
} | ||
} | ||
export class SerializedTransactionFormatException extends Error { | ||
export class SerializedTransactionFormatException extends CustomError { | ||
constructor() { | ||
super(`messageHash is not a Buffer`); | ||
super(`messageHash is not a Buffer`, 400); | ||
} | ||
@@ -49,12 +55,12 @@ } | ||
} | ||
export class EmptyListOfUrlsException extends Error { | ||
export class EmptyListOfUrlsException extends CustomError { | ||
constructor() { | ||
super(`Failed to initialize rest client with empty list of urls`); | ||
super(`Failed to initialize rest client with empty list of urls`, 400); | ||
} | ||
} | ||
export class InvalidBlockchainRIDException extends Error { | ||
export class InvalidBlockchainRIDException extends CustomError { | ||
constructor() { | ||
super(`Failed to initialize rest client with blockchain RID that is not 32 bytes`); | ||
super(`Failed to initialize rest client with blockchain RID that is not 32 bytes`, 400); | ||
} | ||
} | ||
//# sourceMappingURL=errors.js.map |
@@ -5,2 +5,6 @@ import { HandleRequestInputProps, ResponseObject } from "./types"; | ||
export declare function singleEndpoint({ method, path, config, postObject, }: HandleRequestInputProps): Promise<ResponseObject>; | ||
export declare function retryRequest({ method, path, config, postObject }: HandleRequestInputProps, errorCodes: number[]): Promise<ResponseObject>; | ||
type RetryRequestProps = HandleRequestInputProps & { | ||
validateStatusCode: (statusCode: number) => boolean; | ||
}; | ||
export declare function retryRequest({ method, path, config, postObject, validateStatusCode, }: RetryRequestProps): Promise<ResponseObject>; | ||
export {}; |
@@ -13,7 +13,13 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { | ||
import { bftMajority, filterReachableEndpoint, isReachable, nextEndpoint, setEndpointAsReachable, setUnavailable, shuffle, sleep, } from "./restclientutil"; | ||
const clientErrors = [400, 404, 409, 413]; | ||
const serverErrors = [500, 503]; | ||
const hasClientError = (statusCode) => statusCode >= 400 && statusCode < 500; | ||
const hasServerError = (statusCode) => statusCode >= 500 && statusCode < 600; | ||
export function abortOnError({ method, path, config, postObject, }) { | ||
return __awaiter(this, void 0, void 0, function* () { | ||
return yield retryRequest({ method, path, config, postObject }, serverErrors); | ||
return yield retryRequest({ | ||
method, | ||
path, | ||
config, | ||
postObject, | ||
validateStatusCode: (statuscode) => !hasServerError(statuscode), | ||
}); | ||
}); | ||
@@ -23,3 +29,9 @@ } | ||
return __awaiter(this, void 0, void 0, function* () { | ||
return yield retryRequest({ method, path, config, postObject }, serverErrors.concat(clientErrors)); | ||
return yield retryRequest({ | ||
method, | ||
path, | ||
config, | ||
postObject, | ||
validateStatusCode: (statusCode) => !hasClientError(statusCode) && !hasServerError(statusCode), | ||
}); | ||
}); | ||
@@ -30,7 +42,8 @@ } | ||
let statusCode, rspBody, error; | ||
const errorCodes = serverErrors.concat(clientErrors); | ||
for (let attempt = 0; attempt < config.attemptsPerEndpoint; attempt++) { | ||
const endpoint = nextEndpoint(config.endpointPool); | ||
({ error, statusCode, rspBody } = yield handleRequest(method, path, endpoint.url, postObject)); | ||
const isError = errorCodes.includes(statusCode); | ||
const isError = statusCode | ||
? hasServerError(statusCode) || hasClientError(statusCode) | ||
: false; | ||
if (!isError && !error) { | ||
@@ -42,8 +55,13 @@ return { error, statusCode, rspBody }; | ||
} | ||
// TS issue. Variable 'error' is used before being assigned. | ||
// eslint-disable-next-line @typescript-eslint/ban-ts-comment | ||
// @ts-expect-error | ||
return { error, statusCode, rspBody }; | ||
}); | ||
} | ||
export function retryRequest({ method, path, config, postObject }, errorCodes) { | ||
export function retryRequest({ method, path, config, postObject, validateStatusCode, }) { | ||
return __awaiter(this, void 0, void 0, function* () { | ||
let statusCode, rspBody, error; | ||
let statusCode; | ||
let rspBody; | ||
let error; | ||
const reachableEndpoints = filterReachableEndpoint(config.endpointPool); | ||
@@ -57,5 +75,7 @@ if (reachableEndpoints.length < bftMajority(config.endpointPool.length)) { | ||
({ error, statusCode, rspBody } = yield handleRequest(method, path, endpoint.url, postObject)); | ||
const isError = errorCodes.includes(statusCode); | ||
const isServerError = serverErrors.includes(statusCode); | ||
if (!isError && !error) { | ||
const isStatusCodeValid = statusCode | ||
? validateStatusCode(statusCode) | ||
: false; | ||
const isServerError = statusCode ? hasServerError(statusCode) : false; | ||
if (isStatusCodeValid && !error) { | ||
return { error, statusCode, rspBody }; | ||
@@ -71,2 +91,5 @@ } | ||
} | ||
// TS issue. Variable 'error' is used before being assigned. | ||
// eslint-disable-next-line @typescript-eslint/ban-ts-comment | ||
// @ts-expect-error | ||
return { error, statusCode, rspBody }; | ||
@@ -73,0 +96,0 @@ }); |
@@ -32,3 +32,3 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { | ||
return __awaiter(this, void 0, void 0, function* () { | ||
logger.debug("GET URL " + new URL(path, endpoint).href); | ||
logger.debug(`GET URL ${new URL(path, endpoint).href}`); | ||
try { | ||
@@ -38,12 +38,13 @@ const response = yield fetch(new URL(path, endpoint).href); | ||
let rspBody; | ||
if (contentType.includes("application/json")) { | ||
if (contentType === null || contentType === void 0 ? void 0 : contentType.includes("application/json")) { | ||
rspBody = yield response.json(); | ||
} | ||
else if (contentType.includes("text/plain")) { | ||
else if (contentType === null || contentType === void 0 ? void 0 : contentType.includes("text/plain")) { | ||
rspBody = yield response.text(); | ||
} | ||
if (response.status == 404) { | ||
return { error: null, statusCode: response.status, rspBody }; | ||
} | ||
return { error: null, statusCode: response.status, rspBody }; | ||
return { | ||
error: null, | ||
statusCode: response.status, | ||
rspBody, | ||
}; | ||
} | ||
@@ -64,4 +65,4 @@ catch (error) { | ||
return __awaiter(this, void 0, void 0, function* () { | ||
logger.debug("POST URL " + new URL(path, endpoint).href); | ||
logger.debug("POST body " + JSON.stringify(requestBody)); | ||
logger.debug(`POST URL ${new URL(path, endpoint).href}`); | ||
logger.debug(`POST body ${JSON.stringify(requestBody)}`); | ||
if (Buffer.isBuffer(requestBody)) { | ||
@@ -68,0 +69,0 @@ try { |
/// <reference types="node" /> | ||
import { DictPair } from "../gtv/types"; | ||
import { QueryObject, RestClientConfig, StatusObject } from "./types"; | ||
import { QueryObject, RestClientCallback, RestClientConfig, StatusObject } from "./types"; | ||
export interface RestClient { | ||
@@ -15,3 +15,3 @@ config: RestClientConfig; | ||
*/ | ||
getTransaction: (txRID: Buffer, callback: (error: Error, serializedMessage: Buffer) => void) => void; | ||
getTransaction: (txRID: Buffer, callback: RestClientCallback<Buffer>) => void; | ||
/** | ||
@@ -27,3 +27,3 @@ * Sends a transaction to postchain for inclusion in a block. | ||
*/ | ||
postTransaction: (serializedTransaction: Buffer, callback: (error: Error, responseObject: any) => void) => void; | ||
postTransaction: (serializedTransaction: Buffer, callback: RestClientCallback<any>) => void; | ||
/** | ||
@@ -38,3 +38,3 @@ * Queries the status of a certain transaction. | ||
*/ | ||
status: (txRID: Buffer, callback: (error: Error, responseBody: StatusObject) => void) => void; | ||
status: (txRID: Buffer, callback: RestClientCallback<StatusObject>) => void; | ||
/** | ||
@@ -41,0 +41,0 @@ * Interfaces the query enpoint of the Rell backend. Returns either a resolved or rejected promise. The input is the name of the query followed by the arguments of the |
@@ -1,2 +0,2 @@ | ||
import { FailOverConfig } from "./types"; | ||
import { FailOverConfig, RestClientCallback } from "./types"; | ||
import { RestClient } from "./interfaces"; | ||
@@ -11,3 +11,3 @@ import { RawGtv } from "../gtv/types"; | ||
*/ | ||
export declare function handleGetResponse(error: Error, statusCode: number, responseObject: RawGtv, callback: (error: Error, responseObject: RawGtv) => void): void; | ||
export declare function handleGetResponse(error: Error | null, statusCode: number | null, responseObject: RawGtv | null | undefined, callback: RestClientCallback<RawGtv>): void; | ||
/** | ||
@@ -19,2 +19,2 @@ * @param error response error | ||
*/ | ||
export declare function handlePostResponse(error: Error, statusCode: number, responseObject: RawGtv, callback: (error: Error, responseObject?: RawGtv) => void): void; | ||
export declare function handlePostResponse(error: Error | null, statusCode: number | null, responseObject: RawGtv | null, callback: RestClientCallback<RawGtv>): void; |
@@ -21,4 +21,5 @@ "use strict"; | ||
import { createEndpointObjects, getUrlsFromEndpoints, } from "../blockchainClient/utils"; | ||
import { isTxRidValid } from "../blockchainClient/validation/txRid"; | ||
export function createRestClient(endpointPool, blockchainRid, maxSockets = 10, pollingInterval = 500, failOverConfig, unreachableDuration = 5000) { | ||
validateInput(endpointPool, failOverConfig); | ||
validateInput(endpointPool, failOverConfig !== null && failOverConfig !== void 0 ? failOverConfig : {}); | ||
return { | ||
@@ -36,7 +37,7 @@ config: { | ||
return __awaiter(this, void 0, void 0, function* () { | ||
if (!validTxRID(txRID)) { | ||
if (!isTxRidValid(txRID)) { | ||
callback(new InvalidTxRidException(txRID), null); | ||
} | ||
else { | ||
const { error, statusCode, rspBody } = yield requestWithRetry(Method.GET, "tx/" + blockchainRid + "/" + txRID.toString("hex"), this.config); | ||
const { error, statusCode, rspBody } = yield requestWithRetry(Method.GET, `tx/${blockchainRid}/${txRID.toString("hex")}`, this.config); | ||
handleGetResponse(error, statusCode, statusCode === 200 ? toBuffer(rspBody.tx) : rspBody, callback); | ||
@@ -54,3 +55,3 @@ } | ||
}; | ||
const { error, statusCode, rspBody } = yield requestWithRetry(Method.POST, "tx/" + blockchainRid, this.config, transactionObject); | ||
const { error, statusCode, rspBody } = yield requestWithRetry(Method.POST, `tx/${blockchainRid}`, this.config, transactionObject); | ||
handlePostResponse(error, statusCode, rspBody, callback); | ||
@@ -61,7 +62,7 @@ }); | ||
return __awaiter(this, void 0, void 0, function* () { | ||
if (!validTxRID(txRID)) { | ||
if (!isTxRidValid(txRID)) { | ||
callback(new InvalidTxRidException(txRID), null); | ||
} | ||
else { | ||
const { error, statusCode, rspBody } = yield requestWithRetry(Method.GET, "tx/" + blockchainRid + "/" + txRID.toString("hex") + "/status", this.config); | ||
const { error, statusCode, rspBody } = yield requestWithRetry(Method.GET, `tx/${blockchainRid}/${txRID.toString("hex")}/status`, this.config); | ||
handleGetResponse(error, statusCode, rspBody, callback); | ||
@@ -136,14 +137,2 @@ } | ||
} | ||
/** | ||
* Validates that txRID is a Buffer of 32 bytes. | ||
* @param txRID A buffer of 32 bytes | ||
*/ | ||
function validTxRID(txRID) { | ||
if (txRID.length != 32) { | ||
const error = new InvalidTxRidException(txRID); | ||
logger.error(error.toString()); | ||
return false; | ||
} | ||
return true; | ||
} | ||
function validateInput(endpointPool, failOverConfig) { | ||
@@ -153,3 +142,4 @@ if (!endpointPool.length) { | ||
} | ||
if ((failOverConfig === null || failOverConfig === void 0 ? void 0 : failOverConfig.attemptsPerEndpoint) < 1) { | ||
if ((failOverConfig === null || failOverConfig === void 0 ? void 0 : failOverConfig.attemptsPerEndpoint) && | ||
failOverConfig.attemptsPerEndpoint < 1) { | ||
logger.debug("Attempts can not be 0 or below, setting it to 1"); | ||
@@ -173,3 +163,3 @@ failOverConfig.attemptsPerEndpoint = 1; | ||
else if (statusCode !== 200) { | ||
callback(new UnexpectedStatusError(statusCode, responseObjectPrintable), null); | ||
callback(new UnexpectedStatusError(statusCode !== null && statusCode !== void 0 ? statusCode : 400, responseObjectPrintable), null); | ||
} | ||
@@ -181,4 +171,3 @@ else { | ||
catch (error) { | ||
logger.error("restclient.handleGetResponse(): Failed to call the callback function. " + | ||
error); | ||
logger.error(`restclient.handleGetResponse(): Failed to call the callback function. ${error}`); | ||
} | ||
@@ -198,3 +187,3 @@ } | ||
logger.error(`In restclient post(). ${error}`); | ||
callback(error); | ||
callback(error, null); | ||
} | ||
@@ -207,3 +196,3 @@ else if (statusCode != 200) { | ||
logger.error(errorMessage); | ||
callback(new UnexpectedStatusError(statusCode, responseObjectPrintable), responseObject); | ||
callback(new UnexpectedStatusError(statusCode !== null && statusCode !== void 0 ? statusCode : 400, responseObjectPrintable), responseObject); | ||
} | ||
@@ -216,6 +205,5 @@ else { | ||
catch (error) { | ||
logger.error("restclient.handlePostResponse(): Failed to call callback function " + | ||
error); | ||
logger.error(`restclient.handlePostResponse(): Failed to call callback function ${error}`); | ||
} | ||
} | ||
//# sourceMappingURL=restclient.js.map |
/// <reference types="node" /> | ||
import { RestClientConfig, PostRequestObjects, ResponseObject, FailOverConfig } from "./types"; | ||
import { ClientConfig, Endpoint } from "../blockchainClient/types"; | ||
import { PostRequestObjects, ResponseObject, FailOverConfig, HandleRequestInputProps } from "./types"; | ||
import { Endpoint } from "../blockchainClient/types"; | ||
import { Method } from "./enums"; | ||
export declare function getBlockchainRidFromIid(endpointPool: Endpoint[], chainId: number, failOverConfig?: FailOverConfig): Promise<string>; | ||
export declare function requestWithRetry(method: Method, path: string, config: RestClientConfig | ClientConfig, postObject?: PostRequestObjects | Buffer): Promise<ResponseObject>; | ||
export declare function requestWithRetry(method: Method, path: string, config: HandleRequestInputProps["config"], postObject?: PostRequestObjects | Buffer): Promise<ResponseObject>; | ||
export declare function nextEndpoint(endpointPool: Endpoint[]): Endpoint; | ||
@@ -8,0 +8,0 @@ export declare const shuffle: <T>(array: T[]) => T[]; |
@@ -19,3 +19,2 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { | ||
endpointPool, | ||
blockchainRid: undefined, | ||
statusPollInterval: 500, | ||
@@ -42,15 +41,10 @@ statusPollCount: 20, | ||
return __awaiter(this, void 0, void 0, function* () { | ||
let response; | ||
switch (config.failoverStrategy) { | ||
case FailoverStrategy.AbortOnError: | ||
response = yield abortOnError({ method, path, config, postObject }); | ||
break; | ||
return yield abortOnError({ method, path, config, postObject }); | ||
case FailoverStrategy.TryNextOnError: | ||
response = yield tryNextOnError({ method, path, config, postObject }); | ||
break; | ||
return yield tryNextOnError({ method, path, config, postObject }); | ||
case FailoverStrategy.SingleEndpoint: | ||
response = yield singleEndpoint({ method, path, config, postObject }); | ||
break; | ||
return yield singleEndpoint({ method, path, config, postObject }); | ||
} | ||
return response; | ||
}); | ||
@@ -72,6 +66,6 @@ } | ||
if (typeof responseObject === "bigint") { | ||
return responseObject + "n"; | ||
return `${responseObject}n`; | ||
} | ||
else if (typeof responseObject === "object") { | ||
return JSON.stringify(responseObject, (key, value) => typeof value === "bigint" ? value + "n" : value); | ||
return JSON.stringify(responseObject, (key, value) => typeof value === "bigint" ? `${value}n` : value); | ||
} | ||
@@ -78,0 +72,0 @@ else { |
@@ -64,4 +64,4 @@ /// <reference types="node" /> | ||
export type ResponseObject = { | ||
error: Error; | ||
statusCode: number; | ||
error: Error | null; | ||
statusCode: number | null; | ||
rspBody: any; | ||
@@ -72,4 +72,5 @@ }; | ||
path: string; | ||
config: RestClientConfig | ClientConfig; | ||
config: RestClientConfig | Omit<ClientConfig, "blockchainRid">; | ||
postObject?: PostRequestObjects | Buffer; | ||
} | ||
export type RestClientCallback<TData, TError = Error> = (error: TError | null | undefined, responseBody: TData | null | undefined) => void; |
@@ -1,2 +0,2 @@ | ||
Version 1.15.1 | ||
Version 1.16.0 | ||
@@ -10,2 +10,33 @@ # Changelog | ||
## [1.x.x] | ||
## [1.16.0] | ||
## Changed | ||
- Separated non-backend dependent functions from interface `IClient`. Functions `getTransactionRid`, `encodeTransaction`, and `decodeTransactionToGtx` have been extracted and are now separate utility functions. | ||
- Renamed `getTransactionRid` to `calculateTransactionRid` for clarity. Its input type has been changed to `RawGtxBody`. Conversion functions have been introduced to facilitate this transition. | ||
- Modified the input type of `encodeTransaction` to `GTX`. | ||
- Use PascalCase for types and class names: | ||
- `getTransactionRidException` -> `GetTransactionRidException`. | ||
- `transactionInfoInBlockResponse`-> `TransactionInfoInBlockResponse`. | ||
- `transactionInfoInBlock` -> `TransactionInfoInBlock`. | ||
- change `npm install` to `npm ci` command | ||
- split unit tests for `sendTransaction` to separate file. Replace Express mock server with MSW. | ||
- rework validation for client and server errors. Now it covers all 4xx and status codes. | ||
### Added | ||
- function for fetching information about the latest block for a chain. The funcition is added to the `IClient` interface and is called `getLatestBlock`. | ||
- verify if changelog changed in pipeline to prevent merging branch without updating it | ||
- create a custom error which include the http status code. Exported as `CustomError`. | ||
- automate integration tests to get BRID from running test node. | ||
- strictNullChecks in tsconfig.json to provide better type checking | ||
### Fixed | ||
- bug in retryRequest function which in some cases treated https errors as a successfull request. | ||
## [1.15.2] | ||
@@ -12,0 +43,0 @@ |
{ | ||
"name": "postchain-client", | ||
"version": "1.15.2", | ||
"version": "1.16.0", | ||
"main": "built/cjs/index.js", | ||
@@ -23,4 +23,5 @@ "browser": "built/esm/index.js", | ||
"scripts": { | ||
"test:unit": "TEST_ENV=unit env TS_NODE_COMPILER_OPTIONS='{\"module\": \"commonjs\" }' mocha -r ts-node/esm --exit", | ||
"test:integration": "TEST_ENV=integration env TS_NODE_COMPILER_OPTIONS='{\"module\": \"commonjs\" }' mocha -r ts-node/esm 'test/integration/**/*' --exit", | ||
"test:unit": "TEST_ENV=unit env TS_NODE_COMPILER_OPTIONS='{\"module\": \"commonjs\" }' mocha --timeout 20000 -r ts-node/esm --exit", | ||
"test:debug": "TEST_ENV=unit env TS_NODE_COMPILER_OPTIONS='{\"module\": \"commonjs\" }' mocha --inspect-brk -r ts-node/esm --exit", | ||
"test:integration": "BLOCKCHAIN_RID=`curl http://localhost:7740/brid/iid_0` && export BLOCKCHAIN_RID && TEST_ENV=integration env TS_NODE_COMPILER_OPTIONS='{\"module\": \"commonjs\" }' mocha --timeout 20000 -r ts-node/esm 'test/integration/**/*' --exit", | ||
"test:manually": "TEST_ENV=manual env TS_NODE_COMPILER_OPTIONS='{\"module\": \"commonjs\" }' mocha -r ts-node/esm 'test/manual/**/*' --exit", | ||
@@ -80,2 +81,3 @@ "build": "npm run clean && tsc && rollup -c rollup.config.mjs && echo '{\"type\": \"module\"}' > built/esm/package.json", | ||
"mocha": "^10.1.0", | ||
"msw": "^2.2.13", | ||
"prettier": "2.8.1", | ||
@@ -91,2 +93,2 @@ "rimraf": "^3.0.2", | ||
} | ||
} | ||
} |
@@ -7,3 +7,3 @@ # Postchain Client | ||
The Postchain Client is compatible with both JavaScript and TypeScript. You can install the library from npm via https://www.npmjs.com/package/postchain-client. | ||
The Postchain Client is compatible with both JavaScript and TypeScript. You can install the library from npm via [https://www.npmjs.com/package/postchain-client](https://www.npmjs.com/package/postchain-client). | ||
@@ -10,0 +10,0 @@ ## Initializing the Client |
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is not supported yet
215
8403996
35
80489