### Clone Repository and Install Dependencies (Bash) Source: https://docs.symbiotic.fi/get-started/developers/relay-quickstart Clones the Symbiotic Super Sum repository, initializes submodules, and installs npm dependencies. This is the first step to set up the project locally. ```bash git clone https://github.com/symbioticfi/symbiotic-super-sum.git cd symbiotic-super-sum git submodule update --init --recursive npm install ``` -------------------------------- ### Start Relay Network with Docker Compose (Bash) Source: https://docs.symbiotic.fi/get-started/developers/relay-quickstart Launches the Anvil chains, deployer, and relay services using Docker Compose. This command starts the network in detached mode. ```bash docker compose --project-directory temp-network up -d ``` -------------------------------- ### Install Python and Dependencies in Dockerfile Source: https://docs.symbiotic.fi/ai/12_symbiotic-super-sum-example This Dockerfile sets up a build environment using the Foundry image. It installs Python 3, venv, and pip using the system's package manager (apt-get or apk). It then installs the 'tomli' Python package, which is a fallback for TOML parsing, and configures the user to 'foundry'. ```dockerfile FROM ghcr.io/foundry-rs/foundry:v1.4.3 USER root # Install Python (needed by relay deployment helper scripts) together with tomli fallback. RUN set -eux; \ if command -v apt-get >/dev/null 2>&1; then \ apt-get update; \ DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends \ python3 \ python3-venv \ python3-pip; \ rm -rf /var/lib/apt/lists/*; \ elif command -v apk >/dev/null 2>&1; then \ apk add --no-cache \ python3 \ py3-virtualenv \ py3-pip; \ else \ echo "Unable to determine package manager for Python installation." >&2; \ exit 1; \ fi; \ python3 -m pip install --no-cache-dir tomli; \ python3 --version USER foundry ``` -------------------------------- ### Install and Configure Symbiotic.fi Core Contracts Source: https://docs.symbiotic.fi/integrate/curators/deploy-vault These commands are used to install the Symbiotic.fi core contracts repository and update the remappings.txt file. This setup is a prerequisite for deploying core modules. ```bash forge install symbioticfi/core ``` ```txt ... @symbioticfi/core/=lib/core/ ``` -------------------------------- ### Deploy Vault with Whitelist Example (Solidity) Source: https://docs.symbiotic.fi/llms-full This Solidity code snippet illustrates the deployment of a Vault contract with whitelisting enabled. It imports necessary interfaces from the Symbiotic.fi core library, including Vault, IVaultConfigurator, IVault, and interfaces for delegator and slasher modules. This setup is crucial for managing deposits and role assignments within the Symbiotic.fi ecosystem. ```solidity import {Vault} from "@symbioticfi/core/src/contracts/vault/Vault.sol"; import {IVaultConfigurator} from "@symbioticfi/core/src/interfaces/IVaultConfigurator.sol"; import {IVault} from "@symbioticfi/core/src/interfaces/vault/IVault.sol"; import {IBaseDelegator} from "@symbioticfi/core/src/interfaces/delegator/IBaseDelegator.sol"; import {INetworkRestakeDelegator} from "@symbioticfi/core/src/interfaces/delegator/INetworkRestakeDelegator.sol"; import {IBaseSlasher} from "@symbioticfi/core/src/interfaces/slasher/IBaseSlasher.sol"; import {IVetoSlasher} from "@symbioticfi/core/src/interfaces/slasher/IVetoSlasher.sol"; // ... deployment code ... ``` -------------------------------- ### Generate and Run Network with Docker Compose Source: https://docs.symbiotic.fi/llms-full Shell script to generate Docker configuration and a command to start the network. It requires Docker to be installed and configured. ```bash #!/bin/bash docker compose --project-directory temp-network up -d ``` -------------------------------- ### Basic Usage Example in Rust Source: https://docs.symbiotic.fi/ai/11_relay-client-rs Demonstrates the basic usage of the relay client in Rust. This example is intended to showcase typical interactions with the client library. It assumes the necessary dependencies are available. ```rust use relay_client_rs::Client; #[tokio::main] async fn main() -> Result<(), Box> { // Assuming you have a configuration or endpoint to connect to let client = Client::new("ws://localhost:8080").await?; // Example: Sending a message let message = "Hello, relay!"; client.send_message(message).await?; println!("Sent: {}", message); // Example: Receiving messages (in a loop or with a callback) // This is a simplified example; real-world usage might involve more complex handling // For instance, you might use tokio::select! to handle receiving and other tasks. // For demonstration, we'll just try to receive one message. if let Some(received_message) = client.receive_message().await? { println!("Received: {}", received_message); } Ok(()) } ``` -------------------------------- ### Environment Variables Example Source: https://docs.symbiotic.fi/ai/06_rewards-contracts An example .env file outlining necessary environment variables for the project. These typically include RPC endpoint URLs for different networks and API keys for services like Etherscan. ```dotenv ETH_RPC_URL= ETH_RPC_URL_HOLESKY= ETHERSCAN_API_KEY= ``` -------------------------------- ### Example Distribution Data Structure Source: https://docs.symbiotic.fi/ai/06_rewards-contracts This JSON file provides an example structure for defining operator rewards for different tokens. It maps token addresses to a list of operators and their corresponding reward amounts. ```json [ { "token": "0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2", "operators": [ { "operator": "0x0000000000000000000000000000000000000001", "reward": "100000000000000000" }, { "operator": "0x0000000000000000000000000000000000000002", "reward": "300000000000000000" }, { "operator": "0x0000000000000000000000000000000000000003", "reward": "600000000000000000" } ] }, { "token": "0x7f39C581F595B53c5cb19bD0b3f8dA6c935E2Ca0", "operators": [ { "operator": "0x0000000000000000000000000000000000000002", "reward": "200000000000000000" }, { "operator": "0x0000000000000000000000000000000000000003", "reward": "250000000000000000" }, { "operator": "0x0000000000000000000000000000000000000004", "reward": "500000000000000000" } ] } ] ``` -------------------------------- ### Generate and Start Local Network Source: https://docs.symbiotic.fi/ai/12_symbiotic-super-sum-example This snippet covers the initial steps to generate the network configuration and start the local Symbiotic.fi network using Docker Compose. It assumes the `generate_network.sh` script is available. ```bash #!/bin/bash # Generate the network configuration ./generate_network.sh # Start the network in detached mode docker compose --project-directory temp-network up -d ``` -------------------------------- ### Environment Variable Example (.env.example) Source: https://docs.symbiotic.fi/ai/04_relay-contracts An example `.env` file for setting up environment variables. It includes a placeholder for the Ethereum RPC URL, which is essential for blockchain interactions. ```dotenv ETH_RPC_URL= ``` -------------------------------- ### Solidity: Example of Implementing Relay Deployment Configuration Source: https://docs.symbiotic.fi/integrate/networks/relay-onchain MyRelayDeploy.sol serves as an example implementation for the abstract RelayDeploy contract. It demonstrates how to include deployment configurations for Relay modules and implement the virtual functions to wire Symbiotic Core helpers. ```solidity // SPDX-License-Identifier: MIT pragma solidity ^0.8.25; import {RelayDeploy} from "./RelayDeploy.sol"; // Example implementation of RelayDeploy. // To use, rename to MyRelayDeploy.sol and update the TOML path. contract MyRelayDeploy is RelayDeploy { constructor(string memory tomlPath) { // Initialize the SymbioticCore with the path to the TOML configuration file. // The SymbioticCore contract will parse the TOML file to determine deployment settings. core = new SymbioticCore(tomlPath); } function deployKeyRegistry() public virtual override returns (address) { // Deployment logic for KeyRegistry // Example: return address(new KeyRegistry(...)); return address(0); } function deployVotingPowerProvider() public virtual override returns (address) { // Deployment logic for VotingPowerProvider // Example: return address(new VotingPowerProvider(...)); return address(0); } function deploySettlement() public virtual override returns (address) { // Deployment logic for Settlement // Example: return address(new Settlement(...)); return address(0); } function deployValSetDriver() public virtual override returns (address) { // Deployment logic for ValSetDriver // Example: return address(new ValSetDriver(...)); return address(0); } } ``` -------------------------------- ### Get Current Epoch Start Timestamp Source: https://docs.symbiotic.fi/ai/14_cli-python Retrieves the start timestamp of the current epoch. This view function takes no arguments and returns the timestamp as a uint48. ```json { "inputs": [], "name": "currentEpochStart", "outputs": [ { "internalType": "uint48", "name": "", "type": "uint48" } ], "stateMutability": "view", "type": "function" } ``` -------------------------------- ### Main Benchmark Function - Go Source: https://docs.symbiotic.fi/ai/12_symbiotic-super-sum-example This is the main entry point for the benchmark program. It initializes the logging level and then calls the `run` function to execute the benchmark process. Any errors encountered during the run are paniced. ```go func main() { slog.SetLogLoggerLevel(slog.LevelDebug) ctx := context.Background() if err := run(ctx); err != nil { panic(err) } } ``` -------------------------------- ### Get Vault Current Epoch Start Timestamp Source: https://docs.symbiotic.fi/ai/14_cli-python Retrieves the start timestamp of the current epoch for a vault. This function calls the 'currentEpochStart' storage variable for the vault. ```python def get_vault_current_epoch_start(self, vault_address): vault_address = self.normalize_address(vault_address) return self.get_data("vault", vault_address, "currentEpochStart") ``` -------------------------------- ### Deploy Network Configuration Base Script (Solidity) Source: https://docs.symbiotic.fi/ai/05_network-contracts This script provides a base implementation for deploying network configurations. It handles proxy creation using CREATE3 for deterministic deployment and integrates with various Symbiotic.fi core interfaces and OpenZeppelin's transparent upgradeable proxy pattern. It utilizes a salt for deployment and includes logic for initializing the proxy. ```solidity // SPDX-License-Identifier: MIT import {Script} from "forge-std/Script.sol"; import "./Logs.sol"; import {Network} from "../../src/Network.sol"; import {INetwork} from "../../src/interfaces/INetwork.sol"; import {SymbioticCoreConstants} from "@symbioticfi/core/test/integration/SymbioticCoreConstants.sol"; import {INetworkMiddlewareService} from "@symbioticfi/core/src/interfaces/service/INetworkMiddlewareService.sol"; import {IBaseDelegator} from "@symbioticfi/core/src/interfaces/delegator/IBaseDelegator.sol"; import {IVetoSlasher} from "@symbioticfi/core/src/interfaces/slasher/IVetoSlasher.sol"; import {CreateXWrapper} from "@symbioticfi/core/script/utils/CreateXWrapper.sol"; import {ProxyAdmin} from "@openzeppelin/contracts/proxy/transparent/ProxyAdmin.sol"; import {TransparentUpgradeableProxy} from "@openzeppelin/contracts/proxy/transparent/TransparentUpgradeableProxy.sol"; import {ERC1967Utils} from "@openzeppelin/contracts/proxy/ERC1967/ERC1967Utils.sol"; contract DeployNetworkBase is Script, Logs, CreateXWrapper { bytes11 salt; // Salt for CREATE3 deterministic deployment function runBase(DeployNetworkParams memory params) public returns (address) { // Needed for permissioned deploy protection // CreateX-specific salt generation // Create initialization code for TransparentUpgradeableProxy // Deploy proxy using CREATE3 // if target is address(0), it means that the delay is for the any address } function _getProxyAdmin(address proxy) internal view returns (address admin) { } } ``` -------------------------------- ### Initialize Symbiotic Off-Chain Node Configuration and Connections (Go) Source: https://docs.symbiotic.fi/ai/12_symbiotic-super-sum-example This snippet demonstrates the initialization process for the off-chain node. It parses configuration flags, connects to the relay API, establishes connections to multiple EVM networks, and binds to the SumTask smart contract on each network. It also handles potential mismatches in the number of provided RPC URLs and contract addresses, and retrieves the finalized block number for each chain. ```Go package main import ( "context" "encoding/json" "fmt" "log/slog" "math/big" "os" "os/signal" "syscall" "time" "github.com/ethereum/go-ethereum/core/types" "sum/internal/utils" "github.com/ethereum/go-ethereum/accounts/abi" "github.com/ethereum/go-ethereum/accounts/abi/bind" "github.com/ethereum/go-ethereum/common/hexutil" "github.com/ethereum/go-ethereum/crypto" v1 "github.com/symbioticfi/relay/api/client/v1" "sum/internal/contracts" "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/ethclient" "github.com/go-errors/errors" "github.com/spf13/cobra" ) const ( TaskCreated uint8 = iota TaskResponded TaskExpired TaskNotFound ) type config struct { relayApiURL string evmActivityURLs []string contractAddresses []string privateKey string logLevel string } var relayClient *v1.SymbioticClient var evmClients map[int64]*ethclient.Client var sumContracts map[int64]*contracts.SumTask var lastBlocks map[int64]uint64 func main() { slog.Info("Running sum task off-chain client", "args", os.Args) if err := run(); err != nil && !errors.Is(err, context.Canceled) { slog.Error("Error executing command", "error", err) os.Exit(1) } slog.Info("Sum task off-chain client completed successfully") } func run() error { rootCmd.PersistentFlags().StringVarP(&cfg.relayApiURL, "relay-api-url", "r", "", "Relay API URL") rootCmd.PersistentFlags().StringSliceVarP(&cfg.evmActivityURLs, "evm-rpc-urls", "e", []string{}, "EVM RPC URLs separated by comma (e.g., 'https://mainnet.infura.io/v3/,...')") rootCmd.PersistentFlags().StringSliceVarP(&cfg.contractAddresses, "contract-addresses", "a", []string{}, "SumTask contracts' addresses corresponding to the RPC URLs separated by comma (e.g., '0x4826533B4897376654Bb4d4AD88B7faFD0C98528,...')") rootCmd.PersistentFlags().StringVarP(&cfg.privateKey, "private-key", "p", "", "Task response private key") rootCmd.PersistentFlags().StringVarP(&cfg.logLevel, "log-level", "l", "info", "Log level") if err := rootCmd.MarkPersistentFlagRequired("relay-api-url"); err != nil { return errors.Errorf("failed to mark relay-api-url as required: %w", err) } if err := rootCmd.MarkPersistentFlagRequired("evm-rpc-urls"); err != nil { return errors.Errorf("failed to mark evm-rpc-urls as required: %w", err) } if err := rootCmd.MarkPersistentFlagRequired("contract-addresses"); err != nil { return errors.Errorf("failed to mark contract-addresses as required: %w", err) } if err := rootCmd.MarkPersistentFlagRequired("private-key"); err != nil { return errors.Errorf("failed to mark private-key as required: %w", err) } return rootCmd.Execute() } var cfg config type TaskState struct { ChainID int64 Task contracts.SumTaskTask Result *big.Int SigEpoch int64 SigRequestID string AggProof []byte Statuses map[int64]uint8 } var tasks map[common.Hash]TaskState // rootCmd represents the base command when called without any subcommands var rootCmd = &cobra.Command{ Use: "sum-node", SilenceUsage: true, SilenceErrors: true, RunE: func(cmd *cobra.Command, args []string) error { switch cfg.logLevel { case "debug": slog.SetLogLoggerLevel(slog.LevelDebug) case "info": slog.SetLogLoggerLevel(slog.LevelInfo) case "warn": slog.SetLogLoggerLevel(slog.LevelWarn) case "error": slog.SetLogLoggerLevel(slog.LevelError) } ctx := signalContext(context.Background()) var err error conn, err := utils.GetGRPCConnection(cfg.relayApiURL) if err != nil { return errors.Errorf("failed to create relay client: %w", err) } relayClient = v1.NewSymbioticClient(conn) if len(cfg.evmActivityURLs) == 0 { return errors.Errorf("no RPC URLs provided") } if len(cfg.contractAddresses) != len(cfg.evmActivityURLs) { return errors.Errorf("mismatched lengths: evm-rpc-urls=%d, contract-addresses=%d", len(cfg.evmActivityURLs), len(cfg.contractAddresses)) } evmClients = make(map[int64]*ethclient.Client) sumContracts = make(map[int64]*contracts.SumTask) tasks = make(map[common.Hash]TaskState) lastBlocks = make(map[int64]uint64) for i, evmRpcURL := range cfg.evmActivityURLs { evClient, err := ethclient.DialContext(ctx, evmRpcURL) if err != nil { return errors.Errorf("failed to connect to RPC URL '%s': %w", evmRpcURL, err) } chainID, err := evmClient.ChainID(ctx) if err != nil { return errors.Errorf("failed to get chain ID from RPC URL '%s': %w", evmRpcURL, err) } addr := common.HexToAddress(cfg.contractAddresses[i]) sumContract, err := contracts.NewSumTask(addr, evmClient) if err != nil { return errors.Errorf("failed to create sum contract for %s on chain %d: %w", addr.Hex(), chainID, err) } evClients[chainID.Int64()] = evmClient sumContracts[chainID.Int64()] = sumContract finalizedBlockNumber, err := getFinalizedBlockNumber(ctx, evmClient) if err != nil { ``` -------------------------------- ### Symbiotic Super Sum Example Source: https://docs.symbiotic.fi/integrate/builders-researchers/ai-resources Demonstrates the Symbiotic Super Sum functionality. This example likely involves complex data aggregation and calculation. It serves as a practical guide to utilizing this feature. ```markdown ## Symbiotic Super Sum Example This example demonstrates how to use the Symbiotic Super Sum feature to aggregate and analyze data. **Purpose:** To showcase the power of Symbiotic AI in performing complex summations and analyses. **Input:** Various data inputs depending on the specific use case. **Output:** Aggregated and summarized data. **Dependencies:** Requires the Symbiotic AI library to be installed. ``` -------------------------------- ### README.md Basic Usage (Markdown) Source: https://docs.symbiotic.fi/ai/11_relay-client-rs Provides an overview of the Symbiotic Relay Client Examples directory and instructions on how to run the `basic_usage` example. It explains how to connect to a server, use environment variables to specify the server URL, and notes the requirement for majority consensus for signature/proof generation. ```markdown # Symbiotic Relay Client Examples This directory contains examples demonstrating how to use the `symbiotic-relay-client` library to interact with Symbiotic Relay servers. ## Basic Usage Example The `basic_usage.rs` example shows how to: 1. Connect to a Symbiotic Relay server 2. Get current epoch information 3. Sign messages 4. Retrieve aggregation proofs and signatures 5. Get validator set information 6. Use streaming responses for real-time updates ## Running the Example ```bash cd examples cargo run --bin basic_usage ``` By default, the example will try to connect to `localhost:8080`. You can specify a different server URL by setting the `RELAY_SERVER_URL` environment variable: ```bash RELAY_SERVER_URL=my-relay-server:8080 cargo run --bin basic_usage ``` NOTE: for the signature/proof generation to work you need to run the script for all active relay servers to get the majority consensus to generate proof. ``` -------------------------------- ### Deployment Confirmation Logs (Bash) Source: https://docs.symbiotic.fi/ai/05_network-contracts Example console output logs indicating successful network deployment and vault opt-in. Shows addresses of deployed contracts and configured parameters. ```bash Deployed network network:0x90F545649eDA7a2083bA30ECC5C21335d030ae1d proxyAdminContract:0x79d771aeC770C936E05E51fA8e68f019a373f9b1 newImplementation:0x3C00C0ef1B1be4dFFeF07dB148bb5fbF31277091 salt:0x5465737433000000000000000000000000000000000000000000000000000000 Opted network into vault network:0x90F545649eDA7a2083bA30ECC5C21335d030ae1d vault:0x49fC19bAE549e0b5F99B5b42d7222Caf09E8d2a1 subnetworkId:0 maxNetworkLimit:1000 resolver:0xbf616b04c463b818e3336FF3767e61AB44103243 ``` -------------------------------- ### Onboard Network Integration Example Script (Solidity) Source: https://docs.symbiotic.fi/ai/03_core-contracts An example script demonstrating how to onboard a network within Symbiotic Fi. It imports necessary libraries like OpenZeppelin's SafeERC20 and Ownable, and utilizes console2 for logging. The run function takes a seed for randomization. ```solidity // SPDX-License-Identifier: MIT ⋮---- import "../SymbioticCoreInit.sol"; ⋮---- import {SafeERC20, IERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import {Ownable} from "@openzeppelin/contracts/access/Ownable.sol"; ⋮---- import {console2} from "forge-std/Test.sol"; ⋮---- // forge script script/integration/examples/OnboardNetwork.s.sol:OnboardNetworkScript SEED --sig "run(uint256)" --rpc-url=RPC --chain holesky --private-key PRIVATE_KEY --broadcast ⋮---- contract OnboardNetworkScript is SymbioticCoreInit { ⋮---- function run(uint256 seed) public override { // ------------------------------------------------------ CONFIG ------------------------------------------------------ // ⋮---- // ------------------------------------------------------ RUN ------------------------------------------------------ // ⋮---- // ------------------------------------------------------ VERIFY ------------------------------------------------------ // ⋮---- interface IwstETH { function stETH() external view returns (address); function getStETHByWstETH(uint256 _wstETHAmount) external view returns (uint256); function wrap(uint256 _stETHAmount) external returns (uint256); ``` -------------------------------- ### Expected Output for Task Result Verification Source: https://docs.symbiotic.fi/get-started/developers/relay-quickstart This example illustrates the expected JSON output when a task result is successfully retrieved and decoded using the 'cast' tool. It shows a timestamp and a corresponding value. ```json [ 1754052445, 42 ] ``` -------------------------------- ### Run Relay Service with Command-Line Flags (Bash) Source: https://docs.symbiotic.fi/llms-full Demonstrates how to launch the relay service using command-line arguments to override configuration file settings. This is useful for quick adjustments or scripting deployments. ```bash ./relay_sidecar \ --config config.yaml \ --log.level debug \ --storage-dir /var/lib/relay \ --api.listen ":8080" \ --p2p.listen "/ip4/0.0.0.0/tcp/8880" \ --driver.chain-id 1 \ --driver.address "0x..." \ --secret-keys "symb/0/15/0x...,evm/1/31337/0x..." \ --evm.chains "http://localhost:8545" ``` -------------------------------- ### Initialize Contract Source: https://docs.symbiotic.fi/ai/14_cli-python Initializes the contract with the provided data. This is a one-time setup function. ```APIDOC ## POST /initialize ### Description Initializes the contract with the provided data. This is a one-time setup function. ### Method POST ### Endpoint /initialize ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **data** (bytes) - Required - The initialization data. ### Request Example ```json { "data": "0x..." } ``` ### Response #### Success Response (200) This function does not return any value upon successful execution. #### Response Example (No response body for success) ``` -------------------------------- ### Get Current Epoch Response and Type URL (Rust) Source: https://docs.symbiotic.fi/ai/11_relay-client-rs Defines the response structure for the current epoch query, including functions for its full Protocol Buffer name and type URL. This response contains the epoch start time. ```rust pub struct GetCurrentEpochResponse { /// Epoch start time #[prost(message, optional, tag="2")] } fn full_name() -> ::prost::alloc::string::String { "api.proto.v1.GetCurrentEpochResponse".into() } fn type_url() -> ::prost::alloc::string::String { "/api.proto.v1.GetCurrentEpochResponse".into() } ``` -------------------------------- ### Deploy Key Registry and Configure Operators (Solidity) Source: https://docs.symbiotic.fi/ai/12_symbiotic-super-sum-example Deploys the KeyRegistry contract and then proceeds to fund operators and configure their keys. This involves iterating through a defined number of operators to set up their cryptographic keys for participation in the network. ```Solidity function runDeployKeyRegistry() public override { deployKeyRegistry({proxyOwner: getDeployerAddress(), isDeployerGuarded: false, salt: KEY_REGISTRY_SALT}); fundOperators(); for (uint256 i; i < OPERATOR_COUNT; ++i) { configureOperatorKeys(i); } } ``` -------------------------------- ### Symbiotic Network Main Execution Logic (Bash) Source: https://docs.symbiotic.fi/ai/12_symbiotic-super-sum-example This Bash script defines the main execution flow for the Symbiotic Network setup. It includes checks for Docker and Docker Compose availability, prompts the user for necessary input, prints status messages during generation, and provides final instructions for starting and managing the Dockerized network. It also outlines potential startup delays. ```bash # Main execution main() { print_header "Symbiotic Network Generator" # Check if required tools are available if ! command -v docker &> /dev/null; then print_error "Docker is not installed or not in PATH" exit 1 fi if ! command -v docker-compose &> /dev/null && ! docker compose version &> /dev/null; then print_error "Docker Compose is not installed or not in PATH" exit 1 fi get_user_input print_status "Generating Docker Compose configuration..." print_status "Creating $operators new operator accounts..." generate_docker_compose "$operators" "$commiters" "$aggregators" print_header "Setup Complete!" echo print_status "Files generated in temp-network/ directory:" echo " - temp-network/docker-compose.yml" echo " - temp-network/data-* (storage directories)" echo print_status "To start the network, run:" echo " docker compose --project-directory temp-network up -d" echo print_status "To check the status, run:" echo " docker compose --project-directory temp-network ps" echo print_status "To view logs, run:" echo " docker compose --project-directory temp-network logs -f" echo print_warning "Note: The first startup may take several minutes(2-4mins) as it needs to:" echo " 1. Download Docker images" echo " 2. Build the sum-node image" echo " 3. Deploy contracts" echo " 4. Generate network genesis and fund operators" echo } main "$@" ``` -------------------------------- ### Start Sum Node Script (Bash) Source: https://docs.symbiotic.fi/ai/12_symbiotic-super-sum-example This script launches the sum node, configuring it to connect to specified EVM RPC URLs and a relay API. It also sets contract addresses for the sum task and settlement, along with the node's private key and desired log level. The execution uses the exec command to replace the shell process. ```bash #!/bin/sh SUMTASK_ADDRESS=0xDf12251aD82BF1eb0E0951AD15d37AE5ED3Ac1dF SETTLEMENT_SUMTASK_ADDRESS=0xDf12251aD82BF1eb0E0951AD15d37AE5ED3Ac1dF exec /app/sum-node --evm-rpc-urls http://anvil:8545,http://anvil-settlement:8546 --relay-api-url "$1" --contract-addresses "$SUMTASK_ADDRESS,$SETTLEMENT_SUMTASK_ADDRESS" --private-key "$2" --log-level info ``` -------------------------------- ### Install Symbiotic CLI using pip Source: https://docs.symbiotic.fi/ai/14_cli-python This snippet shows how to install the Symbiotic CLI using pip, which requires Python 3.8 or higher. It installs the package from the requirements.txt file. ```bash pip3 install -r requirements.txt ``` -------------------------------- ### Install Symbiotic.fi Rewards Contract Repository Source: https://docs.symbiotic.fi/integrate/curators/deploy-vault Installs the symbioticfi/rewards repository as a dependency in your Foundry project using the forge install command. This is the first step to integrating the rewards contracts. ```bash forge install symbioticfi/rewards ``` -------------------------------- ### Deploy Network with Vault Opt-in (Solidity) Source: https://docs.symbiotic.fi/ai/05_network-contracts This Solidity contract, 'DeployNetworkForVaults', inherits from 'DeployNetworkForVaultsBase' to deploy a network implementation and a TransparentUpgradeableProxy. It uses CREATE3 for deterministic deployment and configures various network parameters such as delays, admin addresses, vault opt-ins, and metadata. The 'run' function is the entry point for the deployment process. ```solidity // SPDX-License-Identifier: MIT import {DeployNetworkForVaultsBase} from "./base/DeployNetworkForVaultsBase.sol"; /** * Deploys Network implementation and a TransparentUpgradeableProxy managed by ProxyAdmin. * Uses CREATE3 for deterministic proxy deployment. * Also, opt-ins the Network to the given Vault. * * Configuration is handled entirely by inherited contract. */ contract DeployNetworkForVaults is DeployNetworkForVaultsBase { // Configuration constants - UPDATE THESE BEFORE DEPLOYMENT // Name of the Network // Default minimum delay (will be applied for any action that doesn't have a specific delay yet) // Cold actions delay (a delay that will be applied for major actions like upgradeProxy and setMiddleware) // Hot actions delay (a delay that will be applied for minor actions like setMaxNetworkLimit and setResolver) // Admin address (will become executor, proposer, and default admin by default) // Vault address to opt-in to (multiple vaults can be set) // Maximum amount of delegation that network is ready to receive (multiple vaults can be set) // Resolver address (optional, is applied only if VetoSlasher is used) (multiple vaults can be set) // Optional // Subnetwork Identifier (multiple subnetworks can be used, e.g., to have different resolvers for the same network) // Metadata URI of the Network // Salt for deterministic deployment function run() public { ``` -------------------------------- ### Symbiotic Flight Delays Example Source: https://docs.symbiotic.fi/integrate/builders-researchers/ai-resources Illustrates the Symbiotic Flight Delays functionality, likely used for predicting or analyzing flight disruptions. This example provides insights into its application. ```markdown ## Symbiotic Flight Delays Example This example demonstrates how to use the Symbiotic Flight Delays feature to analyze and predict flight delays. **Purpose:** To showcase the capability of Symbiotic AI in handling time-series data and predicting events like flight delays. **Input:** Flight data, including schedules, historical delay information, and real-time updates. **Output:** Predictions and analysis of flight delays. **Dependencies:** Requires the Symbiotic AI library and access to relevant flight data. ``` -------------------------------- ### Configure Vault, Delegator, and Slasher Initialization Parameters Source: https://docs.symbiotic.fi/llms-full This snippet demonstrates the initialization parameters for a Vault, including roles for admin, deposit whitelisting, and deposit limits. It also details the configuration for a NetworkRestakeDelegator and a VetoSlasher, specifying parameters like hook addresses, network limits, operator shares, and slashing veto duration. ```solidity defaultAdminRoleHolder: 0xe8616DEcea16b5216e805B0b8caf7784de7570E7, depositWhitelistSetRoleHolder: 0xe8616DEcea16b5216e805B0b8caf7784de7570E7, depositorWhitelistRoleHolder: 0xe8616DEcea16b5216e805B0b8caf7784de7570E7, isDepositLimitSetRoleHolder: 0xe8616DEcea16b5216e805B0b8caf7784de7570E7, depositLimitSetRoleHolder: 0xe8616DEcea16b5216e805B0b8caf7784de7570E7 })), delegatorIndex: 0, delegatorParams: abi.encode(INetworkRestakeDelegator.InitParams({ baseParams: IBaseDelegator.BaseParams({ defaultAdminRoleHolder: 0xe8616DEcea16b5216e805B0b8caf7784de7570E7, hook: 0x0000000000000000000000000000000000000000, hookSetRoleHolder: 0xe8616DEcea16b5216e805B0b8caf7784de7570E7 }), networkLimitSetRoleHolders: networkLimitSetRoleHolders, operatorNetworkSharesSetRoleHolders: operatorNetworkSharesSetRoleHolders })), withSlasher: true, slasherIndex: 1, slasherParams: abi.encode(IVetoSlasher.InitParams({ baseParams: IBaseSlasher.BaseParams({ isBurnerHook: true }), vetoDuration: 86400, resolverSetEpochsDelay: 3 })) })) ``` -------------------------------- ### Wait for Processes to Start Source: https://docs.symbiotic.fi/ai/12_symbiotic-super-sum-example Waits for all managed processes to indicate they have started by checking their stdout for a specific string. It retries periodically and panics if not all processes start within a timeout. This function is crucial for ensuring all background services are ready before proceeding. ```go func (prs processes) waitServerStarted(ctx context.Context) { var startedCound int for i := range 100 { startedCound = 0 for _, pr := range prs { if strings.Contains(pr.stdOut.String(), "All missing epochs loaded") { startedCound++ } } if startedCound == len(prs) { break } slog.Info("Not all processes started successfully, retrying...", "attempt", i+1, "startedCount", startedCound, "totalCount", len(prs)) time.Sleep(time.Second) } if startedCound != len(prs) { prs.printErrLogs() panic("Not all processes started successfully. Check logs for details.") } slog.InfoContext(ctx, "All processes started", "count", len(prs)) } ``` -------------------------------- ### initialize Source: https://docs.symbiotic.fi/ai/14_cli-python Initializes the contract with provided data. ```APIDOC ## POST initialize ### Description Initializes the contract with provided data. ### Method POST ### Endpoint /websites/symbiotic_fi/initialize ### Parameters #### Request Body - **data** (bytes) - Required - The initialization data. ### Response #### Success Response (200) - **message** (string) - Success message. #### Response Example { "message": "Contract initialized successfully." } ``` -------------------------------- ### Install Burners Repository Source: https://docs.symbiotic.fi/llms-full This command installs the symbioticfi/burners repository into your Foundry project. This is a prerequisite for using the BurnerRouterFactory and related contracts. ```bash forge install symbioticfi/burners ``` -------------------------------- ### Deploy Network Script (Solidity) Source: https://docs.symbiotic.fi/ai/05_network-contracts Solidity script for deploying a network implementation and a TransparentUpgradeableProxy using CREATE3 for deterministic deployment. Configuration, including network name, default minimum delay, cold/hot actions delay, admin address, and metadata URI, is handled by inherited contracts. The script includes a run function for deployment. ```solidity // SPDX-License-Identifier: MIT import {DeployNetworkBase} from "./base/DeployNetworkBase.sol"; /** * Deploys Network implementation and a TransparentUpgradeableProxy managed by ProxyAdmin. * Uses CREATE3 for deterministic proxy deployment. * * Configuration is handled entirely by inherited contract. */ contract DeployNetwork is DeployNetworkBase { // Configuration constants - UPDATE THESE BEFORE DEPLOYMENT // Name of the Network // Default minimum delay (will be applied for any action that doesn't have a specific delay yet) // Cold actions delay (a delay that will be applied for major actions like upgradeProxy and setMiddleware) // Hot actions delay (a delay that will be applied for minor actions like setMaxNetworkLimit and setResolver) // Admin address (will become executor, proposer, and default admin by default) // Optional // Metadata URI of the Network // Salt for deterministic deployment function run() public { } } ``` -------------------------------- ### Install and Configure Burners Repository Source: https://docs.symbiotic.fi/integrate/curators/deploy-vault Instructions for installing the Symbiotic.fi burners repository using Forge and updating the remappings.txt file. This is a prerequisite for using the BurnerRouterFactory contract. ```bash forge install symbioticfi/burners ``` ```txt ... @symbioticfi/burners/=lib/burners/ ``` -------------------------------- ### Start Relay Sidecar Script (Bash) Source: https://docs.symbiotic.fi/ai/12_symbiotic-super-sum-example This script configures and starts the relay sidecar. It generates a YAML configuration file with settings for logging, API, metrics, driver contract details, and P2P networking. The sidecar is then executed with the generated configuration and provided secret keys and storage directory. ```bash #!/bin/sh DRIVER_ADDRESS=0x43C27243F96591892976FFf886511807B65a33d5 cat > /tmp/sidecar.yaml << EOFCONFIG # Logging log: level: "debug" mode: "pretty" # API Server Configuration api: listen: ":8080" # Metrics Configuration metrics: pprof: true # Driver Contract driver: chain-id: 31337 address: "$DRIVER_ADDRESS" # P2P Configuration p2p: listen: "/ip4/0.0.0.0/tcp/8880" bootnodes: - /dns4/relay-sidecar-1/tcp/8880/p2p/16Uiu2HAmFUiPYAJ7bE88Q8d7Kznrw5ifrje2e5QFyt7uFPk2G3iR dht-mode: "server" mdns: true # EVM Configuration evm: chains: - "http://anvil:8545" - "http://anvil-settlement:8546" max-calls: 30 EOFCONFIG exec /app/relay_sidecar --config /tmp/sidecar.yaml --secret-keys "$1" --storage-dir "$2" ``` -------------------------------- ### Clone Symbiotic Super Sum Repository (Bash) Source: https://docs.symbiotic.fi/ai/12_symbiotic-super-sum-example This Bash snippet demonstrates the initial steps for setting up the Symbiotic Super Sum project. It includes commands to clone the repository from GitHub, update its submodules to ensure all nested dependencies are fetched, and install the necessary Node.js packages using npm. ```bash git clone https://github.com/symbioticfi/symbiotic-super-sum.git ``` ```bash git submodule update --init --recursive ``` ```bash npm install ``` -------------------------------- ### Get Current Epoch Source: https://docs.symbiotic.fi/ai/11_relay-client-rs Fetches the current epoch number of the network. This is a simple endpoint to get the latest epoch information. ```APIDOC ## GET /api/v1/current_epoch ### Description Retrieves the current epoch number of the network. ### Method GET ### Endpoint /api/v1/current_epoch ### Response #### Success Response (200) - **epoch** (uint64) - The current epoch number. #### Response Example ```json { "epoch": 12345 } ``` ``` -------------------------------- ### Deploy Pure Network Script Configuration (Solidity) Source: https://docs.symbiotic.fi/ai/05_network-contracts Configuration parameters for deploying a new network from scratch using the DeployNetwork.s.sol script. This includes network name, various delay settings, and the admin address. ```solidity // Name of the Network string NAME = "My Network"; // Default minimum delay (will be applied for any action that doesn't have a specific delay yet) uint256 DEFAULT_MIN_DELAY = 3 days; // Cold actions delay (a delay that will be applied for major actions like upgradeProxy and setMiddleware) uint256 COLD_ACTIONS_DELAY = 14 days; // Hot actions delay (a delay that will be applied for minor actions like setMaxNetworkLimit and setResolver) uint256 HOT_ACTIONS_DELAY = 0; // Admin address (will become executor, proposer, and default admin by default) address ADMIN = 0x0000000000000000000000000000000000000000; // Optional // Metadata URI of the Network string METADATA_URI = ""; // Salt for deterministic deployment bytes11 SALT = "SymNetwork"; ``` -------------------------------- ### Install Symbiotic.fi Core Contracts Source: https://docs.symbiotic.fi/integrate/curators/deploy-vault This bash command installs the symbioticfi/core repository as a dependency into your Foundry project. This allows you to import and use the core contracts in your own Solidity projects. ```bash forge install symbioticfi/core ``` -------------------------------- ### Install Dependencies (Bash) Source: https://docs.symbiotic.fi/integrate/networks/register-network Installs the necessary Node.js dependencies for the Symbiotic Network project using npm. This command should be run after cloning the repository. ```bash npm install ``` -------------------------------- ### Get All Operators (Python) Source: https://docs.symbiotic.fi/ai/14_cli-python Fetches a list of all registered operator addresses. It queries the 'op_registry' contract to get the total number of entities and then retrieves each operator's address. ```python def get_ops(self): total_entities = self.contracts["op_registry"].functions.totalEntities().call() w3_multicall = W3Multicall(self.w3) for i in range(total_entities): w3_multicall.add( W3Multicall.Call( self.addresses["op_registry"], "entity(uint256)(address)", i ) ) ops = w3_multicall.call() return [self.normalize_address(op) for op in ops] ``` -------------------------------- ### Deploy Vault with Configuration Addresses (Solidity) Source: https://docs.symbiotic.fi/llms-full This Solidity code snippet shows the deployment of a Vault using the IVaultConfigurator. It imports necessary interfaces and defines addresses for the VaultConfigurator, collateral, and burner router. It then initializes the Vault with parameters such as version, owner, epoch duration, and whitelisting/limit settings. ```solidity import {IVaultConfigurator} from "@symbioticfi/core/src/interfaces/IVaultConfigurator.sol"; import {IVault} from "@symbioticfi/core/src/interfaces/vault/IVault.sol"; import {IBaseDelegator} from "@symbioticfi/core/src/interfaces/delegator/IBaseDelegator.sol"; import {INetworkRestakeDelegator} from "@symbioticfi/core/src/interfaces/delegator/INetworkRestakeDelegator.sol"; import {IBaseSlasher} from "@symbioticfi/core/src/interfaces/slasher/IBaseSlasher.sol"; import {IVetoSlasher} from "@symbioticfi/core/src/interfaces/slasher/IVetoSlasher.sol"; // ... address VAULT_CONFIGURATOR = 0x94c344E816A53D07fC4c7F4a18f82b6Da87CFc8f; // address of the VaultConfigurator (see Deployments page) // ... address[] memory networkLimitSetRoleHolders = new address[](1); networkLimitSetRoleHolders[0] = 0xe8616DEcea16b5216e805B0b8caf7784de7570E7; address[] memory operatorNetworkSharesSetRoleHolders = new address[](1); operatorNetworkSharesSetRoleHolders[0] = 0xe8616DEcea16b5216e805B0b8caf7784de7570E7; (address vault, address networkRestakeDelegator, address vetoSlasher) = IVaultConfigurator(VAULT_CONFIGURATOR).create( IVaultConfigurator.InitParams({ version: 1, // Vault’s version (= common one) owner: 0xe8616DEcea16b5216e805B0b8caf7784de7570E7, // address of the Vault’s owner (can migrate the Vault to new versions in the future) vaultParams: abi.encode(IVault.InitParams({ collateral: 0x8d09a4502Cc8Cf1547aD300E066060D043f6982D, // address of the collateral - wstETH burner: , // address of the deployed burner router epochDuration: 604800, // duration of the Vault epoch in seconds (= 7 days) depositWhitelist: false, // if enable deposit whitelisting isDepositLimit: false, // if enable deposit limit depositLimit: 0, // deposit limit ```