go-interfaces

Type: fact
Tags: amigosgointerfacesapicontractsvmarchitecture
Created: Mon Nov 03 2025 00:00:00 GMT+0000 (Coordinated Universal Time)

Amigos Go Interfaces Specification

Bootstrap interfaces for all core Amigos components to enable parallel development across teams.

VM Core Interface

Virtual Machine

package vm

import (
    "context"
    "time"
)

// VM represents the core virtual machine for contract execution
type VM interface {
    // Contract Management
    AddContract(ctx context.Context, path, content string) error
    RemoveContract(ctx context.Context, path string) error
    ListContracts(ctx context.Context) ([]string, error)
    GetContract(ctx context.Context, path string) (*Contract, error)
    
    // Execution
    RunContract(ctx context.Context, path, function string, args []interface{}) (interface{}, error)
    Eval(ctx context.Context, code string) (interface{}, error)
    
    // State Management
    GetObjectByID(ctx context.Context, path, objectID string) (interface{}, error)
    GetObjectByPath(ctx context.Context, path, variableName string) (interface{}, error)
    SetObjectByPath(ctx context.Context, path, variableName string, value interface{}) error
    
    // Introspection
    GetState(ctx context.Context, path string) (*State, error)
    GetDependencies(ctx context.Context, path string) ([]string, error)
    
    // Lifecycle
    Start(ctx context.Context) error
    Stop(ctx context.Context) error
    Health() error
}

// Contract represents a deployed contract
type Contract struct {
    Path        string            `json:"path"`
    Content     string            `json:"content"`
    Metadata    map[string]string `json:"metadata"`
    CreatedAt   time.Time         `json:"created_at"`
    UpdatedAt   time.Time         `json:"updated_at"`
    Version     string            `json:"version"`
    Dependencies []string         `json:"dependencies"`
}

// State represents the current state of a contract
type State struct {
    Path      string                 `json:"path"`
    Variables map[string]interface{} `json:"variables"`
    Objects   map[string]interface{} `json:"objects"`
    Metadata  map[string]string      `json:"metadata"`
    Checksum  string                 `json:"checksum"`
}

// ExecutionResult represents the result of contract execution
type ExecutionResult struct {
    Value     interface{}            `json:"value"`
    Logs      []string              `json:"logs"`
    GasUsed   uint64                `json:"gas_used"`
    Duration  time.Duration         `json:"duration"`
    Error     error                 `json:"error,omitempty"`
    Metadata  map[string]interface{} `json:"metadata"`
}

Storage Interface

package vm

// Store provides persistent storage for the VM
type Store interface {
    // Contract Storage
    SaveContract(ctx context.Context, contract *Contract) error
    LoadContract(ctx context.Context, path string) (*Contract, error)
    DeleteContract(ctx context.Context, path string) error
    ListContracts(ctx context.Context) ([]*Contract, error)
    
    // State Storage
    SaveState(ctx context.Context, state *State) error
    LoadState(ctx context.Context, path string) (*State, error)
    DeleteState(ctx context.Context, path string) error
    
    // Object Storage
    SaveObject(ctx context.Context, path, objectID string, data interface{}) error
    LoadObject(ctx context.Context, path, objectID string) (interface{}, error)
    DeleteObject(ctx context.Context, path, objectID string) error
    ListObjects(ctx context.Context, path string) ([]string, error)
    
    // Transactions
    Begin(ctx context.Context) (Transaction, error)
    Commit(ctx context.Context, tx Transaction) error
    Rollback(ctx context.Context, tx Transaction) error
}

type Transaction interface {
    ID() string
    Context() context.Context
}

Network Interface

Network Provider

package network

import (
    "context"
    "net/http"
)

// NetworkProvider abstracts different deployment environments
type NetworkProvider interface {
    // Contract Operations
    DeployContract(ctx context.Context, path, content string) error
    CallContract(ctx context.Context, path, function string, args []interface{}) (*CallResult, error)
    QueryContract(ctx context.Context, path string) (*Contract, error)
    ListContracts(ctx context.Context) ([]string, error)
    
    // State Operations
    QueryState(ctx context.Context, path, query string) (interface{}, error)
    GetObject(ctx context.Context, path, objectID string) (interface{}, error)
    SetObject(ctx context.Context, path, objectID string, value interface{}) error
    
    // Authentication
    Authenticate(ctx context.Context, credentials Credentials) error
    IsAuthenticated(ctx context.Context) bool
    GetIdentity(ctx context.Context) (*Identity, error)
    
    // Network Info
    GetNetworkInfo(ctx context.Context) (*NetworkInfo, error)
    GetCapabilities(ctx context.Context) (*Capabilities, error)
    
    // Lifecycle
    Connect(ctx context.Context) error
    Disconnect(ctx context.Context) error
    Health(ctx context.Context) error
}

// CallResult represents the result of a contract call
type CallResult struct {
    Value       interface{}       `json:"value"`
    Logs        []string         `json:"logs"`
    GasUsed     uint64           `json:"gas_used"`
    BlockHeight uint64           `json:"block_height,omitempty"`
    TxHash      string           `json:"tx_hash,omitempty"`
    Error       error            `json:"error,omitempty"`
}

// Credentials for authentication (different per provider)
type Credentials interface {
    Type() string
    Marshal() ([]byte, error)
}

// CryptoCredentials for blockchain networks
type CryptoCredentials struct {
    PrivateKey []byte `json:"private_key"`
    PublicKey  []byte `json:"public_key"`
    Address    string `json:"address"`
}

func (c *CryptoCredentials) Type() string { return "crypto" }
func (c *CryptoCredentials) Marshal() ([]byte, error) { /* implementation */ }

// SessionCredentials for Web2 networks
type SessionCredentials struct {
    Token    string            `json:"token"`
    Cookies  map[string]string `json:"cookies"`
    Headers  map[string]string `json:"headers"`
}

func (s *SessionCredentials) Type() string { return "session" }
func (s *SessionCredentials) Marshal() ([]byte, error) { /* implementation */ }

// Identity represents authenticated user
type Identity struct {
    ID       string            `json:"id"`
    Address  string            `json:"address"`
    Metadata map[string]string `json:"metadata"`
}

// NetworkInfo provides network details
type NetworkInfo struct {
    Name        string `json:"name"`
    Type        string `json:"type"` // "local", "blockchain", "paas"
    Version     string `json:"version"`
    ChainID     string `json:"chain_id,omitempty"`
    BlockHeight uint64 `json:"block_height,omitempty"`
    Endpoint    string `json:"endpoint"`
}

// Capabilities describes what the network supports
type Capabilities struct {
    SupportsImports     bool     `json:"supports_imports"`
    SupportsTransactions bool    `json:"supports_transactions"`
    SupportedAuthTypes  []string `json:"supported_auth_types"`
    MaxContractSize     uint64   `json:"max_contract_size"`
    MaxGasLimit         uint64   `json:"max_gas_limit"`
}

HTTP Server Interface

package network

// HTTPServer provides REST API for network operations
type HTTPServer interface {
    // Server Lifecycle
    Start(ctx context.Context, addr string) error
    Stop(ctx context.Context) error
    
    // Route Registration
    RegisterHandlers() error
    
    // Middleware
    AddMiddleware(middleware func(http.Handler) http.Handler)
    
    // Health
    Health() error
}

// HTTPHandler defines the REST API structure
type HTTPHandler interface {
    // Contract endpoints
    PostContract(w http.ResponseWriter, r *http.Request)     // POST /contract
    GetContract(w http.ResponseWriter, r *http.Request)      // GET /contract/{path}
    DeleteContract(w http.ResponseWriter, r *http.Request)   // DELETE /contract/{path}
    ListContracts(w http.ResponseWriter, r *http.Request)    // GET /contracts
    
    // Execution endpoints
    PostCall(w http.ResponseWriter, r *http.Request)         // POST /call/{path}/{function}
    PostEval(w http.ResponseWriter, r *http.Request)         // POST /eval
    
    // State endpoints
    GetState(w http.ResponseWriter, r *http.Request)         // GET /state/{path}
    GetObject(w http.ResponseWriter, r *http.Request)        // GET /state/{path}/object/{id}
    PostObject(w http.ResponseWriter, r *http.Request)       // POST /state/{path}/object/{id}
    
    // Auth endpoints
    PostAuth(w http.ResponseWriter, r *http.Request)         // POST /auth
    GetAuth(w http.ResponseWriter, r *http.Request)          // GET /auth
    DeleteAuth(w http.ResponseWriter, r *http.Request)       // DELETE /auth
}

Client Interface

CLI Client

package client

import (
    "context"
    "io"
)

// Client provides CLI functionality
type Client interface {
    // Network Management
    AddNetwork(ctx context.Context, name, endpoint string, config NetworkConfig) error
    RemoveNetwork(ctx context.Context, name string) error
    ListNetworks(ctx context.Context) ([]*Network, error)
    UseNetwork(ctx context.Context, name string) error
    GetCurrentNetwork(ctx context.Context) (*Network, error)
    
    // Contract Operations
    Push(ctx context.Context, localPath, remotePath string) error
    Pull(ctx context.Context, remotePath, localPath string) error
    Call(ctx context.Context, path, function string, args []string) (*CallResult, error)
    Eval(ctx context.Context, code string) (interface{}, error)
    
    // Inspection
    Inspect(ctx context.Context, path string) (*ContractInfo, error)
    Logs(ctx context.Context, path string, follow bool) (io.ReadCloser, error)
    State(ctx context.Context, path string) (*State, error)
    
    // Development
    Init(ctx context.Context, path string, template string) error
    Test(ctx context.Context, path string) error
    Build(ctx context.Context, path string) error
    
    // Network Operations
    Map(ctx context.Context, target string) (*PathInfo, error)
    Why(ctx context.Context, dependency string) (*DependencyInfo, error)
    
    // Authentication
    Login(ctx context.Context, credentials Credentials) error
    Logout(ctx context.Context) error
    WhoAmI(ctx context.Context) (*Identity, error)
}

// Network represents a configured network
type Network struct {
    Name     string        `json:"name"`
    Endpoint string        `json:"endpoint"`
    Type     string        `json:"type"`
    Config   NetworkConfig `json:"config"`
    Active   bool          `json:"active"`
}

// NetworkConfig holds network-specific configuration
type NetworkConfig struct {
    AuthType    string            `json:"auth_type"`
    Credentials map[string]string `json:"credentials"`
    Headers     map[string]string `json:"headers"`
    Timeout     int               `json:"timeout"`
}

// ContractInfo provides detailed contract information
type ContractInfo struct {
    Path         string            `json:"path"`
    Size         int64             `json:"size"`
    Functions    []string          `json:"functions"`
    Dependencies []string          `json:"dependencies"`
    State        *State            `json:"state"`
    Metadata     map[string]string `json:"metadata"`
    Health       string            `json:"health"`
}

// PathInfo shows network path to target
type PathInfo struct {
    Target string   `json:"target"`
    Path   []string `json:"path"`
    Hops   int      `json:"hops"`
}

// DependencyInfo explains why a dependency exists
type DependencyInfo struct {
    Dependency string   `json:"dependency"`
    Reasons    []string `json:"reasons"`
    UsedBy     []string `json:"used_by"`
    Required   bool     `json:"required"`
}

Configuration Interface

package client

// Config manages client configuration
type Config interface {
    // Network Configuration
    SetDefaultNetwork(name string) error
    GetDefaultNetwork() string
    
    // Credentials Management
    SetCredentials(network string, creds Credentials) error
    GetCredentials(network string) (Credentials, error)
    ClearCredentials(network string) error
    
    // Settings
    Set(key, value string) error
    Get(key string) string
    Delete(key string) error
    
    // Persistence
    Load() error
    Save() error
    Path() string
}

Blockchain-Specific Interfaces

Blockchain Provider

package blockchain

import (
    "context"
    "crypto/ed25519"
)

// BlockchainProvider implements NetworkProvider for blockchain networks
type BlockchainProvider interface {
    NetworkProvider
    
    // Blockchain-specific operations
    GetBlock(ctx context.Context, height uint64) (*Block, error)
    GetTransaction(ctx context.Context, hash string) (*Transaction, error)
    GetAccount(ctx context.Context, address string) (*Account, error)
    
    // Consensus
    GetValidators(ctx context.Context) ([]*Validator, error)
    GetConsensusInfo(ctx context.Context) (*ConsensusInfo, error)
    
    // Governance (future)
    SubmitProposal(ctx context.Context, proposal *Proposal) error
    Vote(ctx context.Context, proposalID string, vote VoteOption) error
}

// CryptoSigner handles transaction signing
type CryptoSigner interface {
    Sign(msg []byte) ([]byte, error)
    Verify(msg, sig []byte) bool
    PublicKey() ed25519.PublicKey
    Address() string
}

// Block represents a blockchain block
type Block struct {
    Height    uint64        `json:"height"`
    Hash      string        `json:"hash"`
    Time      time.Time     `json:"time"`
    Txs       []Transaction `json:"transactions"`
    Validator string        `json:"validator"`
}

// Transaction represents a blockchain transaction
type Transaction struct {
    Hash      string      `json:"hash"`
    From      string      `json:"from"`
    To        string      `json:"to"`
    Data      []byte      `json:"data"`
    GasUsed   uint64      `json:"gas_used"`
    Fee       uint64      `json:"fee"`
    Result    interface{} `json:"result"`
}

// Account represents a blockchain account
type Account struct {
    Address  string `json:"address"`
    Balance  uint64 `json:"balance"`
    Nonce    uint64 `json:"nonce"`
    CodeHash string `json:"code_hash,omitempty"`
}

// Validator represents a network validator
type Validator struct {
    Address     string `json:"address"`
    PubKey      string `json:"pub_key"`
    VotingPower uint64 `json:"voting_power"`
    Jailed      bool   `json:"jailed"`
}

Error Handling

Standard Errors

package errors

import "errors"

// VM Errors
var (
    ErrContractNotFound   = errors.New("contract not found")
    ErrContractExists     = errors.New("contract already exists")
    ErrInvalidContract    = errors.New("invalid contract content")
    ErrExecutionFailed    = errors.New("contract execution failed")
    ErrInvalidFunction    = errors.New("function not found")
    ErrInvalidArgs        = errors.New("invalid function arguments")
    ErrStateNotFound      = errors.New("state not found")
    ErrObjectNotFound     = errors.New("object not found")
)

// Network Errors
var (
    ErrNetworkNotFound    = errors.New("network not found")
    ErrNotConnected       = errors.New("not connected to network")
    ErrNotAuthenticated   = errors.New("not authenticated")
    ErrInvalidCredentials = errors.New("invalid credentials")
    ErrNetworkUnavailable = errors.New("network unavailable")
    ErrTimeout            = errors.New("operation timeout")
)

// Client Errors
var (
    ErrInvalidPath        = errors.New("invalid path")
    ErrFileNotFound       = errors.New("file not found")
    ErrInvalidConfig      = errors.New("invalid configuration")
    ErrCommandFailed      = errors.New("command failed")
)

// AmigosError provides structured error information
type AmigosError struct {
    Code    string            `json:"code"`
    Message string            `json:"message"`
    Details map[string]string `json:"details,omitempty"`
    Cause   error             `json:"cause,omitempty"`
}

func (e *AmigosError) Error() string {
    return e.Message
}

func (e *AmigosError) Unwrap() error {
    return e.Cause
}

Usage Examples

Basic VM Usage

// Create VM instance
vm := vm.New()
ctx := context.Background()

// Add a contract
contract := `
package hello

func Greet(name string) string {
    return "Hello, " + name + "!"
}
`

err := vm.AddContract(ctx, "hello", contract)
if err != nil {
    log.Fatal(err)
}

// Execute contract
result, err := vm.RunContract(ctx, "hello", "Greet", []interface{}{"World"})
if err != nil {
    log.Fatal(err)
}

fmt.Println(result) // "Hello, World!"

Network Provider Usage

// Create local provider
provider := local.NewProvider("http://localhost:8080")
ctx := context.Background()

// Connect and authenticate
err := provider.Connect(ctx)
if err != nil {
    log.Fatal(err)
}

// Deploy contract
err = provider.DeployContract(ctx, "hello", contract)
if err != nil {
    log.Fatal(err)
}

// Call contract
result, err := provider.CallContract(ctx, "hello", "Greet", []interface{}{"World"})
if err != nil {
    log.Fatal(err)
}

fmt.Println(result.Value) // "Hello, World!"

CLI Client Usage

// Create client
client := client.New()
ctx := context.Background()

// Add network
err := client.AddNetwork(ctx, "local", "http://localhost:8080", config)
if err != nil {
    log.Fatal(err)
}

// Use network
err = client.UseNetwork(ctx, "local")
if err != nil {
    log.Fatal(err)
}

// Push contract
err = client.Push(ctx, "./hello.go", "hello")
if err != nil {
    log.Fatal(err)
}

// Call contract
result, err := client.Call(ctx, "hello", "Greet", []string{"World"})
if err != nil {
    log.Fatal(err)
}

fmt.Println(result.Value) // "Hello, World!"

Implementation Notes

Interface Versioning

Testing Requirements

Documentation Standards

See also

← Back to Knowledge Base