Skip to content

Charli3-Official/charli3-push-oracle-contracts

Charli3's Oracle Smart Contract Plutus CI Suite

Table of Contents

Introduction

Utilizing Distributed Ledger Technology (DLT), Blockchain offers an advanced solution for ensuring secure data transmission and creating a permanent record of transactions. The incorporation of smart contracts amplifies its capabilities, and with the assistance of oracles, an essential connection is established between on-chain processes and real-world data.

In this repository, our focus is primarily on the intricacies of the Charli3's oracle on-chain components. Our discussion begins with an in-depth exploration of Charli3's architectural framework, emphasizing key elements such as UTXOs, datums, tokens, NFTs, and the strategic methodology for efficient data aggregation. Furthermore, we delve into the myriad transactions supported by this contract.

Tooling

Refer to the flake.nix file to identify the required system dependencies tailored to your operating system.

While it's optional, consider leveraging Nix by executing nix develop for streamlined tooling setup. Manual installation is also an option.

Validator Executable Creation

We advise using the serialized executable provided in the main branch's release. Alternatively, you can employ the reliable Docker to produce the executable or simply with cabal build serialized. The following are the options available for the serialized executable:

Charli3's Oracle Validator Generator

Usage: serialized [-a|--aggressive] [-v|--verbose] [--cbor-path SCRIPT_CBOR_PATH]
                  [--argument-path SCRIPT_ARG_PATH] [--script-path SCRIPT_PATH]

  To generate the Charli3's Oracle validator, please ensure that the
  validator-argument.yml file is present in the same directory as this
  executable, or provide filepath to it.

Available options:
  -a,--aggressive          Compilation using Plutonomy's aggressive
                           optimization; elimination of traces messages.
  -v,--verbose             Enable verbose mode.
  --cbor-path SCRIPT_CBOR_PATH
                           Optional: Path where the script cbor will be written
  --argument-path SCRIPT_ARG_PATH
                           Path where the script argument is located
                           (default: "./validator-argument.yml")
  --script-path SCRIPT_PATH
                           Path where the plutus script will be written
                           (default: "./OracleV3.plutus")
  -h,--help                Show this help text

Copyright: (c) 2020 - 2025 Charli3

To utilize the executable, the user must supply the appropriate arguments. For reference, see the sample-validator-argument.yml file. The necessary input values include:

  • oracle_mp: Minting policy for the NFTs incorporated within the contract.
  • aggState_tn: Token Name for the Aggregate UTxO.
  • reward_tn: Token Name for the Reward UTxO.
  • oracleFeed_tn: Token Name for the Feed UTxO.
  • nodeFeed_tn: Token Name for tokens distributed across the node UTxOs.
  • payment_mp: Minting policy for the token serving as a reward within the contract.
  • payment_tn: Token Name for the token serving as a reward within the contract.
  • rate_tn (Optional): Define a token name to facilitate conversion between an external oracle asset and the payment token.
  • rate_mp (Optional): Define a minting policy to enable conversion between an external oracle asset and the payment token.

Tests Guide

Execute the contract tests using:

cabal test

or, to run a particular test:

cabal test --test-options="-p \"/[Test Name]/\" --color=always"

If you have introduced some changes that influence traces in golden files, you can just remove old golden files and rerun the test suite to recreate them. You can use the following snippet to remove all goldens and rerun the test suite.

rm -vf $(fd -egolden)
cabal test

Benchmarking Guide

Execute the benchmark tests using:

cabal run benchmarking -- <mode> <validator> <nodes>

Modes

  • stress: Evaluates the aggregate-transaction with varying node counts.
  • profiling: Produces dual SVG flamegraphs for aggregate transaction resource analysis.

Validators

  • default: Compilation without optimizations, using only PlutusTx code.
  • normal: Incorporates the Plutonomy library with standard optimizations.
  • aggressive: Integrates the Plutonomy library with aggressive optimizations. Note: This mode is incompatible with the profiling mode due to trace message removal.

Nodes

The <nodes> argument is an integer representing the number of simulated nodes in the computation.

Profiling Configuration

For profiling, uncomment the subsequent lines in the Oracle.Validator file:

-- {-# OPTIONS_GHC -fplugin-opt PlutusTx.Plugin:conservative-optimization #-}
-- {-# OPTIONS_GHC -fplugin-opt PlutusTx.Plugin:profile-all #-}

Ensure the presence of uplc and flamegraph executables. For a deeper dive into profiling execution, consult the official documentation.

Cautions

  • When using aggressive mode with a high node count, be wary of considerable resource consumption.
  • Benchmarking mainly focuses on the performance of the aggregate transaction, which stands out as the most resource-intensive transaction in terms of memory and computation steps compared to all others.
  • While in stress mode, it's advised to comment out profiling pragma lines.
  • For best profiling results, it's advised to bypass certain traces prone to errors. Intentionally, some code sections are designed to produce errors during typical operations, potentially affecting the profiling process. Notably, the checkSigned: Incorrect public key hash or checkAggChange traces are anticipated to encounter failures, disrupting the creation of the profiling SVG file.

Architecture

The foundational smart contract is built around five critical UTXOs:

  • Node UTXO: Responsible for ferrying data external to the blockchain. C3's networks can accommodate a maximum of 6 nodes due to memory limitations within the blockchain.
  • Aggregate UTXO: Houses the settings for the contract along with the reward tokens, specifically C3.
  • Reward UTXO: Stash and register the C3 tokens earned as compensation for both the node and the contract operator.
  • Feed UTXO: Maintains the generated feed from aggregating all Node UTXOs, termed as the oracle feed or C3 network feed.
  • Reference Script UTXO: Safeguards the script governing the contract's behavior.

Oracle overall description

An oracle delivers trusted data, termed as oracle feed, obtained from an aggregation transaction. This transaction processes the latest information from C3 node operators, validated through a consensus algorithm.

Before diving deeper, it's vital to understand the available oracle settings:

  • Minimum Node Percentage: Defines the minimum percentage of C3 nodes required to update their data before generating a new C3 network feed. This ensures the feed has up-to-date information.
  • Freshness Window: The duration within which a C3 node's data is considered recent. If data is updated within this period, it's deemed relevant for network computations.
  • Feed Update Interval: The regularity with which a C3 new network feed is generated.
  • Data Change Threshold: The allowable percentage variance in data from C3 nodes that prompts an immediate C3 network feed update.
  • Recharge Threshold: The minimal quantity of C3 tokens for refilling the network's reward pool.
  • Lifetime of the Aggregate transaction: An aggregate-transaction must be sent to the blockchain within a specified timeframe. If it exceeds this window, the transaction is deemed invalid. This safeguard ensures that outdated data, potentially caused by system delays or high blockchain network congestion, isn't accepted.
  • Node Consensus Reward: Amount awarded to nodes participating in consensus generation.
  • Transaction Reward: Reward for nodes covering the aggregate-transaction expenses.
  • Maintenance Reward: Allocated for platform upkeep and legacy system operations.
  • Interquartile Range (IQR): Measures the spread of C3 node data to identify outliers.
  • Percentage divergence: A threshold for data variation from C3 nodes. Exceeding this results in network actions to ensure data integrity (outlier detection).
  • Authorized Modifiers: Individuals/entities allowed to adjust the smart contract settings.
  • Minimum Approvals: The least number of authorizations required for modifying the contract.

Aggregation

To initiate an aggregation transaction, a set percentage of nodes must provide updated data. The consensus algorithm, incorporating the Interquartile Range Algorithm (IQR) and the Divergence Percentage Algorithm (DP), facilitates this aggregation. IQR identifies outliers, and DP does so by assessing percentage variations against a predefined dispersion limit.

An aggregation update occurs if:

  • Data alters beyond a specified percentage compared to the previous oracle feed value.
  • A predetermined duration elapses since the last generated oracle feed value.

Node operators, incentivized to provide accurate data, will strive to be included in the reward payment system. Consider a simple example with these oracle settings:

  • 10 nodes.
  • 70% node participation for new aggregations.
  • 60 second freshness window.
  • 900 second window for new aggregations, regardless of data changes.
  • 2% data change threshold for immediate aggregation.

In this scenario, after the first successful aggregation with 7 nodes, they await the next. Two situations can arise:

  1. Nodes detect over 2% change compared to the last value.
  2. 900 seconds pass since the last update without significant data changes.

Regardless of the scenario, nodes compete to update their values. Once 7 nodes succeed in updating, aggregation ensues. During this process, each node assesses the oracle's present state to determine whether to merely refresh their data, both update and aggregate, or defer to the next cycle if they've missed the ongoing one (given that 7 nodes have already refreshed).

Other Transactions Supported

  • Add Transaction: Integrates new C3 nodes into the network.
  • Remove Transaction: Removes underperforming C3 nodes to ensure network integrity.
  • Edit Setting Transaction: Allows easy modifications of contract settings.
  • Add Funds Transaction: Replenishes the C3 token pool, rewarding entities for generating new oracle feeds.
  • Node Update: Operators can refresh node data.
  • Node Collect Transaction: Covers rewards for node operators stored in the reward UTXO and reimburses for aggregate transactions.
  • Platform Collect Transaction: Funds network maintenance, tools, and alarms, letting administrators withdraw operational costs.
  • Closing Transaction: Marks the contract's end by consuming all its UTXOs. Remaining C3 tokens in reward UTXO return to node wallets.

Module Design and Overview

In this section, we provide an in-depth analysis of the primary modules within our system, highlighting their essential roles and functionalities.

Oracle.OnChain

Responsible for the on-chain operations of the smart contract, this module is central to defining and implementing the core logic for all supported transactions. Its design ensures operations are consistent with the established rules and conditions.

Oracle.Validator

Beyond acting as a boilerplate for the validator compilation, this module incorporates logic pertinent to Plutonomy optimizations.

Oracle.AggregateConditions

This module is specifically tailored to set clear conditions for calculating new aggregations. Its precision ensures the integrity and relevance of data at all times.

Oracle.Consensus

Dedicated to computations for aggregating values from diverse nodes, it is instrumental in achieving a consensus amongst node operators. The module houses the algorithms for Interquartile Range (IQR) and Divergence Percentage (DP).

Oracle.DataFeed

This module embodies the data feeds furnished by C3 nodes. It underscores each node feed's contribution to the consensus-driven aggregated value.

Oracle.Tokens

This serves as a hub for the standard token definitions employed within the oracle smart contract.

Oracle.Types

A critical component, this module maintains essential type definitions for the oracle smart-contract:

  • OracleDatum: An inductive type with four unique constructors, each pinpointing a distinct UTXO type.
  • OracleRedeemer: This inductive type is versatile, crafted with constructors for various transaction validation needs.
  • Oracle: Acting mainly as a contract parameter, it sheds light on the NFTs active within the C3 network. These NFTs distinctly identify various UTxOs and the associated reward token.

Utils.ScriptContext

Packed with utilities linked to script contexts, this module aids in fluidly executing and deciphering scripts.

Utils.OnChain

This utility suite is all about on-chain operations. It equips developers with functions that promise seamless blockchain interactions.

Utils.Percent

This module houses functions and type definitions related to percentages, which are paramount for the contract's logic. It especially aids when gauging thresholds and other criteria grounded in percentages.

Utils.Constants

Serving as a repository for constants, this module ensures that internally referenced values within the contract are centrally located and remain static throughout the contract's lifecycle.

General Notes

  • The prime focus of this repository is on the on-chain facets and operations of the contract. It isn't configured to handle PAB actions or off-chain code interactions. Moreover, some off-chain functions, although present here, may no longer be necessary.

  • The Oracle Feed standard datum code can be found in the following repository: oracle-datum-lib.

  • You can find a demo example that read the C3 network feed with pycardano in the following repository: datum-demo-v3.

License

This repository is licensed under the MIT license.

License Rationale

Charli3 uses a combination of OSI-approved open-source licenses, primarily AGPL-3.0 and MIT, depending on the role of each repository within the ecosystem. Repositories that implement core or protocol-critical logic are licensed under AGPL-3.0 to ensure that improvements and modifications remain transparent and benefit the entire ecosystem, including node operators, developers, and token holders, while maintaining full OSI compliance. This may include both on-chain and select off-chain components where protocol logic and token usage are integral.

Repositories focused on tooling, SDKs, and supporting components are typically licensed under the MIT License to promote broad adoption, flexibility, and ease of integration.

AGPL-3.0 is applied where reciprocal openness is important to protect shared protocol infrastructure, while MIT is used where permissiveness and developer flexibility are the primary goals.

Please refer to each repository’s LICENSE file for the specific terms that apply.

Official Deployments

Charli3 maintains and supports only official deployments that use the $C3 token and unmodified protocol economics.

About

Push-based smart contracts for Charli3's decentralized oracle network on Cardano blockchain, enabling secure off-chain data aggregation with consensus mechanisms and node operator rewards

Resources

License

Code of conduct

Contributing

Security policy

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors

Languages