# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
This site has an agentic ask interface you may use to query the documentation dynamically by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://docs.polystream.xyz/index.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

---

# Overview

Welcome to Polystream, a one-stop-shop that unlocks DeFi Yields with various strategies.&#x20;

#### What is Polystream?

Polystream is the cutting edge decentralized platform that offers unified crypto vaults and yield aggregation services for users to maximize asset utilization. Our vision is to create a seamless staking experience for users who have no understanding of crypto to still be able to generate crypto-type yields.

We offer a frictionless way for normies who want to be part of DeFi to be part of DeFi, abstracting away all complicated crypto jargon like approvals, signatures and L2s networks. We even go as far as supporting local fiat deposits and withdrawals.

### Core strategies

#### Stable Vaults

* Stable vaults powered by stablecoins
* Neutral Liquidity Pool (LP) Strategies with Active Asset Rebalancing and Hedging

#### Crypto Vaults

* Liquid Staking and Restaking
* Asset Collateralization

### Jump right in

<table data-view="cards"><thead><tr><th></th><th></th><th></th><th data-hidden data-card-cover data-type="files"></th><th data-hidden></th><th data-hidden data-card-target data-type="content-ref"></th></tr></thead><tbody><tr><td><strong>The Crypto Problem</strong></td><td>"Crypto is unnecessarily hard."</td><td></td><td></td><td></td><td><a href="/getting-started/the-crypto-problem">The Crypto Problem</a></td></tr><tr><td><strong>Polystream Vaults</strong></td><td>Engineering crypto yield strategies.</td><td></td><td></td><td></td><td><a href="/polystream/polystream-vaults">Polystream Vaults</a></td></tr><tr><td><strong>ERC4337 Smart Account Wallets</strong></td><td>Crypto for consumers</td><td></td><td></td><td></td><td><a href="/polystream/erc4337-smart-account-wallets">ERC4337 Smart Account Wallets</a></td></tr><tr><td><strong>Crypto-Fiat Ramp</strong></td><td>Seamless fiat to crypto experience.</td><td></td><td></td><td></td><td><a href="/polystream/crypto-fiat-ramp">Crypto-Fiat Ramp</a></td></tr><tr><td><strong>Rewards</strong></td><td>Earn extra rewards</td><td></td><td></td><td></td><td><a href="/polystream/rewards">Rewards</a></td></tr></tbody></table>


# The Crypto Problem

"Crypto is unnecessarily hard"

For the average person, cryptocurrency and DeFi represent a world of opportunity locked behind an intimidating wall of complexity. Despite the promise of financial inclusion, the reality is that most people cannot participate in this revolution due to unnecessary technical barriers.

<table><thead><tr><th width="158">Step</th><th width="193">What Should Happen</th><th>What Actually Happens</th></tr></thead><tbody><tr><td><strong>Getting Started</strong></td><td>Download a wallet and buy crypto</td><td>Confusion about dozens of wallet options, fear of scams, uncertainty about KYC requirements</td></tr><tr><td><strong>Moving Funds</strong></td><td>Transfer crypto to DeFi platform</td><td>Anxiety about sending to wrong addresses, shock at gas fees sometimes exceeding $50-100</td></tr><tr><td><strong>Finding Opportunities</strong></td><td>Choose best yield option</td><td>Overwhelmed by terms like "impermanent loss," "AMMs," "liquidity pools," and "rebase tokens"</td></tr><tr><td><strong>Managing Investment</strong></td><td>Set and forget</td><td>Constant worry about protocol hacks, unexpected token devaluations, or governance changes</td></tr><tr><td><strong>Withdrawing Profits</strong></td><td>Cash out gains easily</td><td>Surprise at multiple transactions needed, additional fees, and tax reporting complexities</td></tr></tbody></table>

### Real Problems Real People Face

#### 1. The Technical Knowledge Gap

The average person doesn't understand (and shouldn't need to understand):

* Private key management
* Blockchain addresses and verification
* Gas optimization
* Smart contract interaction
* Network congestion

> ***"I accidentally sent my crypto to the wrong address and lost everything. There was no customer service to call."*** — Average Joe

#### 2. The Language Barrier

DeFi speaks a language most people don't understand:

* **What they hear:** "Connect your wallet and approve the token to stake in our liquidity pool for optimized APY"
* **What they think:** "Is this English? Am I being scammed?"

#### 3. The User Experience Nightmare

<figure><img src="https://511560137-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FBRX14z25wLMxFcY12pGf%2Fuploads%2Fz0LpcHXsZvwIfMtSmB9t%2FScreenshot%202025-02-25%20at%203.19.20%E2%80%AFPM.png?alt=media&amp;token=bf837d68-d443-4451-8390-b256bf342dab" alt=""><figcaption></figcaption></figure>

Most DeFi interfaces assume users:

* Are comfortable with technical risk
* Understand financial concepts
* Can distinguish between legitimate protocols and scams
* Have time to research tokenomics and security audits
* Can manage multiple wallets and passwords without support

> ***"I tried to use a yield farm but I couldn't figure out how to 'approve' my tokens. I gave up after an hour."*** — Potential DeFi user

#### 3. The Multi-Chain Maze

The fragmentation of DeFi across blockchains creates overwhelming complexity:

* Different wallets for different chains
* Bridging assets with high fees and security risks
* Learning multiple interfaces and token standards
* Managing native tokens for gas on each chain

#### 4. The Cost Prohibitive Reality

DeFi's promise of inclusion is undermined by high costs:

| Action             | Ethereum Cost  | Traditional Finance Cost |
| ------------------ | -------------- | ------------------------ |
| Account Creation   | $0-50 in gas   | Free                     |
| Transaction        | $5-100+ in gas | Free-$0.50               |
| Failed Transaction | Still pay gas  | No cost                  |
| Customer Support   | Non-existent   | Free (phone/chat)        |

####

### The Result: Massive Exclusion

Despite crypto's promise to "bank the unbanked" and provide financial freedom, the reality is stark...

### What Needs To Change

For DeFi to achieve mass adoption, we need solutions that:

1. **Abstract complexity** - Users shouldn't need to understand the underlying technology
2. **Speak human language** - No more crypto jargon in user interfaces
3. **Provide safety nets** - Clear warnings, and protection from common mistakes
4. **Reduce costs** - Transactions should be affordable for everyone
5. **Simplify cross-chain** - The blockchain used should be invisible to the user

### How Polystream Solves These Problems

Polystream addresses each of these barriers with our innovative approach:

* **Familiar Banking Experience** with crypto yields behind the scenes
* **Fiat On/Off Ramps** for seamless deposits and withdrawals
* **Gasless Transactions** with fees absorbed through efficiency
* **Signatureless Transactions** with session keys.
* **Simplified User Journey** reduced from 15+ steps to just 3

By removing these unnecessary barriers, we're making DeFi's benefits accessible to everyone, by introducing a few familiar Web 2 flows into Web 3.

### Links

{% hint style="info" %}
Head to the [Crypto-Fiat ramps](/polystream/crypto-fiat-ramp) section to learn more.
{% endhint %}

{% hint style="info" %}
Head to the [Session Keys](/polystream/erc4337-smart-account-wallets) section to learn more.
{% endhint %}


# Polystream Vaults

Engineering advanced crypto yield strategies.

### A Simple Way to Earn Crypto Yields

Polystream Vaults offer a familiar banking-like experience with the higher yields of crypto - without any of the complexity. We handle all the technical details so you don't have to.

### A Truly Simple Experience

With Polystream, you'll only see one asset in your account: **USDC**. Behind the scenes, our protocol handles everything else:

* Converting between currencies
* Deploying to optimal yield strategies
* Managing positions across protocols
* Hedging against market volatility
* Rebalancing for maximum returns

> You never need to know what terms like "AMM," "crosschain," or "LP" mean - because you shouldn't have to.

### What You See

Your dashboard shows only what matters:

1. **Your Balance**: The current value of your deposits in USDC
2. **Your Earnings**: How much your deposit has grown
3. **Current APY**: The annual yield rate you're currently earning
4. **Risk Level**: Simple indicator of the strategy's risk profile

### Getting Started is Easy

1. **Deposit**: Buy USDC directly with your local currency
2. **Choose a Strategy**: Select based on risk level and target yield
3. **Earn**: Watch your balance grow while we handle everything else

### Available Strategies

<table><thead><tr><th>Strategy</th><th>Risk Level</th><th width="143">Target APY</th><th>Description</th></tr></thead><tbody><tr><td>Conservative</td><td>⚠️</td><td>3-5%</td><td>Focus on lending to established protocols</td></tr><tr><td>Balanced</td><td>⚠️⚠️</td><td>5-10%</td><td>Mix of lending and staking strategies</td></tr><tr><td>Growth</td><td>⚠️⚠️⚠️</td><td>10%+</td><td>Higher yield with managed risk through advanced strategies</td></tr></tbody></table>

#### Strategy Breakdowns

**Conservative Strategy**

The Conservative strategy prioritizes capital preservation while still delivering yields significantly higher than traditional banking:

* **What we do**: We allocate your USDC primarily to leading lending protocols with the strongest security track records and most consistent returns.
* **Behind the scenes**: Your funds are distributed across multiple established lending platforms where borrowers pay interest to use these funds. We continuously monitor interest rates and shift allocations to maximize returns while maintaining strict risk parameters.
* **Ideal for**: Users who prioritize security and stable returns over maximum yield potential.

**Balanced Strategy**

Our Balanced strategy offers the sweet spot between risk and reward:

* **What we do**: We deploy your USDC across a diversified mix of lending protocols and staking opportunities, with strategic hedging to protect against market volatility.
* **Behind the scenes**: A portion of your funds is converted to ETH and other assets for staking while maintaining significant allocations in stablecoin lending. Our automated rebalancing system adjusts the ratio between these strategies based on market conditions.
* **Optimization advantage**: Research shows that optimal rebalancing frequency can improve returns by up to 27%. By pooling user funds, we can execute these rebalancing operations cost-effectively, even for smaller deposits.
* **Ideal for**: Users looking for enhanced yields while maintaining moderate risk exposure.

**Growth Strategy**

The Growth strategy aims for maximum sustainable yields:

* **What we do**: We utilize advanced DeFi techniques including strategic positions in Scroll ($SCR), ETH restaking, and optimized liquidity provision.
* **Behind the scenes**: Your USDC is strategically allocated across the entire yield spectrum, including:
  * ETH and Liquid Staking Derivatives for base staking returns
  * Liquid Restaking Tokens to enhance ETH staking yields
  * Scroll Token ($SCR) staking and ecosystem opportunities
  * Strategic hedging positions to mitigate downside risk
  * Dynamic rebalancing at optimal frequencies based on deposit size
* **Risk management**: Despite the higher yield target, we employ sophisticated risk controls:
  * Real-time protocol monitoring for early risk detection
  * Automatic position adjustments based on volatility metrics
  * Smart deposit limits per protocol to limit exposure
  * Diversification across multiple yield sources
* **Ideal for**: Users seeking maximum yields who understand and accept the associated higher risk level.

### What Happens Behind the Scenes

While you see a simple USDC balance, Polystream is working hard for you:

* Converting portions to ETH, stablecoins, and other tokens
* Deploying to verified lending platforms
* Participating in ETH staking and restaking
* Opening strategic positions to maximize yield
* Continuously monitoring and adjusting allocations

#### Advanced Yield Engineering

Our platform leverages several sophisticated techniques that would typically be inaccessible to average users:

**Smart Rebalancing**

* Research shows optimal rebalancing frequency varies by investment size:
  * Small portfolios ($2K-$6K): Monthly rebalancing optimal
  * Medium portfolios ($6K-$18K): Bi-weekly rebalancing optimal
  * Large portfolios (>$18K): Weekly rebalancing optimal
* By pooling user funds, we can implement the most efficient rebalancing strategy regardless of your deposit size
* Our algorithms continuously monitor for rebalancing opportunities, executing only when the potential gain exceeds transaction costs

**Protocol Selection & Risk Management**

* We only integrate with top protocols (>$5M TVL) that have passed our rigorous security assessments
* AI-powered monitoring system evaluates protocol health in real-time:
  * TVL (Total Value Locked) stability and growth
  * Smart contract audit status
  * Developer activity and community support
  * Historical reliability and incident response
* Automatic adjustments when risk parameters exceed thresholds

**Strategic Hedging**

For stable yield generation:

* Opening calibrated short positions to neutralize market volatility
* Maintaining optimal ratios between correlated assets
* Implementing liquidation protection mechanisms
* Diversifying yield sources to prevent single-point failures

**Fiat Integration Efficiency**

* Our fiat-crypto ramp optimizes conversion rates and minimizes slippage
* Batched processing reduces individual transaction costs
* Strategic timing of conversions based on market conditions
* Seamless multi-currency support (USD, EUR, MYR, etc.)

### Withdraw Anytime

Your funds remain accessible:

1. Simply request a withdrawal in the app&#x20;
2. Receive funds quickly without dealing with bridges, swaps, or gas fees

### For Those Who Want More Detail

{% hint style="info" %}
Detailed Strategies Breakdown: <https://www.example.com>

..

{% endhint %}


# ERC4337 Smart Account Wallets

Crypto for consumers

Polystream integrates ERC-4337 Account Abstraction to provide a seamless user experience by abstracting away complex blockchain interactions. This architecture allows users to interact with DeFi protocols without managing gas fees directly or dealing with the traditional complications of cryptocurrency wallets.

Polystream's ERC-4337 integration is enabled by leveraging [Biconomy’s Nexus Smart Accounts](https://bcnmy.github.io/abstractjs/index.html).

***

### Smart Account Architecture

#### 1. EntryPoint Contract

The [`EntryPoint.sol`](https://github.com/eth-infinitism/account-abstraction/blob/abff2aca61a8f0934e533d0d352978055fddbd96/contracts/core/EntryPoint.sol) contract is the central hub through which all user operations are processed:

```solidity
// Core contract that validates and executes UserOperations
contract EntryPoint {
    function handleOps(UserOperation[] calldata ops, address payable beneficiary) external;
    function handleAggregatedOps(...) external;
    function simulateValidation(UserOperation calldata userOp) external;
    // Additional functionality...
}
```

* Validates signatures and transaction parameters
* Executes batched user operations
* Manages gas refunds and paymaster interactions
* Provides simulation capabilities for off-chain validation

#### 2. Bundler&#x20;

Bundlers are a critical component of the ERC-4337 infrastructure that collect "UserOperation" objects from users and submit them to the EntryPoint contract:

<figure><img src="https://511560137-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FBRX14z25wLMxFcY12pGf%2Fuploads%2Fpk74nXiKenHO5FZqFDaY%2FUntitled%20Diagram.drawio%20(1).png?alt=media&amp;token=6f45ce62-26c6-444e-b360-99d1338f6cf1" alt=""><figcaption></figcaption></figure>

While the bundler itself is typically an off-chain service, your codebase integrates with bundlers through:

* UserOperation creation and signing in client-side code
* Verification and validation mechanisms in the smart contracts
* Tests for bundler compatibility

The core bundler interaction happens through the `SendUserOp` interface which is referenced in the `AASigner` class:

```typescript
export class AASigner extends Signer {
  // ...
  constructor(
    readonly signer: Signer,
    readonly entryPointAddress: string,
    readonly sendUserOp: SendUserOp, // Function to send UserOperations to a bundler
    readonly accountFactoryAddress: string,
    readonly index = 0,
    readonly provider = signer.provider
  ) {
    // ...
  }
  // ...
}
```

#### 3. Factory Contract

The [`SimpleAccountFactory.sol`](https://github.com/eth-infinitism/account-abstraction/blob/abff2aca61a8f0934e533d0d352978055fddbd96/contracts/samples/SimpleAccountFactory.sol) contract deploys new smart accounts when needed:

```solidity
// Creates new SimpleAccount instances
contract SimpleAccountFactory {
    function createAccount(address owner, uint256 salt) public returns (SimpleAccount);
    function getAddress(address owner, uint256 salt) public view returns (address);
    // Additional functionality...
}
```

* Deterministic account creation with CREATE2
* Address calculation for counterfactual accounts
* Batched account creation

#### 4. Paymaster

The optional [`VerifyingPaymaster.sol`](https://github.com/eth-infinitism/account-abstraction/blob/abff2aca61a8f0934e533d0d352978055fddbd96/contracts/samples/VerifyingPaymaster.sol) contract can sponsor gas fees for users:

```solidity
// Sponsors gas fees for users
contract VerifyingPaymaster {
    function validatePaymasterUserOp(
        UserOperation calldata userOp,
        bytes32 userOpHash,
        uint256 maxCost
    ) external returns (bytes memory context, uint256 validationData);
    
    function postOp(
        PostOpMode mode,
        bytes calldata context,
        uint256 actualGasCost
    ) external;
    // Additional functionality...
}
```

* Validates operations it's willing to sponsor
* Implements post-operation logic for accounting
* Defines payment criteria and limitations

***

### User Operation Structure

The [`UserOperation.ts`](https://github.com/eth-infinitism/account-abstraction/blob/abff2aca61a8f0934e533d0d352978055fddbd96/test/UserOperation.ts) structure is the fundamental data type in ERC-4337:

```javascript
class UserOperation {
  constructor(params) {
    this.sender = getAddress(params.sender);          // Smart Account address
    this.nonce = params.nonce;                        // Unique nonce for operation
    this.factory = params.factory ?? undefined;       // Factory for counterfactual accounts
    this.factoryData = params.factoryData ?? '0x';    // Init data for account creation
    this.callData = params.callData ?? '0x';          // The operation data
    this.verificationGas = params.verificationGas;    // Gas for signature verification
    this.callGas = params.callGas;                    // Gas for the main call
    this.preVerificationGas = params.preVerificationGas; // Gas for pre-verification
    this.maxPriorityFee = params.maxPriorityFee;      // Max priority fee (EIP-1559)
    this.maxFeePerGas = params.maxFeePerGas;          // Max fee per gas (EIP-1559)
    this.paymaster = params.paymaster ?? undefined;   // Paymaster contract (optional)
    this.paymasterData = params.paymasterData ?? '0x'; // Paymaster verification data
    this.signature = params.signature ?? '0x';        // Account signature
    // Additional fields...
  }
}
```

***

### Sponsored Transactions

Polystream implements sponsored transactions through paymasters, allowing users to execute transactions without holding ETH. This creates a "Web2-like" experience where users don't need to understand gas or acquire ETH to use the platform.

The PaymasterFlow implementation is referenced in several test files, showing how transactions can be sponsored:

```typescript
// From account-abstraction/test/entrypoint.test.ts
describe('with paymaster (account with no eth)', () => {
  let testPaymasterAcceptAll: TestPaymasterAcceptAll
  let testPaymasterWithPostOp: TestPaymasterWithPostOp
  // ...
  
  beforeEach(async () => {
    testPaymasterAcceptAll = await new TestPaymasterAcceptAll__factory(ethersSigner).deploy(entryPoint.address)
    testPaymasterWithPostOp = await new TestPaymasterWithPostOp__factory(ethersSigner).deploy(entryPoint.address)
    await testPaymasterAcceptAll.addStake(globalUnstakeDelaySec, { value: paymasterStake })
    // ...
  })
  // ...
})
```

Paymasters can sponsor gas fees and can implement different payment models:

1. **Free transactions**: Subsidizing user operations as a business expense
2. **Token payments**: Users pay in ERC-20 tokens instead of ETH
3. **Subscription models**: Users with active subscriptions get free transactions

***

### Dealing with popups and signing for every transaction is one of the worst parts of crypto UX.

<figure><img src="https://511560137-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FBRX14z25wLMxFcY12pGf%2Fuploads%2Fy7yChNk3c8u1XhAA7Rv8%2FScreenshot%202025-02-25%20at%203.48.13%E2%80%AFPM.png?alt=media&amp;token=9d73e45e-46de-41f4-ab4d-9a847aa5d629" alt=""><figcaption></figcaption></figure>

Thanks to ERC4337, you won't need to sign endless transaction prompts:

* Set up once with a single approval
* No more constant wallet connection requests
* No more confusing technical permissions
* No more gas fee surprises

If interaction is needed, you'll only see one final confirmation - not dozens of confusing approval requests.


# Crypto-Fiat Ramp

Polystream integrates a seamless crypto-to-fiat on/off ramp solution, allowing users to easily convert between traditional currencies and cryptocurrencies directly within the application.

### Architecture

<figure><img src="https://511560137-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FBRX14z25wLMxFcY12pGf%2Fuploads%2Fg0kWGybDmJXeuARBOSJX%2FUntitled%20Diagram.drawio.png?alt=media&amp;token=562a5e34-4532-47d8-841a-7ac73540aad3" alt=""><figcaption><p>Architecture diagram</p></figcaption></figure>

The crypto-fiat on/off ramp solution in the Polystream frontend uses three main components:

1. **Privy Authentication**: Handles user identity and wallet management
2. **Transak Integration**: Provides the fiat-to-crypto conversion services
3. **Native UI Integration**: Creates a seamless user experience within the app


# Rewards

#### All Rewards in USDC

* **No confusing token claims**: Unlike traditional DeFi where you receive various governance tokens, LP tokens, and reward tokens, Polystream automatically converts all rewards to USDC
* **No manual swapping needed**: We handle all conversions behind the scenes, optimizing for the best rates and timing
* **Immediate usability**: Your rewards are in the same currency as your deposit, ready to compound or withdraw

#### Automatic Compounding

* All earned rewards are automatically reinvested to maximize your yield
* Compounding occurs at optimal intervals based on reward amounts and gas costs
* Watch your principal grow without taking any action

#### Future Governance Benefits

As Polystream evolves, we plan to introduce:

* **Governance token**: Early users will be eligible for future token distributions
* **Boost mechanisms**: Long-term users can earn enhanced APYs
* **Voting rights**: Help shape the future of the platform

All governance benefits will maintain our commitment to simplicity:

* Future tokens will have clear utility and value
* Governance participation will be optional and user-friendly
* Token management will remain intuitive even for crypto beginners

#### Referral Program

Share Polystream with friends and earn additional rewards:

* Earn 5% of the yield your referrals generate (paid in USDC)
* No reduction in your referrals' returns
* Unlimited referral earning potential

The bottom line: with Polystream, you only need to think about one number—your growing USDC balance. We handle all the complex token management, conversions, and optimizations behind the scenes.


# AI Agents

Turn your intents into blockchain actions

Polystream AI Agent is an intelligent conversational assistant that provides users with real-time support for DeFi operations, yield optimization strategies, and portfolio management directly within the Polystream mobile application. Designed to make DeFi accessible to mainstream users, the agent serves as both an educational tool and a transaction interface.

{% embed url="<https://youtu.be/gf2MNxz9g-Q>" %}
Polystream AI Agent demo video
{% endembed %}

***

### Conversational Financial Assistant

The AI assistant is specialized in DeFi topics relevant to Polystream users:

* **Yield Strategy Explanations**: Clear descriptions of different yield strategies and their risk profiles
* **Protocol Education**: Information about integrated protocols (Aave, LayerBank, SyncSwap, etc.)
* **Market Insights**: General understanding of market conditions and yield opportunities
* **Portfolio Analysis**: Ability to discuss the user's current investments and positions

### Transaction Initiation

Users can perform financial actions using natural language:

* **Deposit Funds**: "I want to deposit 500 USDC into the conservative yield strategy"
* **Withdraw Funds**: "Withdraw 200 USDC from my vault"
* **Portfolio Adjustments**: "Move my assets to a more aggressive strategy"
* **Balance Checks**: "What's my current balance?"

### Future Roadmap

The Polystream AI Agent will continue to evolve with planned enhancements:

* **Integration of AVS (Autonomous Verification Services)**\
  Introduce AVS to securely verify and audit agent-executed actions, enhancing user trust and operational transparency.
* **Integration with Oracles (API Data Feeds)**\
  Enable AI agents to fetch real-time, reliable off-chain and on-chain data via oracle APIs to optimize decision-making.
* **Enhanced Predictive Analytics**\
  Implement AI-driven predictive analytics to proactively suggest profitable investment opportunities based on market trends.


# Foundry

## Running Foundry Test Scripts

This documentation provides a step-by-step guide to setting up Foundry, configuring dependencies, and executing test scripts for integrations with Compound, Aave, and LayerBank protocols.

***

### 1. Install Foundry

Foundry is a Rust-based Ethereum development framework providing tools like `forge`, `cast`, and `anvil` for compiling, deploying, and testing smart contracts.

1\. Install Foundry (Linux/Mac):

```bash
curl -L https://foundry.paradigm.xyz | bash
```

Reload your environment:

```bash
foundryup
```

Verify installation:

```bash
forge --version
```

2\. For Windows users (WSL):

Option 1: Using Windows Subsystem for Linux (WSL)

* Install WSL and Ubuntu from the Microsoft Store.
* Follow the above Linux installation steps within WSL.

Option 2: Using PowerShell Run the following command in PowerShell:

```bash
iwr -useb https://foundry.paradigm.xyz | iex
```

Restart the terminal and run:

```bash
foundryup
```

Verify installation:

```bash
forge --version
```

***

### Clone and Configure the Repository

Clone the repository and enter its directory:

```bash
git clone https://github.com/polystream-core/polystream-contracts
cd polystream-contracts
```

### Install Dependencies

Foundry requires external libraries (Compound, Aave, LayerBank). Install them using `forge install`:

```bash
forge install \
    foundry-rs/forge-std \
    account-abstraction/contracts \
    aave/aave-v3-core \
    layerbank/layerbank-core \
    openzeppelin/openzeppelin-contracts \
    account-abstraction/contracts
```

This command ensures all dependencies are placed in the `lib/` directory.

#### Configure `foundry.toml`

Set your `foundry.toml` configuration as follows:

```toml
[profile.default]
optimizer = true
optimizer_runs = 200
via_ir = true
src = 'src/'
out = 'out/'
libs = ['lib/']
remappings = [
    "@syncswapcontracts/=lib/core-contracts/contracts/",
    "@layerbank-contracts/=lib/contracts/",
    "@openzeppelin/=lib/openzeppelin-contracts/",
    "@aave/=lib/aave-v3-origin/src/",
    "@forge-std/=lib/forge-std/",
    "@account-abstraction/=lib/account-abstraction/contracts/"
]
```

This configuration:

* Enables IR-based compilation (`via_ir = true`) for optimized bytecode.
* Enables Solidity optimizer with 200 runs (`optimizer = true`).
* Defines remappings for external dependencies.
* Specifies `src/` as the source directory and `lib/` as the library directory.

***

### Run Local Fork with Anvil

Anvil is a fast Ethereum RPC fork provider for running local blockchain simulations.

#### 1. Start Local Anvil Node

Run Anvil for local blockchain development:

```bash
anvil --fork-url YOUR_RPC_URL --chain-id YOUR_CHAIN_ID
```

Replace:

* `https://your-rpc-url.com` with your RPC provider.
* `YOUR_CHAIN_ID` with your blockchain's Chain ID (e.g., `1` for Ethereum, `534352` for Scroll).

Example for Scroll Mainnet (using Alchemy):

```bash
anvil --fork-url https://scroll-mainnet.g.alchemy.com/v2/YOUR_ALCHEMY_KEY --chain-id 534352
```

What This Does:

* Forks the mainnet, allowing contract interactions as if on mainnet.
* Persists the blockchain state, so transactions behave realistically.
* Runs a local RPC server (`127.0.0.1:8545`) for Foundry tests.

#### 2. Run Foundry Tests

Navigate to the test directory:

```bash
cd test
```

Run specific tests:

```bash
forge test --fork-url http://127.0.0.1:8545 --match-path test/YOUR_TEST_SCRIPT.t.sol -vvv
```

Replace `YOUR_TEST_SCRIPT.t.sol` with the actual test file name. Example:

```bash
forge test --fork-url http://127.0.0.1:8545 --match-path test/CompoundAdapterTest.t.sol -vvv
```

Explanation of Flags:

* \--fork-url `http://127.0.0.1:8545`→ Connects to the locally running Anvil fork.
* `--match-path test/YOUR_TEST_SCRIPT.t.sol` → Runs a specific test script.
* `-vvv` → Enables verbose mode (displays logs, transactions, and errors).

***

### Log Successful Test Runs

Use the following command to log test results and store them in a file:

```bash
forge test --fork-url http://127.0.0.1:8545 -vvv | tee test-results.log
```

`tee test-results.log` → Saves all logs to test-results.log.

Review logs by opening the file:

```bash
cat test-results.log
```

Example Running Test Script for Combined Vault

```bash
forge test --fork-url http://127.0.0.1:8545 --match-path test/CombinedVault.t.sol -vvv
```

If successful, the output will look like:

```bash
Ran 8 tests for test/CombinedVault.t.sol:CombinedVaultTest
[PASS] testEarlyWithdrawalFee() (gas: 607134)
Logs:
  User 1 USDC balance: 1000000000
  User 2 USDC balance: 1000000000
  Distributing assets to Active Protocol ID: 1
  Supplied to Protocol ID: 1 Amount: 100000000
  Initial USDC balance before withdrawal: 900000000
  Final USDC balance after withdrawal: 995000000
  Actual received: 95000000
  Expected to receive: 95000000
  Early withdrawal fee test passed

// ... other test cases

Suite result: ok. 8 passed; 0 failed; 0 skipped; finished in 2.24s (13.10s CPU time)      

Ran 1 test suite in 2.28s (2.24s CPU time): 8 tests passed, 0 failed, 0 skipped (8 total tests)
```

### Additional Resources

* [Foundry Documentation](https://book.getfoundry.sh/)
* [Polystream Documentation](https://docs.polystream.xyz/)


# Smart Contracts

The source code of Polystream contracts is available on [Github](https://github.com/polystream-core/polystream-contracts).

The core contracts fall into following categories in the Github repository:

* Adapter
* Core
* Rewards
* Strategy

### Adapter

Adapter contracts serve as standardized connectors between Polystream and various decentralized lending protocols (e.g., Aave, LayerBank). Each adapter abstracts the complexities and differences of individual protocols, enabling a uniform method for supplying assets, withdrawing assets, and harvesting yield.

### Core

The Core contracts serve as the backbone of Polystream, managing user deposits, withdrawals, yield distribution, and the registry of supported DeFi protocols and adapters. They enable smooth interactions between users, adapters, and yield-generating protocols.

### Rewards

The **Rewards** contracts handle the accurate and fair distribution of yield rewards generated by the Polystream vault. Rewards are distributed based on each user's share and the duration their assets are staked (time-weighted contributions). The system ensures that rewards are calculated, tracked, and claimed transparently.

### Strategy

Polystream employs an automated **Yield Optimization Strategy** designed to continuously maximize returns for users. By dynamically evaluating and reallocating funds across supported DeFi protocols, the system ensures user deposits always benefit from the highest available APY (Annual Percentage Yield).


# Adapter

### Purpose

* **Uniform Interface:** Adapters implement the `IProtocolAdapter` interface, providing a consistent set of functions regardless of underlying protocol differences.
* **Simplified Interaction:** They allow Polystream to interact seamlessly with multiple DeFi protocols without dealing directly with each protocol's unique implementations.
* **Yield Management:** Adapters handle yield harvesting, compounding, and fee management, simplifying profit calculations and risk management.

#### Key Components and Functionalities

[`IProtocolAdapter.sol`](https://github.com/polystream-core/polystream-contracts/blob/main/src/adapters/interfaces/IProtocolAdapter.sol)

Defines the standardized interface that all adapters must implement, including methods to:

* Supply and withdraw assets.
* Harvest and compound yields.
* Convert platform fees to rewards.
* Retrieve APY, balances, and principal data.

[`AaveAdapter.sol`](https://github.com/polystream-core/polystream-contracts/blob/main/src/adapters/AaveAdapter.sol)

Specific adapter for interacting with the Aave lending protocol:

* Handles supplying and withdrawing of assets to/from Aave pools.
* Harvests yield by withdrawing accrued interest and redepositing it, thereby compounding returns.
* Manages the conversion of fees into yield, tracks principal deposits, and calculates APY from Aave's interest rate models.

[`LayerBankAdapter.sol`](https://github.com/polystream-core/polystream-contracts/blob/main/src/adapters/LayerBankAdapter.sol)

Adapter specifically designed for LayerBank protocol:

* Manages asset deposits, withdrawals, and yield harvesting on LayerBank.
* Implements advanced handling, including error management for different redeem methods.
* Calculates APY based on LayerBank’s rate models, compounding yields by harvesting interest regularly.


# Core

### Purpose

* **Unified Management:** Centralizes interactions between users, adapters, and underlying DeFi protocols.
* **Yield Optimization:** Automates asset allocation, yield harvesting, reward distribution, and fee handling.
* **Protocol Flexibility:** Allows dynamic registration, removal, and switching of underlying DeFi protocols.

### Key Contracts and Responsibilities

#### [`ProtocolRegistry.sol`](https://github.com/polystream-core/polystream-contracts/blob/main/src/core/ProtocolRegistry.sol)

**Role:**

* Manages and stores information about registered DeFi protocols and their adapters.
* Allows adding or removing protocols and adapters dynamically.

**Functions:**

* `registerProtocol`: Add new protocols.
* `registerAdapter`: Link specific adapters to protocols and assets.
* `removeAdapter`: Remove adapters from registry.
* `setActiveProtocol`: Set the currently active protocol for asset deposits and yield harvesting.

**Interactions:**

* Utilized by the `CombinedVault` to query and interact with appropriate adapters based on registered protocols.

#### [`CombinedVault.sol`](https://github.com/polystream-core/polystream-contracts/blob/main/src/core/CombinedVault.sol)

**Role:**

* Handles user asset deposits, withdrawals, and yield harvesting.
* Implements time-weighted accounting to fairly distribute harvested rewards.
* Allocates funds evenly across registered DeFi protocols.

**Key Features:**

* **Epoch-based harvesting:** Harvests and distributes yields to users periodically (every epoch).
* **Time-weighted rewards:** Ensures fair yield distribution based on how long funds were deposited during each epoch.
* **Protocol flexibility:** Dynamically adds/removes underlying protocols and redistributes funds accordingly.

**Main Functionalities:**

* `deposit`: Users deposit assets into the vault, automatically allocated to registered protocols.
* `withdraw`: Users withdraw assets, applying fees if withdrawn prematurely within the same epoch.
* `checkAndHarvest`: Periodically harvests yields from all active protocols, distributing earnings based on users' time-weighted shares.

**Important Accounting Details:**

* Tracks individual user deposits, balances, and entry times.
* Maintains total user and adapter balances, ensuring accuracy in rewards and withdrawals.
* Manages early withdrawal fees, converting these fees into additional rewards for long-term users.

#### Interfaces ([`IRegistry.sol`](https://github.com/polystream-core/polystream-contracts/blob/main/src/core/interfaces/IRegistry.sol), [`IVault.sol`](https://github.com/polystream-core/polystream-contracts/blob/main/src/core/interfaces/IVault.sol))

* **`IRegistry` Interface:** Standardizes registry functionalities for protocol and adapter management, allowing consistency across implementations.
* **`IVault` Interface:** Defines essential vault functions such as deposits, withdrawals, yield harvesting, and user balance tracking, ensuring consistent behavior across implementations.


# Strategy

### **Purpose**

The **YieldOptimizer** ensures that users' deposits always generate the maximum possible returns by:

* Continuously comparing APYs (Annual Percentage Yields) across supported protocols.
* Automatically switching users' funds to the most profitable protocol at regular intervals.
* Reducing manual intervention, thus minimizing risk and enhancing efficiency.

### Key Contract and Responsibilities

#### [`YieldOptimizer.sol`](https://github.com/polystream-core/polystream-contracts/blob/main/src/Strategy/YieldOptimizer.sol)

* Manages asset allocation across lending protocols to achieve the highest possible returns.

***

**`optimizeYield()`**

Executes the yield optimization routine. Intended to run automatically via Chainlink Automation at each epoch's end.

**Operational Steps:**

* Retrieves the current active protocol’s APY.
* Iterates through all registered protocols to identify a protocol offering a higher APY.
* Executes fund withdrawal from the previously active protocol, if a better APY is identified.
* Sets the new protocol as active within the `ProtocolRegistry`.
* Immediately reinvests funds into the newly selected protocol.

**Events**

* **`OptimizedYield(oldProtocolId, newProtocolId, amount)`**:\
  Triggered whenever funds are moved to a new protocol for improved returns.


# Polystream Contract Address

This documentation lists all verified contract addresses deployed across the Scroll Sepolia and Base Sepolia networks, utilized by Polystream.

### Scroll Sepolia (Testnet)

| Contract                 | Address                                                                                                                           |
| ------------------------ | --------------------------------------------------------------------------------------------------------------------------------- |
| **MockUSDC**             | [`0x1d089e4b7697e2ae810731740d1ce005a04a631e`](https://sepolia.scrollscan.com/address/0x1d089e4b7697e2ae810731740d1ce005a04a631e) |
| **ProtocolRegistry**     | [`0x753d1Bb295c5543f15500C020C2981515918eBb5`](https://sepolia.scrollscan.com/address/0x753d1Bb295c5543f15500C020C2981515918eBb5) |
| **CombinedVault**        | [`0x4b935D786C207Ee20152893B67cA5a92cc146B78`](https://sepolia.scrollscan.com/address/0x4b935D786C207Ee20152893B67cA5a92cc146B78) |
| **YieldOptimizer**       | [`0x9dfD058D3a332dAaA46fc0cFacFC857472902032`](https://sepolia.scrollscan.com/address/0x9dfD058D3a332dAaA46fc0cFacFC857472902032) |
| **MockAaveAdapter**      | [`0x17c25D7A3c8B3e79ff7C488D140635DB8a62b5F4`](https://sepolia.scrollscan.com/address/0x17c25D7A3c8B3e79ff7C488D140635DB8a62b5F4) |
| **MockCompoundAdapter**  | [`0x989b87198D66A8df5c7901752e4241f212413F00`](https://sepolia.scrollscan.com/address/0x989b87198D66A8df5c7901752e4241f212413F00) |
| **MockLayerBankAdapter** | [`0x00EE29eA9177F05DB670AF7493D91c00e204A38B`](https://sepolia.scrollscan.com/address/0x00EE29eA9177F05DB670AF7493D91c00e204A38B) |

#### Scroll Mainnet Fork Compatible

| Contract             | Address                                                                                                                   |
| -------------------- | ------------------------------------------------------------------------------------------------------------------------- |
| **AaveAdapter**      | [`0xBBb91b3d5B8a9cbd653efC42b3C08358E75A1b90`](https://scrollscan.com/address/0xBBb91b3d5B8a9cbd653efC42b3C08358E75A1b90) |
| **LayerBankAdapter** | [`0x3599C2CB151D7D8CE4242B2E19dF0Ba6b474EeBA`](https://scrollscan.com/address/0x3599C2CB151D7D8CE4242B2E19dF0Ba6b474EeBA) |
| **SyncSwapAdapter**  | [`0x21B021ea2925a43025A783976D64Ee3B8015E6F6`](https://scrollscan.com/address/0x21B021ea2925a43025A783976D64Ee3B8015E6F6) |
| **CompoundAdapter**  | [`0xE0420B6EAf66cb13B94a8942058b59a15c38e356`](https://scrollscan.com/address/0xE0420B6EAf66cb13B94a8942058b59a15c38e356) |

### Base Sepolia (Testnet)

#### ERC-4337 Implementations

| Contract               | Address                                                                                                                         |
| ---------------------- | ------------------------------------------------------------------------------------------------------------------------------- |
| **K1ValidatorFactory** | [`0x2828A0E0f36d8d8BeAE95F00E2BbF235e4230fAc`](https://sepolia.basescan.org/address/0x2828A0E0f36d8d8BeAE95F00E2BbF235e4230fAc) |
| **Entrypoint(0.7.0)**  | [`0x0000000071727De22E5E9d8BAf0edAc6f37da032`](https://sepolia.basescan.org/address/0x0000000071727De22E5E9d8BAf0edAc6f37da032) |
| **Paymasters**         | [`0x00000072a5f551d6e80b2f6ad4fb256a27841bbc`](https://sepolia.basescan.org/address/0x00000072a5f551d6e80b2f6ad4fb256a27841bbc) |

#### Vaults

**High Risk**

| Contract                 | Address                                                                                                                         |
| ------------------------ | ------------------------------------------------------------------------------------------------------------------------------- |
| **MockUSDC**             | [`0x78bD59b3d9DAbDab8A39958E32dA04CCe9E2E6e8`](https://sepolia.basescan.org/address/0x78bD59b3d9DAbDab8A39958E32dA04CCe9E2E6e8) |
| **ProtocolRegistry**     | [`0xC16F0f7A9e8F7C4E08B317B184d69e21129A9Ba4`](https://sepolia.basescan.org/address/0xC16F0f7A9e8F7C4E08B317B184d69e21129A9Ba4) |
| **MockAaveAdapter**      | [`0xa95783A0AdE0D8f95b1E42c46d7E64A289E81e80`](https://sepolia.basescan.org/address/0xa95783A0AdE0D8f95b1E42c46d7E64A289E81e80) |
| **MockLayerBankAdapter** | [`0xA668fe5a33422D616484B030E0b568D769A62BF4`](https://sepolia.basescan.org/address/0xA668fe5a33422D616484B030E0b568D769A62BF4) |
| **CombinedVault**        | [`0xB309Ae62D176bDa6DfE469f1406292a7543fBF49`](https://sepolia.basescan.org/address/0xB309Ae62D176bDa6DfE469f1406292a7543fBF49) |
| **YieldOptimizer**       | [`0x888C7a03e25Cb398F6f848419eEc36af458f153A`](https://sepolia.basescan.org/address/0x888C7a03e25Cb398F6f848419eEc36af458f153A) |

**Medium Risk**

| Contract                 | Address                                                                                                                         |
| ------------------------ | ------------------------------------------------------------------------------------------------------------------------------- |
| **MockUSDC**             | [`0x78bD59b3d9DAbDab8A39958E32dA04CCe9E2E6e8`](https://sepolia.basescan.org/address/0x78bD59b3d9DAbDab8A39958E32dA04CCe9E2E6e8) |
| **ProtocolRegistry**     | [`0x16c321aE69165a1903Cbb47C563113575881A322`](https://sepolia.basescan.org/address/0x16c321aE69165a1903Cbb47C563113575881A322) |
| **MockAaveAdapter**      | [`0x3A63fb5CD3f1A05eB6179E5ac50b3B1B3F637993`](https://sepolia.basescan.org/address/0x3A63fb5CD3f1A05eB6179E5ac50b3B1B3F637993) |
| **MockLayerBankAdapter** | [`0xe6870e61765a26e4fb1E922318C9F08Ac4E0B09E`](https://sepolia.basescan.org/address/0xe6870e61765a26e4fb1E922318C9F08Ac4E0B09E) |
| **CombinedVault**        | [`0x1FB4128dAac9EFf5c10A3f1De2C2365e8636885a`](https://sepolia.basescan.org/address/0x1FB4128dAac9EFf5c10A3f1De2C2365e8636885a) |
| **YieldOptimizer**       | [`0x3F3B713c0Fe6e37feCB9E471451be4e5De77dDCd`](https://sepolia.basescan.org/address/0x3F3B713c0Fe6e37feCB9E471451be4e5De77dDCd) |

**Low Risk**

| Contract                 | Address                                                                                                                         |
| ------------------------ | ------------------------------------------------------------------------------------------------------------------------------- |
| **MockUSDC**             | [`0x78bD59b3d9DAbDab8A39958E32dA04CCe9E2E6e8`](https://sepolia.basescan.org/address/0x78bD59b3d9DAbDab8A39958E32dA04CCe9E2E6e8) |
| **ProtocolRegistry**     | [`0x32c7978865C87def85029307Db05129C33103f8C`](https://sepolia.basescan.org/address/0x32c7978865C87def85029307Db05129C33103f8C) |
| **MockAaveAdapter**      | [`0x200FE13eB88aa53Be3671dc49573b4eeDD4DB9F2`](https://sepolia.basescan.org/address/0x200FE13eB88aa53Be3671dc49573b4eeDD4DB9F2) |
| **MockLayerBankAdapter** | [`0xEFF624A3E34e2EaC412ba734244B5fB220633e7c`](https://sepolia.basescan.org/address/0xEFF624A3E34e2EaC412ba734244B5fB220633e7c) |
| **CombinedVault**        | [`0xb36881666A9f886Aee2C21e5490983782C76D8F8`](https://sepolia.basescan.org/address/0xb36881666A9f886Aee2C21e5490983782C76D8F8) |
| **YieldOptimizer**       | [`0x288936D022EcCA9d48354C691B16B12e3aea351C`](https://sepolia.basescan.org/address/0x288936D022EcCA9d48354C691B16B12e3aea351C) |

#### Base Mainnet Production-Ready (Non-mock)

| Contract            | Address                                                                                                                 |
| ------------------- | ----------------------------------------------------------------------------------------------------------------------- |
| **CompoundAdapter** | [`0x03a1E7f27cF9FDC3b391f9cbAdA38867C8542B1C`](https://basescan.org/address/0x03a1E7f27cF9FDC3b391f9cbAdA38867C8542B1C) |

#### Chainlink Automation Upkeeps

* **Low Risk**
  * [Yield Optimizer](https://automation.chain.link/base-sepolia/19592633126236891682666043125258171533116166520941179685825646141645925432339)
  * [Check and Harvest](https://automation.chain.link/base-sepolia/87721494756957191100234032125401142591208032377220498353673678292683728673730)
* **Medium Risk**
  * [Yield Optimizer](https://automation.chain.link/base-sepolia/98314516364213539040790969844350770599744547289741055073636813964628480151061)
  * [Check and Harvest](https://automation.chain.link/base-sepolia/111354042029573592214927345359678256484228151768938293740336212040373641721436)
* **High Risk**
  * [Yield Optimizer](https://automation.chain.link/base-sepolia/5722856465140387540441604925408038381342243203718227198244158903361646393851)
  * [Check and Harvest](https://automation.chain.link/base-sepolia/9221094301717693037134162986003226806540908205494210047742633189647059819185)

***

For more details visit [Polystream Documentation](https://docs.polystream.xyz/).


# Project Architecture

Learn more about our project and tech used.

<figure><img src="https://511560137-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FBRX14z25wLMxFcY12pGf%2Fuploads%2FLt3ftBGk5xFzYFwfPhbs%2Fimage.png?alt=media&amp;token=873cb443-4058-43d7-b2d8-3bd9b9cb3059" alt=""><figcaption></figcaption></figure>


# Sequence Diagram

Learn more about flow of Polystream

<figure><img src="https://511560137-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FBRX14z25wLMxFcY12pGf%2Fuploads%2FPPOl08ajlj01yUz52shP%2FUntitled%20diagram-2025-03-17-200646.png?alt=media&amp;token=7c635e8f-f5aa-4a95-b137-146e3d8bdca4" alt=""><figcaption></figcaption></figure>


# Cranker

Cranker with chainlink automation upkeep

Chainlink Automation provides a decentralized network of automated agents (keepers) that trigger on-chain smart contract executions based on predefined conditions, eliminating manual intervention and operational risks.

#### Use Cases in Polystream

* **Epoch Management:**\
  Automated triggering of epoch changes to handle yield harvesting, yield optimization, and state updates at consistent intervals.
* **Reward Distributions:**\
  Automating distribution and accounting of accrued yield rewards at each epoch boundary to ensure timely and fair distribution.<br>

### How it Works (Technical Flow)

1. **Condition Definition:**\
   On-chain conditions (`checkUpkeep`) defined in the smart contract specify precisely when automation triggers should activate.

```solidity
solidityCopyEditfunction checkUpkeep(bytes calldata) external view returns (bool upkeepNeeded, bytes memory performData) {
    upkeepNeeded = (block.timestamp >= lastEpochTime + EPOCH_DURATION);
}
```

2. **Automated Execution:**\
   Once conditions are met, Chainlink Automation calls the `performUpkeep` function on your deployed contract:

```solidity
solidityCopyEditfunction performUpkeep(bytes calldata) external {
    checkAndHarvest(); // Harvest yield and distribute rewards
    optimizeYield();   // Automatically selects best yielding protocol
}
```

3. **$LINK Token Payments:**\
   Each automation execution consumes Chainlink's `$LINK` tokens from the project's Automation balance, compensating the keepers for their service.<br>

<figure><img src="https://511560137-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FBRX14z25wLMxFcY12pGf%2Fuploads%2FMva0inEBcn8j5ANfgifO%2Fimage.png?alt=media&amp;token=c7b51428-2275-4989-a620-b1b627258ca1" alt=""><figcaption><p>Chainlink Automation dashboard showing periodic <code>performUpkeep</code> executions and $LINK payments</p></figcaption></figure>


# Developer Contributions

This documentation explains how to create your own protocol adapter to integrate additional yield sources into the Polystream ecosystem.

Polystream is designed with a modular architecture that allows for easy integration of new yield-generating protocols. This is accomplished through the `IProtocolAdapter` interface, enabling developers to add support for any DeFi protocol that provides yield opportunities.

***

### Protocol Adapter Interface

Protocol adapters serve as standardized bridges between Polystream's core functionality and external DeFi protocols. All adapters implement the [`IProtocolAdapter.sol`](https://github.com/polystream-core/polystream-contracts/blob/main/src/adapters/interfaces/IProtocolAdapter.sol) interface.

```solidity
interface IProtocolAdapter {
    function supply(address asset, uint256 amount) external returns (uint256);
    function withdraw(address asset, uint256 amount) external returns (uint256);
    function withdrawToUser(address asset, uint256 amount, address user) external returns (uint256);
    function harvest(address asset) external returns (uint256);
    function convertFeeToReward(address asset, uint256 fee) external;
    function getAPY(address asset) external view returns (uint256);
    function getBalance(address asset) external view returns (uint256);
    function getTotalPrincipal(address asset) external view returns (uint256);
    function isAssetSupported(address asset) external view returns (bool);
    function getProtocolName() external view returns (string memory);
}
```

***

### Implementing a Protocol Adapter

#### Step 1: Create a new adapter contract

Create a new contract file in the `src/adapters` directory that implements the `IProtocolAdapter` interface:

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

import "./interfaces/IProtocolAdapter.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol";

/**
 * @title YourProtocolAdapter
 * @notice Adapter for interacting with YourProtocol
 */
contract YourProtocolAdapter is IProtocolAdapter, Ownable {
    // Protocol-specific variables and mappings
    
    // Implementation of interface methods
    // ...
}
```

#### Step 2: Implement key functions

**2.1 Supply Function**

The `supply` function allows users to deposit assets into the external protocol:

```solidity
/**
 * @dev Supply assets to the protocol
 * @param asset The address of the asset to supply
 * @param amount The amount of the asset to supply
 * @return The actual amount supplied
 */
function supply(address asset, uint256 amount) external override returns (uint256) {
    require(isAssetSupported(asset), "Asset not supported");
    require(amount > 0, "Amount must be greater than 0");
    
    // Get initial balance to verify transfer
    uint256 initialBalance = IERC20(asset).balanceOf(address(this));
    
    // Transfer asset from sender to this contract
    IERC20(asset).transferFrom(msg.sender, address(this), amount);
    
    // Verify the transfer
    uint256 receivedAmount = IERC20(asset).balanceOf(address(this)) - initialBalance;
    
    // Update your tracking variables
    totalPrincipal[asset] += receivedAmount;
    
    // Protocol-specific deposit logic
    // Example: depositToProtocol(asset, receivedAmount);
    
    return receivedAmount;
}
```

**2.2 Withdraw Function**

The `withdraw` function allows users to withdraw assets from the protocol:

```solidity
/**
 * @dev Withdraw assets from the protocol
 * @param asset The address of the asset to withdraw
 * @param amount The amount of the asset to withdraw
 * @return The actual amount withdrawn
 */
function withdraw(address asset, uint256 amount) external override returns (uint256) {
    require(isAssetSupported(asset), "Asset not supported");
    require(amount > 0, "Amount must be greater than 0");
    
    // Calculate maximum withdrawal amount
    uint256 maxWithdrawal = totalPrincipal[asset];
    uint256 withdrawAmount = amount > maxWithdrawal ? maxWithdrawal : amount;
    
    // Protocol-specific withdrawal logic
    // Example: uint256 withdrawn = withdrawFromProtocol(asset, withdrawAmount);
    uint256 withdrawn = 0; // Replace with actual implementation
    
    // Update state
    if (withdrawn <= totalPrincipal[asset]) {
        totalPrincipal[asset] -= withdrawn;
    } else {
        totalPrincipal[asset] = 0;
    }
    
    // Transfer withdrawn assets to the sender
    IERC20(asset).transfer(msg.sender, withdrawn);
    
    return withdrawn;
}
```

**2.3 Harvest Function**

The `harvest` function collects and compounds accumulated yield:

```solidity
/**
 * @dev Harvest yield from the protocol
 * @param asset The address of the asset
 * @return The total amount harvested
 */
function harvest(address asset) external override returns (uint256) {
    require(isAssetSupported(asset), "Asset not supported");
    
    // Protocol-specific yield harvesting logic
    // Example:
    // 1. Withdraw all assets
    // 2. Calculate yield as (withdrawn - principal)
    // 3. Claim any reward tokens
    // 4. Potentially swap reward tokens to the asset
    // 5. Redeposit everything
    
    uint256 yieldAmount = 0; // Replace with actual implementation
    
    // Update last harvest timestamp
    lastHarvestTimestamp[asset] = block.timestamp;
    
    return yieldAmount;
}
```

**2.4 APY Calculation Function**

The `getAPY` function provides the current annual percentage yield:

```solidity
/**
 * @dev Get the current APY for an asset
 * @param asset The address of the asset
 * @return The current APY in basis points (1% = 100)
 */
function getAPY(address asset) external view override returns (uint256) {
    require(isAssetSupported(asset), "Asset not supported");
    
    // Protocol-specific APY calculation logic
    // Example: Query protocol's rate, convert to basis points
    
    uint256 apyBps = 0; // Replace with actual implementation
    return apyBps;
}
```

#### Step 3: Implement additional helper functions

Additional functions include:

```solidity
/**
 * @dev Get the current balance in the protocol
 * @param asset The address of the asset
 * @return The current balance
 */
function getBalance(address asset) external view override returns (uint256) {
    require(isAssetSupported(asset), "Asset not supported");
    
    // Protocol-specific balance retrieval
    uint256 balance = 0; // Replace with actual implementation
    return balance;
}

/**
 * @dev Check if an asset is supported
 * @param asset The address of the asset
 * @return True if the asset is supported
 */
function isAssetSupported(address asset) external view override returns (bool) {
    return supportedAssets[asset];
}

/**
 * @dev Get the name of the protocol
 * @return The protocol name
 */
function getProtocolName() external pure override returns (string memory) {
    return "Your Protocol Name";
}

/**
 * @dev Get total principal amount for this asset
 * @param asset The address of the asset
 * @return The total principal amount
 */
function getTotalPrincipal(address asset) external view override returns (uint256) {
    return totalPrincipal[asset];
}

/**
 * @dev Convert fees to rewards in the protocol
 * @param asset The address of the asset
 * @param fee The amount of fee to convert
 */
function convertFeeToReward(address asset, uint256 fee) external override {
    require(isAssetSupported(asset), "Asset not supported");
    require(fee > 0, "Fee must be greater than 0");
    require(fee <= totalPrincipal[asset], "Fee exceeds total principal");
    
    // Reduce the total principal to convert fee to yield
    totalPrincipal[asset] -= fee;
}

/**
 * @dev Withdraw assets from the protocol directly to user
 * @param asset The address of the asset
 * @param amount The amount to withdraw
 * @param user The recipient address
 * @return The actual amount withdrawn
 */
function withdrawToUser(address asset, uint256 amount, address user) external override returns (uint256) {
    // Implementation similar to withdraw but sends assets to user instead of msg.sender
}
```

***

### Example Adapter Implementation: AaveAdapter

The [`AaveAdapter.sol`](https://github.com/polystream-core/polystream-contracts/blob/main/src/adapters/AaveAdapter.sol) provides a comprehensive implementation example for integrating with the Aave protocol:

```solidity
contract AaveAdapter is IProtocolAdapter, Ownable {
    // Aave Pool contract
    IAavePoolMinimal public immutable pool;

    // Optional contracts for reward token harvesting
    IRewardsController public rewardsController;
    IPriceOracleGetter public priceOracle;
    ISyncSwapRouter public syncSwapRouter;

    // Mapping of asset address to aToken address
    mapping(address => address) public aTokens;

    // Supported assets
    mapping(address => bool) public supportedAssets;

    // Protocol name
    string private constant PROTOCOL_NAME = "Aave V3";

    // Tracking initial deposits for profit calculation
    mapping(address => uint256) private initialDeposits;

    // Last harvest timestamp per asset
    mapping(address => uint256) public lastHarvestTimestamp;

    // Add tracking for total principal per asset
    mapping(address => uint256) public totalPrincipal;
    
    // Additional implementation...
}
```

Key implementation patterns from the AaveAdapter:

1. **Asset Management**: Track both principal deposits and yield separately
2. **Yield Harvesting**: Withdraw all assets, calculate yield, claim rewards, and redeposit
3. **Principal Protection**: Ensure withdrawals don't exceed the tracked principal
4. **Reward Handling**: Claim and potentially swap additional reward tokens

### Testing Your Protocol Adapter

Create a test file in the `test` directory to verify your adapter's functionality:

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

import "forge-std/Test.sol";
import "../src/adapters/YourProtocolAdapter.sol";

contract YourProtocolAdapterTest is Test {
    YourProtocolAdapter public adapter;
    address public testUser;
    address public testAsset;
    
    function setUp() public {
        // Setup adapter and test environment
        adapter = new YourProtocolAdapter(...constructor params...);
        testUser = address(0x1);
        testAsset = address(0x2);
        
        // Mock necessary functions
        // ...
    }
    
    function testSupply() public {
        // Test logic
        // ...
    }
    
    function testWithdraw() public {
        // Test logic
        // ...
    }
    
    function testHarvest() public {
        // Test logic
        // ...
    }
    
    // Additional tests
    // ...
}
```

### Examples

For more comprehensive examples, refer to the existing adapter implementations:

* [`AaveAdapter.sol`](https://github.com/polystream-core/polystream-contracts/blob/main/src/adapters/AaveAdapter.sol): Integrates with Aave for lending-based yield
* [`SyncSwapAdapter.sol`](https://github.com/polystream-core/polystream-contracts/blob/main/src/adapters/SyncSwapAdapter.sol): Integrates with SyncSwap for LP-based yield


# Socials

Join our community and get updated with our latest developments

Discord: <https://discord.gg/s3a4F8R4ch>

Twitter: <https://x.com/polystream_xyz>

For developers:

Github: <https://github.com/polystream-core>


# Feedback

Leave your feedback here: [https://www.github.com/polystream-core/discussions](https://github.com/orgs/polystream-core/discussions)


