TUTORIAL 01 / MACHINE-TO-MACHINE SETTLEMENT
Build an x402 Metered AI Inference API Gateway
Implement the 4-state HTTP 402 state machine (REQUEST_RESOURCE -> PAYMENT_REQUIRED_402 -> SUBMIT_SIGNED_RECEIPT -> VERIFIED_FULFILLMENT) using createX402Middleware and SessionKeyManager.
Step 1.1 — Mount Zero-Dependency x402 Server Middleware
Configure createX402Middleware from sdk/linghe-chain-sdk.mjs to emit deterministic WWW-Authenticate challenges referencing ChainID 88888, LUSD, and ERC-8004 Validation Escrow.
import http from "node:http";
import { createX402Middleware, PREDEPLOYS } from "./sdk/linghe-chain-sdk.mjs";
const x402Gate = createX402Middleware({
priceAtomic: "50000", // 0.05 LUSD (6 decimals)
asset: "LUSD",
payTo: PREDEPLOYS.ERC8004_VALIDATION_ESCROW,
resource: "/v1/inference",
verifyPayment: async (paymentHeader) => {
// Verify EIP-712 session receipt + 250ms slot finality + TIP-403 status
const receipt = JSON.parse(Buffer.from(paymentHeader, "base64").toString("utf8"));
return { valid: Boolean(receipt.txHash && receipt.lane >= 0 && receipt.lane < 32) };
}
});
http.createServer((req, res) => {
x402Gate(req, res, async () => {
res.writeHead(200, { "Content-Type": "application/json", "X-TIP403-Policy-Status": "AUTHORIZED" });
res.end(JSON.stringify({ status: "VERIFIED_FULFILLMENT", output: "Deterministic inference payload" }));
});
}).listen(8402);Step 1.2 — Invoke Metered Endpoint with Bounded Session Signer
Use createX402Client to handle HTTP 402 negotiation automatically, signing only within the pre-authorized SessionKeyManager (0x8402...0001) budget.
import { createX402Client } from "./sdk/linghe-chain-sdk.mjs";
const client = createX402Client({ x402Url: "https://myrilum.network" });
const response = await client.invokeSkill("compliance-merkle-audit", { asset: "LHKD" }, {
payerSigner: async (challenge, headers) => {
const lane = Number(headers.get("x-payment-noncelane") || 0);
// Delegate signing to local LingheOS Wallet 14-MCP gateway (zero key in agent process)
return Buffer.from(JSON.stringify({
chainId: 88888,
asset: challenge.asset || "LUSD",
lane,
sessionManager: "0x8402000000000000000000000000000000000001",
txHash: "0x" + "1".repeat(64)
})).toString("base64");
}
});
console.log("x402 status:", response.status, response.body);TUTORIAL 02 / AUTONOMOUS AGENT ECONOMICS
Register an ERC-8004 Agent with 20%/80% Bilateral Split
Register an autonomous agent on LingheERC8004IdentityRegistry (0x8004...0001), lock an inference task on LingheERC8004ValidationEscrow (0x8004...0003) with skillRoyaltyBps = 2000, and settle with hardware-attested proof.
Step 2.1 — Register Agent Identity on Block-0 Contract 0x8004...0001
Call registerAgent(operator, handle, agentCardUri, endpoint, capabilityHash) to anchor an immutable agentId and machine-discoverable endpoint.
import { encodeFunctionData, keccak256, toHex } from "viem";
import { PREDEPLOYS } from "./sdk/linghe-chain-sdk.mjs";
const identityAbi = [{
name: "registerAgent",
type: "function",
stateMutability: "nonpayable",
inputs: [
{ name: "operator", type: "address" },
{ name: "handle", type: "string" },
{ name: "agentCardUri", type: "string" },
{ name: "endpoint", type: "string" },
{ name: "capabilityHash", type: "bytes32" }
],
outputs: [{ name: "agentId", type: "uint256" }]
}];
const calldata = encodeFunctionData({
abi: identityAbi,
functionName: "registerAgent",
args: [
"0x0000000000000000000000000000000000008004",
"quant-verifier-hk-01",
"https://docs.myrilum.network/agent-card.json",
"https://myrilum.network/x402/",
keccak256(toHex("cap656-merkle-auditor-v2"))
]
});
console.log("Target:", PREDEPLOYS.ERC8004_IDENTITY, "Calldata bytes:", calldata.length);Step 2.2 — Create Verifiable Escrow (20% Skill Author / 80% Agent Payee)
Invoke createVerifiableTask with skillRoyaltyBps = 2000 (20.00%). On validateAndSettleWithHardwareQuote, the contract verifies the EIP-7951 P-256 enclave via 0x8900...0003 and distributes 20% to skillAuthor and 80% to agentPayee atomically.
// Solidity interface anchored at 0x8004000000000000000000000000000000000003
interface ILingheValidationEscrow {
function createVerifiableTask(
bytes32 taskId,
uint256 agentId,
address agentPayee, // Receives 80% (8000 bps)
address skillAuthor, // Receives 20% (2000 bps)
uint16 skillRoyaltyBps, // 2000 = 20.00% (MYRILUM protocol rake = 0%)
address paymentToken, // 0x20c0...0001 (LUSD)
uint256 escrowAmount,
bytes32 promptDigest,
bytes32 modelDigest,
address enclaveVerifier // Hardware-attested via 0x8900...0003
) external;
function validateAndSettleWithHardwareQuote(
bytes32 taskId,
bytes32 resultDigest,
bytes calldata enclaveSignature
) external;
}TUTORIAL 03 / HIGH-FREQUENCY CONCURRENT DISPATCH
Dispatch 20 Concurrent Transactions Across 32 2D-Nonce Lanes in 1004ms
Traditional 1D EVM accounts stall whenever one transaction waits in the mempool. Linghe Chain's Rust-enshrined NONCE_MANAGER_2D (0x4e4f...0000) assigns independent sequence counters per laneKey.
Step 3.1 — Initialize Nonce2DPool0x76 with 32 Parallel Lanes
Instantiate Nonce2DPool0x76 from sdk/linghe-chain-sdk.mjs. Each lease returns a unique laneIndex, nonceKeyHex, monotonically incrementing lane nonce, and txType: '0x76'.
import { LingheChainClient } from "./sdk/linghe-chain-sdk.mjs";
const client = new LingheChainClient({
rpcUrl: "https://rpc.myrilum.network",
laneCount: 32
});
const startMs = Date.now();
const jobs = Array.from({ length: 20 }, (_, i) =>
client.noncePool.runInLane(async (lease) => {
// Each concurrent task owns an isolated 2D nonce lane (0..31)
return {
taskIndex: i,
txType: lease.txType, // "0x76"
laneIndex: lease.laneIndex, // 0..31
nonceKeyHex: lease.nonceKeyHex,
nonce: lease.nonce.toString()
};
})
);
const receipts = await Promise.all(jobs);
console.log("Dispatched:", receipts.length, "Collisions:", client.noncePool.collisionsDetected);
console.log("Elapsed (ms):", Date.now() - startMs, "Snapshot:", client.noncePool.getSnapshot());Step 3.2 — Audit Zero-Collision Metrics on NONCE_MANAGER_2D
On the 4-validator Simplex BFT benchmark testbed (250ms slot cadence), 20 concurrent agent transactions settle across isolated lanes in ~1004ms total wall-clock time with 0 nonce collisions.
# Inspect live 2D-Nonce lane telemetry & precompile health
curl -sS https://myrilum.network/api/v2/network-portal-summary | node -e '
const data = JSON.parse(require("node:fs").readFileSync(0, "utf8"));
console.log({
chainId: data.chainId,
slotMs: data.slotCadenceMs,
parallelLanes: data.parallelNonceLanes
});
'TUTORIAL 04 / ENSHRINED REGTECH & ZK VERIFICATION
Enforce TIP-403 Policy & BN254 Groth16 Verification
Combine Rust-enshrined TIP-403 transfer policy screening (0x403c...0000), native BN254 Groth16 pairing verification (0x06/0x07/0x08 at 815,381 Gas), and offline Cap. 656 Binary Merkle PoR auditing.
Step 4.1 — Check TIP-403 Policy Before State Mutation
Query LHKD's transferPolicyId() and validate counterparties via TIP403_REGISTRY.isAuthorized(policyId, account) just as LingheOmnichainSettler and LingheZkLightClientBridge enforce on-chain.
// SPDX-License-Identifier: Apache-2.0
pragma solidity ^0.8.24;
interface ITIP20 { function transferPolicyId() external view returns (uint64); }
interface ITIP403 { function isAuthorized(uint64 policyId, address account) external view returns (bool); }
contract CompliantSettlementGuard {
address constant LHKD = 0x20C0000000000000000000000000000000000002;
address constant TIP403 = 0x403c000000000000000000000000000000000000;
function requireCompliant(address counterparty) public view {
uint64 policyId = ITIP20(LHKD).transferPolicyId();
if (policyId > 1) {
require(ITIP403(TIP403).isAuthorized(policyId, counterparty), "TIP403_POLICY_DENIED");
}
}
}Step 4.2 — Verify BN254 Groth16 Proof & Cap. 656 Merkle PoR
LingheZkLightClientBridge (0x8900...0002) executes 4-pair BN254 ecPairing (0x08) in 815,381 Gas (0.027% of a 3.0 Ggas block). Pair this with verifyCap656MerkleProof and verifyHkmaPegCorridor from linghe-chain-sdk.mjs.
import {
verifyCap656MerkleProof,
verifyHkmaPegCorridor,
POR_DOMAIN_SEPARATOR
} from "./sdk/linghe-chain-sdk.mjs";
// 1. Verify HKD/USD corridor invariant [7.7500, 7.8500]
const pegCheck = verifyHkmaPegCorridor(7.8);
console.log("HKMA Corridor:", pegCheck.inCorridor, pegCheck.bounds);
// 2. Independently verify Cap. 656 Binary Merkle Proof-of-Reserve vector
const res = await fetch("https://status.myrilum.network/v1/status/telemetry");
const telemetry = await res.json();
console.log("Domain Separator:", POR_DOMAIN_SEPARATOR, "Telemetry ready:", Boolean(telemetry));