DEV Community

Zerod0wn Gaming
Zerod0wn Gaming

Posted on

Building a Privacy-Preserving AI Oracle on Oasis Sapphire

Recently, I built a cross-chain confidential Trust Score Oracle using Sapphire ParaTime, Oasis Privacy Layer, and ROFL on the Oasis Network. That project focused on computing a reputation score across multiple blockchains while keeping the scoring logic private.

In this tutorial, we’ll explore a different but related use case: building a privacy-preserving AI inference oracle.

Instead of calculating a trust score from on-chain activity, we will:

  • run an AI model privately
  • process sensitive user data
  • return verifiable results on-chain

This pattern is extremely useful for applications like:

  • private credit scoring
  • confidential trading signals
  • healthcare ML analytics
  • AI-powered DeFi risk models

Why Privacy Matters for AI on Blockchain

Most blockchains are fully transparent. Every transaction and input is publicly visible.

That creates a major problem for AI applications.

Example: a credit scoring system.

Inputs might include:

  • income
  • transaction history
  • loan repayment data
  • identity attributes

None of this can safely be published on a public blockchain.

This is where the confidential compute model of Oasis Network becomes powerful.

It allows smart contracts to execute encrypted computations inside secure enclaves.


Oasis Network Architecture

The Oasis architecture separates consensus from computation, which allows specialized runtimes for different workloads.

+------------------------------------------------+
|                 Applications                   |
+------------------------------------------------+
|                ParaTime Layer                  |
|------------------------------------------------|
|  Sapphire (Confidential EVM)                   |
|  Emerald (EVM Compatible)                      |
|  Custom Runtimes                               |
+------------------------------------------------+
|              Consensus Layer                   |
|           Proof-of-Stake Validators            |
+------------------------------------------------+
Enter fullscreen mode Exit fullscreen mode

In this tutorial we use Sapphire ParaTime, which provides:

  • EVM compatibility
  • encrypted state
  • confidential smart contracts

What We Will Build

We will build a Confidential AI Oracle.

                 Confidential AI Oracle System

       +-------------------+
       |   User Wallet     |
       | (encrypted data)  |
       +---------+---------+
                 |
                 v
        +---------------------+
        | Sapphire Smart      |
        | Contract            |
        | (confidential EVM)  |
        +---------+-----------+
                  |
                  v
        +---------------------+
        | ROFL Oracle Worker  |
        |---------------------|
        | Secure Enclave      |
        | AI Model Inference  |
        +---------+-----------+
                  |
                  v
        +---------------------+
        | Signed Result       |
        | returned on-chain   |
        +---------------------+
Enter fullscreen mode Exit fullscreen mode

The system will:

  1. Receive encrypted user data
  2. Run an AI model inside a secure environment
  3. Produce a prediction
  4. Store only the result on-chain

High-Level Architecture

User Wallet
     |
     v
Encrypted Data
     |
     v
Sapphire Smart Contract
     |
     v
ROFL Worker
     |
     v
AI Model Inference
     |
     v
Signed Result
     |
     v
Smart Contract Storage
Enter fullscreen mode Exit fullscreen mode

Real Use Case: Private Credit Scoring

Imagine a DeFi lending protocol.

It wants to compute a credit score before issuing a loan.

But the borrower’s financial data must remain private.

Traditional blockchain flow:

User -> Smart Contract -> Public Data
Enter fullscreen mode Exit fullscreen mode

Everyone can see the input.

With confidential computation:

User Data (encrypted)
        |
        v
Confidential Runtime
        |
        v
AI Model
        |
        v
Credit Score Result
Enter fullscreen mode Exit fullscreen mode

Only the result is visible.


Project Repository Structure

oasis-private-ai-oracle/

contracts/
  CreditOracle.sol

oracle/
  worker.py
  model.py
  enclave_runner.py

scripts/
  deploy.js

frontend/
  submit-data.ts

README.md
Enter fullscreen mode Exit fullscreen mode

Smart Contract (Sapphire)

Example confidential oracle contract.

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.19;

contract CreditOracle {

    address public oracle;

    struct ScoreRecord {
        uint256 score;
        uint256 timestamp;
    }

    mapping(address => ScoreRecord) public scores;

    event ScoreUpdated(address indexed user, uint256 score);

    constructor(address _oracle) {
        oracle = _oracle;
    }

    function submitScore(
        address user,
        uint256 score,
        bytes calldata signature
    ) external {

        require(verify(user, score, signature), "invalid signature");

        scores[user] = ScoreRecord({
            score: score,
            timestamp: block.timestamp
        });

        emit ScoreUpdated(user, score);
    }

    function verify(
        address user,
        uint256 score,
        bytes memory signature
    ) internal view returns (bool) {

        bytes32 message = keccak256(
            abi.encodePacked(user, score)
        );

        bytes32 ethSigned = keccak256(
            abi.encodePacked(
                "\x19Ethereum Signed Message:\n32",
                message
            )
        );

        (bytes32 r, bytes32 s, uint8 v) = splitSignature(signature);

        address recovered = ecrecover(ethSigned, v, r, s);

        return recovered == oracle;
    }

    function splitSignature(bytes memory sig)
        internal
        pure
        returns (bytes32 r, bytes32 s, uint8 v)
    {
        require(sig.length == 65, "invalid signature length");

        assembly {
            r := mload(add(sig, 32))
            s := mload(add(sig, 64))
            v := byte(0, mload(add(sig, 96)))
        }
    }

}
Enter fullscreen mode Exit fullscreen mode

The contract:

  • verifies oracle signatures
  • prevents tampering
  • stores final scores
  • event logging
  • timestamped scores
  • full signature verification

Oracle Worker

The oracle runs the AI model and signs the result.

Example Python worker:

from web3 import Web3
import json
from model import predict_score
from eth_account import Account

RPC_URL = "https://sapphire.oasis.io"
PRIVATE_KEY = "YOUR_ORACLE_PRIVATE_KEY"

contract_address = "DEPLOYED_CONTRACT_ADDRESS"
contract_abi = json.load(open("CreditOracleABI.json"))

w3 = Web3(Web3.HTTPProvider(RPC_URL))

account = Account.from_key(PRIVATE_KEY)

contract = w3.eth.contract(
    address=contract_address,
    abi=contract_abi
)

def run_oracle(user_address, user_data):

    score = predict_score(user_data)

    message = Web3.solidity_keccak(
        ["address","uint256"],
        [user_address, score]
    )

    signed = account.sign_message(
        Web3.eth.account._hash_message(message)
    )

    tx = contract.functions.submitScore(
        user_address,
        score,
        signed.signature
    ).build_transaction({
        "from": account.address,
        "nonce": w3.eth.get_transaction_count(account.address)
    })

    signed_tx = w3.eth.account.sign_transaction(tx, PRIVATE_KEY)

    tx_hash = w3.eth.send_raw_transaction(signed_tx.rawTransaction)

    return tx_hash.hex()
Enter fullscreen mode Exit fullscreen mode

In a real deployment this worker would run inside:

  • a secure enclave
  • confidential compute environment

It:

  • computes the AI score
  • signs it
  • sends a transaction on-chain

Example AI Model

A simplified scoring function:

import numpy as np

def normalize(value, max_value):
    return min(value / max_value, 1)

def predict_score(data):

    income = normalize(data["income"], 100000)
    debt = normalize(data["debt"], 50000)
    history = normalize(data["history"], 10)

    score = (
        income * 0.5
        - debt * 0.3
        + history * 0.2
    )

    score = max(score, 0)

    return int(score * 100)
Enter fullscreen mode Exit fullscreen mode

It does some real feature normalization and gives realistic scoring output

In production you could replace this with:

  • XGBoost
  • LightGBM
  • neural networks

Deployment

Install development tools

npm install -g hardhat
Enter fullscreen mode Exit fullscreen mode

Configure Sapphire network

networks: {
  sapphire: {
    url: "https://sapphire.oasis.io",
    chainId: 23294
  }
}
Enter fullscreen mode Exit fullscreen mode

Deploy contract

npx hardhat run scripts/deploy.js --network sapphire
Enter fullscreen mode Exit fullscreen mode

End-to-End Flow

User submits encrypted data
        |
        v
Oracle decrypts inside secure compute
        |
        v
AI model runs prediction
        |
        v
Oracle signs result
        |
        v
Smart contract stores score
Enter fullscreen mode Exit fullscreen mode

Why This Architecture Is Powerful

Without privacy infrastructure, AI + blockchain rarely works because:

  • training data is private
  • models are proprietary
  • inputs contain sensitive information

Using confidential runtimes on Oasis Network enables a new class of applications:

  • private DeFi analytics
  • confidential AI marketplaces
  • encrypted healthcare ML
  • secure financial scoring

Possible next additions

Possible extensions to this project:

  • add zero-knowledge proofs for inference
  • build a data marketplace
  • enable federated learning
  • create private trading signals

Conclusion

The combination of blockchain verification and confidential computation unlocks entirely new types of applications.

With runtimes like Sapphire ParaTime on the Oasis Network, developers can build systems where:

  • data remains private
  • computation is verifiable
  • results are trustless

This opens the door to privacy-first AI in Web3.

Top comments (0)