# Onchain & Offchain machine learning

On-chain machine learning involves implementing simple machine learning algorithms directly within smart contracts, enabling them to autonomously execute tasks based on data-driven decisions. \\

Examples of such algorithms that are lightweight enough for on-chain deployment include linear regression, which can be used for financial forecasting in decentralized finance (DeFi); logistic regression for binary outcomes like fraud detection; decision trees for rule-based decision making in governance protocols; naive Bayes classifiers for text categorization in decentralized content platforms; and simple rule-based systems that can automate compliance checks in supply chain management. \
\
These applications leverage the transparency and immutability of blockchain to enhance trust and automation in various sectors.

'Traditional' decentralized autonomous organizations (DAOs) have often relied on manual interventions for updates or changes, thereby not being actually autonomous. \
\
In contrast, Conwai aims to achieve genuine autonomy by enabling smart contracts that can adapt, evolve, and potentially even self-write new contracts, drawing inspiration from Conway's Game of Life, where autonomous entities evolve based on predefined rules. \
\
This feature could revolutionize how smart contracts operate, moving towards a truly autonomous system where contracts are not only self-executing but also self-improving and self-generating.

Expanding beyond on-chain capabilities, Conwai also facilitates the integration of off-chain AI models that plug into the blockchain. These AI agents can perform complex computations and then interact with the blockchain to update or verify data without compromising the efficiency and scalability of the network. \
\
Examples include AI-powered factories that analyze vast amounts of market and operational data to generate optimal smart contract templates, which can then be deployed by users to maximize efficiency and reduce errors. \
\
Additionally, AI agents could autonomously launch new tokens based on real-time economic analyses, protocols could manage token supply dynamically or deploy capital based on ongoing data analysis.\
\
This integration of AI and blockchain not only enhances the functionality and applicability of smart contracts but also paves the way for more sophisticated, adaptive, and autonomous blockchain ecosystems.

On-chain computation involves processing data directly on a blockchain, ensuring transparency and immutability of operations but at the cost of higher transaction fees and limited processing capacity. \
\
Off-chain computation, on the other hand, takes place outside the blockchain and is used for complex data processing tasks that are computationally intensive or require handling large volumes of data, which would be impractical or too expensive to perform on-chain. \
\
Both approaches are complementary: on-chain computation is ideal for operations requiring trust and auditability, while off-chain computation is suited for intensive calculations, with results potentially integrated back onto the blockchain via oracles or other secure methods to combine efficiency with the reliability of blockchain technology.

**Off-chain AI**

Incorporating off-chain AI into smart contracts effectively leverages the strengths of both environments: the computational power and flexibility of off-chain systems and the trustworthiness and security of on-chain processes. Here are three primary methods through which off-chain AI can be integrated with smart contracts, focusing on upgradeable contracts, oracles, and contract creation:

#### 1. **Oracles**

Oracles are the most common method for integrating off-chain AI into smart contracts. They act as bridges that fetch data from external sources or execute computations off-chain and then feed the results back to the blockchain in a secure manner. This is particularly useful for AI models that require significant computational resources or need to interact with data that is not natively available on the blockchain.

**Example**: An oracle could periodically run a complex machine learning model to predict market trends and update a DeFi smart contract with these predictions. This data can then be used by the smart contract to adjust trading strategies or rebalance portfolios automatically.

#### 2. **Upgradeable Contracts**

Upgradeable contracts are designed to allow their logic or parts of their data storage to be changed post-deployment. This is particularly useful for AI-driven applications where the model might need to be updated as new data becomes available or as better algorithms are developed.

**Example**: A smart contract that uses a machine learning model to score credit applications could start with a basic logistic regression model. Over time, as more data is collected and analyzed off-chain, the model could be upgraded to a more sophisticated neural network. This upgrade can be facilitated through a proxy contract or a similar upgradeable pattern, where the address pointing to the logic contract can be updated to a new one containing the improved AI model.

#### 3. **Contract Creation (Factory Pattern)**

Using the factory pattern, new contracts can be created dynamically based on off-chain computations. This is useful when the initialization parameters of a contract depend on complex calculations that are performed off-chain.

**Example**: An AI-driven analytics platform might use off-chain computations to determine optimal parameters for a series of contracts managing different user groups or subscription levels. A factory contract can then deploy these individual contracts with parameters set based on the off-chain AI analysis.

**On-chain AI**

#### 1. **Algorithm: Moving Average**

**Application: Trend Analysis for Asset Prices**

**Description**: A moving average is a statistical analysis tool used to smooth out short-term fluctuations and highlight longer-term trends in data. It's relatively simple to compute and can be used to analyze asset price trends in a decentralized finance (DeFi) application.

**Smart Contract Use**: An oracle updates a moving average of an asset's price periodically. Traders can query the smart contract to determine if the current price is above or below the moving average, helping them make buy or sell decisions based on trend analysis.

#### 2. **Algorithm: Simple Classification (Threshold-based)**

**Application: Loan Approval System**

**Description**: A simple classification algorithm could use a threshold on a few parameters (like credit score and income-to-debt ratio) to determine loan approval. This is a binary classification with a straightforward decision rule.

**Smart Contract Use**: Loan applicants submit their data, which is either pre-verified off-chain or through decentralized oracles. The smart contract applies a threshold rule to decide on loan approvals, automating the process in a transparent manner.

#### 3. **Algorithm: Decision Trees**

**Application: Insurance Premium Calculation**

**Description**: Decision trees are a non-linear model used to make a series of decisions. They can be used to calculate insurance premiums based on various factors like age, health, and driving history.

**Smart Contract Use**: Parameters for decision trees (like splits and conditions) are set and updated via oracles. Customers input their data, and the contract calculates the premium using the decision tree logic. This could simplify the insurance process and enhance transparency.

#### 4. **Algorithm: Naive Bayes Classifier**

**Application: Spam Detection in Decentralized Messaging Platforms**

**Description**: Naive Bayes classifiers are probabilistic classifiers based on applying Bayes' theorem with strong independence assumptions. This can be used for spam detection in messages based on word frequencies and other indicators.

**Smart Contract Use**: A decentralized application (DApp) for messaging could use a Naive Bayes classifier to filter out spam messages. Training data and updates to the model's probabilities could be managed by oracles, while classification happens on-chain to keep user data private and secure.

#### 5. **Algorithm: K-Nearest Neighbors (K-NN)**

**Application: Recommendation System for NFTs**

**Description**: K-Nearest Neighbors is a simple algorithm that finds the 'k' closest points in a dataset to a query point and makes decisions based on the properties of these nearby points. It can be used for recommending similar Non-Fungible Tokens (NFTs) based on attributes like artist, style, and past sales.

**Smart Contract Use**: For efficiency, only the distances to a small set of nearest neighbors are calculated on-chain, while detailed metadata is stored off-chain. Users query the smart contract to find NFTs similar to one they like, enhancing user engagement on NFT platforms.

Each of these examples reflects a balance between on-chain execution for trust and transparency, and off-chain computation to manage the data-intensive or complex aspects of the algorithms.
