Skip to content

Commit

Permalink
feat: add ducktyping functions
Browse files Browse the repository at this point in the history
  • Loading branch information
tammo committed Apr 16, 2020
1 parent 50b71d1 commit 0cfd418
Show file tree
Hide file tree
Showing 3 changed files with 32 additions and 9 deletions.
15 changes: 10 additions & 5 deletions src/Block.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,6 @@ export enum BlockType {
}

export class Block {
__type: 'Block';
id: StorageId;
chainId: StorageId;
txId: string;
Expand All @@ -58,10 +57,6 @@ export class Block {

state?: string;

constructor() {
this.__type = 'Block';
}

getDataForSignature(): SignatureData {
const {
type,
Expand Down Expand Up @@ -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;
}
24 changes: 22 additions & 2 deletions src/Blockchain.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@ export enum AssetSymbol {
}

export class Blockchain {
__type: 'Blockchain';
id: StorageId;
leafId: StorageId | undefined;
publicSig: SigPublicKey;
Expand All @@ -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;
Expand Down Expand Up @@ -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<string, Blockchain>
const testFirstChain = fields[0];

return isBlockchain(val[testFirstChain]);
}
2 changes: 0 additions & 2 deletions src/Transaction.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}

Expand Down

0 comments on commit 0cfd418

Please sign in to comment.