From 0cfd4186798076f8767a0372eb8fbd454b72c5a2 Mon Sep 17 00:00:00 2001 From: Tammo Date: Thu, 16 Apr 2020 16:44:56 +0200 Subject: [PATCH] feat: add ducktyping functions --- src/Block.ts | 15 ++++++++++----- src/Blockchain.ts | 24 ++++++++++++++++++++++-- src/Transaction.ts | 2 -- 3 files changed, 32 insertions(+), 9 deletions(-) diff --git a/src/Block.ts b/src/Block.ts index dace278..2acf02e 100644 --- a/src/Block.ts +++ b/src/Block.ts @@ -33,7 +33,6 @@ export enum BlockType { } export class Block { - __type: 'Block'; id: StorageId; chainId: StorageId; txId: string; @@ -58,10 +57,6 @@ export class Block { state?: string; - constructor() { - this.__type = 'Block'; - } - getDataForSignature(): SignatureData { const { type, @@ -179,3 +174,13 @@ export type BlockCommitments = { balanceCommitmentBlindFactor: any; amountCommitmentBlindFactor: any; }; + +export function isBlock(val: any): boolean { + if (!val) return false; + + // Ducktyping: maybe extend check with more fields + if (!val.type) return false; + if (!val.senderAmount) return false; + + return true; +} diff --git a/src/Blockchain.ts b/src/Blockchain.ts index b6014c7..01c7862 100644 --- a/src/Blockchain.ts +++ b/src/Blockchain.ts @@ -8,7 +8,6 @@ export enum AssetSymbol { } export class Blockchain { - __type: 'Blockchain'; id: StorageId; leafId: StorageId | undefined; publicSig: SigPublicKey; @@ -17,7 +16,6 @@ export class Blockchain { blocks: Block[] = []; constructor(publicSig: SigPublicKey, publicNtru?: NTRUPublicKey, symbol?: AssetSymbol) { - this.__type = 'Blockchain'; this.publicSig = publicSig; this.publicNtru = publicNtru; this.assetSymbol = symbol || AssetSymbol.TXL; @@ -51,3 +49,25 @@ export function fromBlockchainObject(obj: any) { export function deserializeBlock(block: object): Block { return fromBlockObject(block); } + +export function isBlockchain(val: any): boolean { + if (!val) return false; + + // Ducktyping: maybe extend check with more fields + return Array.isArray(val.blocks); +} + +export function isBlockchainRecord(val: any): boolean { + if (!val) return false; + + const fields = Object.getOwnPropertyNames(val); + + // an empty record is a valid record.. + if (fields.length === 0) return true; + + // test the first object if it is a blockchain + // if so the val behaves like a Record + const testFirstChain = fields[0]; + + return isBlockchain(val[testFirstChain]); +} diff --git a/src/Transaction.ts b/src/Transaction.ts index ee80a02..fad3480 100644 --- a/src/Transaction.ts +++ b/src/Transaction.ts @@ -4,12 +4,10 @@ import { StorageId } from './Storage'; import { AssetSymbol } from './Blockchain'; export class Transaction { - __type: 'Transaction'; id: StorageId; blocks: Block[] = []; constructor(symbol?: AssetSymbol) { - this.__type = 'Transaction'; this.assetSymbol = symbol || AssetSymbol.TXL; }