JavaScript transaction logic

After we have modeled the example's participants, assets, and transactions, it's time to encode the business logic in the form of transaction processor functions. These functions are typically considered as a Chaincode or smart contract function.

For that purpose, create a new directory called lib/, under which we will define the JavaScript files written in ECMAScript ES5. This script (or scripts) will contain transaction processor functions that will be called when a transaction is submitted.

In your lib/ directory, create a logic.js file (optionally from Visual Studio Code), and then paste in the following transaction processor function:

/**
* Create the sample asset
* @param {org.example.lc.cto.TransactionExample} tx- the TransactionExample transaction
* @transaction
*/
async function TransactionExample (tx) {

// Get the factory.
var factory = getFactory();
// Create a new vehicle.
var asset= factory.newResource('org.example.lc', 'SampleAsset', 'ASSET_1');
// Create a new relationship to the owner.
asset.owner= factory.newRelationship(namespace,'SampleParticipant',tx.owner.getIdentifier());
// Get the asset registry for the asset. let assetRegistry = getAssetRegistry('org.example.lc.SampleAsset');
// Update the asset in the asset registry. await assetRegistry.add(tx.asset); // Emit an event for the new created asset. let event = getFactory().newEvent('org.example.lc', 'SampleEvent'); event.asset = tx.asset; emit(event);

}

In the preceding example, the first line comment contains a human-readable description of what TransactionExample does. The second line must include the @param annotation to indicate which resource name of the transaction defined in the model file will be triggered by this transaction processor function. After the resource name, we define the parameter name (tx in this case), which must be supplied to the JavaScript function as an argument. The last line must contain the @transaction annotation to indicate that this function is defined as a transaction processor function.

The transaction processor function defines the TransactionExample type as the associated transaction and passes the parameter, tx.

The getFactory and newResource functions are used to create a new instance of the asset SampleAsset. The properties of the newly created instance can be set as standard JavaScript object properties, for instance, asset.value=xyz.

We instantiate a new relationship using newRelationship with the given namespace, type, and identifier to point at an existing instance of the specified namespace and identifier.

Finally, once we have updated its attribute, we store the new instance in the appropriate asset registry using the Add function (from AssetRegistry API), and then an event is emitted.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset