Skip to content

Instantly share code, notes, and snippets.

@yongkangc
Created July 20, 2025 03:51
Show Gist options
  • Save yongkangc/5cba6d97174eb8854e396b22d147fd52 to your computer and use it in GitHub Desktop.
Save yongkangc/5cba6d97174eb8854e396b22d147fd52 to your computer and use it in GitHub Desktop.
Porto + Relay Technical Q&A - Comprehensive Architecture Analysis

Porto + Relay Technical Q&A

Comprehensive analysis of the Porto SDK and Relay architecture based on codebase examination

1. Overall Architecture

1.1 Why Layer Zero over other bridging solutions?

LayerZero was chosen over Chainlink CCIP, Axelar, and Debridge for several key reasons:

  1. Decentralized Verification Network (DVN) System

    • Uses multiple independent verifiers (oracles) instead of single point of failure
    • Configurable security with required/optional DVNs and thresholds
    • No reliance on centralized bridge operators
  2. Native Cross-Chain Messaging

    • Provides programmable cross-chain communication, not just asset bridging
    • Enables complex intent execution across chains
    • Built-in message verification and delivery guarantees
  3. Production-Ready Infrastructure

    • Established endpoints across major EVM chains
    • Proven track record with billions in TVL secured
    • Mature SDK and developer tools
  4. Flexible Security Model

    • Custom confirmation requirements per chain pair
    • Ability to configure different security levels for different use cases
    • Support for both speed and security optimizations

1.2 What does "trustless" mean in the design?

Trustless operation occurs at multiple levels:

  1. User-Relay Trustlessness

    • Users sign specific intents with exact execution parameters
    • Relay cannot deviate from signed intent or access user funds directly
    • Payment is atomic - relay only gets paid if execution succeeds
    • Orchestrator contract enforces execution rules on-chain
  2. Cross-Chain Trustlessness

    • LayerZero's DVN system eliminates single points of failure
    • Multiple independent verifiers must attest to cross-chain messages
    • No centralized custodians or bridge operators
  3. Account-Level Security

    • Porto accounts maintain full sovereignty over funds
    • Multi-signature and hierarchical key management
    • WebAuthn integration for secure, user-controlled authentication

1.3 Rationale for Orchestrator being on-chain

The Orchestrator must be on-chain because:

  1. Security Enforcement

    • Trustlessly validates intent signatures and parameters
    • Enforces payment logic (pre/post payment tranches)
    • Prevents relay from executing unauthorized operations
  2. Atomic Operations

    • Ensures payment and execution happen atomically
    • Provides rollback mechanisms if execution fails
    • Maintains consistency across multi-step operations
  3. Verifiable State

    • All intent executions are publicly auditable
    • Transparent fee calculations and payment flows
    • Immutable record of all account interactions

Philosophy: Security-critical operations on-chain, optimization off-chain

  • Fund custody and authorization: On-chain (Porto accounts, Orchestrator)
  • Complex routing and liquidity management: Off-chain (Relay)
  • Cross-chain verification: Hybrid (LayerZero DVN system)

1.4 Historical underpinning of the architecture

The architecture evolved from several key insights:

  1. Account Abstraction Limitations

    • Traditional AA requires gas tokens on each chain
    • Limited to single-chain operations
    • Complex user experience with multiple wallets
  2. Intent-Based Design

    • Users specify outcomes, not execution steps
    • Enables sophisticated optimization and routing
    • Abstracts away blockchain complexity
  3. Cross-Chain Native Philosophy

    • Built from ground up for multi-chain world
    • Not retrofitted from single-chain solution
    • Treats all chains as unified liquidity layer

2. Relay

2.1 Multi-nonce system and parallel execution

The multi-nonce system enables parallel execution through clever bit packing:

Nonce Structure (256 bits):
├─ Sequence Key (192 bits) - Groups related intents
├─ Sequential Nonce (64 bits) - Ordering within sequence
└─ Multichain Flag (upper 16 bits) - 0xc1d0 for cross-chain

Benefits:

  • Parallel Execution: Different sequence keys can execute simultaneously
  • Ordering Guarantee: Sequential nonces ensure ordering within each sequence
  • Cross-Chain Replay Protection: Multichain flag enables signature reuse across chains
  • User Control: Users can define custom sequence keys for grouping related operations

Implementation in relay/src/nonce.rs:

  • Uses DashMap<(ChainId, Address), Arc<Mutex<u64>>> for concurrent access
  • Allows multiple transactions per EOA as long as they use different sequence keys
  • Efficient nonce management without blocking unrelated transactions

2.2 Relay vs RPC differences and naming conventions

Key Differences from Traditional RPC:

  1. Intent-Based vs Transaction-Based

    • RPC: Execute specific transactions with exact parameters
    • Relay: Process user intents with flexible execution
  2. Multi-Chain Native

    • RPC: Single chain per endpoint
    • Relay: Cross-chain coordination built-in
  3. Fee Abstraction

    • RPC: Requires native gas tokens
    • Relay: Pay in any supported token
  4. Queue Management

    • RPC: Stateless request handling
    • Relay: Sophisticated transaction queuing and ordering

Naming Conventions:

  • Intent: User's desired outcome with signature
  • Quote: Fee estimation and execution parameters
  • Bundle: Group of related transactions (especially multichain)
  • Settler: Cross-chain settlement implementation
  • Orchestrator: On-chain contract managing execution

2.3 Types of intents available

Intent Classifications:

  1. By Scope:

    • Single: Single chain execution
    • MultiOutput: Output chain of multichain intent
    • MultiInput: Input chain of multichain intent
  2. By Structure:

    • Standard Intent: Complete execution package with signature
    • PreCall Intent: Subset for pre-execution operations
    • Transfer Intent: Fund movement for multichain operations
  3. By Execution:

    • Gas Sponsored: Relay pays gas, user pays in chosen token
    • User Paid: Traditional gas payment model
    • Hybrid: Combination of sponsored and user payment

Intent Components:

  • Execution data (calls to make)
  • Payment specification (pre/post amounts)
  • Nonce and expiry
  • Authorization (keys/delegations)
  • Optional pre-calls for setup

2.4 How apps like Privy integrate

Integration Points:

  1. Key Management Integration

    • Privy provides WebAuthn/social login keys
    • Porto keychain system accepts external keys
    • Seamless migration from Privy-managed to Porto accounts
  2. SDK Integration

    • Porto SDK wraps intent creation and signing
    • Compatible with existing Privy wallet interfaces
    • Minimal code changes for existing dApps
  3. Authentication Flow

    • Privy handles user authentication
    • Porto manages on-chain account and execution
    • Relay provides cross-chain and gas abstraction

2.5 Validation steps required

Multi-layered validation process:

  1. Intent Validation

    • EIP-712 signature verification
    • Nonce uniqueness and ordering
    • Expiry timestamp checks
    • Key authorization verification
  2. Economic Validation

    • Fee token balance verification
    • Gas estimation through simulation
    • Cross-chain fund availability checks
    • Payment amount validation
  3. Execution Validation

    • State override simulation
    • Revert reason analysis
    • Gas limit verification
    • Cross-chain message validation

Implementation in relay/src/transactions/service.rs

2.6 Most computationally intensive processes

Computational Bottlenecks:

  1. Simulation and Gas Estimation

    • Fork state creation for each simulation
    • Multiple simulation rounds for multichain
    • State override application and execution
  2. Merkle Tree Operations

    • EIP-712 hash computation for each intent
    • Merkle root calculation for batches
    • Proof generation for verification
  3. Fund Sourcing Algorithm

    • Iterative optimization across multiple chains
    • Complex cost calculation with escrow fees
    • Multiple simulation rounds for accurate estimates

Network/Database Intensity:

  • PostgreSQL for persistent state
  • Real-time price oracle feeds
  • Cross-chain RPC calls for state queries
  • LayerZero message verification

2.7 Intent-Smart Contract interaction

Execution Flow:

  1. Intent Processing

    • Relay validates and simulates intent
    • Constructs execution transaction
    • Routes through appropriate Orchestrator
  2. On-Chain Execution

    • Orchestrator validates signature and nonce
    • Executes pre-payment if specified
    • Calls target contracts with intent data
    • Processes post-payment
  3. Cross-Chain Coordination

    • Source chain execution through escrow
    • LayerZero message passing
    • Destination chain settlement
    • Completion verification

Key Contracts:

  • Orchestrator.sol: Intent execution coordination
  • Account.sol: User account management
  • Escrow.sol: Cross-chain fund management

2.8 Transaction Processing - Memory Queue Rationale

Why queues are stored in memory:

  1. Performance Requirements

    • Sub-second transaction ordering decisions
    • High-frequency nonce management
    • Minimal latency for user experience
  2. State Consistency

    • In-memory queues prevent race conditions
    • Atomic operations on transaction ordering
    • Immediate consistency for dependent transactions
  3. Recovery Design

    • PostgreSQL stores persistent state
    • Memory queues rebuilt from DB on restart
    • Pending transactions recovered automatically

Implementation in relay/src/transactions/queue.rs:

  • Three-tier system: ready, pending, blocked
  • Per-EOA isolation for parallel processing
  • Automatic promotion when transactions complete

2.9 Settlement process

Settlement Definition: Cross-chain transaction finalization where funds and state changes are confirmed across all involved chains.

Settlement Steps:

  1. Bundle Creation

    • Group related cross-chain intents
    • Generate Merkle tree for batch verification
    • Calculate optimal execution order
  2. Source Execution

    • Execute funding intents on source chains
    • Lock funds in escrow contracts
    • Emit LayerZero messages
  3. Message Verification

    • DVN attestation collection
    • Cross-chain message validation
    • State proof verification
  4. Destination Execution

    • Receive and verify LayerZero messages
    • Execute output intents
    • Release escrowed funds

Implementation in relay/src/interop/settler/mod.rs

2.10 Retry Logic - e.is_retriable()

Error Classification System:

impl Error {
    fn is_retriable(&self) -> bool {
        match self {
            Error::NetworkTimeout => true,
            Error::TemporaryRpcFailure => true,
            Error::InsufficientFunds => false, // User issue
            Error::InvalidSignature => false, // Permanent failure
            Error::NonceAlreadyUsed => false, // Cannot retry
            // ... more classifications
        }
    }
}

Retry Strategy:

  • Exponential backoff for retriable errors
  • Circuit breaker for persistent failures
  • Dead letter queue for manual intervention
  • Maximum retry limits to prevent infinite loops

2.11 Fee bumping logic

Fee Bumping Strategy (relay/src/transactions/fees.rs):

  1. Base Fee Management

    • 20% delta for new transactions
    • Monitor network congestion
    • Adjust based on time sensitivity
  2. Priority Fee Optimization

    • 10% minimum bump for replacements
    • Target inclusion within 2-3 blocks
    • Balance cost vs. speed requirements
  3. Replacement Triggers

    • Transaction pending > 30 seconds
    • Network base fee increases significantly
    • User priority level changes

Implementation:

fn calculate_replacement_fees(current: &FeeContext) -> (U256, U256) {
    let min_base_bump = current.base_fee * 110 / 100; // 10% minimum
    let min_priority_bump = current.priority_fee * 110 / 100;
    // Apply strategic increases based on network conditions
}

2.12 Interop state and implementation

Current Interop Status:

  1. Production Settlers

    • LayerZero: Full production deployment
    • Simple: Development/testing only
  2. Supported Operations

    • Cross-chain fund transfers
    • Intent coordination across chains
    • Settlement verification
  3. Limitations

    • Limited to EVM-compatible chains
    • Requires LayerZero endpoints
    • DVN availability constraints

Implementation Architecture:

  • Trait-based settler interface
  • Pluggable verification systems
  • Extensible for future bridge protocols

2.13 Fund sourcing algorithm necessity

Why Fund Sourcing is Critical:

  1. Liquidity Distribution

    • Users have funds spread across multiple chains
    • Need to aggregate for large transactions
    • Optimize for minimal fees and time
  2. Cost Optimization

    • Each source chain incurs escrow costs
    • Algorithm minimizes total fees
    • Balances speed vs. cost trade-offs
  3. Capital Efficiency

    • Relay doesn't need to pre-position massive liquidity
    • Uses user's existing funds optimally
    • Reduces working capital requirements

Algorithm in relay/src/relay.rs:

fn source_funds(intent: &Intent) -> Result<Vec<FundingSource>> {
    // 1. Assess existing balance on destination
    // 2. Calculate remaining needs
    // 3. Evaluate source chains by balance and cost
    // 4. Iteratively select sources minimizing total cost
    // 5. Re-simulate for accurate fee estimation
}

2.14 Funding source definition

A funding source consists of:

  1. Source Chain: Chain where funds are currently located
  2. Available Balance: Amount available after escrow costs
  3. Escrow Cost: Fee to move funds to destination chain
  4. Time Estimate: Expected settlement duration

Selection Criteria:

  • Sufficient balance after costs
  • Reasonable escrow fees
  • Acceptable settlement time
  • Chain reliability and uptime

2.15 Liquidity management rationale

Why Liquidity Management is Essential:

  1. Instant Settlement

    • Users expect immediate execution
    • Cross-chain messages take time to settle
    • Relay advances funds for instant UX
  2. Capital Efficiency

    • Optimal distribution across chains
    • Minimize idle capital
    • Rebalance based on demand patterns
  3. Risk Management

    • Limit exposure per chain
    • Diversify across protocols and assets
    • Monitor and react to market conditions

Liquidity Sources:

  • Relay's own capital reserves
  • User funds being managed
  • Partner liquidity providers
  • Just-in-time sourcing from users

Implementation:

  • Real-time balance tracking across chains
  • Automated rebalancing triggers
  • Risk monitoring and circuit breakers

3. Smart Contracts

3.1 WebAuthnP256 key type usage

WebAuthnP256 enables native passkey support:

  1. Browser Integration

    • Native WebAuthn API support
    • Hardware security keys (YubiKey, etc.)
    • Biometric authentication (TouchID, FaceID)
  2. Security Benefits

    • Hardware-backed key storage
    • Phishing resistance
    • No seed phrase management
  3. User Experience

    • Familiar authentication flow
    • Cross-device synchronization
    • Progressive enhancement

Key Differences:

  • P256: Standard ECDSA on secp256r1 (browser session keys)
  • WebAuthnP256: P256 with WebAuthn attestation and verification
  • Secp256k1: Ethereum-standard keys for compatibility
  • External: Custom verification logic via external contracts

3.2 Simulator contract for gas estimation

The Simulator enables accurate off-chain estimation by:

  1. State Fork Simulation

    • Creates blockchain fork for testing
    • Applies state overrides for "what-if" scenarios
    • Executes transactions in isolated environment
  2. Combined Gas Search

    • Iteratively finds optimal gas limits
    • Accounts for payment, verification, and execution gas
    • Handles variable gas costs across different execution paths
  3. Error Simulation

    • Captures revert reasons for debugging
    • Provides detailed execution traces
    • Enables sophisticated error handling

Implementation Features:

  • Integration with eth_simulateV1 for advanced tracing
  • Support for multiple simulation modes
  • Batch processing for efficiency

3.3 Escrow contract fund management

What the Escrow manages:

  1. Cross-Chain Transfers

    • Locks funds on source chain
    • Releases funds on destination after verification
    • Handles failed transfer refunds
  2. Temporal Lock

    • Prevents double-spending during cross-chain settlement
    • Ensures atomic cross-chain operations
    • Provides safety during network delays
  3. Multi-Chain Coordination

    • Coordinates with LayerZero for verification
    • Manages fund release timing
    • Handles complex multi-hop transfers

Not RFQ-based:

  • Direct fund management, not quote-based
  • User funds locked and released, not market-making
  • Settlement-driven rather than price-driven

4. Code Quality Analysis

4.1 Code smells identified

High Priority Issues:

  1. Security: HTML Injection Risk

    • dangerouslySetInnerHTML in TryItOut.tsx without sanitization
    • Risk: XSS vulnerabilities
    • Location: porto/apps/docs/components/TryItOut.tsx
  2. Performance: Database Efficiency

    • Individual transaction inserts instead of batching
    • Impact: Reduced throughput under load
    • Location: relay/src/storage/pg.rs
  3. Test Coverage Gap

    • Only 6.4% test coverage (34 test files vs 531 source files)
    • Risk: Undetected regressions

Medium Priority Issues:

  1. Error Handling Inconsistency

    • Mixed error patterns between Rust (excellent) and TypeScript (basic)
    • No centralized error handling in Porto SDK
  2. Memory Allocation Optimization

    • Frequent cloning in storage operations
    • DashMap usage could be optimized for specific access patterns

4.2 Coding style and paradigms

Rust Codebase (Relay):

  • Paradigm: Functional programming with strong type safety
  • Error Handling: Comprehensive Result types with thiserror
  • Concurrency: Actor-based with async/await patterns
  • Documentation: Good inline documentation and module organization

TypeScript Codebase (Porto):

  • Paradigm: Object-oriented with functional elements
  • State Management: Zustand with persistence
  • Error Handling: Traditional JavaScript patterns (needs improvement)
  • Architecture: Modular with clear separation of concerns

Solidity Contracts:

  • Libraries: Uses Solady for gas optimization
  • Patterns: Standard access control and safety patterns
  • Documentation: Basic NatSpec documentation

5. Storage Layer

5.1 PostgreSQL choice rationale

PostgreSQL was chosen for:

  1. ACID Compliance

    • Critical for financial transaction integrity
    • Strong consistency guarantees
    • Reliable transaction rollback
  2. Complex Query Support

    • Advanced filtering for transaction history
    • Analytics queries for fee optimization
    • JSON support for flexible schema evolution
  3. Scalability

    • Proven performance at scale
    • Read replica support
    • Partitioning capabilities for growth
  4. Ecosystem

    • Mature tooling and monitoring
    • Strong backup and recovery tools
    • Extensive operational knowledge

5.2 Redis cache necessity

Redis would provide value for:

  1. Hot Path Optimization

    • Quote caching for repeated requests
    • Transaction status caching
    • Account balance caching
  2. Session Management

    • User session state
    • Temporary computation results
    • Cross-request state sharing
  3. Rate Limiting

    • Per-user request limiting
    • API endpoint protection
    • DDoS mitigation

Current State: No Redis implementation found, but would be beneficial for performance optimization.

6. ELI5 Architecture Summary

The Complete System

Imagine you have a super-smart wallet (Porto) that works across all blockchains, and a personal assistant (Relay) that handles all the complicated blockchain stuff for you.

Traditional DeFi: Like having to exchange money at every country's border and pay fees in each country's currency.

Porto + Relay: Like having a universal credit card that works anywhere, with a personal assistant who handles all the currency exchanges behind the scenes.

How It All Works Together

  1. You: "I want to buy an NFT on Ethereum using my USDC on Polygon"
  2. Porto Account: Creates a secure, signed "intent" with your request
  3. Relay: Figures out the optimal way to make it happen across chains
  4. Smart Contracts: Execute everything trustlessly while you pay one simple fee

Key Innovation: You think in outcomes ("I want X"), not processes ("First do A, then B, then C"). The system handles all the complexity while keeping your funds secure and minimizing costs.


Questions for the Team

Based on this analysis, here are clarification questions that would be valuable:

Technical Clarifications

  1. How are product features and roadmap prioritized? Who owns the technical roadmap?
  2. What are the biggest technical challenges currently being faced?
  3. What's the timeline for expanding to non-EVM chains?
  4. How do you handle incident response and on-call responsibilities?

Development Process

  1. What's the preferred Git workflow and how are tickets assigned?
  2. Are there specific coding style preferences or linting rules?
  3. How do code reviews and testing practices work?
  4. What's the team's stance on AI tooling and development tools?

Operational Questions

  1. How does team communication typically work (async vs meetings)?
  2. What are the key metrics and KPIs the team tracks?
  3. How does performance review and career development work?
  4. What's the work-life balance expectation (weekends, etc.)?

This analysis is based on comprehensive codebase examination and represents the current state of the Porto + Relay architecture as of the analysis date.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment