Contract Class

Every chaincode program contains one or more smart contracts. Each smart contract must extend the Contract class, whose methods are called in response to received transactions. The Contract class is declared in the fabric-contract-api npm package:

export class Contract {
   constructor(name?: string); 

   static _isContract(): boolean; 

   beforeTransaction(ctx: Context): Promise<void>;
   afterTransaction(ctx: Context, result: any): Promise<void>; 

   unknownTransaction(ctx: Context): Promise<void>; 

   createContext(): Context;
   getName(): string;
}

Within each smart contract instance, it is possible to have as many functions as necessary. These can either be a transaction function that can be called by applications, or a helper function prefixed by an underscore. If the function name is prefixed by an underscore, the function is "unknown" for external callers.

Every transaction function must take a transaction context as the first parameter. A transaction context object is represented by the Context class or its inheritors and provides two crucial objects to interact with the ledger and transaction proposal data.

  • stub: ChaincodeStub encapsulates API to interact with the world state, private collections, transaction proposal, etc.

  • clientIdentity: ClientIdentity provides details about the transaction creator.

The Context object is created by Contract.createContext function which can be overridden to extend information provided by the transaction context.

The Contract class also provides default implementations of Before, After, and Unknown transaction handlers. Transaction handlers are optional functions that receive control before or after a transaction, or in case a request is made to invoke a transaction not defined in a smart contract. They can be used if specific actions should be performed around each transaction, such as caller identity checks.

Considering the above, we can implement a dummy contract, that does nothing valuable, but can be operated in the network:

simpleContract.js
'use strict'; 

const { Contract } = require('fabric-contract-api'); 

class SimpleContract extends Contract {
} 

module.exports = SimpleContract;

Let’s save this chaincode in a simpleContract.js file into the simple_chaincode/lib folder.

Last updated

Was this helpful?