Chaincode
FractaLedger Chaincode
Chaincode is the smart contract code that runs on the Hyperledger Fabric network. It defines the business logic for your FractaLedger application.
Overview
In FractaLedger, chaincode (smart contracts) runs on the Hyperledger Fabric network and provides the business logic for your application. The chaincode is responsible for:
- Managing internal wallet balances
- Processing internal transfers
- Implementing custom business logic (fee calculations, distribution rules, etc.)
- Maintaining the state of the system
FractaLedger uses a single chaincode deployment for the entire system, but you can customize this chaincode to implement your specific business requirements. The system provides several chaincode templates that you can use as a starting point for your customization.

┌─────────────────────────────────────────────────────────────┐ │ FractaLedger Core │ │ │ │ ┌───────────────┐ ┌───────────────┐ ┌──────────────┐ │ │ │ API Server │ │ Wallet │ │ Blockchain │ │ │ │ │───▶│ Manager │───▶│ Connector │ │ │ └───────────────┘ └───────────────┘ └──────────────┘ │ │ │ │ └──────────────────────────────┼──────────────────────────────┘ │ ▼ ┌─────────────────────────────────────────────────────────────┐ │ Hyperledger Fabric │ │ │ │ ┌───────────────┐ ┌───────────────┐ ┌──────────────┐ │ │ │ Channel │ │ Chaincode │ │ World State │ │ │ │ │───▶│ (Smart │───▶│ (Ledger) │ │ │ │ │ │ Contract) │ │ │ │ │ └───────────────┘ └───────────────┘ └──────────────┘ │ │ │ └─────────────────────────────────────────────────────────────┘
Chaincode Templates
FractaLedger provides several chaincode templates that you can use as a starting point for your customization:
Default Template
The default template provides basic functionality for managing internal wallets and transactions. It includes:
- Internal wallet creation and management
- Internal transfers between wallets
- Withdrawal processing
- Balance tracking
This template is a good starting point for most applications and can be extended to implement your specific business logic.
Merchant Fee Template
The merchant fee template extends the default template with functionality for merchant fee collection. It includes:
- Fee configuration management
- Merchant transaction processing with fee calculation
- Fee distribution to fee wallets
- Merchant-specific fee rates
This template is ideal for applications that need to take a percentage fee for facilitating cryptocurrency transfers between customers and merchants.
Employee Payroll Template
The employee payroll template extends the default template with functionality for employee payment processing. It includes:
- Employee management
- Salary configuration
- Scheduled payment processing
- Payment history tracking
This template is ideal for applications that need to distribute funds to employees based on predefined rules and schedules.
Customizing Chaincode
You can customize the chaincode to implement your specific business requirements. FractaLedger provides two main ways to customize chaincode:
Using the API
You can create, update, and deploy custom chaincodes using the API endpoints. This approach is useful for applications that need to manage chaincode programmatically.
Create a Custom Chaincode
Use the POST /api/chaincode/custom
endpoint to create a custom chaincode based on a template:
curl -X POST http://localhost:3000/api/chaincode/custom \
-H "Content-Type: application/json" \
-H "Authorization: Bearer YOUR_JWT_TOKEN" \
-d '{
"templateId": "merchant-fee",
"customId": "my-merchant-fee"
}'
This creates a new custom chaincode in the src/chaincode/custom/my-merchant-fee
directory, based on the merchant fee template.
Update the Custom Chaincode
Use the PUT /api/chaincode/custom/:id
endpoint to update the custom chaincode:
curl -X PUT http://localhost:3000/api/chaincode/custom/my-merchant-fee \
-H "Content-Type: application/json" \
-H "Authorization: Bearer YOUR_JWT_TOKEN" \
-d '{
"filePath": "index.js",
"content": "// Updated chaincode content\nconst { Contract } = require(\"fabric-contract-api\");\n\nclass MerchantFeeContract extends Contract {\n // ...\n}"
}'
This updates the index.js
file in the custom chaincode directory with the new content.
Deploy the Custom Chaincode
Use the POST /api/chaincode/custom/:id/deploy
endpoint to deploy the custom chaincode to the Hyperledger Fabric network:
curl -X POST http://localhost:3000/api/chaincode/custom/my-merchant-fee/deploy \
-H "Content-Type: application/json" \
-H "Authorization: Bearer YOUR_JWT_TOKEN"
This deploys the custom chaincode to the Hyperledger Fabric network, making it available for use by the FractaLedger system.
Direct File Editing
You can directly edit the chaincode files in the src/chaincode/custom
directory. This approach is useful for development and testing.
Create a Custom Chaincode Directory
Create a new directory in the src/chaincode/custom
directory for your custom chaincode:
mkdir -p src/chaincode/custom/my-merchant-fee
Copy Template Files
Copy the files from the template directory to your custom chaincode directory:
cp -r src/chaincode/templates/merchant-fee/* src/chaincode/custom/my-merchant-fee/
Edit the Chaincode Files
Edit the files in your custom chaincode directory to implement your specific business logic:
vim src/chaincode/custom/my-merchant-fee/index.js
Deploy the Custom Chaincode
Use the Hyperledger Fabric CLI tools to deploy your custom chaincode to the Fabric network:
cd fabric-samples/test-network
./network.sh deployCC -ccn fractaledger-chaincode -ccp /path/to/src/chaincode/custom/my-merchant-fee -ccl javascript
Deploying Chaincode
Once you've customized your chaincode, you need to deploy it to the Hyperledger Fabric network. FractaLedger provides several ways to deploy chaincode:
API Deployment
You can deploy chaincode using the API endpoints. This approach is useful for applications that need to manage chaincode programmatically.
curl -X POST http://localhost:3000/api/chaincode/custom/my-merchant-fee/deploy \
-H "Content-Type: application/json" \
-H "Authorization: Bearer YOUR_JWT_TOKEN"
This deploys the custom chaincode to the Hyperledger Fabric network, making it available for use by the FractaLedger system.
CLI Deployment
You can deploy chaincode using the Hyperledger Fabric CLI tools. This approach is useful for development and testing.
cd fabric-samples/test-network
./network.sh deployCC -ccn fractaledger-chaincode -ccp /path/to/src/chaincode/custom/my-merchant-fee -ccl javascript
This deploys the custom chaincode to the Hyperledger Fabric network using the Fabric CLI tools.
Automated Deployment
You can set up automated deployment using CI/CD pipelines. This approach is useful for production environments.
Example GitHub Actions workflow:
name: Deploy Chaincode
on:
push:
branches: [ main ]
paths:
- 'src/chaincode/custom/**'
jobs:
deploy:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- name: Set up Node.js
uses: actions/setup-node@v2
with:
node-version: '14'
- name: Install dependencies
run: npm install
- name: Deploy chaincode
run: |
curl -X POST http://your-fractaledger-api/api/chaincode/custom/my-merchant-fee/deploy \
-H "Content-Type: application/json" \
-H "Authorization: Bearer $"
API Extensions
FractaLedger allows you to extend the API with custom endpoints that interact with your chaincode. This is done through API extensions, which are JavaScript modules that register new endpoints with the API server.
Creating an API Extension
You can create an API extension using the generate-api-extension
tool:
npx fractaledger-generate-api-extension --name my-extension --output ./api-extensions
This generates a new API extension file in the ./api-extensions
directory.
Example API Extension
Here's an example API extension that adds endpoints for managing a custom feature:
/**
* My Custom API Extension
*
* This extension adds endpoints for managing a custom feature.
*/
/**
* Register the custom extension with the API server
* @param {Object} app The Express app instance
* @param {Function} authenticateJWT The authentication middleware
* @param {Object} dependencies Additional dependencies (walletManager, fabricClient, etc.)
*/
function registerMyExtension(app, authenticateJWT, dependencies) {
const { walletManager, fabricClient } = dependencies;
/**
* Create a custom feature
* POST /api/custom-feature
*/
app.post('/api/custom-feature', authenticateJWT, async (req, res) => {
try {
const { name, config } = req.body;
if (!name) {
return res.status(400).json({ error: 'Missing required parameters' });
}
// Submit the custom feature to the Fabric network
const result = await fabricClient.submitTransaction(
'createCustomFeature',
name,
JSON.stringify(config || {})
);
const customFeature = JSON.parse(result.toString());
res.json(customFeature);
} catch (error) {
res.status(500).json({ error: error.message });
}
});
/**
* Get custom features
* GET /api/custom-features
*/
app.get('/api/custom-features', authenticateJWT, async (req, res) => {
try {
// Get the custom features from the Fabric network
const result = await fabricClient.evaluateTransaction('getCustomFeatures');
const customFeatures = JSON.parse(result.toString());
res.json(customFeatures);
} catch (error) {
res.status(500).json({ error: error.message });
}
});
}
module.exports = registerMyExtension;
Registering an API Extension
To register your API extension with the FractaLedger system, you need to add it to the api.extensions
array in your config.json
file:
"api": {
"port": 3000,
"host": "localhost",
"extensions": [
{
"module": "./api-extensions/my-extension.js"
}
]
}
This registers your API extension with the FractaLedger API server, making your custom endpoints available for use.
Use Cases
Here are some example use cases for customizing chaincode:
Merchant Fee Collection
Take a percentage fee for facilitating cryptocurrency transfers between customers and merchants.
Use the merchant fee template as a starting point.
Customize the fee calculation logic to fit your fee structure.
Deploy the custom chaincode.
Create an API extension for merchant-specific endpoints.
Employee Payment System
Distribute funds to employees based on predefined rules and schedules.
Use the employee payroll template as a starting point.
Add custom logic for salary calculation and payment scheduling.
Deploy the custom chaincode.
Create an API extension for employee management endpoints.
Investment Fund
Manage fractional ownership of cryptocurrency investments with custom distribution rules.
Use the default template as a starting point.
Add custom logic for investment tracking and profit distribution.
Deploy the custom chaincode.
Create an API extension for investment management endpoints.
Best Practices
Here are some best practices for working with chaincode in FractaLedger:
Use Templates as a Starting Point
Start with one of the provided templates and customize it to fit your specific requirements. This saves time and ensures that you're following best practices for chaincode development.
Keep Chaincode Simple
Chaincode should focus on the core business logic and data storage. Complex calculations or operations should be handled by the API server or client applications.
Test Thoroughly
Test your chaincode thoroughly before deploying it to production. FractaLedger provides testing utilities to help you test your chaincode in a simulated environment.
Use API Extensions
Create API extensions to expose your chaincode functionality through the API server. This provides a clean separation between the API and the chaincode.
Version Your Chaincode
Use version numbers in your chaincode to track changes and ensure compatibility with the rest of the system. This is especially important when upgrading chaincode in a production environment.
Document Your Chaincode
Document your chaincode thoroughly, including the purpose of each function, the expected inputs and outputs, and any side effects. This makes it easier for others to understand and maintain your code.