Transaction Flow from KA to Blockchain

Overview

This document outlines the detailed process flow for how transactions move from ERPNext to Knowledge Assets (KAs) in the Decentralized Knowledge Graph (DKG), and then to the blockchain through smart contracts. Understanding this flow is essential for developers to implement the correct sequence of operations, contract interactions, and data transformations.

The flow described here expands upon the smart contract architecture outlined in the Smart Contract Integration documentation, focusing on the orchestration between systems and the role of ontology in mapping KA data to blockchain transactions.

High-Level Transaction Flow

graph TD
    A[ERPNext] -->|Transaction Data| B[Edge Node]
    B -->|Create Knowledge Asset| C[DKG Network]
    B -->|Notify KA Creation| D[Web Application]
    D -->|Create Smart Contract Transaction| E[Blockchain]
    F[Financier Wallet] -->|Approve Token Transfer| G[Token Management Contract]
    G -->|Record Stake| H[Trade Agreement Contract]
    D -->|Monitor Funding Status| H
    H -->|Emit Financing Complete Event| D
    D -->|Update KA with Status| B
    B -->|Update Knowledge Asset| C

Detailed Process Flow

1. Initial Data Creation in ERPNext

The process begins in the ERPNext system where transaction data is created:

// Example ERPNext purchase order
{
  "transaction_id": "PO-12345",
  "supplier": "Global Shipping Co.",
  "buyer": "Tech Distribution Inc.",
  "products": [
    {
      "sku": "CPU-X7700",
      "quantity": 150,
      "unit_price": 420
    }
  ],
  "total_value": 63000,
  "currency": "USD",
  "required_documents": ["Invoice", "Bill of Lading", "Certificate of Origin"]
}

2. Knowledge Asset Creation in DKG

The ERPNext system sends this data to the Edge Node, which transforms it into a Knowledge Asset:

  1. Data Transformation: The Edge Node applies the appropriate ontology to map ERPNext fields to standardized concepts
  2. Ontology Application: The data is enriched with semantic context from the appropriate ontologies (GS1, Web3, etc.)
  3. KA Creation: A Knowledge Asset is created in the DKG with a unique UAL (Universal Asset Locator)

The ontology plays a critical role here by:

  • Mapping ERPNext fields to standardized GS1 terms
  • Adding Web3-specific properties that will trigger blockchain interactions
  • Defining the relationship between document states and blockchain contract states

Example of KA with ontology applied:

{
  "@context": [
    "https://w3id.org/gs1/epcis",
    "https://skyocean.io/context/web3"
  ],
  "id": "DKG:PONO12345:2023:04:12",
  "type": "PurchaseOrder",
  "buyer": {
    "id": "urn:epc:id:sgln:0614141.00001.0",
    "name": "Tech Distribution Inc.",
    "web3Wallet": "0x1234567890123456789012345678901234567890"
  },
  "seller": {
    "id": "urn:epc:id:sgln:0614142.00001.0",
    "name": "Global Shipping Co.",
    "web3Wallet": "0x2345678901234567890123456789012345678901"
  },
  "orderValue": {
    "value": 63000,
    "currency": "USD",
    "targetFinancingAmount": 50000,
    "financierRewardRate": 350
  },
  "requiredDocuments": ["Invoice", "Bill of Lading", "Certificate of Origin"],
  "pendingWeb3Transaction": {
    "status": "Pending",
    "contractAddress": null,
    "transactionId": null,
    "financingStatus": "NotStarted",
    "currentFinancingAmount": 0,
    "financiers": []
  }
}

3. Transaction Initialization in Blockchain

After the KA is created, the web application is notified and initiates the blockchain transaction:

  1. Web Application Notification: The Edge Node notifies the web application of the new KA
  2. API Trigger: The web application calls the Transaction Creation API
  3. Smart Contract Interaction: The API interacts with the Trade Agreement Contract

API Trigger Sequence

// Web application receives notification
edgeNode.on('knowledgeAssetCreated', async (kaUAL) => {
  // Fetch the KA details
  const kaData = await edgeNode.fetchKnowledgeAsset(kaUAL);
  
  // Extract needed data based on ontology mapping
  const buyerInfo = kaData.buyer.web3Wallet || kaData.buyer.id;
  const sellerAddress = kaData.seller.web3Wallet;
  
  // Determine payment method based on KA data
  const paymentMethod = determinePaymentMethod(kaData);
  
  // Call the Transaction Creation API
  await createTransaction(
    kaUAL,
    buyerInfo,
    sellerAddress,
    paymentMethod,
    kaData.orderValue.targetFinancingAmount,
    kaData.orderValue.financierRewardRate
  );
});

Smart Contract Execution

When the Transaction Creation API is called, multiple smart contracts are involved in the process:

  1. Trade Agreement Contract:
    • Creates a new transaction entry with a unique transaction ID
    • Generates events that other contracts and systems listen for
  2. Document Verification Registry:
    • Registers the new transaction with required documents
    • Sets up document tracking for the transaction
  3. Knowledge Asset Registry:
    • Maps the blockchain transaction ID to the KA UAL
    • Enables bidirectional lookups between systems

4. Transaction Pending Phase

At this point, the transaction exists in both the DKG and blockchain but is in a pending state awaiting financing:

  1. KA Update: The KA is updated with the blockchain transaction ID
  2. Web Application Display: The transaction appears in the web application for financiers to view
  3. Storage: The pending transaction details are stored in:
    • The DKG as part of the Knowledge Asset metadata
    • The blockchain in the Trade Agreement Contract
    • The web application’s database for quick access

5. Financier Participation

When financiers decide to participate, the following process occurs:

  1. Token Flow:
    • Financiers initially hold tokens in their personal wallets
    • They approve token transfers to the Token Management System contract
    • The web application facilitates this by calling the appropriate APIs
  2. Smart Contract Interaction Sequence:
    Financier Wallet → Token Management System → Trade Agreement Contract
    
  3. Contract Execution:
    • The Token Management System first records the staked tokens
    • The Trade Agreement Contract then records the financier’s participation and expected return
    • If the funding target is reached, the contract state automatically transitions to “FinancingSecured”

Token Approval and Staking Process

// Web application code to facilitate financier participation
async function participateInTransaction(transactionId, financierWallet, amount) {
  // 1. Get token contract instance
  const tokenContract = await getTokenContract();
  
  // 2. Financier approves tokens to be transferred to Token Management System
  await tokenContract.approve(tokenManagementAddress, amount, {
    from: financierWallet
  });
  
  // 3. Call the Financier Participation API
  await addFinancierToTransaction(transactionId, financierWallet, amount);
}

6. Automated State Transition

Once the financing target is reached, a chain of contract interactions occurs automatically:

  1. Contract State Change:
    • Trade Agreement Contract updates transaction state to “FinancingSecured”
    • Contract emits a FinancingCompleted event
  2. Event-Driven APIs:
    • Web application listens for the FinancingCompleted event
    • When detected, it triggers an API call to update the KA in the DKG
  3. Multi-Contract Coordination:
    • Trade Agreement Contract: Manages the overall transaction state
    • Token Management System: Holds the staked tokens
    • Document Verification Registry: Ready to receive document references
// Event listener in web application
tradeAgreementContract.on("FinancingCompleted", async (transactionId, totalAmount) => {
  // 1. Get the Knowledge Asset UAL
  const kaRegistry = await getKnowledgeAssetRegistry();
  const knowledgeAssetUAL = await kaRegistry.getKnowledgeAssetForTransaction(transactionId);
  
  // 2. Update the Knowledge Asset with new status
  await updateKnowledgeAssetWithFinancingCompleted(knowledgeAssetUAL, totalAmount);
  
  // 3. Notify relevant parties
  notifyFinancingCompleted(knowledgeAssetUAL, transactionId, totalAmount);
});

7. Ontology-Driven Document Processing

As the transaction progresses to document submission, the ontology plays a crucial role:

  1. Ontology Mapping:
    • The KA uses ontology to map document types and statuses to blockchain concepts
    • This ensures interoperability between the DKG and blockchain systems
  2. Document State Tracking:
    • Documents are verified in the DKG based on business rules defined in the ontology
    • When document status changes in the DKG, the blockchain is updated to reflect this
  3. Smart Contract Update:
    • Document Verification Registry contract records the verification status
    • Trade Agreement Contract updates transaction state based on document verification

Ontology-Based Document Mapping

The ontology defines:

  • How document types in the KA map to document types expected by the smart contract
  • Which document states in the KA correspond to “verified” in the blockchain
  • The relationship between all documents being verified and the transaction being ready for payment
// Example of ontology mapping for documents
{
  "@context": {
    "skyocean": "https://skyocean.io/context/",
    "dkg": "https://dkg.io/context/"
  },
  "@type": "skyocean:DocumentMapping",
  "documentTypes": {
    "Invoice": {
      "blockchainIdentifier": "INV",
      "requiredForPayment": true,
      "verificationStates": {
        "Approved": "Verified",
        "Rejected": "Invalid",
        "Pending": "Unverified"
      }
    },
    "BillOfLading": {
      "blockchainIdentifier": "BOL",
      "requiredForPayment": true,
      "verificationStates": {
        "Approved": "Verified",
        "Rejected": "Invalid",
        "Pending": "Unverified"
      }
    }
  }
}

Full Transaction Lifecycle

The complete lifecycle of a transaction flows through these states:

  1. Creation: KA created in DKG → Transaction created in blockchain
  2. Financing: Financiers stake tokens → Financing target reached
  3. Document Processing: Documents uploaded to DKG → Verified in DKG → Verification recorded in blockchain
  4. Payment: Payment conditions met → Payment executed (on-chain or off-chain)
  5. Completion: Tokens released to financiers → Transaction marked complete

Throughout this process, the ontology ensures that the data in the KA is correctly interpreted by the blockchain contracts, and the API layer orchestrates the interactions between systems.

Implementation Considerations

1. Event-Driven Architecture

The transaction flow is fundamentally event-driven, with systems reacting to changes in other systems:

  • DKG events trigger blockchain updates
  • Blockchain events trigger DKG updates
  • Both trigger web application updates

Implement robust event listeners and queues to ensure reliable processing.

2. Ontology Management

Maintain a clean and well-defined ontology that maps:

  • ERPNext fields to KA properties
  • KA properties to blockchain contract parameters
  • Document states in the KA to verification states in blockchain

The ontology is the “translation layer” that enables these disparate systems to communicate.

3. Error Handling and Recovery

Build resilient error handling for:

  • Failed API calls
  • Blockchain transaction reversions
  • DKG network issues
  • Inconsistent states between systems

Include mechanisms to retry operations and reconcile state between systems.

4. API Orchestration

The API layer serves as the conductor for this complex process:

  • Transaction Creation API: Initializes the blockchain transaction
  • Financier Participation API: Manages token staking
  • Document Submission API: Handles document references
  • Document Verification API: Records verification from DKG to blockchain
  • Payment Processing API: Manages payment execution
  • Event Listening API: Monitors for key state changes

Conclusion

The transaction flow from KA to blockchain is a sophisticated orchestration of multiple systems, with the DKG providing rich data storage and semantics, the blockchain providing immutable transaction records and enforcement, and the web application coordinating the interactions between them.

By understanding this flow, developers can implement the correct sequence of API calls, contract interactions, and data transformations needed to create a seamless experience for users of the SKYOCEAN platform.

The key to successful implementation lies in adherence to the defined ontology, proper event handling, and robust API orchestration between the systems.