Plutus: Oracles + PAB + Swap dApp

Topic: Oracle-based smart contract with update & usage logic Includes: On-chain logic, off-chain contract, EmulatorTrace, and PAB integration Tools: Plutus, Haskell, Template Haskell, PAB

🔢 Table of Contents

  1. 🔍 What Are Oracles?

  2. ⚙️ Oracle Implementation Overview

  3. 🧹 Oracle Types and Core Logic

  4. ⚖️ Swap Contract (Using the Oracle)

  5. 📊 Oracle Lifecycle

  6. 📚 Off-Chain Contracts

  7. 🔢 Test with EmulatorTrace

  8. ✨ PAB Integration

  9. 💡 Glossary of Key Terms

  10. 📄 Next Steps


1️⃣ 🔍 What Are Oracles?

An oracle bridges off-chain data to the blockchain. Smart contracts on Cardano can't directly access external data like exchange rates, weather, or random numbers. Oracles solve this by publishing such data on-chain in a secure and verifiable way.

Examples:

  • ADA/USD exchange rates

  • Weather data for insurance contracts

  • Randomness for games

  • Sports match results


2️⃣ ⚙️ Oracle Implementation Overview

We implement an oracle that provides an ADA/USD exchange rate using:

  • ⚫ A UTxO carrying the exchange rate in its datum

  • 🏷️ An NFT to uniquely identify the "true" oracle output

  • ✍️ A validator supporting two actions:

    • Update (by the oracle operator)

    • Use (by contracts that read the value)


3️⃣ 🧹 Oracle Types and Core Logic

🔹 Oracle Record (Parameters)

data Oracle = Oracle
  { oSymbol   :: CurrencySymbol
  , oOperator :: PubKeyHash
  , oFee      :: Integer
  , oAsset    :: AssetClass
  }

🔹 Redeemer

data OracleRedeemer = Update | Use

🔹 Validator: mkOracleValidator

mkOracleValidator :: Oracle -> Integer -> OracleRedeemer -> ScriptContext -> Bool

Key checks:

  • 🔒 NFT must be present in both input/output

  • 🛎️ If Update: Signed by operator & datum is valid

  • ✅ If Use: Oracle value unchanged & fee paid


4️⃣ ⚖️ Swap Contract (Using the Oracle)

Users deposit ADA at a swap script address. Another user can buy ADA by providing the required USDT (price calculated using the oracle).

👤 Datum: PubKeyHash (seller)

➞ Redeemer: () (unit)

🔹 Swap Validator: mkSwapValidator

mkSwapValidator :: Oracle -> Address -> PubKeyHash -> () -> ScriptContext -> Bool

Key logic:

  • If signed by seller: refund allowed

  • If used by buyer:

    • Requires oracle input

    • Enforces price based on oracle value

    • Checks correct amount of USDT paid to seller


5️⃣ 📊 Oracle Lifecycle

Step
Action
By
Redeemer
Result

1

Mint NFT

Oracle

Token identifies oracle

2

Start oracle

Oracle

Update

Initial value set

3

Update value

Oracle

Update

Datum updated

4

Use value

Any contract

Use

Oracle value consumed


6️⃣ 📚 Off-Chain Contracts

🔹 startOracle

  • Mints NFT

  • Constructs Oracle parameters

  • Uses forgeContract

🔹 updateOracle

  • Looks up UTxO with NFT

  • Consumes it, creates a new one with updated datum

  • Paid fees can be collected by oracle operator

🔹 runOracle

  • Combines startOracle and loops updateOracle

🔹 offerSwap, useSwap, retrieveSwaps

  • offerSwap: Locks ADA at swap address

  • useSwap: Uses oracle to calculate USDT price and executes swap

  • retrieveSwaps: Seller reclaims their ADA if not swapped


7️⃣ 🔢 Test with EmulatorTrace

🏋️ Actors:

  • Wallet 1: Oracle operator

  • Wallets 2–5: Swap participants

🔹 Test Flow:

  1. Oracle is started, value initialized

  2. Swaps are offered

  3. Oracle is used to complete swaps

  4. Oracle is updated, fees collected


8️⃣ ✨ PAB Integration

🔹 oracle-pab.hs

  • Starts web server

  • Initializes oracle, swaps, and distributes tokens

  • Writes contract instance IDs to disk

🔹 oracle-client.hs

  • Reads oracle instance ID

  • Fetches live rate (e.g., from CoinMarketCap)

  • Calls update endpoint every few seconds

🔹 swap-client.hs

  • CLI tool for Wallets

  • Endpoints:

    • Offer

    • Retrieve

    • Use

    • View funds


9️⃣ 💡 Glossary of Key Terms

Term
Meaning

Oracle

Bridge between off-chain data and smart contracts

NFT

Uniquely identifies a UTxO (oracle instance)

Datum

Stores data like price in UTxO

Redeemer

Input to a script that describes action taken

UTxO

Unspent Transaction Output

Validator

On-chain function that enforces logic

PAB

Plutus Application Backend for real-world deployment

AssetClass

Tuple of CurrencySymbol + TokenName


🔣 10. 📄 Next Steps

  • 📚 Build a front-end UI for the swap dApp

  • ✨ Extend oracle to support median-of-n feeds

  • ⚖️ Add slashing for invalid data via staking

  • 🎯 Deploy on Cardano testnet using real oracle feeds


Last updated