Categories
Blockchain Finance Financial Services Supply Chain

8 no-nonsense use cases based on Hyperledger Fabric blockchain

Spend any amount of time in the blockchain sector and you’ll find a flood of opinions for ways blockchain technology will be “a game-changer.” Where this goes wrong is that it’s light on how it will change the game exactly and why there’s a game at all. But with the right use cases, organizations can benefit from the efficiency and shared recordkeeping a distributed ledger or specifically Hyperledger Fabric can offer.

A private blockchain for business creates a common version of the truth, the so-called source of truth, that’s difficult to change and easy to audit. Using permissioned networks also limits network participants to ensure data is secure. For businesses, this means better collaboration, streamlining business processes, and more transparency among business partners.

Table of contents:
  1. Innovation cycle
  2. Financial settlement
  3. Enterprise blockchain for contract validation
  4. Invoice processing
  5. Blockchain as a tamper-proof audit trail
  6. Managing data access
  7. Tracking supply chain network and origin
  8. Commission management
  9. Time-sensitive distribution
  10. Internal secured marketplace
  11. Conclusion

Innovation cycle

Like any technology, it takes a while for the value to finally emerge. Take photography for example. Since the beginning, the point has always been the same. It captures a copy of the truth — however selective — and keeps it forever.

Just like blockchain, early photography was not user-friendly, not cheap, not fast, and not for the masses. The full potential of the technology cannot be released in real-time, but over years as it needs time. Think of early blockchain projects as photography circa 1860 technically limited, reserved for specialists, and complicated to use.

At the time, few grasped its full potential. Many critics objected because an existing medium — painting — captured moments just fine.

Photography’s business benefits are clear to us today in hindsight, though. The global medical imaging market — a spinoff of photography — was worth $25 billion in 2019 according to Markets and Markets report. If Instagram were a stand-alone company Bloomberg estimates it would be worth more than $100 billion.

Of course, the fundamental reason we still take pictures has not changed in nearly 200 years. What has changed is the tools, business opportunities, specific use cases, and major advances in usability. We’re still innovating with blockchain. That’s not to say that there are no benefits, rather breakthroughs unfold as companies invest in development.

Below you can find eight no-nonsense use cases for private blockchains.

Financial settlement

Among the first blockchain including Hyperledger use cases were those in the payments. Cryptocurrencies like Bitcoin, and Ethereum lend themselves well to cross-border and digital payment systems. The world’s most popular public blockchain, Bitcoin, has especially captured a competitive advantage for a niche market. Bitcoin, however, is more of a philosophical choice than practical financial technology. Other blockchain protocols offer better usability and scalability, especially at scale.

At Espeo Software we design enterprise blockchain applications i.e. we have designed a remittance service using the Stellar protocol as an example of a system that will allow the following financial transactions – transfer money quickly and cheaply across borders. Cryptocurrency enables real-time money transfers anywhere in the world. With cryptographic guarantees, blockchain technology facilitates peer-to-peer payments by making sure users can’t spend their tokens twice — double-spending is something other payment processors use financial institutions like banks and credit rating agencies to prevent.

This, of course, removes money transfer services from the transaction, significantly reducing operating costs to transfer money internationally. When end users can trust both contract counterparties it is good for the money and enables more trustworthy peer-to-peer asset transfers.

For internal settlements, though, i.e. Hyperledger Fabric offers a way to both manage and carry out payments between an organization’s branches or close partners. An open and transparent blockchain solution helps organizations to ensure trust and create a transparent record. Network participants can clearly see where transactions go and for what.

Enterprise blockchain for contract validation

Companies with many branches and partners can create an ecosystem with a private blockchain such as Hyperledger Fabric. When a contract expires, certain actions such as issuing an invoice or renewing the contract need to be taken. Currently, these actions are often carried out through manual or semi-automated processes. Companies have to integrate multiple systems and fight data siloing. Using the blockchain network you get one place to store all information consistently and transparently. Moreover, we can use blockchain smart contracts to trigger new automatic actions when the contracts expire. The smart contract’s behaviour can adjust to the asset type and treat different product or service delivery than inventory sales.

Contract validation features can combine with other features like invoices and internal payments. One of the biggest challenges with large companies is transparency and trust between parties. A private, permissioned blockchain together with traditional IT solutions can resolve these problems. While designing software for multiple entities, a consensus mechanism needs to be taken into consideration, as commonly used PoW will generate significant costs.

Invoice processing

Large organizations with global offices struggle with the complexity of invoice processing. Some branches within an organization still do it manually, which can get too complicated. Centralized record-keeping software also limits transparency and can cause chaos when organizations don’t share access to it.

Blockchain enterprise systems using i.e. Hyperledger fabric technology puts all the records a conglomerate produces in one place. Thanks to such a blockchain network none of the organizations can modify the records or add new records without the other participants seeing the change.

Blockchain as a tamper-proof audit trail

What blockchains do is clear — they record a tamper-proof audit trail and distribute a current copy to everyone who’s interested in seeing it. Whether that’s in a public blockchain like Ethereum or in a closed group like the Linux Foundation’s Hyperledger Fabric, the motivation is largely the same. Gather and keep reliable information for every asset type.

What isn’t as clear yet is why.

Die-hard proponents harp on how blockchain will fix the world’s problems. This is overly optimistic, of course. The one reason to use a blockchain is to establish an audit trail, especially if you can’t trust the other actors you’re working with. If you share data with people you trust or don’t share much data at all, don’t think about consensus mechanisms and smart b2b contracts, use a database. This has been our line from the beginning.

Whether you’re tracking invoices, managing referrals, checking a contract’s validity, settling internal payments, managing access to records or tracking supply, tamper-proof auditing matters, and can significantly reduce liability and overhead.

We’ve worked on several of these use-case puzzles in in-house proofs of concept enterprise-grade applications and in applications for our clients. To explore exactly how business blockchain technology and the Hyperledger Fabric network will grow existing businesses and spin off new industries, it’s often important to try to build out a proof of concept first.

Here’s an overview of some of our POC projects and some ways to apply blockchain platforms to business.

Managing data access

One of the many blockchains for business use cases is keeping track of records and who has access to them. In a proof-of-concept application, we’ve developed, our team created an app that manages medical record storage for patients and their doctors based on Hyperledger Fabric.

Patients use their private keys to access a patient portal and can grant and revoke access to doctors. In turn, doctors use their keys to enter a doctor’s portal where they can add records of procedures.

The system shows how the blockchain platform plays a role in securing patient data and can improve some inefficiencies in the current system especially, in the cost of securing medical data. The system’s built-in security allows patients, doctors, and administrators to seamlessly coordinate over the application.

Tracking supply chain network and origin

Another excellent use for a tamper-proof audit trail is in supply chain tracking. Blockchain for the supply chain is one of the areas where we believe in a big technological impact, naming the pharmaceutical supply chain as the starting point. In our supply chain POC, we explored the role of a blockchain-based platform in verifying digital interactions that allow checking if a product has been shipped from a valid source and that it travelled through the supply chain in the right conditions.

Counterfeiting and mishandled drugs account for billions of dollars of losses to Big Pharma each year. Ensuring that consumers get exactly what they’re paying for and verifying that it’s not harmful is the main benefit to this use case.

Additional use cases of blockchain for the supply chain sector are in food tracking. As with pharmaceuticals, a blockchain-based supply platform which is tracking food to its source can help regulators verify that fish, for example, was properly harvested and is the species the package claims. It can also help retailers contain outbreaks of foodborne illness by quickly pinpointing which farm your spinach came from and how it was transported.

Walmart together with IBM has already launched a Hyperledger-based application, FoodTrack, to audit the source of leafy greens in its stores accurately.

Blockchain logistics offer significant utility in handling complex supply chains efficiently.

stellar blockchain update diagram

Commission management

Just as Hyperledger permissioned blockchain projects can help with the efficient processing of invoices, they can also track commissions and clearly show a history of accepted work and the payments for it. This is especially useful for conglomerates that operate in multiple countries that struggle with managing commission or referral payments.

Whether a particular partner uses a different accounting system, provides low-quality data with many duplicates, or is purposefully misrepresenting commissions, an application using Hyperledger Fabric can help establish order.

Blockchain-based time-sensitive distribution

The pandemic has affected all organizations in various possible ways. But it has obviously impacted healthcare organizations most significantly. While science came with its own answers to the situation which began in 2019 – new challenges regarding that occurred as well.

Scientists created effective vaccines, but they have to be transported in very strict conditions and to the places where they will be used on time. Especially at the early stages of vaccination, each dose was close to being priceless and none of it could have been wasted. On the other hand, the rapid introduction of the product to the market and extremely high demand have also encouraged potential frauds and counterfeits.

All of those new issues were solved with blockchain implementation. Tech Mahindra has created an interesting system based on Hyperledger Fabric – VaccineLedger which was developed in cooperation with a startup funded by Unicef and Gavi. Thanks to it the monitoring and distribution of vaccines can operate smoothly using precise information on the logistics, temperature, current location, purchase orders and transport conditions. You can read more about it in Forbes.

Development of an internally secured marketplace

The pandemic has also extorted robust cooperation between healthcare equipment owners. Different entities required special inventory like respirators or oxygen supplies and coordinating these needs with minimal mismanagement is not easy. Medical institutions use different systems, but permanent e-mail and phone coordination is neither accurate nor time efficient. If you add some time that will be consumed by the repairs, operating the central procurement system and a need to care about the patients – the real problem arises.

In order to build a comprehensive, nationwide internal system dedicated to the healthcare industry Healthcare Quality Improvement Partnership has organized a dedicated think-tank. Using the report from the debate as a starting point at Espeo Blockchain we have organized a product specification workshop with one of our clients. As an effect, we have built a prototype with a blockchain framework in mind, planned interaction of different groups of users with the system and infrastructure of private blockchain with direct access for all participants with immutable records by design.

Conclusion of use cases for Hyperledger Fabric

I hope your takeaway from this article, is a better understanding of the fundamental feature of blockchain systems — tamper-proof auditing — and how it drives blockchain use cases. 

Shared recordkeeping, smart contracts, supply chain management, shared assets, provenance, and payments are particularly salient now with existing blockchain tech to build apps around. The flexibility of blockchain solutions supports many business use cases even sensitive ones. Other use cases will take more time to work out — especially considering usability for a general audience. Don’t let it discourage you, this is a normal and healthy part of any technological innovation.

As more businesses find valuable Hyperledger Fabric use cases, new ways to innovate will continue to emerge. Blockchain is here to stay, it is important to get education and training on the subject to make an honest assessment of what it is and what it isn’t vital to use it right. And we are here to provide you with every practical guidance you might need.

Do you consider any of the above use cases relevant to your business?

We are helping businesses with powerful enterprise blockchain applications based on Hyperledger fabric. Click here to contact us and one of our experts will get in touch with you.

Categories
Software Technology

30 Angular tricks and tips to improve your application

Angular shortens development time for applications, reducing the time it takes to deliver custom software. Improving your app’s performance is vital to staying competitive and profitable. Here are 30 Angular tips.

Time and time again companies have trusted us as a software development provider. Read more about some of our projects and find out why.

  1. Define form parameters before Component definition. [dm_code_snippet background=”yes” background-mobile=”yes” bg-color=”#eeeeee” theme=”dark” language=”javascript” wrapped=”no” copy-text=”Copy Code” copy-confirmed=”Copied”]
     
    export const FORM_PARAMS = {
     status: 'status',
     classification: 'classification',
     note: 'note'
    };
    
    
    
    @Component({
     selector: 'app-preview',
     templateUrl: './preview.component.html',
     styleUrls: ['./preview.component.scss']
    })
    
    
    
    this.form = this.formBuilder.group({
     [FORM_PARAMS.status]: [false],
     [FORM_PARAMS.classification]: [null],
     [FORM_PARAMS.note]: [null, Validators.required]
    });
    
    
    
    this.form.patchValue({ [FORM_PARAMS.status]: 'status' });
    

    [/dm_code_snippet]

     

  2. Use renderer addClass, removeClass where possible. It will prevent too many change detection checks. [dm_code_snippet background=”yes” background-mobile=”yes” bg-color=”#eeeeee” theme=”dark” language=”javascript” wrapped=”no” copy-text=”Copy Code” copy-confirmed=”Copied”]
     
    // SLOWER
     
    collapseRow(rowIndex: number) {
     this.setRowCollapsed(rowIndex);
    }
    
    
    // FASTER
    collapseRow(event, rowIndex: number) { 
      this.setRowCollapsed(rowIndex);
      this.render.removeClass(event.target, 'arrowDown');
      this.render.addClass(event.target, 'arrowRight');
    }

    [/dm_code_snippet]

  3. Try to use get, set on Input() instead ngOnChanges. When you have many Inputs in the ngOnChanges, each “if” has to be checked. [dm_code_snippet background=”yes” background-mobile=”yes” bg-color=”#eeeeee” theme=”dark” language=”javascript” wrapped=”no” copy-text=”Copy Code” copy-confirmed=”Copied”]
     
    // SLOWER when many ifs
    ngOnChanges(changes: SimpleChanges) {
     const data: SimpleChange = changes.data;
     if (data && data.currentValue) {
       this.data = [...data.currentValue];
     }
     if (configuration && configuration.currentValue) {
       this.config = configuration.currentValue;
     }
    }	
    
    
    
    // FASTER
    
    
    
    public _config: Config;
    @Input('configuration')
    set configuration(value: Config) {
     this._config = value;
    }
    
    
    
    get configuration(): Config {
     return this._config;
    }
    
    
    
    _data: Data;
    @Input('data')
    set data(value: Data) {
     this._data = [...value];
    }
    
    
    
    get data(): any[] {
     return this._data;
    }
    

    [/dm_code_snippet]

     

  4. Use pipe when rendering content in ngFor. [dm_code_snippet background=”yes” background-mobile=”yes” bg-color=”#eeeeee” theme=”dark” language=”javascript” wrapped=”no” copy-text=”Copy Code” copy-confirmed=”Copied”]
     
    // Slower
     {{ render(row, column) }}
    
    render(row: any, column: string) {
     return YourService.render(row, column);
    }
    
    
    
    // Faster
     {{ row | render:column }}
    
    
    
    
    @Pipe({
     name: 'render',
    })
    export class RenderPipe implements PipeTransform {
     transform(row: any, column: string) {
       return YourService.render(row, column);
     }
    }
    

    [/dm_code_snippet]

  5. Specify baseUrl and module aliases (paths) to your compilerOptions to avoid any inconsistency when importing other files. [dm_code_snippet background=”yes” background-mobile=”yes” bg-color=”#eeeeee” theme=”dark” language=”javascript” wrapped=”no” copy-text=”Copy Code” copy-confirmed=”Copied”]
     
    {
     "compilerOptions": {
       "baseUrl": "src",
       "paths": {
         "@core/*": ["app/*"],
         "@assets/*": ["assets/*"]
       }
     }
    }
    
    
    
    import { Recruitment } from '@core/domain/recruitment';
    
    
    
    instead
    
    
    
    import { Recruitment } from '../../../domain/recruitment';
    

    [/dm_code_snippet]

     

  6. Add stylePreprocessorOptions to your angular.json file to avoid inconsistency while importing other files. [dm_code_snippet background=”yes” background-mobile=”yes” bg-color=”#eeeeee” theme=”dark” language=”javascript” wrapped=”no” copy-text=”Copy Code” copy-confirmed=”Copied”]
     
     "projects": {
       "project-frontend": {
         "root": "",
         "sourceRoot": "src",
         "projectType": "app",
         "architect": {
           "build": {
             "builder": "@angular-devkit/build-angular:browser",
             "options": {
               "stylePreprocessorOptions": { // <--- add this
                 "includePaths": [
                   "./src/assets/style/scss"
                 ]
               }
             }
           }
         }
       }
      
     @import "variables";
      
     instead
    
    
     @import "../../assets/style/scss/variables";
    

    [/dm_code_snippet]

     

  7. Run npm outdated command or add npm-check once a month to keep your dependencies updated. It will definitely help you keep track of changes. It’s much easier to update Angular 5 to 6 than 4 to 6.
  8. Run npm audit command once a month to check if any of the libraries has any vulnerabilities. It will help you keep your app secure. [dm_code_snippet background=”yes” background-mobile=”yes” bg-color=”#eeeeee” theme=”dark” language=”javascript” wrapped=”no” copy-text=”Copy Code” copy-confirmed=”Copied”]
     
    if [[ $(npm audit | grep Critical -B3 -A10) != '' ]]; then exit 1; fi"
    

    [/dm_code_snippet]

     

  9. Use parent in form validation instead of this.form which may not be initialised while doing/performing custom validation check. [dm_code_snippet background=”yes” background-mobile=”yes” bg-color=”#eeeeee” theme=”dark” language=”javascript” wrapped=”no” copy-text=”Copy Code” copy-confirmed=”Copied”]
     
    // Correct 
    
    
    
    static validateEndDate(fc: FormControl) {
     const startDate = fc.parent.get(FORM_PARAMS.startDate);
     if (startDate.value) {
       const diff = fc.value - startDate.value;
       return (diff < 86400) ? { endDateInvalid: true } : null;
     }
     return null;
    }
    
    
    
    // Incorrect 
    
    
    
    static validateEndDate(fc: FormControl) {
     const startDate = this.form.get(FORM_PARAMS.startDate);
     if (startDate.value) {
       const diff = fc.value - startDate.value;
       return (diff < 86400) ? { endDateInvalid: true } : null;
     }
     return null;
    }
    

    [/dm_code_snippet]

     

  10. Keep route names as const. It will prevent accidental typos. [dm_code_snippet background=”yes” background-mobile=”yes” bg-color=”#eeeeee” theme=”dark” language=”javascript” wrapped=”no” copy-text=”Copy Code” copy-confirmed=”Copied”]
     
    export class ROUTE {
     public static readonly LOGIN = '/login';
     public static readonly RECRUITMENTS = '/recruitments';
     public static readonly RECRUITMENT_EDIT = '/recruitments/:id';
    }
    
    
    
    goToRecruitment($event, id: number) {
     $event.preventDefault();
     this.router.navigate([ROUTE.RECRUITMENT_EDIT.replace(':id', id)]);
    }
    

    [/dm_code_snippet]

     

  11. Start using webpack-bundle-analyzer. It will help you detect any fast-growing modules.In our case by mistake main.scss has been included in another file instead variable.scss. It has doubled the size of the bundle! [dm_code_snippet background=”yes” background-mobile=”yes” bg-color=”#eeeeee” theme=”dark” language=”javascript” wrapped=”no” copy-text=”Copy Code” copy-confirmed=”Copied”]
     
    "scripts": {
       "bundle-report": "ng build --prod --stats-json && webpack-bundle-analyzer dist/stats.json"
    },
    93f72404-b338-11e6-92d4-9a365550a701.gif
    Gif Source: https://github.com/webpack-contrib/webpack-bundle-analyzer
    

    [/dm_code_snippet]

     

  12. Use browser Performance tests. 17ms rendering time means you use 60fps. Actions with fewer than 60fps and more than 30fps are ok. Any speed below 30fps makes the user notice the visualized slowdown of the application.
  13. Use the Augury chrome extension to track the current state of components.
  14. Prettier as code formaterTo prevent conflicts between tslint and prettier use the npm tool. [dm_code_snippet background=”yes” background-mobile=”yes” bg-color=”#eeeeee” theme=”dark” language=”javascript” wrapped=”no” copy-text=”Copy Code” copy-confirmed=”Copied”]
     
    // .prettierrc
    {
     "printWidth": 140,
     "parser": "typescript",
     "tabWidth": 2,
     "singleQuote": true,
     "trailingComma": "all"
    }
    

    [/dm_code_snippet]

     

  15. Use trackBy in ngFor loops to optimize the re-rendering of iterable.trackByFn is a  function that defines how to track changes for items in the iterable. When items are added, moved or removed in the iterable, only those nodes that have changed are re-rendered.
    Example: [dm_code_snippet background=”yes” background-mobile=”yes” bg-color=”#eeeeee” theme=”dark” language=”javascript” wrapped=”no” copy-text=”Copy Code” copy-confirmed=”Copied”]

     

    @Component({
     template: `
    • {{item.id}}
     `,
    })
    export class SampleComponent {
     constructor() {
       this.items = [
         {id: 1},
         {id: 2},
         {id: 3}
       ];
    

    [/dm_code_snippet]

  16.  Use a virtualized scroll list like e.g. CDK Virtual Scroll when you need to display a very large records collection. It will render just items that fit within ViewPort in the current scroll position, in comparison to rendering all items at once without virtualization.
    [dm_code_snippet background=”yes” background-mobile=”yes” bg-color=”#eeeeee” theme=”dark” language=”javascript” wrapped=”no” copy-text=”Copy Code” copy-confirmed=”Copied”]

     

    import { ScrollingModule } from '@angular/cdk/scrolling';
     
    @NgModule({
     ...,
     imports: [
       ...,
       ScrollingModule
     ],
     ...,
    })
    export class AppModule { }
     
    @Component({
     template: `
    • {{item.id}}
     `,
    })
    export class SampleComponent {
     constructor() {
       for (let index = 0; index < 10000; index++) {
         this.items.push({ id: index });
       }
     }
     trackByFn(index, item) {
       return item.id;
     }
    }
    

    [/dm_code_snippet]

  17. From Angular v9+, use ngZoneEventCoalescing flag to reduce the amount of change detection cycles while Event Bubbling.
    [dm_code_snippet background=”yes” background-mobile=”yes” bg-color=”#eeeeee” theme=”dark” language=”javascript” wrapped=”no” copy-text=”Copy Code” copy-confirmed=”Copied”]

     

    platformBrowserDynamic()
     .bootstrapModule(AppModule, { ngZoneEventCoalescing: true })
     .catch(err => console.error(err));

    [/dm_code_snippet]
    Example: [dm_code_snippet background=”yes” background-mobile=”yes” bg-color=”#eeeeee” theme=”dark” language=”javascript” wrapped=”no” copy-text=”Copy Code” copy-confirmed=”Copied”]

    platformBrowserDynamic()
     .bootstrapModule(AppModule, { ngZoneEventCoalescing: true })
     .catch(err => console.error(err));
    

    [/dm_code_snippet]

    Normally when we click on the button element, both “childrenFn” and “parentFn” are invoked, causing two change detection cycles. With ngZoneEventCoalescing flag set to true, there is only one change detection cycle to run. 

  18. Debugging Angular component in console
    1. Open browser developer tools.
    2. Select element in “Elements” tab
    3. Debug this element in console: ($0 – in this variable is selected element)

    Before Angular v9:[dm_code_snippet background=”yes” background-mobile=”yes” bg-color=”#eeeeee” theme=”dark” language=”javascript” wrapped=”no” copy-text=”Copy Code” copy-confirmed=”Copied”]

    const selectedComponent = ng.probe($0).componentInstance;
    selectedComponent.value = "New value";
    ng.probe($0).injector.get(ng.coreTokens.ApplicationRef).tick();

    [/dm_code_snippet]

    From Angular v9+:
    [dm_code_snippet background=”yes” background-mobile=”yes” bg-color=”#eeeeee” theme=”dark” language=”javascript” wrapped=”no” copy-text=”Copy Code” copy-confirmed=”Copied”]

    const selectedComponent = ng.getComponent($0);
    selectedComponent.value = "New value";
    ng.applyChanges(myComponent);
    

    [/dm_code_snippet]

    From Angular v9+ it is even better to use this SB Angular Inspector.

  19.  Lazy loading in Angular – instead of loading a complete app, Angular loads only the modules which are required at the moment. It reduces the initial load time. 
  20. Always keep an eye on your Bundle Size. Depends on the scale of your project, in enterprise apps if your main.*.js file exceeds more than 0.5 MB, you may need to be aware. After your Angular app is deployed check if your cloud platform or CDN, hosts your bundles gzipped. In the network tab in the developer console in Response Headers, you should see the header: “Content-Encoding: gzip.” If you have your own server serving your app and it doesn’t implement gzip compression, you should definitely add those. 
  21. While you don’t need to validate or react on every single change of your FormControl, use updateOn: ‘blur’. Event callbacks will be executed on blur events. [dm_code_snippet background=”yes” background-mobile=”yes” bg-color=”#eeeeee” theme=”dark” language=”javascript” wrapped=”no” copy-text=”Copy Code” copy-confirmed=”Copied”]
    this.email = new FormControl(null, { updateOn: 'blur' });

    [/dm_code_snippet]

     

  22. Use Services for any Side Effects.It is a good place for any  HTTP requests, event handlers, time-based events. It reduces the complexity of the component and provides reusability to our codebase. [dm_code_snippet background=”yes” background-mobile=”yes” bg-color=”#eeeeee” theme=”dark” language=”javascript” wrapped=”no” copy-text=”Copy Code” copy-confirmed=”Copied”]
    @Injectable({
     providedIn: 'root'
    })
    export class UsersService {
     constructor (private http: HttpClient) {}
     
     getUsers() {
       return this.http.get(API_ENDPOINT);
     }
    }
      
    @Component({
     selector: 'app-component',
     template: '
    • {{item}}
    ',
    })
    export class AppComponent implements OnInit{
     constructor(private usersService: UsersService){
     }
     items = [];
      ngOnInit(){
       this.usersService.getUsers().subscribe(items => this.items = items);
     }
    }
    

    [/dm_code_snippet]

  23. Use the Angular CLI tool that makes it easy to create your application. With just one command you can generate whatever you want, use analytics, sets project configuration, and many more. Here are some useful commands.

    To generate component under desired path with sass style files: [dm_code_snippet background=”yes” background-mobile=”yes” bg-color=”#eeeeee” theme=”dark” language=”javascript” wrapped=”no” copy-text=”Copy Code” copy-confirmed=”Copied”]

     

    ng generate component components/yourComponentName --style=sass
     
    Abbreviation:
    ng g c components/yourComponentName --style=sass
    

    [/dm_code_snippet]

    To see what files will be generated without creating them use flag: [dm_code_snippet background=”yes” background-mobile=”yes” bg-color=”#eeeeee” theme=”dark” language=”javascript” wrapped=”no” copy-text=”Copy Code” copy-confirmed=”Copied”]

    ng g c components/yourComponentName --dryRun=true

    [/dm_code_snippet]

    To generate without tests files: [dm_code_snippet background=”yes” background-mobile=”yes” bg-color=”#eeeeee” theme=”dark” language=”javascript” wrapped=”no” copy-text=”Copy Code” copy-confirmed=”Copied”]

    ng g c components/yourComponentName --skipTests=true

    [/dm_code_snippet]

     

  24. From Angular 6 on, with the help of @angular/elements package you can create custom native components (Web Components) that can be used outside of the Angular. This package provides polyfills to support browsers that don’t support Web Components.To get started, install the package in an Angular project with the following command: [dm_code_snippet background=”yes” background-mobile=”yes” bg-color=”#eeeeee” theme=”dark” language=”javascript” wrapped=”no” copy-text=”Copy Code” copy-confirmed=”Copied”]
    ng add @angular/elements --name=

    [/dm_code_snippet]

     

  25. Use an ErrorHandler from @angular/core to handle errors in your app. With this dedicated service, you can easily manage errors in your entire application. As a default, the service catches the errors and logs them to the console, but it can be extended by additional side effects, whatever you need. It is pretty easy to implement such a service: Simply create a file called e.g. error-handler. [dm_code_snippet background=”yes” background-mobile=”yes” bg-color=”#eeeeee” theme=”dark” language=”javascript” wrapped=”no” copy-text=”Copy Code” copy-confirmed=”Copied”]
    import { ErrorHandler } from '@angular/core';
     
    class MyErrorHandler implements ErrorHandler {
     handleError(error: any) {
       // do something with the exception
       super.handleError(error);
     }
    }
     
    @NgModule({
     providers: [{provide: ErrorHandler, useClass: MyErrorHandler}]
    })
    class MyModule {}
    

    [/dm_code_snippet]

     

  26. Add Aliases support to your project. If you think importing your components is ugly, try this. [dm_code_snippet background=”yes” background-mobile=”yes” bg-color=”#eeeeee” theme=”dark” language=”javascript” wrapped=”no” copy-text=”Copy Code” copy-confirmed=”Copied”]
    import { MyComponent } from '../../../../components/parent-component/my-component'

    [/dm_code_snippet]

    Specify aliases to your project folders in tsconfig.json file: [dm_code_snippet background=”yes” background-mobile=”yes” bg-color=”#eeeeee” theme=”dark” language=”markup” wrapped=”no” copy-text=”Copy Code” copy-confirmed=”Copied”]

    {
     "compilerOptions": {
       "baseUrl": "src",
       "paths": {
         "@components": "app/components",
         "@services": "app/services"
       }
     }
    }
    

    [/dm_code_snippet]

    And import your code in this way: [dm_code_snippet background=”yes” background-mobile=”yes” bg-color=”#eeeeee” theme=”dark” language=”javascript” wrapped=”no” copy-text=”Copy Code” copy-confirmed=”Copied”]

    import { MyComponent } from '@components/parent-component/my-component';

    [/dm_code_snippet]

  27. Preload your resources and routes to speed up your application.

    Angular has a preloading strategy implemented already in @anuglar/router module. It allows us to preload routes/links but also resources, modules etc. This process speeds uploading and rendering time of the resources, by preloading them to a browser cache. [dm_code_snippet background=”yes” background-mobile=”yes” bg-color=”#eeeeee” theme=”dark” language=”javascript” wrapped=”no” copy-text=”Copy Code” copy-confirmed=”Copied”]

    class CustomPreloadingStrategy implements PreloadingStrategy {
     preload(route: Route, fn: ()=> Observable) {
         // ...
     }
    }
     
    RouterModule.forRoot([
     ...
    ], {
     preloadingStrategy: OurPreloadingStrategy
    })
    

    [/dm_code_snippet]

  28. Do you have a heavy computational function that slows your application down? From default JavaScript is a single-threaded language, so your heavy computations runs along with UI updates, but there is a remedy for it. With help of the Web Workers you can move your heavy non-UI algorithm to run on separate non-UI-blocking thread.Create file with your custom Web Worker (‘./myWebWorker.js’): [dm_code_snippet background=”yes” background-mobile=”yes” bg-color=”#eeeeee” theme=”dark” language=”javascript” wrapped=”no” copy-text=”Copy Code” copy-confirmed=”Copied”]
    onmessage = function(e) {
     console.log('Worker: Message received from main script');
     const result = e.data[0] * e.data[1];
     if (isNaN(result)) {
       postMessage('Please write two numbers');
     } else {
       const workerResult = 'Result: ' + result;
       console.log('Worker: Posting message back to main script');
       postMessage(workerResult);
     }
    }
    

    [/dm_code_snippet]

    Then in your component subscribe on it: [dm_code_snippet background=”yes” background-mobile=”yes” bg-color=”#eeeeee” theme=”dark” language=”javascript” wrapped=”no” copy-text=”Copy Code” copy-confirmed=”Copied”]

    @Component({
     selector: 'app',
    })
    export class App implements OnInit{
     private output
     private webworker: Worker
     ngOnInit() {
         if(typeof Worker !== 'undefined') {
             this.webWorker = new Worker('./myWebWorker')
             this.webWorker.onmessage = function(data) {
                 this.output = data
                 console.log('Message received from worker');
             }
         }
     }
     runHeavyAlgorithm(firstValue: number, secondValue: number) {
         this.webWorker.postMessage([firstValue, secondValue])
     }
    }
    

    [/dm_code_snippet]

  29.  Use Pure PipesTo specify that your Pipe as “Pure” simply just set the “pure” flag in its configuration: [dm_code_snippet background=”yes” background-mobile=”yes” bg-color=”#eeeeee” theme=”dark” language=”javascript” wrapped=”no” copy-text=”Copy Code” copy-confirmed=”Copied”]
    @Pipe({
     name: "units",
     pure: true
    })
    class UnitsPipe implements PipeTransform {
    ...
    }
    

    [/dm_code_snippet]

    In this way any inputs passing through this Pipe is computed only once and cached, next calls with the same inputs will be skipped and returned the cached data.

  30. Remove all caret “^” and tilde “~” from your package.json. If you want your project to be stable and not to fail in the future you should stick to specific versions of packages you use.

Go to our expertise page and read more about what we excel at.

Categories
Blockchain Financial Services Software

Hyperledger fabric – what do you need to know about this enterprise blockchain?

Enterprises need to ensure a significant level of security, privacy, compliance, and performance. These processes are very complex and time-consuming. Problems frequently emerge with data incompatibility or lack of trust. How can Hyperledger Fabric help in such situations?

Blockchain is a distributed, decentralized public ledger. To picture it, it can be described as a constantly growing list of transactions stored on devices on the network called nodes. Cryptographic protocols connect the nodes and keep transactions confidential.

All the data on the blockchain network is visible to users, and each is responsible for their actions. Data is immutable and not controlled by one central authority. But what happens when we want to use blockchain for business so that we need to certify authorities and control who is in our network, and we want to keep all our data confidential from the outside world? One thing is for sure – in such a case, a public blockchain network won’t be suitable; you need a private network. To create blockchain applications meeting the above requirements, it’s best to use enterprise blockchain platforms.

What are private blockchain networks, and what are their benefits

Private blockchains are a version of blockchain technology that can be either open-source, consortium, or privately developed. There is a wide range of private blockchain platforms, but the most popular ones are Hyperledger Fabric (sometimes shortened to Fabric, or HLF) hosted by the Linux Foundation, and R3’s Corda.

Joining a private blockchain network

One feature that sets private blockchains apart is that participants can limit or grant permission to access this blockchain network. This is why it is also called a permissioned network. Network administrators have to invite you to join the enterprise blockchain. Limiting access to the network and implementing proper identity management ensure private transactions. Only entities participating in a transaction will know about it. “To achieve a higher level of privacy, it is sufficient to specify user identities, limit read permissions, and certify authorities. These measures provide a high level of data protection.

Transaction scalability across the network

Hyperledger Fabric is an open-source blockchain; its scalability depends on many factors. Software infrastructure design and complexity impact performance. The Hyperledger Foundation claims that its private blockchain is more scalable and allows more transactions per second than public blockchains. A 2019 study by Christian Gorenflo, Stephen Lee, Lukasz Golab, and S. Keshav even states that it has achieved a fantastic transaction flow of up to 20,000 business transactions per second.

One significant tradeoff for higher transaction processing rates is that private blockchains are more centralized, permissioned networks. Rather than public proof-of-work consensus, which Bitcoin and Ethereum use, Hyperledger Fabric networks use the Raft consensus algorithm.

Consensus in Hyperledger Fabric network

To reach consensus in HLF, you need an odd number of nodes, and there needs to be a simple majority of those working to confirm transactions. For example, if there are seven nodes in a network, four would need to be working to verify new transactions. However, having such a limited number of nodes also comes with risk.

Blockchain developer Tomasz Kaliszuk explained that “Raft [consensus] might lose more nodes, and it will continue to work. It is an approach to a consensus that enables actors in a network to gain a lot of power — so be sure it’s someone you trust. It is less secure because it does not protect against ‘bad actors,’ meaning ‘bad nodes,’ so it’s essential in enterprise blockchains to trust that such bad users will not gain access. Raft, however, is faster, much more scalable when it comes to network expansion.”

When designing blockchain systems based on Hyperledger Fabric, we approach it from a technical point of view using its built-in components like chaincode and ordered. But we also approach it from the perspective of business logic. We try to understand how our client’s business works, what problems we are to solve, and how we can combine technology and business to optimize processes and bring tangible benefits.

What is Hyperledger Fabric blockchain platform– need-to-know basis

Hyperledger Fabric supports transaction validation. This blockchain network is characterized by a modular architecture that breaks down transaction processing into phases. This separation is intended to optimize network scalability and performance.

Permissioned blockchain ledger and smart contract model

Distributed ledger technology includes blockchain technologies and smart contracts called chaincode. Moreover, we can build a traditional application using, for example, node.js technology and use blockchain as a layer for synchronizing, processing, and securing data. That can work well in the context of financial sectors, for example.

Secure transactions based on blockchain infrastructure

Using Hyperledger Fabric allows a high level of security. The blockchain framework raises several concerns related to competitiveness, protection laws, rules regarding confidentiality of personal data, the risk of data leaks, and the management of private data. All of them can be mitigated thanks to partitioning the data in the network that is also available in Fabric.

Use case of Hyperledger Fabric blockchain technology for business

I want to present the case of our recent Hyperledger project. On the high-level architecture above, you can see the structure of the decision-making business processes before the implemented changes. Making and confirming a decision or approving a document requires that all parties communicate with each other to agree to the changes at the same time.

Communication between the systems of partners or branches in one organization was processed without a central trusted data source that would guarantee that the transaction details confirmation of all members of this network would be fast and saved information in the database would be the same. This structure’s convoluted and time-consuming.

Central database solution pros and cons

As shown in the diagram above, we can add a back-end system with a database as a central solution. This solution could improve the process between participants in business networks like this one. However, we still have a problem with distrust and a lack of immutable data. The data transferred between participants can be changed without the consent of the settling parties, resulting in a potential asymmetric version of data in at least one of the system participants. The lack of trusted data affects future transactions and will not resolve our problems. The optimized, centralized database could be faster and easier to search in than decentralized solutions.

Distributed network pros and cons

Data immutability and trustless data exchange were essential; we decided to use DLT as a private blockchain infrastructure with intelligent contracts to resolve these problems. The blockchain will become a root of trust that makes communication between peers symmetrical and eliminates levels of trust fluctuations or its complete lack.

Solution

A private blockchain is the most relevant solution in this use case. We solved this problem with smart contracts and created a blockchain network – Hyperledger Fabric decentralized ledger technology is one data source in which all saved changes are visible to users. Each participant in the blockchain network can be transparent with others.

By implementing the private blockchain as distributed ledger framework, the client gained one common root of trust – a database with consistent data, which solved the problem of lack of trust. By optimizing current manual or semi-automation processes, decision-making time has been shortened, which also reduced the costs of the process and decision delays.

We are helping various businesses with powerful enterprise blockchain solutions based on Hyperledger Fabric. Contact us, and one of our experts will get in touch with you.

Related posts:

Categories
Blockchain Software Technology

Multi-cloud deployment of blockchain infrastructure

Cloud (or Cloud Computing) was one of the largest buzzwords of the last decade. Still many people identify “the cloud” with Amazon Web Services. Despite that, there are several other cloud computing vendors that are worth looking at, especially if you’re building a blockchain solution supporting a large group.

These are primarily cloud service providers Google Cloud Platform, Microsoft Azure, Oracle Cloud, IBM Cloud, Rackspace and Hetzner Cloud. Below, I’ll discuss their advantages and show how we deployed our blockchain infrastructure.

Multi-cloud deployment of blockchain infrastructure

Table of contents:

  1. The domination of AWS
  2. Location, location, location
  3. More pros and cons of other cloud computing vendors
  4. Espeo’s solutions
  5. Let’s take a look at our entire blockchain infrastructure:
  6. Conclusion

The domination of AWS

Amazon’s domination among cloud providers in the minds of people is somewhat justified because Amazon was the precursor and main promoter of the concept of cloud computing. Amazon’s services are the most known, have the highest reliability, the best documentation. In short, they’re the role model for the competition.

But there are also a number of other vendors that provide private clouds and public clouds. Some examples are the Chinese Alibaba Cloud or the Polish e24cloud. These are more or less successful AWS clones and have even more or less similar APIs. Most often, technologically they don’t bring anything new, but they operate in regions poorly handled by competitors (e.g. Alibaba Cloud in China).

Location, location, location

Let’s begin with data center locations. As I’ll show later, this might be an issue for blockchain infrastructure. With the increase in the physical distance between the client and the data center, network delays increase. In transaction systems, this may determine the order of transaction processing from individual clients, and consequently, profitability or other economic parameters.

AWS covers most of the world but doesn’t have data centers in Africa, China, and Russia. The data centers in India, Brazil, and Australia don’t offer a full range of services. So if we want to start a service strongly dependent on the quality of connections (e.g. blockchain network or high-frequency trading), then it may be reasonable to take multicloud approach and use several different cloud vendors at the same time.

Multicloud strategy translates into various advantages, for instance one of the main pros of Microsoft Azure is having over 50 data centers in various regions of the world. These include the central states of the USA, Eastern Canada, Switzerland, Norway, China, India, Australia, South Korea, South Africa or the United Arab Emirates — in these regions AWS offers relatively large network delays.

More pros and cons of other cloud computing vendors

Google Cloud Platform

In addition to services based on open-source software (Linux, Docker, MySQL, Postgres, MongoDB, HBase, etc.), also provides its own services. These are, for example, BigTable and Realtime Database. They allow more efficient operation of large amounts of data than if you’re using only open source technology, as well as more efficient load balancing than AWS services. The price for this, however, is vendor lock-in, i.e. the impossibility of departing from this particular vendor.

Microsoft Azure

In addition to a number of locations, is also the best place to run all kinds of solutions based on Windows. This can be important if in our blockchain stack we use ready-made .NET libraries that don’t have their own implementations for Linux.

Hetzner Cloud

It’s a relatively new service of Hetzner Online, so far specializing in web hosting and low-cost dedicated servers. The Cloud offer brought a significant improvement in quality in relation to the current offer while maintaining very low prices. It still can’t compete with AWS in terms of stability, but it seems to be a matter of time. Its unique advantage is a data center in Finland.

Espeo’s solutions

Let’s take a look at the solutions we’ve used in Espeo for multi-cloud infrastructure management as well as the blockchain platform itself for blockchain infrastructure.

First approach — manual management

Our blockchain journey with working on distributed ledger technologies on cloud was, of course, manual management. By this, I mean logging into different cloud consoles from several different browsers. This approach worked quite well until we were in control of about 5-6 AWS accounts and one account for each other cloud vendors. With so few accounts, it was still possible to manage them so efficiently “on foot.” It seemed that the investments in the implementation of appropriate tools would take way too long to start paying off, especially that we didn’t know what technologies to stick to and which ones to avoid.

Second approach — tools. Open source?

The second approach was to analyze the available tools, but we wanted them to be open source tools. We were interested, among others, in the Terraform tool (from the creators of Vagrant). Very quickly, however, we got the impression that almost all existing open-source tools didn’t line up with how we work. So, either to manage your own infrastructure (for one company or one group of companies) or in the best case for managing large projects in the Infrastructure as Code model. The latter means describing the infrastructure elements in the form of a language specially created for this purpose.

Infrastructure as Code is, of course, a very sensible approach, but it has a disadvantage. It doesn’t work well for very small projects, which are often at the MVP stage and operate on a single server. In such cases, the Infrastructure as Code approach is to shoot a fly with a cannon. You’ll achieve it, but clients will want to know why they’re paying so much for it.

Third approach — Polynimbus

Ultimately, we decided to use the Polynimbus tool. It supports multicloud environments – eight different cloud vendors and have a competitive advantage of being a relatively simple (compared to Terraform) cloud resources pool, which perfectly suited our needs. Polynimbus supports an unlimited number of AWS accounts and requires minimum configuration for each of them. It basically covers only issuing the access key, secret access key, and the default region. All the rest, including e.g. fast changing AMI ID numbers of system images, are detected automatically.

Let’s take a look at our entire blockchain infrastructure:

As you can see, Polynimbus is one of the elements of a perfectly integrated stack. It covers the management of the full lifecycle of the instance, regardless of whether they are instances of AWS (EC2), Azure, Oracle or others. Creating an instance looks like this:

  • Polynimbus – proper creation of a new instance.
  • ZoneManager – adding a DNS record to Amazon Route53, binding the destination hostname to the IP address returned by Polynimbus.
  • Server Farmer – provisioning of the instance; at this stage various aspects of server security are configured. Central logging of events, backups, automatic updates, and then the instance is plugged into the farm (ie the central management system).
  • Ansible – application provisioning, starting with Docker and support tools. Then the Go stack is built (non-standard due to Hyperledger requirements), after which Hyperledger Fabric and Consul services are installed and configured. The latter in client or server mode. In general, there is no real need to run more than two Consul instances per single availability zone.
  • Next, the integration with a separate Apache Kafka cluster is configured, as well as with CircleCI.com responsible for the CI / CD processes, ie deployment of new versions of the application. So, the next step would be to start the Fabric node by CircleCI.com.

Conclusion

What’s important for both us and our clients, Polynimbus gives us full independence from any cloud vendor. Therefore, if we get a dedicated, more advantageous price offer, e.g. from Oracle, we don’t have to stay with AWS to provide blockchain services to our clients just because of some technical reasons.

One must remember real limitations. Not all power of each subsequent instance can be allocated to the proper application because one must remember about Consul cluster — so that Hyperledger connects to Consul in its own availability zone. And therefore, each of them must contain one or two Consul instances.

Thanks to this, we avoid a situation where global network failure causes problems with the correct operation of the application. In a correctly configured multi-cloud environment, multi-region, multi-AZ… In the case of global network failure, selected nodes simply cease to support current traffic. However, this failure doesn’t result in any other consequences. Thanks to an efficient management stack, in this case, if we anticipate longer problems, we’re able to add new blockchain nodes in other cloud vendors and regions.