### Install Project Dependencies Source: https://github.com/symbioticfi/symbiotic-flight-delays/blob/main/README.md Installs all necessary dependencies for the Symbiotic Flight Delay Insurance project using pnpm and Go modules. It also ensures submodules are initialized. ```bash git clone --recurse-submodules https://github.com/symbioticfi/symbiotic-flight-delays.git cd symbiotic-flight-delays pnpm install cd off-chain && go mod tidy cd ../ui && pnpm install cd .. ``` -------------------------------- ### Start Oracle Node Source: https://context7.com/symbioticfi/symbiotic-flight-delays/llms.txt Launches the oracle node that synchronizes flight data to the blockchain. This includes command-line usage with various parameters and a Docker Compose configuration for deployment. ```bash # Command-line usage go run off-chain/cmd/node/main.go \ --relay-api-url="relay-sidecar-0:8080" \ --evm-rpc-url="http://localhost:8545" \ --flight-delays-address="0xA4b0f5eb09891c1538494c4989Eea0203b1153b1" \ --flights-api-url="http://localhost:8085" \ --private-key="0xac0974bec39a17e36ba4a6b4d238ff944bacb478cbed5efcae784d7bf4f2ff80" \ --poll-interval=5s \ --proof-poll-interval=3s \ --log-level=info # Docker compose configuration services: flight-node: image: flight-oracle:latest environment: - RELAY_API_URL=relay-sidecar-0:8080 - EVM_RPC_URL=http://anvil:8545 - CONTRACT_ADDRESS=0xA4b0f5eb09891c1538494c4989Eea0203b1153b1 - FLIGHTS_API_URL=http://flights-api:8085 - PRIVATE_KEY=${ORACLE_PRIVATE_KEY} depends_on: - anvil - flights-api - relay-sidecar-0 # Expected logs # INFO: Flights API listening addr=:8085 # INFO: scheduled flight action airline=ALPHA flight=ALPHA-001 action=CREATE epoch=42 # INFO: aggregation proof ready airline=ALPHA flight=ALPHA-001 action=CREATE # INFO: submitted flight action airline=ALPHA flight=ALPHA-001 action=CREATE tx=0x1234... # INFO: action confirmed on-chain airline=ALPHA flight=ALPHA-001 action=CREATE ``` -------------------------------- ### Start Local Development Network Source: https://github.com/symbioticfi/symbiotic-flight-delays/blob/main/README.md Launches the complete local development network for the Symbiotic Flight Delay Insurance project, including the anvil chain, relays, Settlement, mock flights API, and the off-chain oracle node. ```bash ./generate_network.sh docker compose --project-directory temp-network up -d ``` -------------------------------- ### Start Oracle Node Source: https://context7.com/symbioticfi/symbiotic-flight-delays/llms.txt Launches the oracle node responsible for syncing flight data to the blockchain. Configuration can be done via command-line flags or Docker environment variables. ```APIDOC ## Oracle Node Configuration: Start Oracle Node ### Description Launches the oracle node that syncs flight data to the blockchain. This node connects to various APIs and services to monitor and record flight information on-chain. ### Method Execution (Command-line or Docker) ### Endpoint N/A (Service execution) ### Parameters #### Command-line Flags - **--relay-api-url** (string) - Required - URL for the relay API. - **--evm-rpc-url** (string) - Required - RPC URL for the Ethereum Virtual Machine. - **--flight-delays-address** (string) - Required - The blockchain address of the flight delays contract. - **--flights-api-url** (string) - Required - URL for the flights API. - **--private-key** (string) - Required - Private key for signing transactions. - **--poll-interval** (duration) - Optional - Interval for polling the flights API (e.g., `5s`). - **--proof-poll-interval** (duration) - Optional - Interval for polling for aggregation proofs (e.g., `3s`). - **--log-level** (string) - Optional - Logging level (e.g., `info`, `debug`). #### Docker Environment Variables - **RELAY_API_URL** (string) - Required - URL for the relay API. - **EVM_RPC_URL** (string) - Required - RPC URL for the Ethereum Virtual Machine. - **CONTRACT_ADDRESS** (string) - Required - The blockchain address of the flight delays contract. - **FLIGHTS_API_URL** (string) - Required - URL for the flights API. - **PRIVATE_KEY** (string) - Required - Private key for signing transactions. ### Request Example (Command-line) ```bash go run off-chain/cmd/node/main.go \ --relay-api-url="relay-sidecar-0:8080" \ --evm-rpc-url="http://localhost:8545" \ --flight-delays-address="0xA4b0f5eb09891c1538494c4989Eea0203b1153b1" \ --flights-api-url="http://localhost:8085" \ --private-key="0xac0974bec39a17e36ba4a6b4d238ff944bacb478cbed5efcae784d7bf4f2ff80" \ --poll-interval=5s \ --proof-poll-interval=3s \ --log-level=info ``` ### Request Example (Docker Compose) ```yaml services: flight-node: image: flight-oracle:latest environment: - RELAY_API_URL=relay-sidecar-0:8080 - EVM_RPC_URL=http://anvil:8545 - CONTRACT_ADDRESS=0xA4b0f5eb09891c1538494c4989Eea0203b1153b1 - FLIGHTS_API_URL=http://flights-api:8085 - PRIVATE_KEY=${ORACLE_PRIVATE_KEY} depends_on: - anvil - flights-api - relay-sidecar-0 ``` ### Response (This section describes expected logs and operational output rather than a direct API response) #### Expected Logs - **INFO**: Flights API listening addr=:8085 - **INFO**: scheduled flight action airline=ALPHA flight=ALPHA-001 action=CREATE epoch=42 - **INFO**: aggregation proof ready airline=ALPHA flight=ALPHA-001 action=CREATE - **INFO**: submitted flight action airline=ALPHA flight=ALPHA-001 action=CREATE tx=0x1234... - **INFO**: action confirmed on-chain airline=ALPHA flight=ALPHA-001 action=CREATE ``` -------------------------------- ### Mock Flights API - Delay Flight Endpoint Source: https://github.com/symbioticfi/symbiotic-flight-delays/blob/main/README.md An example of how to mark a flight as delayed using the mock Flights API. This is crucial for triggering insurance claims. ```http POST /airlines/{airlineId}/flights/{flightId}/delay ``` -------------------------------- ### Mock Flights API - Create Flight Endpoint Source: https://github.com/symbioticfi/symbiotic-flight-delays/blob/main/README.md An example of how to create a new flight using the mock Flights API. This endpoint is used by the off-chain oracle and can be called directly for testing. ```http POST /airlines/{airlineId}/flights Request Body: { "flightId": "string", "departureTimestamp": "number" } ``` -------------------------------- ### Mock Flights API - Depart Flight Endpoint Source: https://github.com/symbioticfi/symbiotic-flight-delays/blob/main/README.md An example of how to mark a flight as departed using the mock Flights API. This signifies the flight has commenced its journey. ```http POST /airlines/{airlineId}/flights/{flightId}/depart ``` -------------------------------- ### Buy Flight Insurance Policy (Solidity, TypeScript) Source: https://context7.com/symbioticfi/symbiotic-flight-delays/llms.txt Allows users to purchase flight delay insurance by transferring a premium to the contract. The TypeScript example uses wagmi to interact with the contract, including approving the collateral token before purchasing the policy. ```solidity function buyInsurance(bytes32 airlineId, bytes32 flightId) external; ``` ```typescript import { writeContract } from '@wagmi/core' import { parseEther } from 'viem' // First approve collateral token await writeContract({ address: collateralAddress, abi: ERC20_ABI, functionName: 'approve', args: [flightDelaysAddress, parseEther('100')] }) // Then buy policy const airlineId = keccak256(toBytes('ALPHA')) const flightId = keccak256(toBytes('ALPHA-001')) const { hash } = await writeContract({ address: flightDelaysAddress, abi: FlightDelaysABI, functionName: 'buyInsurance', args: [airlineId, flightId] }) console.log('Insurance purchased:', hash) ``` -------------------------------- ### List Airlines - cURL Source: https://context7.com/symbioticfi/symbiotic-flight-delays/llms.txt Retrieves a list of all registered airlines from the mock Flights API. This cURL command demonstrates how to make a GET request to the /airlines endpoint. ```bash # GET /airlines - List all airlines curl http://localhost:8085/airlines # Response { "airlines": [ { "airlineId": "ALPHA", "name": "Alpha Air", "code": "AA" }, { "airlineId": "BETA", "name": "Beta Wings", "code": "BW" } ] } ``` -------------------------------- ### Fetch Airlines with Flights Source: https://context7.com/symbioticfi/symbiotic-flight-delays/llms.txt Retrieves all airlines and their associated flights from the API. This TypeScript function handles fetching and aggregating data, and includes an example of its usage in a React component. ```typescript // ui/src/api/flights.ts import type { AirlineWithFlights } from '../types' export async function fetchAirlinesWithFlights( baseUrl: string ): Promise { const normalized = baseUrl.replace(//+$/, '') // Fetch airlines const airlinesResp = await fetch(`${normalized}/airlines`) if (!airlinesResp.ok) { throw new Error(`Failed to fetch airlines: ${airlinesResp.status}`) } const { airlines } = await airlinesResp.json() // Fetch flights for each airline in parallel const results = await Promise.all( airlines.map(async (airline) => { const flightsResp = await fetch( `${normalized}/airlines/${encodeURIComponent(airline.airlineId)}/flights` ) if (!flightsResp.ok) { console.error(`Failed to fetch flights for ${airline.airlineId}`) return { ...airline, flights: [] } } const { flights } = await flightsResp.json() return { ...airline, flights } }) ) return results } // Usage in React component import { useEffect, useState } from 'react' import { fetchAirlinesWithFlights } from './api/flights' function FlightsList() { const [data, setData] = useState([]) const [loading, setLoading] = useState(true) useEffect(() => { fetchAirlinesWithFlights('http://localhost:8085') .then(setData) .catch(console.error) .finally(() => setLoading(false)) }, []) if (loading) return
Loading flights...
return (
{data.map(airline => (

{airline.name} ({airline.code})

    {airline.flights.map(flight => (
  • {flight.flightId} - {flight.status}
  • ))}
))}
) } ``` -------------------------------- ### List Flights - cURL Source: https://context7.com/symbioticfi/symbiotic-flight-delays/llms.txt Retrieves all flights for a specific airline from the mock Flights API. This cURL command demonstrates a GET request to the /airlines/{airlineId}/flights endpoint. ```bash # GET /airlines/{airlineId}/flights - List airline flights curl http://localhost:8085/airlines/ALPHA/flights # Response { "flights": [ { "airlineId": "ALPHA", "flightId": "ALPHA-001", "departureTimestamp": 1704067200, "status": "scheduled" }, { "airlineId": "ALPHA", "flightId": "ALPHA-002", "departureTimestamp": 1704070800, "status": "delayed" } ] } ``` -------------------------------- ### Create Flight on-chain (Solidity, Go) Source: https://context7.com/symbioticfi/symbiotic-flight-delays/llms.txt Creates a new scheduled flight on the blockchain, verifying cryptographic proof. Requires flight details and an aggregation proof from Symbiotic Settlement. The Go example demonstrates how to call this function from the oracle node. ```solidity function createFlight( bytes32 airlineId, bytes32 flightId, uint48 scheduledTimestamp, bytes32 previousFlightId, uint48 epoch, bytes calldata proof ) external; ``` ```go airlineHash := crypto.Keccak256Hash([]byte("ALPHA")) flightHash := crypto.Keccak256Hash([]byte("ALPHA-001")) previousHash := common.Hash{} // zero hash for first flight scheduledTime := big.NewInt(1704067200) // Unix timestamp epoch := big.NewInt(42) proof := []byte{0x1a, 0x2b, ...} // aggregation proof from Settlement tx, err := contract.CreateFlight( txOpts, airlineHash, flightHash, scheduledTime, [32]byte(previousHash), epoch, proof ) if err != nil { log.Fatal("createFlight failed:", err) } fmt.Println("Flight created, tx:", tx.Hash().Hex()) ``` -------------------------------- ### Claim Insurance Payout (Solidity, TypeScript) Source: https://context7.com/symbioticfi/symbiotic-flight-delays/llms.txt Enables policyholders to claim an insurance payout after a flight delay is confirmed on-chain. The TypeScript example includes checking the flight status before attempting to claim and provides error handling for common issues like non-delayed flights or non-existent policies. ```solidity function claimInsurance(bytes32 airlineId, bytes32 flightId) external; ``` ```typescript import { readContract, writeContract } from '@wagmi/core' async function claimFlightInsurance(airlineId: string, flightId: string) { try { // Check flight status first const flight = await readContract({ address: flightDelaysAddress, abi: FlightDelaysABI, functionName: 'flights', args: [airlineId, flightId] }) if (flight.status !== 2) { // 2 = DELAYED throw new Error('Flight not delayed') } // Claim payout const { hash } = await writeContract({ address: flightDelaysAddress, abi: FlightDelaysABI, functionName: 'claimInsurance', args: [airlineId, flightId] }) console.log('Claim submitted:', hash) return hash } catch (error) { if (error.message.includes('FlightNotDelayed')) { console.error('Cannot claim: flight not delayed') } else if (error.message.includes('PolicyNotFound')) { console.error('No policy purchased for this flight') } throw error } } ``` -------------------------------- ### Delay Flight - Solidity and Go Source: https://context7.com/symbioticfi/symbiotic-flight-delays/llms.txt Marks a flight as delayed on the blockchain, triggering slashing and enabling claims. Includes Solidity function and a Go example for an oracle node to build, sign, and submit the delay transaction with an aggregation proof. ```solidity // FlightDelays.sol - Update flight to delayed status function delayFlight( bytes32 airlineId, bytes32 flightId, uint48 epoch, bytes calldata proof ) external; ``` ```go // Go oracle node example - full delay flow func (n *flightNode) delayFlight(ctx context.Context, airline, flightId string) error { airlineHash := hashIdentifier(airline) flightHash := hashIdentifier(flightId) // Build and sign delay message payload := buildDelayPayload(airlineHash, flightHash) epoch, requestID := n.requestSettlementSignature(ctx, payload) // Poll for aggregation proof var proof []byte for i := 0; i < 10; i++ { resp, _ := n.relayClient.GetAggregationProof(ctx, requestID) if resp.AggregationProof != nil { proof = resp.AggregationProof.Proof break } time.Sleep(3 * time.Second) } // Submit delay transaction tx, err := n.contract.DelayFlight( txOpts, airlineHash, flightHash, big.NewInt(int64(epoch)), proof ) if err != nil { return fmt.Errorf("delayFlight tx failed: %w", err) } log.Println("Flight delayed on-chain, tx:", tx.Hash().Hex()) // Contract automatically slashes vault for total coverage amount return nil } ``` -------------------------------- ### Depart Flight - Solidity and Go Source: https://context7.com/symbioticfi/symbiotic-flight-delays/llms.txt Marks a flight as departed (on-time), distributing premiums as staker rewards. Includes Solidity function and a Go example for an oracle node to handle departure, pack status arguments, request a settlement signature, wait for proof, and submit the transaction. ```solidity // FlightDelays.sol - Mark flight departed (on-time) function departFlight( bytes32 airlineId, bytes32 flightId, uint48 epoch, bytes calldata proof ) external; ``` ```go // Oracle node workflow func (n *flightNode) handleDeparture(ctx context.Context, action *pendingAction) error { // Build depart message payload inner, err := statusInnerArgs.Pack( departTypehash, action.AirlineHash, action.FlightHash ) if err != nil { return err } // Get Settlement signature epoch, requestID, err := n.requestSignature(ctx, inner) if err != nil { return fmt.Errorf("sign depart message: %w", err) } // Wait for proof proof := n.waitForProof(ctx, requestID) // Submit transaction tx, err := n.contract.DepartFlight( txOpts, action.AirlineHash, action.FlightHash, big.NewInt(int64(epoch)), proof ) if err != nil { return err } fmt.Printf("Flight departed: %s, rewards distributed\n", tx.Hash().Hex()) // Premiums automatically distributed to stakers via BaseRewards return nil } ``` -------------------------------- ### Solidity: Import Grouping and Ordering Source: https://github.com/symbioticfi/symbiotic-flight-delays/blob/main/CONTRIBUTING.md Imports in Solidity should be grouped into distinct categories (contracts, libraries, interfaces, external files) and ordered alphabetically within each group. This structured approach enhances code readability and simplifies dependency management. ```solidity import {NetworkManager} from "../base/NetworkManager.sol"; import {OzEIP712} from "../base/OzEIP712.sol"; import {PermissionManager} from "../base/PermissionManager.sol"; import {Checkpoints} from "../../libraries/structs/Checkpoints.sol"; import {KeyTags} from "../../libraries/utils/KeyTags.sol"; import {ISettlement} from "../interfaces/modules/settlement/ISettlement.sol"; import {ISigVerifier} from "../interfaces/modules/settlement/sig-verifiers/ISigVerifier.sol"; import {StaticDelegateCallable} from "@symbioticfi/core/src/contracts/common/StaticDelegateCallable.sol"; import {Subnetwork} from "@symbioticfi/core/src/contracts/libraries/Subnetwork.sol"; import {Initializable} from "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol"; ``` -------------------------------- ### Solidity: Interface Naming Convention Source: https://github.com/symbioticfi/symbiotic-flight-delays/blob/main/CONTRIBUTING.md Interface names in Solidity should begin with a capital 'I' prefix. This convention clearly identifies interfaces and differentiates them from regular contract implementations, enhancing code organization. ```solidity interface IERC777 { ``` -------------------------------- ### Solidity: Explicit Version Pragma for Deployable Contracts Source: https://github.com/symbioticfi/symbiotic-flight-delays/blob/main/CONTRIBUTING.md Contracts intended for deployment in Solidity must specify an explicit version in their `pragma` statement. This ensures predictable behavior and prevents unintended compilations with incompatible Solidity versions. ```solidity pragma solidity 0.8.X; ``` -------------------------------- ### Solidity: msg.sender and tx.origin Comparison Source: https://github.com/symbioticfi/symbiotic-flight-delays/blob/main/CONTRIBUTING.md When comparing `msg.sender` or `tx.origin` in Solidity, these keywords should always appear on the right side of the inequality operator. This consistent placement improves code readability and adheres to established security patterns. ```solidity modifier onlyOwner() internal { if (owner != msg.sender) { revert NotOwner(); } } ``` -------------------------------- ### Mock Flights API (Go) Source: https://github.com/symbioticfi/symbiotic-flight-delays/blob/main/README.md A Go application that simulates a flights API, exposing endpoints for airlines and their flights. It allows for status transitions and is used by the off-chain oracle node for local testing. ```go // Example snippet from mock flights API (logic not provided in text) package main import ( "encoding/json" "net/http" ) func main() { http.HandleFunc("/airlines", handleAirlines) http.HandleFunc("/airlines/{airlineId}/flights", handleFlights) http.HandleFunc("/airlines/{airlineId}/flights/{flightId}/delay", handleDelayFlight) http.HandleFunc("/airlines/{airlineId}/flights/{flightId}/depart", handleDepartFlight) // Start the HTTP server on port 8085 http.ListenAndServe(":8085", nil) } func handleAirlines(w http.ResponseWriter, r *http.Request) { // ... implementation for handling airline requests ... } func handleFlights(w http.ResponseWriter, r *http.Request) { // ... implementation for handling flight requests ... } func handleDelayFlight(w http.ResponseWriter, r *http.Request) { // ... implementation for handling delay flight requests ... } func handleDepartFlight(w http.ResponseWriter, r *http.Request) { // ... implementation for handling depart flight requests ... } ``` -------------------------------- ### Solidity: Event Emission After State Change Source: https://github.com/symbioticfi/symbiotic-flight-delays/blob/main/CONTRIBUTING.md In Solidity, events should generally be emitted immediately after the state change they represent and share the same name as the function causing the change. This ensures that event logs accurately reflect state transitions. Exceptions for gas efficiency may be made if the observable event ordering is not affected. ```solidity function _burn(address who, uint256 value) internal { super._burn(who, value); emit Burn(who, value); } ``` -------------------------------- ### Solidity: Caret Range Pragma for Abstract Contracts, Libraries, and Interfaces Source: https://github.com/symbioticfi/symbiotic-flight-delays/blob/main/CONTRIBUTING.md Abstract contracts, libraries, and interfaces in Solidity should use the caret (`^`) range operator in their `pragma` statements. This promotes compatibility across minor version updates while maintaining a degree of control over the compiler version. ```solidity pragma solidity ^0.X.0; ``` -------------------------------- ### Smart Contract Management (Solidity) Source: https://github.com/symbioticfi/symbiotic-flight-delays/blob/main/README.md The core smart contracts for the flight delay insurance protocol, written in Solidity and managed with Foundry. These contracts handle airline registration, vault deployment, premium collection, slashing, and claims processing. ```solidity // Example snippet from FlightDelays.sol (contracts not provided in text) contract FlightDelays is ISymbioticSettlementController { // ... contract logic for managing flight insurance ... } ``` ```solidity // Example snippet from VotingPowers.sol (contracts not provided in text) contract VotingPowers { // ... contract logic for managing voting powers related to claims ... } ``` -------------------------------- ### User Interface (React/wagmi) Source: https://github.com/symbioticfi/symbiotic-flight-delays/blob/main/README.md The front-end user interface built with React and wagmi. It allows policy buyers to purchase coverage and claim payouts, and liquidity providers to deposit collateral, claim rewards, and manage their positions in Symbiotic vaults. ```javascript // Example snippet from UI components (code not provided in text) import React from 'react'; import { useContractWrite, useContractRead } from 'wagmi'; function PolicyBuyer() { // ... UI for buying policies and claiming ... return (
{/* Policy purchase form */} {/* Claim submission button */}
); } function LiquidityProvider() { // ... UI for depositing/withdrawing and claiming rewards ... return (
{/* Deposit/Withdraw forms */} {/* Reward claim button */}
); } ``` -------------------------------- ### Solidity: Unchecked Arithmetic Blocks Source: https://github.com/symbioticfi/symbiotic-flight-delays/blob/main/CONTRIBUTING.md When using unchecked arithmetic blocks in Solidity, a comment must explain why overflow is guaranteed not to happen or is permissible. If the reason is obvious from the preceding line, the comment can be omitted for conciseness. ```solidity unchecked { // Reason for overflow safety a + b; } ``` -------------------------------- ### Solidity: Private and Internal Variable/Function Naming Source: https://github.com/symbioticfi/symbiotic-flight-delays/blob/main/CONTRIBUTING.md Internal or private state variables and functions in Solidity contracts should be prefixed with an underscore to distinguish them from public or external counterparts. This convention improves code readability and maintainability. ```solidity contract TestContract { uint256 private _privateVar; uint256 internal _internalVar; function _testInternal() internal { ... } function _testPrivate() private { ... } } ``` -------------------------------- ### Off-chain Oracle Node (Go) Source: https://github.com/symbioticfi/symbiotic-flight-delays/blob/main/README.md The Go-based off-chain oracle node responsible for monitoring the mock flights API, requesting signatures from Symbiotic Settlement for flight events, and submitting transactions to the blockchain. ```go // Example snippet from off-chain oracle node (logic not provided in text) package node import ( "net/http" "time" ) func PollFlightsAPI(apiEndpoint string) { // Polls the flights API for updates // Requests signatures from Settlement // Submits transactions like createFlight, delayFlight, departFlight } func main() { // ... setup and start the oracle node ... go PollFlightsAPI("http://localhost:8085") // ... keep running ... } ``` -------------------------------- ### Solidity: Abstract Contract Declaration Source: https://github.com/symbioticfi/symbiotic-flight-delays/blob/main/CONTRIBUTING.md Contracts in Solidity that are not intended for standalone use and must be inherited by other contracts should be marked as abstract. This keyword enforces inheritance and prevents direct instantiation of incomplete contracts. ```solidity abstract contract AccessControl is ..., { // ... } ``` -------------------------------- ### Flights API Endpoints Source: https://github.com/symbioticfi/symbiotic-flight-delays/blob/main/README.md This section details the available endpoints for the mock Flights API, which serves airline and flight data and allows for flight status updates. ```APIDOC ## GET /healthz ### Description Readiness probe for the Flights API. ### Method GET ### Endpoint /healthz ### Parameters None ### Request Example None ### Response #### Success Response (200) - **status** (string) - Indicates the API health. #### Response Example ```json { "status": "ok" } ``` ## GET /airlines ### Description Lists all airlines and their current metadata. ### Method GET ### Endpoint /airlines ### Parameters None ### Request Example None ### Response #### Success Response (200) - **airlines** (array) - An array of airline objects. - **airlineId** (string) - Unique identifier for the airline. - **name** (string) - The name of the airline. - **code** (string) - The IATA airline code. #### Response Example ```json { "airlines": [ { "airlineId": "airline-1", "name": "Example Airlines", "code": "EXA" } ] } ``` ## POST /airlines ### Description Creates a new airline. ### Method POST ### Endpoint /airlines ### Parameters #### Request Body - **airlineId** (string) - Required - Unique identifier for the airline. - **name** (string) - Required - The name of the airline. - **code** (string) - Required - The IATA airline code. ### Request Example ```json { "airlineId": "airline-2", "name": "Another Airline", "code": "ANR" } ``` ### Response #### Success Response (200) - **message** (string) - Confirmation message. #### Response Example ```json { "message": "Airline created successfully." } ``` ## GET /airlines/{airlineId}/flights ### Description Lists flights for a specific airline. ### Method GET ### Endpoint /airlines/{airlineId}/flights ### Parameters #### Path Parameters - **airlineId** (string) - Required - The ID of the airline whose flights to list. ### Request Example None ### Response #### Success Response (200) - **flights** (array) - An array of flight objects. - **flightId** (string) - Unique identifier for the flight. - **departureTimestamp** (integer) - Unix timestamp for the flight departure. - **status** (string) - Current status of the flight (e.g., 'scheduled', 'delayed', 'departed'). #### Response Example ```json { "flights": [ { "flightId": "flight-101", "departureTimestamp": 1678886400, "status": "scheduled" } ] } ``` ## POST /airlines/{airlineId}/flights ### Description Creates or schedules a new flight for an airline. ### Method POST ### Endpoint /airlines/{airlineId}/flights ### Parameters #### Path Parameters - **airlineId** (string) - Required - The ID of the airline to which the flight belongs. #### Request Body - **flightId** (string) - Required - Unique identifier for the new flight. - **departureTimestamp** (integer) - Required - Unix timestamp for the flight departure. ### Request Example ```json { "flightId": "flight-102", "departureTimestamp": 1678972800 } ``` ### Response #### Success Response (200) - **message** (string) - Confirmation message. #### Response Example ```json { "message": "Flight scheduled successfully." } ``` ## POST /airlines/{airlineId}/flights/{flightId}/delay ### Description Marks a specific flight as delayed. ### Method POST ### Endpoint /airlines/{airlineId}/flights/{flightId}/delay ### Parameters #### Path Parameters - **airlineId** (string) - Required - The ID of the airline. - **flightId** (string) - Required - The ID of the flight to mark as delayed. ### Request Example None ### Response #### Success Response (200) - **message** (string) - Confirmation message. #### Response Example ```json { "message": "Flight marked as delayed." } ``` ## POST /airlines/{airlineId}/flights/{flightId}/depart ### Description Marks a specific flight as departed. ### Method POST ### Endpoint /airlines/{airlineId}/flights/{flightId}/depart ### Parameters #### Path Parameters - **airlineId** (string) - Required - The ID of the airline. - **flightId** (string) - Required - The ID of the flight to mark as departed. ### Request Example None ### Response #### Success Response (200) - **message** (string) - Confirmation message. #### Response Example ```json { "message": "Flight marked as departed." } ``` ``` -------------------------------- ### Create Flight - cURL Source: https://context7.com/symbioticfi/symbiotic-flight-delays/llms.txt Schedules a new flight for an airline in the mock system. This cURL command shows a POST request to the /airlines/{airlineId}/flights endpoint with flight details. ```bash # POST /airlines/{airlineId}/flights - Create flight curl -X POST http://localhost:8085/airlines/ALPHA/flights \ -H "Content-Type: application/json" \ -d '{ "flightId": "ALPHA-099", "departureTimestamp": 1704154800 }' # Success (201) { "flight": { "airlineId": "ALPHA", "flightId": "ALPHA-099", "departureTimestamp": 1704154800, "status": "scheduled" } } ``` -------------------------------- ### Create Airline - cURL Source: https://context7.com/symbioticfi/symbiotic-flight-delays/llms.txt Registers a new airline in the mock system. This cURL command shows how to use POST to the /airlines endpoint with JSON payload for airline details. ```bash # POST /airlines - Create new airline curl -X POST http://localhost:8085/airlines \ -H "Content-Type: application/json" \ -d '{ "airlineId": "DELTA", "name": "Delta Airlines", "code": "DL" }' # Success response (201) { "airline": { "airlineId": "DELTA", "name": "Delta Airlines", "code": "DL" } } # Error response (409 if exists) { "error": "airline already exists" } ``` -------------------------------- ### Solidity: Avoiding Naming Collisions with Trailing Underscore Source: https://github.com/symbioticfi/symbiotic-flight-delays/blob/main/CONTRIBUTING.md To prevent naming collisions between state variables and constructor parameters in Solidity, a single trailing underscore is used for parameters that share the same name as a state variable. This ensures clarity and avoids unintended variable shadowing. ```solidity contract TestContract { uint256 public foo; constructor(uint256 foo_) { foo = foo_; } } ``` -------------------------------- ### Mock Flights API Endpoints Source: https://context7.com/symbioticfi/symbiotic-flight-delays/llms.txt API endpoints for managing airlines and flights within a mock system. These endpoints simulate flight data operations. ```APIDOC ## Mock Flights API Endpoints ### List Airlines Returns all registered airlines. #### Method GET #### Endpoint `/airlines` #### Parameters None #### Response ##### Success Response (200) - **airlines** (array) - An array of airline objects. - **airlineId** (string) - Unique identifier for the airline. - **name** (string) - The name of the airline. - **code** (string) - The IATA code for the airline. ##### Response Example ```json { "airlines": [ { "airlineId": "ALPHA", "name": "Alpha Air", "code": "AA" } ] } ``` ### Create Airline Registers a new airline in the mock system. #### Method POST #### Endpoint `/airlines` #### Parameters ##### Request Body - **airlineId** (string) - Required - Unique identifier for the new airline. - **name** (string) - Required - The name of the new airline. - **code** (string) - Required - The IATA code for the new airline. ##### Request Example ```json { "airlineId": "DELTA", "name": "Delta Airlines", "code": "DL" } ``` ##### Success Response (201) - **airline** (object) - The newly created airline object. - **airlineId** (string) - Unique identifier for the airline. - **name** (string) - The name of the airline. - **code** (string) - The IATA code for the airline. ##### Error Response (409) - **error** (string) - Message indicating the airline already exists. ### List Flights Returns all flights for a specific airline. #### Method GET #### Endpoint `/airlines/{airlineId}/flights` #### Parameters ##### Path Parameters - **airlineId** (string) - Required - The unique identifier of the airline whose flights to list. #### Response ##### Success Response (200) - **flights** (array) - An array of flight objects for the specified airline. - **airlineId** (string) - The ID of the airline. - **flightId** (string) - The unique identifier for the flight. - **departureTimestamp** (integer) - The scheduled departure timestamp. - **status** (string) - The current status of the flight (e.g., "scheduled", "delayed"). ##### Response Example ```json { "flights": [ { "airlineId": "ALPHA", "flightId": "ALPHA-001", "departureTimestamp": 1704067200, "status": "scheduled" } ] } ``` ### Create Flight Schedules a new flight for an airline. #### Method POST #### Endpoint `/airlines/{airlineId}/flights` #### Parameters ##### Path Parameters - **airlineId** (string) - Required - The unique identifier of the airline to which the flight belongs. ##### Request Body - **flightId** (string) - Required - The unique identifier for the new flight. - **departureTimestamp** (integer) - Required - The scheduled departure timestamp for the flight. ##### Request Example ```json { "flightId": "ALPHA-099", "departureTimestamp": 1704154800 } ``` ##### Success Response (201) - **flight** (object) - The newly created flight object. - **airlineId** (string) - The ID of the airline. - **flightId** (string) - The unique identifier for the flight. - **departureTimestamp** (integer) - The scheduled departure timestamp. - **status** (string) - The initial status of the flight (usually "scheduled"). ##### Response Example ```json { "flight": { "airlineId": "ALPHA", "flightId": "ALPHA-099", "departureTimestamp": 1704154800, "status": "scheduled" } } ``` ### Update Flight Status to Delayed Marks a flight as delayed in the mock system. #### Method POST #### Endpoint `/airlines/{airlineId}/flights/{flightId}/delay` #### Parameters ##### Path Parameters - **airlineId** (string) - Required - The unique identifier of the airline. - **flightId** (string) - Required - The unique identifier of the flight to update. #### Response ##### Success Response (200) - **flight** (object) - The updated flight object with status "delayed". - **airlineId** (string) - The ID of the airline. - **flightId** (string) - The unique identifier for the flight. - **departureTimestamp** (integer) - The scheduled departure timestamp. - **status** (string) - The updated status of the flight (should be "delayed"). ##### Response Example ```json { "flight": { "airlineId": "ALPHA", "flightId": "ALPHA-001", "departureTimestamp": 1704067200, "status": "delayed" } } ``` ##### Error Response (400) - **error** (string) - Message indicating an invalid status transition. ##### Error Response Example ```json { "error": "invalid status transition" } ``` ``` -------------------------------- ### Stop and Clean Local Development Network Source: https://github.com/symbioticfi/symbiotic-flight-delays/blob/main/README.md Shuts down and removes all containers and associated volumes for the local Symbiotic Flight Delay Insurance development network. Also cleans up generated network files. ```bash docker compose --project-directory temp-network down -v rm -rf temp-network ``` -------------------------------- ### Deposit Collateral to Airline Vault (TypeScript) Source: https://context7.com/symbioticfi/symbiotic-flight-delays/llms.txt Deposits collateral tokens into a specific airline's vault to provide liquidity. This function requires the airline ID, amount, collateral token address, and the FlightDelays contract address. It first retrieves the airline's vault address, then approves the collateral token for the vault, and finally deposits the specified amount. ```typescript import { writeContract, readContract } from '@wagmi/core' import { parseEther } from 'viem' async function depositToAirlineVault( airlineId: string, amount: string, collateralToken: string, flightDelaysContract: string ) { // Get airline vault address const airlineHash = keccak256(toBytes(airlineId)) const airline = await readContract({ address: flightDelaysContract, abi: FlightDelaysABI, functionName: 'airlines', args: [airlineHash] }) const vaultAddress = airline.vault if (vaultAddress === '0x0000000000000000000000000000000000000000') { throw new Error('Airline vault not deployed yet') } // Approve collateral await writeContract({ address: collateralToken, abi: ERC20_ABI, functionName: 'approve', args: [vaultAddress, parseEther(amount)] }) // Deposit to vault const { hash } = await writeContract({ address: vaultAddress, abi: VaultABI, functionName: 'deposit', args: [parseEther(amount), userAddress] }) console.log(`Deposited ${amount} tokens to ${airlineId} vault:`, hash) return hash } // Usage await depositToAirlineVault('ALPHA', '1000', collateralAddr, contractAddr) // Output: Deposited 1000 tokens to ALPHA vault: 0xabcd... ``` -------------------------------- ### Fetch Airlines with Flights API Source: https://context7.com/symbioticfi/symbiotic-flight-delays/llms.txt Retrieves all airlines and their associated flights from the API. This is used by the frontend client to display flight information. ```APIDOC ## Frontend API Client: Fetch Airlines with Flights ### Description Retrieves all airlines and their flights from the API. This function is part of the frontend client's API interaction layer. ### Method GET ### Endpoint /airlines (for airlines) /airlines/{airlineId}/flights (for flights associated with an airline) ### Parameters #### Query Parameters - **baseUrl** (string) - Required - The base URL of the API. ### Request Example (TypeScript Client) ```typescript import type { AirlineWithFlights } from '../types' export async function fetchAirlinesWithFlights( baseUrl: string ): Promise { const normalized = baseUrl.replace(//+$/, '') // Fetch airlines const airlinesResp = await fetch(`${normalized}/airlines`) if (!airlinesResp.ok) { throw new Error(`Failed to fetch airlines: ${airlinesResp.status}`) } const { airlines } = await airlinesResp.json() // Fetch flights for each airline in parallel const results = await Promise.all( airlines.map(async (airline) => { const flightsResp = await fetch( `${normalized}/airlines/${encodeURIComponent(airline.airlineId)}/flights` ) if (!flightsResp.ok) { console.error(`Failed to fetch flights for ${airline.airlineId}`) return { ...airline, flights: [] } } const { flights } = await flightsResp.json() return { ...airline, flights } }) ) return results } ``` ### Response #### Success Response (200) - **airlines** (array) - A list of airlines, where each airline object contains its details and a list of its flights. - **airlineId** (string) - The unique identifier for the airline. - **name** (string) - The name of the airline. - **code** (string) - The IATA or ICAO code for the airline. - **flights** (array) - A list of flights associated with the airline. - **flightId** (string) - The unique identifier for the flight. - **status** (string) - The current status of the flight (e.g., "scheduled", "departed", "arrived"). #### Response Example (Conceptual for /airlines) ```json { "airlines": [ { "airlineId": "ALPHA", "name": "Alpha Air", "code": "AA", "flights": [ { "flightId": "ALPHA-001", "status": "scheduled" } ] } ] } ``` ``` -------------------------------- ### Buy Insurance Policy API Source: https://context7.com/symbioticfi/symbiotic-flight-delays/llms.txt Allows users to purchase flight delay insurance by transferring the premium to the contract. Requires prior approval of the collateral token. ```APIDOC ## POST /buyInsurance ### Description Purchases flight delay insurance by transferring a premium to the contract. ### Method POST ### Endpoint `FlightDelays.sol - Buy insurance for a specific flight` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **airlineId** (bytes32) - Required - Unique identifier for the airline. - **flightId** (bytes32) - Required - Unique identifier for the flight. ### Request Example ```json { "airlineId": "0xabc123...", "flightId": "0xdef456..." } ``` ### Response #### Success Response (200) Emits an `InsurancePurchased` event with `airlineId`, `flightId`, `buyer`, and `premium`. #### Response Example ```json { "txHash": "0x5678..." } ``` ``` -------------------------------- ### Create Flight API Source: https://context7.com/symbioticfi/symbiotic-flight-delays/llms.txt Creates a new scheduled flight on-chain. This function is typically called by an oracle node that has verified flight data. ```APIDOC ## POST /createFlight ### Description Creates a new scheduled flight on-chain with cryptographic proof verification. ### Method POST ### Endpoint `FlightDelays.sol - Create a new flight with Settlement proof` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **airlineId** (bytes32) - Required - Unique identifier for the airline. - **flightId** (bytes32) - Required - Unique identifier for the flight. - **scheduledTimestamp** (uint48) - Required - Unix timestamp for the scheduled departure. - **previousFlightId** (bytes32) - Required - The ID of the previous flight in the sequence (zero hash for the first flight). - **epoch** (uint48) - Required - The epoch number associated with the flight. - **proof** (bytes) - Required - Cryptographic proof from the Symbiotic Settlement layer. ### Request Example ```json { "airlineId": "0xabc123...", "flightId": "0xdef456...", "scheduledTimestamp": 1704067200, "previousFlightId": "0x0000...", "epoch": 42, "proof": "0x1a2b..." } ``` ### Response #### Success Response (200) Emits an event indicating successful flight creation. #### Response Example ```json { "txHash": "0x1234..." } ``` ```