Skip to content

FeverTokens/vlei-trade-finance-protocol

vLEI Trade Finance Protocol

Real-World Identity Meets On-Chain Assets: Institutional-Grade Trade Finance with Zero-Trust vLEI Verification


The Vision

Our protocol brings institutional-grade identity and security to the world of digital assets. We've built a decentralized system for issuing and managing promissory notes, where every action is authorized by a cryptographically secure, GLEIF-verified vLEI credential. This bridges the gap between the established legal framework of global trade and the efficiency of blockchain, creating a truly trustless and compliant financial instrument.


Core Innovation: Zero-Trust, Real-Time vLEI Verification

To ensure the highest level of security, our system abandons insecure practices like offline credential caching. Instead, we use Chainlink Functions to perform real-time, authoritative validation directly against GLEIF's vLEI data sources for every single privileged action. This zero-trust model provides critical security guarantees:

Security Guarantees

  • Eliminates Credential Theft: Only the legitimate holder of an Official Organizational Role (OOR) credential, proven via a KERI signature, can authorize actions.
  • Prevents Replay Attacks: A nonce-based system ensures that a signature cannot be intercepted and reused.
  • Guarantees Role-Based Authorization: The protocol checks that the user's verified role (e.g., "CFO" or "Authorized Signatory") has the specific permissions required for the requested action.
  • Ensures Credential Liveness: The system verifies that the vLEI credential is "active" and has not been revoked or expired.

How It Works

User (KERI Identity)
    ↓ Signs authorization with KERI private key
    ↓ (includes: action, nonce, challenge)
Relayer Service
    ↓ Submits transaction (pays gas)
    ↓
Smart Contract
    ↓ Stores pending action
    ↓ Generates unique challenge
    ↓
Chainlink Functions
    ↓ Executes JavaScript validator
    ↓ POST → GLEIF API (https://gleif-web.vercel.app/api/v1/oor)
    ↓
GLEIF vLEI API
    ↓ Validates KERI signature
    ↓ Verifies credential status
    ↓ Returns: isValid, LEI, role, status
    ↓
Chainlink Callback
    ↓ Validates response
    ↓ Checks role permissions
    ↓ Increments nonce (prevents replay)
    ↓ Executes pending action
    ↓
Action Completes

No credential caching. No trust assumptions. Every operation validated at the source.


Designed for Adoption: A Seamless, Gasless Experience

For this technology to be adopted by legal and finance professionals, it must be seamless. Our gasless implementation allows corporate representatives to interact with the protocol using their existing KERI identities—the same ones they already use for credential management.

Users sign authorizations with their familiar tools, without ever needing to:

  • Install a crypto wallet
  • Acquire tokens
  • Pay gas fees

A background relayer system sponsors the on-chain transaction, creating a user experience that is both intuitive and powerful, removing the most significant barriers to enterprise adoption.

User Experience Benefits

Traditional Blockchain vLEI Trade Finance Protocol
Install wallet software Use existing KERI identity
Buy ETH for gas Zero gas costs (relayer pays)
Manage private keys Sign with familiar KERI tools
~$1-5 per transaction Free for users
Complex UX Familiar signing workflow

Built for Institutional Finance: Security is the Priority

Executing a real-time vLEI validation for every on-chain operation introduces a deliberate trade-off of cost (~$1.00) and latency (~30-60 seconds). For the world of institutional trade finance, this is not a drawback—it's a feature.

The ability to enforce real-time compliance and instantly respect credential revocations is a critical security requirement. For high-value assets like promissory notes, the negligible validation fee is a small price to pay for unparalleled, source-of-truth security.

Why Real-Time Validation Matters

Scenario: Credential Revocation

Without real-time validation:

  • Employee is terminated at 9:00 AM
  • Credential revoked at 9:05 AM
  • Malicious employee uses cached credential at 9:10 AM
  • Fraudulent transaction succeeds ❌

With real-time validation:

  • Employee is terminated at 9:00 AM
  • Credential revoked at 9:05 AM
  • Malicious employee attempts transaction at 9:10 AM
  • GLEIF API returns status: "revoked"
  • Transaction rejected instantly ✅

Key Features

✅ GLEIF vLEI Integration (Zero-Trust)

  • Real-time verification via Chainlink Functions on every operation
  • KERI signature validation by GLEIF API (no on-chain verification needed)
  • Nonce-based replay protection (per holderAID)
  • Role-based authorization (ISO 5009 standard roles: CFO, Treasurer, Finance Officer, etc.)
  • Challenge binding prevents cross-chain, cross-contract, and parameter manipulation attacks
  • No credential caching for maximum security

✅ Gasless User Experience (ERC-2771)

  • Users sign with KERI identities (no wallet needed)
  • Relayer pays all transaction fees
  • Zero-friction onboarding for financial institutions
  • Familiar workflow for credential holders

✅ Full Promissory Note Lifecycle

  • Creation, issuance, endorsement
  • Transfer with holder control
  • Pledge management and freezing
  • Presentment for payment and settlement
  • Complete evidence and audit trail

✅ Package-Oriented Framework

  • Strict package boundaries for interface, storage, internal logic, and delegation
  • Single-note model composed from reusable packages
  • Efficient package reuse across deployments via a lightweight Diamond router
  • ERC-7201 namespaced storage per package

✅ Security & Compliance

  • Reentrancy protection on all state-changing functions
  • Immutable audit trail
  • Support for multiple legal frameworks (French, English, UNCITRAL, Singapore)

Architecture

Package-Oriented Framework

All contracts follow the FeverTokens Package-Oriented Framework, which layers strict package rules on top of the EIP-2535 Diamond router. Every package ships five files so that interfaces, storage, and logic stay isolated and auditable.

File Purpose
IMyPackageInternal.sol File-scope enums/structs and the internal-only interface, including events/errors
IMyPackage.sol External interface that inherits the internal interface and declares every selector
MyPackageStorage.sol ERC-7201 namespaced storage layout with a dedicated layout() accessor
MyPackageInternal.sol Internal functions (all _-prefixed) that implement reusable logic
MyPackage.sol External delegation layer that wires public entry points to the internal functions

Compliance snapshot

  • No package mixes interface, storage, and logic responsibilities.
  • External contracts inherit the interface plus their internal counterpart and delegate immediately.
  • All state reads/writes flow through the storage layout helper.
  • Packages can be added, removed, or upgraded independently while staying ABI-stable.

This structure lets us version, audit, and reuse packages across multiple note deployments while keeping each Diamond proxy extremely thin.

vLEI Authentication Layer (Zero-Trust Core)

The vLEIAuth package is the heart of the protocol, providing cryptographic proof of organizational authority for every privileged action.

Key Components:

  1. KERI Signature Validation (vLEIAuthInternal.sol:611-661)

    • User signs challenge with KERI private key
    • Challenge binds: action type, parameters, chain ID, contract address, user AID, and nonce
    • Prevents replay, cross-chain, and parameter manipulation attacks
  2. Chainlink Functions Integration (vLEIAuthInternal.sol:676-781)

    • JavaScript validator executes off-chain
    • Calls GLEIF API: POST https://gleif-web.vercel.app/api/v1/oor
    • Request: {holderAID, credentialSAID, signature, challenge}
    • Response: {isValid, lei, role, status}
  3. Role-Based Authorization (vLEIAuthInternal.sol:435-570)

    • ISO 5009 standard organizational roles
    • Permission mapping: CFO, Treasurer, Finance Officer, Controller, Authorized Signatory, Admin, Legal Officer
    • Granular permissions: canIssueNotes, canEndorse, canPresent, canFreeze, canRevoke
  4. Pending Action Execution (vLEIAuthInternal.sol:849-917)

    • Action stored during validation request
    • Executed via delegatecall after successful validation
    • Single-use authorization token (consumed immediately)
    • Nonce incremented before execution (reentrancy protection)

Supported Roles:

Role Issue Notes Endorse Present Freeze Revoke
CFO
TREASURER
FINANCE_OFFICER
CONTROLLER
AUTHORIZED_SIGNATORY
ADMIN
LEGAL_OFFICER

Single-Note Package-Oriented Deployment

Each promissory note is a Diamond proxy that simply routes to FeverTokens packages:

  • Contract address = Note ID (no global registries)
  • Composable packages provide functionality and can be versioned independently
  • Isolated state per package via ERC-7201 storage namespaces
  • Shared implementation across all note deployments through package reuse

Core Packages

Each package is shipped with the five-file structure above, so storage, interfaces, and logic remain auditable and hot-swappable across note deployments.

Package Purpose vLEI Integration
vLEIAuth GLEIF credential validation, role-based authorization Core authentication layer
NoteCore Note creation, lifecycle, maturity calculations Validates issuer/maker credentials
ControlRegistry Exclusive holder management, transfers, pledges Validates holder credentials on transfers
Endorsement Negotiability, endorsement chains, blank/special endorsements Validates endorser credentials
Presentment Payment presentment, acceptance, settlement, dishonor Validates presenter/maker credentials
Evidence Document storage, audit trails, IPFS references Records vLEI validation events

Gasless Infrastructure (ERC-2771)

User (KERI Identity)
    ↓ Signs authorization with KERI private key
    ↓ Submits to relayer (off-chain)
Relayer Service
    ↓ Validates signature structure
    ↓ Pays gas fees for user
    ↓ Submits to TrustedForwarder
TrustedForwarder (ERC-2771)
    ↓ Extracts real sender from calldata
    ↓ Forwards to target contract
Smart Contracts (Packages)
    ↓ Stores pending action
    ↓ Requests vLEI validation
Chainlink Functions
    ↓ Executes JavaScript validator
    ↓ Calls GLEIF API
    ↓ Returns validation result
Smart Contract (Callback)
    ↓ Validates response
    ↓ Checks role permissions
    ↓ Executes pending action
    ✓ Action completes with full audit trail

Key Innovation: Users never need wallets or gas tokens. They authenticate with the same KERI identities used for vLEI credential management.


Quick Start

Prerequisites

  • Node.js >= 18.x
  • npm >= 9.x
  • Hardhat

Installation

# Install dependencies
npm install

# Compile contracts
npx hardhat compile

# Run tests
npm test

# Run tests with coverage
npm run test:coverage

Deployment

1. Deploy Gasless Infrastructure (One-Time Setup)

Deploy the ERC-2771 TrustedForwarder for gasless transactions:

npx hardhat run scripts/deploy-gasless-system.ts --network sepolia

2. Deploy vLEI-Enabled Note Packages

Each promissory note is a separate package-oriented Diamond deployment with vLEI authentication:

npx hardhat run scripts/deploy-sepolia.ts --network sepolia

This deploys:

  • vLEIAuth package: Real-time GLEIF verification
  • NoteCore package: Note lifecycle management
  • ControlRegistry package: Holder control and transfers
  • Endorsement package: Endorsement chains
  • Presentment package: Payment presentment
  • Evidence package: Audit trail storage
  • Diamond router: Combines all packages

Key Configuration:

// Chainlink Functions Router (Sepolia)
const FUNCTIONS_ROUTER = "0xb83E47C2bC239B3bf370bc41e1459A34b41238D0";

// Deploy vLEIAuth with Chainlink integration
const vLEIAuth = await VLEIAuthFactory.deploy(
  FUNCTIONS_ROUTER,
  trustedForwarderAddress
);

3. Configure Chainlink Functions for vLEI Validation

Set up Chainlink subscription to enable real-time GLEIF API calls:

# Create Chainlink Functions subscription
npx hardhat functions-sub-create --network sepolia

# Fund subscription with LINK tokens
# Note: Each vLEI validation costs ~0.1 LINK ($0.10-$1.00)
npx hardhat functions-sub-fund --subid <SUB_ID> --amount 10 --network sepolia

# Add your deployed contract as authorized consumer
npx hardhat functions-sub-add --subid <SUB_ID> --contract <DIAMOND_ADDRESS> --network sepolia

Set subscription on contract:

const diamond = await ethers.getContractAt("vLEIAuth", diamondAddress);
await diamond.setSubscriptionId(SUB_ID);
await diamond.setCallbackGasLimit(300000); // Default: 300k gas

4. Configure GLEIF API Endpoint (Optional)

The default GLEIF API endpoint is https://gleif-web.vercel.app/api/v1/oor. To use a custom endpoint:

// If you have a custom GLEIF API deployment
await diamond.setGLEIFApiUrl("https://your-gleif-api.com/api/v1/oor");

5. Test vLEI Integration

Verify your vLEI authentication setup:

# Run KERI integration test
npx hardhat run scripts/test-sepolia-keri.ts --network sepolia

This test:

  • Creates KERI AIDs for issuer and holder
  • Signs challenges with KERI signatures
  • Submits vLEI validation requests
  • Verifies Chainlink callback execution
  • Confirms action execution after validation

Usage Example: vLEI-Validated Promissory Note Lifecycle

Step 1: Create a Promissory Note with vLEI Authorization

The maker's CFO signs the issuance authorization with their KERI identity. The system validates their vLEI credential in real-time before issuing the note.

// 1. Initialize KERI client (Signify-TS)
const makerClient = await initializeKERIClient("maker-corp");
const makerAID = await makerClient.identifiers().get("maker-aid");

// 2. Prepare note parameters
const noteParams = {
  version: "ePN-FR/1.0",
  makerLEI: "5493001KJTIIGC8Y1R12",           // Maker's legal entity
  payeeLEI: "549300UXZBWSH104NX42",           // Payee's legal entity
  faceValue: {
    amount: 100000n,                          // €100,000
    currencyCode: "0x455552"                  // EUR
  },
  maturity: {
    convention: 0,                            // DATE
    date: Math.floor(Date.now() / 1000) + (90 * 24 * 60 * 60), // 90 days
    tenorDays: 0,
    sightTimestamp: 0
  },
  placeOfPayment: "Paris",
  placeOfIssuance: "Paris",
  governingLaw: 0,                            // FRENCH
  termsHash: ethers.keccak256(ethers.toUtf8Bytes("note-terms-v1")),
  invoiceRef: ethers.keccak256(ethers.toUtf8Bytes("INV-2024-001")),
  purchaseOrderRef: ethers.keccak256(ethers.toUtf8Bytes("PO-2024-001"))
};

// 3. Prepare vLEI authorization
const actionData = ethers.AbiCoder.defaultAbiCoder().encode(
  ["tuple(string version, string makerLEI, string payeeLEI, ...)"],
  [noteParams]
);

const holderAID = makerAID.prefix;                    // KERI AID
const credentialSAID = "EBfKQpUOUvNhYjzP2Q0L9K2N...";  // OOR credential SAID
const expectedLEI = "5493001KJTIIGC8Y1R12";           // Maker's LEI
const nonce = await diamond.getNonce(holderAID);      // Get current nonce

// 4. Generate challenge and sign with KERI
const challenge = {
  action: "ISSUE_NOTE",
  actionData: actionData,
  chainId: 11155111,                          // Sepolia
  contract: diamondAddress,
  holderAID: holderAID,
  nonce: nonce
};

const challengeMessage = JSON.stringify(challenge);
const keriSignature = await makerClient.sign(
  makerAID.name,
  Buffer.from(challengeMessage).toString("base64")
);

// 5. Submit vLEI-validated issuance request (gasless!)
const tx = await diamond.requestActionWithKERI(
  "ISSUE_NOTE",
  actionData,
  holderAID,
  credentialSAID,
  keriSignature,
  expectedLEI,
  nonce
);

console.log("✓ vLEI validation request submitted");
console.log("⏳ Waiting for Chainlink callback (30-60 seconds)...");

// 6. Wait for Chainlink callback
const receipt = await tx.wait();
const requestId = receipt.logs[0].args.requestId;

// 7. Listen for validation result
diamond.on("CredentialValidationFulfilled", (reqId, isValid, lei, role) => {
  if (reqId === requestId) {
    console.log("✓ vLEI validation completed");
    console.log(`  - Valid: ${isValid}`);
    console.log(`  - LEI: ${lei}`);
    console.log(`  - Role: ${role}`);
    console.log("✓ Note issued successfully!");
  }
});

What happens during validation:

  1. Smart contract stores pending action
  2. Chainlink Functions calls GLEIF API with KERI signature
  3. GLEIF validates signature, credential status, and role
  4. Chainlink returns result to smart contract
  5. Smart contract checks role has canIssueNotes permission
  6. If valid, executes issueNote() automatically
  7. Nonce incremented to prevent replay

Step 2: Endorse Note with vLEI Authorization

The current holder's Authorized Signatory endorses the note to transfer it:

// 1. Get holder's KERI identity
const holderClient = await initializeKERIClient("holder-corp");
const holderAID = await holderClient.identifiers().get("holder-aid");

// 2. Prepare endorsement parameters
const endorsementParams = {
  endorsementType: 1,                         // SPECIAL (named endorsee)
  newHolderLEI: "549300NEWHOLDERXXX123",
  endorsementText: "For value received"
};

const actionData = ethers.AbiCoder.defaultAbiCoder().encode(
  ["uint8", "string", "string"],
  [endorsementParams.endorsementType, endorsementParams.newHolderLEI, endorsementParams.endorsementText]
);

// 3. Sign and submit (gasless)
const nonce = await diamond.getNonce(holderAID.prefix);
const keriSignature = await signKERIChallenge(holderClient, holderAID, {
  action: "ENDORSE",
  actionData,
  nonce
});

await diamond.requestActionWithKERI(
  "ENDORSE",
  actionData,
  holderAID.prefix,
  holderCredentialSAID,
  keriSignature,
  currentHolderLEI,
  nonce
);

console.log("✓ Endorsement validated and executed");

Step 3: Present for Payment

At maturity, the holder presents the note for payment:

// 1. Prepare presentment
const presentmentParams = {
  presenterLEI: holderLEI,
  draweeClass: 0,                             // MAKER
  draweeLEI: makerLEI,
  faceValue: {
    amount: 100000n,
    currencyCode: "0x455552"
  },
  maturity: { /* same as issuance */ }
};

const actionData = ethers.AbiCoder.defaultAbiCoder().encode(
  ["tuple(string presenterLEI, uint8 draweeClass, ...)"],
  [presentmentParams]
);

// 2. Sign and submit presentment (gasless)
const nonce = await diamond.getNonce(holderAID.prefix);
const keriSignature = await signKERIChallenge(holderClient, holderAID, {
  action: "PRESENT_NOTE",
  actionData,
  nonce
});

await diamond.requestActionWithKERI(
  "PRESENT_NOTE",
  actionData,
  holderAID.prefix,
  holderCredentialSAID,
  keriSignature,
  holderLEI,
  nonce
);

console.log("✓ Note presented for payment");

Step 4: Settle Payment

The maker settles the presented note:

// 1. Prepare settlement
const settlementParams = {
  presentmentId: 1,
  settlementMethod: 0,                        // WIRE_TRANSFER
  paymentProof: ethers.keccak256(ethers.toUtf8Bytes("TXN-2024-12345"))
};

const actionData = ethers.AbiCoder.defaultAbiCoder().encode(
  ["uint256", "uint8", "bytes32"],
  [settlementParams.presentmentId, settlementParams.settlementMethod, settlementParams.paymentProof]
);

// 2. Sign and submit settlement (gasless)
const nonce = await diamond.getNonce(makerAID.prefix);
const keriSignature = await signKERIChallenge(makerClient, makerAID, {
  action: "SETTLE",
  actionData,
  nonce
});

await diamond.requestActionWithKERI(
  "SETTLE",
  actionData,
  makerAID.prefix,
  makerCredentialSAID,
  keriSignature,
  makerLEI,
  nonce
);

console.log("✓ Payment settled");
console.log("✓ Promissory note lifecycle complete");

Key Points:

  • Every operation validated in real-time against GLEIF API
  • Users never need wallets or gas tokens
  • All signatures use KERI identities (same as vLEI credential management)
  • Complete audit trail of all vLEI validations
  • Nonce-based replay protection
  • Role-based authorization enforced automatically

Testing

Test Status

⚠️ Tests are currently being rebuilt following recent architecture refactoring.

The test suite is being redesigned to reflect:

  • Zero-trust vLEI validation architecture
  • Single-note package-oriented Diamond model
  • Gasless meta-transaction flows
  • Real GLEIF API integration

Run Tests

# Compile contracts
npm run compile

# Run tests (when available)
npm test

# With coverage
npm run test:coverage

Cost Analysis & Trade-offs

Deployment Costs

Contract Gas % of Block Deployment Cost (20 gwei)
vLEIAuth ~5,500,000 18.3% ~$20 (one-time)
NoteCore 5,261,827 17.5% ~$19 (one-time)
ControlRegistry 4,541,831 15.1% ~$16 (one-time)
Presentment 4,412,752 14.7% ~$16 (one-time)
Endorsement 4,232,947 14.1% ~$15 (one-time)
Evidence 3,785,969 12.6% ~$14 (one-time)
TrustedForwarder 869,900 2.9% ~$3 (one-time)
Total per note ~28M gas ~93% ~$103

vLEI Validation Costs (Per Operation)

Cost Component Amount Payer Notes
Chainlink Functions 0.1 LINK ($0.10-$1.00) Relayer GLEIF API call + callback
Gas for callback 300k gas ($1.08 @ 20 gwei) Relayer Chainlink fulfillment
Gas for user request 150k gas ($0.54 @ 20 gwei) Relayer (gasless) Initiate validation
Total per validation ~$1.72-$2.62 Relayer User pays $0

Gasless Transaction Benefits

Operation Traditional Cost (User) With Gasless (User) Relayer Cost User Savings
Issue Note + vLEI Validation ~$5-7 $0 ~$2.62 100%
Endorse Note + vLEI Validation ~$4-6 $0 ~$2.62 100%
Present for Payment + vLEI Validation ~$4-6 $0 ~$2.62 100%
Settle Payment + vLEI Validation ~$3-5 $0 ~$2.62 100%

Cost-Benefit Analysis for Institutional Finance

Traditional Blockchain:

  • User pays gas (~$5 per transaction)
  • Credentials cached on-chain (security risk)
  • Credential revocation may not be respected instantly
  • High-value notes at risk if credential compromised

vLEI Trade Finance Protocol:

  • User pays $0 (relayer sponsors)
  • Real-time validation against GLEIF API ($2.62 per operation)
  • Instant credential revocation enforcement
  • Zero-trust security model

For a €100,000 promissory note:

  • Validation cost: ~$2.62
  • Security benefit: Instant revocation, real-time compliance
  • Cost as % of note value: 0.0026%

Verdict: For high-value institutional finance, the negligible validation fee is a small price to pay for maximum security and compliance.

Latency Considerations

Operation Latency Reason
Traditional blockchain transaction ~15 seconds Block confirmation
vLEI-validated transaction ~30-60 seconds + Chainlink callback

For institutional trade finance:

  • Traditional promissory notes: days to weeks for verification
  • vLEI protocol: ~1 minute with cryptographic proof
  • Still 1000x faster than traditional processes

Documentation

📚 Complete Documentation

The docs/ folder contains comprehensive documentation:

🎯 Quick Navigation


Project Structure

vlei-trade-finance-protocol/
├── contracts/
│   ├── core/              # NoteCore package
│   ├── control/           # ControlRegistry package
│   ├── endorsement/       # Endorsement package
│   ├── presentment/       # Presentment package
│   ├── evidence/          # Evidence package
│   ├── vlei/              # vLEI authentication
│   ├── gasless/           # ERC-2771 infrastructure
│   └── libraries/         # Utility libraries
├── test/                  # Test suite
├── scripts/               # Deployment scripts
├── docs/                  # Documentation
└── typechain-types/       # Generated TypeScript types

Smart Contract Specifications

Supported Features

  • Maturity Types: Fixed date, days after sight, at sight
  • Currencies: ISO 4217 codes (EUR, USD, GBP, etc.)
  • Governing Laws: French, English, UNCITRAL, Singaporean
  • Endorsement Types: Blank (bearer), Special (named endorsee), Restrictive
  • Settlement Methods: Wire transfer, check, digital payment, cash, offset

Legal Compliance

The protocol supports multiple legal frameworks for promissory notes:

  • French Commercial Code (Articles L511-1 to L512-7)
  • Bills of Exchange Act 1882 (UK)
  • UNCITRAL Convention on International Bills of Exchange
  • Singapore Bills of Exchange Act

Security Considerations

vLEI Zero-Trust Security Model

The protocol implements multiple layers of security through its vLEI integration:

1. Eliminates Credential Theft

Problem: Traditional systems cache credentials, allowing stolen credentials to be used until expiration.

Solution: Real-time GLEIF API validation on every operation.

// No on-chain credential storage
// No credential caching
// Every action requires live GLEIF validation
function _requestKERIValidation(...) internal {
    // Chainlink Functions calls GLEIF API in real-time
    _sendRequest(donId, source, args, subscriptionId, callbackGasLimit);
}

Security Guarantee: Only the legitimate holder of the KERI private key can generate valid signatures.

2. Prevents Replay Attacks

Problem: Attacker intercepts a valid signature and reuses it.

Solution: Nonce-based challenge system.

// Each holder has a unique nonce
mapping(string => uint256) holderNonces;

// Challenge binds all critical parameters
bytes32 challenge = keccak256(abi.encodePacked(
    actionType,      // Prevents action type substitution
    actionData,      // Prevents parameter manipulation
    block.chainid,   // Prevents cross-chain replay
    address(this),   // Prevents cross-contract replay
    holderAID,       // Binds to specific user
    nonce            // Prevents same-chain replay
));

// Nonce incremented before execution (prevents reentrancy)
_incrementNonce(action.holderAID);

Security Guarantee: Each signature can only be used once, for one specific action, on one specific chain and contract.

3. Guarantees Role-Based Authorization

Problem: Not all employees should have all permissions.

Solution: ISO 5009 standard role-based permissions validated by GLEIF.

// Role permissions validated against GLEIF response
function _checkRolePermission(string memory role, string memory actionType)
    internal view returns (bool)
{
    RolePermissions memory perms = _getHardcodedRolePermissions(role);

    if (keccak256(bytes(actionType)) == keccak256("ACTION_ISSUE_NOTE")) {
        return perms.canIssueNotes;  // Only CFO, Treasurer, etc.
    }
    // ... role-specific checks
}

Security Guarantee: Users can only perform actions authorized for their specific organizational role.

4. Ensures Credential Liveness

Problem: Revoked or expired credentials should not work.

Solution: Real-time status check via GLEIF API.

// GLEIF API returns credential status
function _validateAndAuthorizeOOR(bytes32 requestId, OORVerificationResult memory result)
    internal returns (bool)
{
    // Check credential status is "active"
    if (keccak256(bytes(result.status)) != keccak256("active")) {
        emit ValidationFailed(requestId, credentialHash, "credential not active");
        return false;
    }
}

Security Guarantee: Revoked credentials are rejected immediately (no waiting for cache expiry).

5. Single-Use Authorization Token

Problem: Authorization context could be reused within a transaction.

Solution: One-time authorization token consumed immediately.

modifier onlyWhenAuthorizedForLEI(string memory lei) {
    bytes32 requiredLEIHash = keccak256(bytes(lei));

    // Check authorization exists
    require(l.authorizedLEIHash == requiredLEIHash, "not authorized");

    // Consume authorization immediately
    l.authorizedLEIHash = bytes32(0);

    _;
}

Security Guarantee: Authorization cannot be reused, even within the same transaction.

Additional Security Protections

Reentrancy guards on all state-changing functions ✅ Input validation (LEI format, amounts, dates) ✅ Transfer restrictions (pledge/freeze states) ✅ Immutable audit trail via Evidence package ✅ ERC-2771 meta-transaction security (signature verification) ✅ Package-oriented Diamond upgradeability (controlled upgrades without state loss) ✅ ERC-7201 namespaced storage (prevents storage collisions)

Attack Vectors Mitigated

Attack Mitigation
Credential theft Real-time GLEIF validation (no caching)
Replay attack Nonce + challenge binding
Cross-chain replay Challenge includes chainId
Cross-contract replay Challenge includes contract address
Parameter manipulation Challenge includes action data
Unauthorized actions Role-based permissions from GLEIF
Revoked credential use Real-time status check
Front-running Nonce prevents signature reuse
Reentrancy Guards + single-use authorization
Storage collision ERC-7201 namespaced storage

Known Limitations

⚠️ Chainlink dependency: System relies on Chainlink Functions availability ⚠️ GLEIF API dependency: Downtime would prevent validations ⚠️ Latency: 30-60 second validation time (acceptable for trade finance) ⚠️ Cost: ~$2.62 per validation (acceptable for high-value notes)

Audit Status

⚠️ Not yet audited - This is experimental software under active development.

Do not use in production without:

  • Professional security audit (smart contracts + Chainlink integration)
  • Comprehensive integration testing with real vLEI credentials
  • Legal review for your jurisdiction
  • Penetration testing of relayer infrastructure
  • Incident response plan for Chainlink/GLEIF outages

Contributing

Development Setup

  1. Fork the repository
  2. Create a feature branch: git checkout -b feature/my-feature
  3. Make your changes
  4. Run tests: npm test
  5. Commit: git commit -m "Add my feature"
  6. Push: git push origin feature/my-feature
  7. Open a Pull Request

Code Style

  • Follow existing code structure
  • Use package-oriented architecture
  • Include NatSpec documentation
  • Write comprehensive tests
  • Update documentation

License

Apache License 2.0 - See LICENSE file for details


Support & Resources

Documentation

  • Architecture docs in docs/ folder
  • Test documentation in test/README.md
  • Inline NatSpec in contracts

External Resources

Community

  • Report issues on GitHub
  • Contribute via Pull Requests

Roadmap

Completed ✅

vLEI Integration (Core Innovation)

  • Zero-trust real-time vLEI validation via Chainlink Functions
  • KERI signature validation through GLEIF API
  • Nonce-based replay protection
  • Role-based authorization (ISO 5009 standard)
  • Challenge binding (prevents cross-chain, cross-contract, parameter attacks)
  • Single-use authorization token pattern
  • Credential liveness checking (instant revocation enforcement)

Smart Contract Architecture

  • Single-note package-oriented Diamond architecture (EIP-2535)
  • Six core packages: vLEIAuth, NoteCore, ControlRegistry, Endorsement, Presentment, Evidence
  • ERC-7201 namespaced storage (prevents collisions)
  • Reentrancy protection and security hardening
  • Support for multiple legal frameworks (French, English, UNCITRAL, Singapore)

Gasless User Experience

  • ERC-2771 TrustedForwarder implementation
  • KERI-based authentication (no wallet required)
  • Meta-transaction relayer infrastructure design
  • Complete gasless transaction flow

Documentation & Tooling

  • Comprehensive README with vLEI focus
  • Architecture documentation
  • Security documentation
  • Deployment guides (Sepolia)
  • KERI integration test scripts
  • TypeScript type generation

In Progress 🚧

Testing & Validation

  • Test suite rebuild (post-refactoring)
  • Real vLEI credential integration testing with live GLEIF API
  • End-to-end lifecycle testing (issue → endorse → present → settle)
  • Chainlink Functions stress testing

Infrastructure

  • Relayer service deployment (Sepolia)
  • Monitoring and alerting for Chainlink callbacks
  • GLEIF API fallback/redundancy strategy

Planned 📋

Security & Production Readiness

  • Professional security audit (smart contracts + Chainlink integration)
  • Penetration testing of relayer infrastructure
  • Gas optimization (reduce callback costs)
  • Incident response plan for Chainlink/GLEIF outages
  • Multi-signature support for admin functions

Deployment & Adoption

  • Testnet deployment (Sepolia) with real institutions
  • Pilot program with trade finance institutions
  • Mainnet deployment (Ethereum)
  • L2 deployment (Optimism, Arbitrum) for lower costs

User Experience

  • Frontend interface (web application)
  • KERI wallet integration (Signify browser extension)
  • Real-time vLEI validation status dashboard
  • Audit trail explorer

Advanced Features

  • ISO 20022 payment reference integration
  • Cross-chain bridge support
  • Batch validation for multiple notes
  • Delegated authorization (sub-credentials)
  • Privacy-preserving vLEI validation (zk-proofs)

Summary

The vLEI Trade Finance Protocol represents a fundamental shift in how institutional finance can leverage blockchain technology. By combining:

  • Zero-trust vLEI verification (real-time GLEIF API validation)
  • KERI-based authentication (no wallets, no gas fees for users)
  • Role-based authorization (ISO 5009 standard organizational roles)
  • Package-oriented framework (strict separation layered on a lightweight Diamond router)

...we've created a system that bridges the gap between traditional trade finance and blockchain efficiency, without compromising on security, compliance, or user experience.

For institutional finance, security is not optional—it's everything. The deliberate trade-offs of cost (~$2.62 per validation) and latency (~30-60 seconds) are negligible for high-value promissory notes, but the security guarantees are priceless: instant credential revocation, real-time compliance, and cryptographic proof of organizational authority.


Built for the future of institutional trade finance

Where real-world identity meets on-chain assets

About

No description, website, or topics provided.

Resources

License

Code of conduct

Contributing

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors