chain

package
v1.0.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jan 28, 2026 License: MIT Imports: 36 Imported by: 0

README

Chain Module

The infrastructure/chain module is the single source of truth for Neo N3 chain communication in this repository.

It centralizes:

  • Neo JSON-RPC client + endpoint pooling/failover
  • contract invocation helpers (invoke + wait)
  • transaction construction + signing helpers
  • event monitoring/listening and typed event parsing
  • stack item parsing helpers for typed wrappers
  • platform contract wrappers (PriceFeed / RandomnessLog / AutomationAnchor)

Key Components

RPC Client (client.go, rpcpool.go)

Create a Neo N3 client:

client, err := chain.NewClient(chain.Config{
    RPCURL:    "https://testnet1.neo.coz.io:443",
    NetworkID: 894710606,
})
Contract Addresses (contracts_common.go)

Contract addresses are typically provided via env vars. For the MiniApp platform, these are the primary contract vars:

  • CONTRACT_PAYMENT_HUB_ADDRESS
  • CONTRACT_GOVERNANCE_ADDRESS
  • CONTRACT_PRICE_FEED_ADDRESS
  • CONTRACT_RANDOMNESS_LOG_ADDRESS
  • CONTRACT_APP_REGISTRY_ADDRESS
  • CONTRACT_AUTOMATION_ANCHOR_ADDRESS
  • CONTRACT_SERVICE_GATEWAY_ADDRESS
contracts := chain.ContractAddressesFromEnv()
Event Listener (listener_core.go)

The listener polls Neo RPC for application logs and emits typed events for the Service Layer contracts. Contract addresses are normalized (strip 0x, lowercase) before filtering, to avoid silent mismatches between configs and RPC output.

listener := chain.NewEventListener(&chain.ListenerConfig{
    Client:     client,
    Contracts:  contracts,
    StartBlock: 0, // or a saved cursor
    // MaxHandlerConcurrency defaults to 32; set <0 for unlimited.
})
go listener.Start(ctx)
Signers (Local / GlobalSigner)

Transactions that write to platform contracts are signed by the enclave-managed signer (recommended: GlobalSigner). The chain module provides signer adapters:

  • NewLocalTEESignerFromPrivateKeyHex (dev/testing)
  • NewGlobalSignerSigner (production; key never leaves enclave)

Responsibility Rules

  • Services should not talk to Neo RPC directly.
  • Contract bindings and typed event parsing live in infrastructure/chain (contracts_*.go, listener_events_*.go) so services don't duplicate chain I/O.

Testing

go test ./infrastructure/chain/... -v

Documentation

Overview

Package chain provides base contract wrapper for service-specific contracts.

Package chain provides Neo N3 blockchain interaction for the Service Layer.

Package chain provides contract registry for managing deployed contracts.

Package chain provides contract interaction for the Service Layer.

Package chain provides event listening for Neo N3 contracts.

Package chain provides NEO N3 blockchain interaction utilities.

Package chain provides Neo N3 blockchain interaction for the Service Layer.

Index

Constants

View Source
const (
	AppRegistryStatusPending  = 0
	AppRegistryStatusApproved = 1
	AppRegistryStatusDisabled = 2
)
View Source
const (
	ScopeNone            = "None"
	ScopeCalledByEntry   = "CalledByEntry"
	ScopeCustomContracts = "CustomContracts"
	ScopeCustomGroups    = "CustomGroups"
	ScopeGlobal          = "Global"
	ScopeWitnessRules    = "WitnessRules"
)

WitnessScope constants.

View Source
const DefaultPollInterval = 2 * time.Second

DefaultPollInterval is the default interval for polling transaction status.

View Source
const DefaultTxWaitTimeout = 2 * time.Minute

DefaultTxWaitTimeout is the default timeout for waiting for transaction execution.

Variables

View Source
var EnvVarMapping = map[string][]string{
	"PaymentHub":          {"CONTRACT_PAYMENT_HUB_ADDRESS"},
	"Governance":          {"CONTRACT_GOVERNANCE_ADDRESS"},
	"PriceFeed":           {"CONTRACT_PRICE_FEED_ADDRESS"},
	"RandomnessLog":       {"CONTRACT_RANDOMNESS_LOG_ADDRESS"},
	"AppRegistry":         {"CONTRACT_APP_REGISTRY_ADDRESS"},
	"AutomationAnchor":    {"CONTRACT_AUTOMATION_ANCHOR_ADDRESS"},
	"ServiceLayerGateway": {"CONTRACT_SERVICE_GATEWAY_ADDRESS"},
}

EnvVarMapping maps contract names to environment variable names.

View Source
var LegacyContractMapping = map[string]string{
	"Gateway":    "PaymentHub",
	"DataFeeds":  "PriceFeed",
	"VRF":        "RandomnessLog",
	"Automation": "AutomationAnchor",
}

LegacyContractMapping maps legacy contract names to new platform contracts.

View Source
var PlatformContracts = []string{
	"PaymentHub",
	"Governance",
	"PriceFeed",
	"RandomnessLog",
	"AppRegistry",
	"AutomationAnchor",
	"ServiceLayerGateway",
}

PlatformContracts defines the MiniApp platform contract names.

Functions

func AccountFromPrivateKey

func AccountFromPrivateKey(privateKeyHex string) (*wallet.Account, error)

AccountFromPrivateKey creates a neo-go wallet account from a private key hex string.

func AccountFromWIF

func AccountFromWIF(wif string) (*wallet.Account, error)

AccountFromWIF creates a neo-go wallet account from a WIF string.

func ExtractContractCallTargets

func ExtractContractCallTargets(script string) ([]string, error)

ExtractContractCallTargets scans a Neo VM script and returns contract addresses invoked via System.Contract.Call (normalized as lowercase LE hex without 0x).

func InvokeAndParse

func InvokeAndParse[T any](b *BaseContract, ctx context.Context, method string, parser func(StackItem) (T, error), params ...ContractParam) (T, error)

InvokeAndParse invokes a method and parses the result using a custom parser. Use this when the result needs complex parsing (e.g., struct types).

Example:

func (c *MyContract) GetConfig(ctx context.Context, id string) (*Config, error) {
    return chain.InvokeAndParse(c.BaseContract, ctx, "getConfig",
        func(item StackItem) (*Config, error) {
            return parseConfig(item)
        },
        chain.NewStringParam(id))
}

func InvokeArray

func InvokeArray[T any](b *BaseContract, ctx context.Context, method string, parser func(StackItem) (T, error), params ...ContractParam) ([]T, error)

InvokeArray invokes a method and parses the result as an array. Each element is parsed using the provided parser function.

func InvokeBool

func InvokeBool(ctx context.Context, client *Client, scriptHash, method string, params ...ContractParam) (bool, error)

InvokeBool invokes a method and parses the first stack item as a bool.

func InvokeInt

func InvokeInt(ctx context.Context, client *Client, scriptHash, method string, params ...ContractParam) (*big.Int, error)

InvokeInt invokes a method and parses the first stack item as an Integer.

func InvokeStruct

func InvokeStruct[T any](ctx context.Context, client *Client, scriptHash, method string, parser func(StackItem) (T, error), params ...ContractParam) (T, error)

InvokeStruct invokes a method and parses the first stack item using the provided parser.

func ParseBoolean

func ParseBoolean(item StackItem) (bool, error)

func ParseByteArray

func ParseByteArray(item StackItem) ([]byte, error)

func ParseEndpoints

func ParseEndpoints(csv string) []string

ParseEndpoints parses a comma-separated list of RPC URLs.

func ParseHash160

func ParseHash160(item StackItem) (string, error)

func ParseInteger

func ParseInteger(item StackItem) (*big.Int, error)

func ParseScriptHash

func ParseScriptHash(hashStr string) (util.Uint160, error)

ParseScriptHash parses a script hash from hex string (handles 0x prefix and endianness).

func ParseString

func ParseString(item StackItem) (string, error)

ParseString parses a string from a StackItem. Alias for ParseStringFromItem for consistency.

func ParseStringFromItem

func ParseStringFromItem(item StackItem) (string, error)

Types

type AppRegistryApp

type AppRegistryApp struct {
	AppID           string
	Developer       string
	DeveloperPubKey []byte
	EntryURL        string
	ManifestHash    []byte
	Status          int
	AllowlistHash   []byte
	Name            string
	Description     string
	Icon            string
	Banner          string
	Category        string
	ContractAddress []byte
}

AppRegistryApp represents a decoded AppRegistry entry.

type AppRegistryContract

type AppRegistryContract struct {
	*BaseContract
}

AppRegistryContract is a minimal wrapper for the AppRegistry contract.

func NewAppRegistryContract

func NewAppRegistryContract(client *Client, contractAddress string) *AppRegistryContract

func (*AppRegistryContract) GetApp

func (c *AppRegistryContract) GetApp(ctx context.Context, appID string) (*AppRegistryApp, error)

GetApp returns the on-chain app entry or nil if not found.

type AppRegistryEvent

type AppRegistryEvent struct {
	AppID        string
	Developer    string
	ManifestHash []byte
	Status       int
}

AppRegistryEvent represents a lifecycle event from AppRegistry.

func ParseAppRegistryEvent

func ParseAppRegistryEvent(event *ContractEvent) (*AppRegistryEvent, error)

ParseAppRegistryEvent parses AppRegistry events: - AppRegistered(appId, developer) - AppUpdated(appId, manifestHash) - StatusChanged(appId, status)

type ApplicationLog

type ApplicationLog struct {
	TxID       string      `json:"txid"`
	Executions []Execution `json:"executions"`
}

ApplicationLog represents the application log of a transaction.

type AutomationAnchorContract

type AutomationAnchorContract struct {
	// contains filtered or unexported fields
}

AutomationAnchorContract is a minimal wrapper for the platform AutomationAnchor contract. It registers tasks (admin) and records executions (updater) with nonce-based anti-replay.

func NewAutomationAnchorContract

func NewAutomationAnchorContract(client *Client, hash string) *AutomationAnchorContract

func (*AutomationAnchorContract) BalanceOf

func (c *AutomationAnchorContract) BalanceOf(ctx context.Context, taskID *big.Int) (*big.Int, error)

BalanceOf returns the GAS balance for a periodic task.

func (*AutomationAnchorContract) GetSchedule

func (c *AutomationAnchorContract) GetSchedule(ctx context.Context, taskID *big.Int) (*ScheduleData, error)

GetSchedule returns the schedule data for a periodic task.

func (*AutomationAnchorContract) GetTask

func (c *AutomationAnchorContract) GetTask(ctx context.Context, taskID []byte) (*AutomationTask, error)

GetTask returns the current task definition for taskID.

func (*AutomationAnchorContract) Hash

func (c *AutomationAnchorContract) Hash() string

func (*AutomationAnchorContract) IsNonceUsed

func (c *AutomationAnchorContract) IsNonceUsed(ctx context.Context, taskID []byte, nonce *big.Int) (bool, error)

IsNonceUsed checks whether a nonce has already been used for a task.

func (*AutomationAnchorContract) MarkExecuted

func (c *AutomationAnchorContract) MarkExecuted(
	ctx context.Context,
	signer TxSigner,
	taskID []byte,
	nonce *big.Int,
	txHash []byte,
	wait bool,
) (*TxResult, error)

MarkExecuted records an execution for a task and marks the nonce as used (updater-only).

func (*AutomationAnchorContract) SetUpdater

func (c *AutomationAnchorContract) SetUpdater(ctx context.Context, signer TxSigner, updater string, wait bool) (*TxResult, error)

SetUpdater sets the updater address (admin-only).

type AutomationAnchorExecutedEvent

type AutomationAnchorExecutedEvent struct {
	TaskID []byte
	Nonce  *big.Int
	TxHash []byte
}

AutomationAnchorExecutedEvent represents an Executed event. Event: Executed(taskId, nonce, txHash)

func ParseAutomationAnchorExecutedEvent

func ParseAutomationAnchorExecutedEvent(event *ContractEvent) (*AutomationAnchorExecutedEvent, error)

type AutomationAnchorTaskRegisteredEvent

type AutomationAnchorTaskRegisteredEvent struct {
	TaskID []byte
	Target string
	Method string
}

AutomationAnchorTaskRegisteredEvent represents a TaskRegistered event. Event: TaskRegistered(taskId, target, method)

func ParseAutomationAnchorTaskRegisteredEvent

func ParseAutomationAnchorTaskRegisteredEvent(event *ContractEvent) (*AutomationAnchorTaskRegisteredEvent, error)

type AutomationTask

type AutomationTask struct {
	TaskID   []byte
	Target   string
	Method   string
	Trigger  []byte
	GasLimit *big.Int
	Enabled  bool
}

AutomationTask mirrors the platform AutomationAnchor.Task struct layout. Fields are returned by the contract in this order: (task_id, target, method, trigger, gas_limit, enabled).

type BaseContract

type BaseContract struct {
	// contains filtered or unexported fields
}

BaseContract provides common contract interaction patterns. Service-specific contracts embed this to reduce boilerplate.

Usage:

type MyServiceContract struct {
    *chain.BaseContract
}

func NewMyServiceContract(client *Client, hash string, wallet *Wallet) *MyServiceContract {
    return &MyServiceContract{
        BaseContract: chain.NewBaseContract(client, hash, wallet),
    }
}

func (c *MyServiceContract) GetValue(ctx context.Context, key string) (*big.Int, error) {
    return c.InvokeInteger(ctx, "getValue", chain.NewStringParam(key))
}

func NewBaseContract

func NewBaseContract(client *Client, contractAddress string, wallet *Wallet) *BaseContract

NewBaseContract creates a new base contract wrapper.

func (*BaseContract) Client

func (b *BaseContract) Client() *Client

Client returns the chain client.

func (*BaseContract) ContractAddress

func (b *BaseContract) ContractAddress() string

ContractAddress returns the contract address.

func (*BaseContract) InvokeBoolean

func (b *BaseContract) InvokeBoolean(ctx context.Context, method string, params ...ContractParam) (bool, error)

InvokeBoolean invokes a method and returns the result as bool.

func (*BaseContract) InvokeByteArray

func (b *BaseContract) InvokeByteArray(ctx context.Context, method string, params ...ContractParam) ([]byte, error)

InvokeByteArray invokes a method and returns the result as []byte.

func (*BaseContract) InvokeInteger

func (b *BaseContract) InvokeInteger(ctx context.Context, method string, params ...ContractParam) (*big.Int, error)

InvokeInteger invokes a method and returns the result as *big.Int.

func (*BaseContract) InvokeRaw

func (b *BaseContract) InvokeRaw(ctx context.Context, method string, params ...ContractParam) (*InvokeResult, error)

InvokeRaw invokes a contract method and returns the raw result. Use this when you need custom result parsing.

func (*BaseContract) InvokeString

func (b *BaseContract) InvokeString(ctx context.Context, method string, params ...ContractParam) (string, error)

InvokeString invokes a method and returns the result as string.

func (*BaseContract) InvokeUint64

func (b *BaseContract) InvokeUint64(ctx context.Context, method string, params ...ContractParam) (uint64, error)

InvokeUint64 invokes a method and returns the result as uint64.

func (*BaseContract) InvokeVoid

func (b *BaseContract) InvokeVoid(ctx context.Context, method string, params ...ContractParam) error

InvokeVoid invokes a method that doesn't return a value. Useful for state-changing methods where we only care about success/failure.

func (*BaseContract) Wallet

func (b *BaseContract) Wallet() *Wallet

Wallet returns the wallet for signing.

type Block

type Block struct {
	Hash              string        `json:"hash"`
	Size              int           `json:"size"`
	Version           int           `json:"version"`
	PreviousBlockHash string        `json:"previousblockhash"`
	MerkleRoot        string        `json:"merkleroot"`
	Time              uint64        `json:"time"`
	Nonce             string        `json:"nonce"`
	Index             uint64        `json:"index"`
	NextConsensus     string        `json:"nextconsensus"`
	Witnesses         []Witness     `json:"witnesses"`
	Tx                []Transaction `json:"tx"`
}

Block represents a Neo N3 block.

type Client

type Client struct {
	// contains filtered or unexported fields
}

Client provides Neo N3 RPC client functionality.

func NewClient

func NewClient(cfg Config) (*Client, error)

NewClient creates a new Neo N3 client.

func (*Client) Call

func (c *Client) Call(ctx context.Context, method string, params []interface{}) (json.RawMessage, error)

Call makes an RPC call to the Neo N3 node.

func (*Client) CloneWithRPCURL

func (c *Client) CloneWithRPCURL(rpcURL string) (*Client, error)

CloneWithRPCURL returns a new Client that uses the provided RPC URL while retaining the existing client's NetworkID and HTTP client configuration.

func (*Client) GetApplicationLog

func (c *Client) GetApplicationLog(ctx context.Context, txHash string) (*ApplicationLog, error)

GetApplicationLog returns the application log for a transaction.

func (*Client) GetBlock

func (c *Client) GetBlock(ctx context.Context, indexOrHash interface{}) (*Block, error)

GetBlock returns a block by index or hash.

func (*Client) GetBlockCount

func (c *Client) GetBlockCount(ctx context.Context) (uint64, error)

GetBlockCount returns the current block height.

func (*Client) GetTransaction

func (c *Client) GetTransaction(ctx context.Context, txHash string) (*Transaction, error)

GetTransaction returns a transaction by hash.

func (*Client) InvokeFunction

func (c *Client) InvokeFunction(ctx context.Context, scriptHash, method string, params []ContractParam) (*InvokeResult, error)

InvokeFunction invokes a contract function (read-only).

func (*Client) InvokeFunctionAndWait

func (c *Client) InvokeFunctionAndWait(ctx context.Context, contractAddress, method string, params []ContractParam, wait bool) (*TxResult, error)

InvokeFunctionAndWait invokes a contract function and optionally waits for execution. Deprecated: This method only simulates the transaction and does NOT broadcast it. Use InvokeFunctionWithSignerAndWait for actual on-chain transactions. If wait is true, it waits for the transaction to be included in a block and returns the application log. If wait is false, it returns immediately after broadcasting with only the TxHash populated. Uses DefaultTxWaitTimeout (2 minutes) and DefaultPollInterval (2 seconds).

func (*Client) InvokeFunctionWithScope

func (c *Client) InvokeFunctionWithScope(ctx context.Context, scriptHash, method string, params []ContractParam, signerHash interface{}, scope string) (*InvokeResult, error)

InvokeFunctionWithScope simulates a contract invocation with signers and a specific scope. This is used when the contract requires a specific witness scope (e.g., Global for GAS transfers).

func (*Client) InvokeFunctionWithSignerAndWait

func (c *Client) InvokeFunctionWithSignerAndWait(
	ctx context.Context,
	contractAddress, method string,
	params []ContractParam,
	account TxSigner,
	signerScopes transaction.WitnessScope,
	wait bool,
) (*TxResult, error)

InvokeFunctionWithSignerAndWait properly builds, signs, and broadcasts a transaction. This is the correct way to invoke contract functions that modify state. Parameters:

  • ctx: context for RPC calls
  • contractAddress: target contract address (hex string with or without 0x prefix)
  • method: contract method name
  • params: contract parameters
  • account: neo-go wallet account for signing
  • signerScopes: witness scope for the signer (use transaction.CalledByEntry for most cases)
  • wait: if true, waits for transaction confirmation

Returns TxResult with transaction hash and application log (if wait=true).

func (*Client) InvokeFunctionWithSigners

func (c *Client) InvokeFunctionWithSigners(ctx context.Context, scriptHash, method string, params []ContractParam, signerHash interface{}) (*InvokeResult, error)

InvokeFunctionWithSigners simulates a contract invocation with signers. This is used to get accurate gas estimates before building the actual transaction.

func (*Client) InvokeScript

func (c *Client) InvokeScript(ctx context.Context, script string, signers []Signer) (*InvokeResult, error)

InvokeScript invokes a script (read-only).

func (*Client) NetworkID

func (c *Client) NetworkID() uint32

NetworkID returns the configured Neo N3 network magic for this client.

func (*Client) SendRawTransaction

func (c *Client) SendRawTransaction(ctx context.Context, txHex string) (string, error)

SendRawTransaction sends a signed transaction.

func (*Client) SendRawTransactionAndWait

func (c *Client) SendRawTransactionAndWait(ctx context.Context, txHex string, pollInterval, waitTimeout time.Duration) (*ApplicationLog, error)

SendRawTransactionAndWait broadcasts a signed transaction and waits for its application log. If waitTimeout is 0, DefaultTxWaitTimeout (2 minutes) is used. pollInterval <=0 defaults to 2s.

func (*Client) TransferGAS

func (c *Client) TransferGAS(ctx context.Context, account *wallet.Account, to util.Uint160, amount *big.Int) (util.Uint256, error)

TransferGAS transfers GAS from a signer account to a target address using the neo-go actor pattern. This uses a persistent actor for the account to support concurrent transactions with proper nonce management.

func (*Client) TransferGASWithData

func (c *Client) TransferGASWithData(ctx context.Context, account *wallet.Account, to util.Uint160, amount *big.Int, data any) (util.Uint256, error)

TransferGASWithData transfers GAS from a signer account to a target address with optional data. The data parameter is passed to the OnNEP17Payment callback of the receiving contract. This is used for payments to contracts like PaymentHub that need to identify the payment source.

func (*Client) WaitForApplicationLog

func (c *Client) WaitForApplicationLog(ctx context.Context, txHash string, pollInterval time.Duration) (*ApplicationLog, error)

WaitForApplicationLog polls for a transaction application log until it is available or context is done. A missing transaction is treated as transient and retried until the context deadline/timeout expires.

type Config

type Config struct {
	RPCURL     string
	NetworkID  uint32 // MainNet: 860833102, TestNet: 894710606
	Timeout    time.Duration
	HTTPClient *http.Client // Optional custom HTTP client (e.g. Marble.ExternalHTTPClient()).
}

Config holds client configuration.

type ContractAddresses

type ContractAddresses struct {
	// MiniApp platform contracts.
	PaymentHub          string `json:"paymenthub"`
	Governance          string `json:"governance"`
	PriceFeed           string `json:"pricefeed"`
	RandomnessLog       string `json:"randomnesslog"`
	AppRegistry         string `json:"appregistry"`
	AutomationAnchor    string `json:"automationanchor"`
	ServiceLayerGateway string `json:"servicelayergateway"`
}

ContractAddresses holds the deployed contract addresses.

func ContractAddressesFromEnv

func ContractAddressesFromEnv() ContractAddresses

ContractAddressesFromEnv creates ContractAddresses from environment variables.

func (*ContractAddresses) LoadFromEnv

func (c *ContractAddresses) LoadFromEnv()

LoadFromEnv loads contract addresses from environment variables.

type ContractEvent

type ContractEvent struct {
	TxHash     string
	BlockIndex uint64
	BlockHash  string
	Contract   string
	EventName  string
	State      []StackItem
	Timestamp  time.Time
	Sender     string
	LogIndex   int
}

ContractEvent represents a contract event.

type ContractInfo

type ContractInfo struct {
	Name         string `json:"name"`
	Address      string `json:"address"`
	Version      string `json:"version,omitempty"`
	DeployedAt   string `json:"deployed_at,omitempty"`
	DeployTxHash string `json:"deploy_tx_hash,omitempty"`
	UpdatedAt    string `json:"updated_at,omitempty"`
	UpdateTxHash string `json:"update_tx_hash,omitempty"`
	Network      string `json:"network,omitempty"`
	Deployer     string `json:"deployer,omitempty"`
	Status       string `json:"status,omitempty"` // deployed, updated, deprecated
}

ContractInfo holds information about a deployed contract.

type ContractParam

type ContractParam struct {
	Type  string      `json:"type"`
	Value interface{} `json:"value"`
}

ContractParam represents a contract parameter.

func NewAnyParam

func NewAnyParam() ContractParam

NewAnyParam creates an "Any" parameter (encoded as JSON null). Useful for optional parameters like NEP-17 transfer `data` when unused.

func NewArrayParam

func NewArrayParam(values []ContractParam) ContractParam

NewArrayParam creates an array parameter.

func NewBoolParam

func NewBoolParam(value bool) ContractParam

NewBoolParam creates a boolean parameter.

func NewByteArrayParam

func NewByteArrayParam(value []byte) ContractParam

NewByteArrayParam creates a byte array parameter. Neo N3 RPC expects ByteArray values to be base64 encoded.

func NewHash160Param

func NewHash160Param(value string) ContractParam

NewHash160Param creates a Hash160 (address) parameter.

func NewHash256Param

func NewHash256Param(value string) ContractParam

NewHash256Param creates a Hash256 parameter.

func NewIntegerParam

func NewIntegerParam(value *big.Int) ContractParam

NewIntegerParam creates an integer parameter.

func NewPublicKeyParam

func NewPublicKeyParam(value string) ContractParam

NewPublicKeyParam creates a public key parameter.

func NewStringParam

func NewStringParam(value string) ContractParam

NewStringParam creates a string parameter.

type ContractRegistry

type ContractRegistry struct {
	// contains filtered or unexported fields
}

ContractRegistry manages deployed contract addresses and versions.

func DefaultRegistry

func DefaultRegistry(network string) *ContractRegistry

DefaultRegistry returns a registry loaded from environment and default config.

func NewContractRegistry

func NewContractRegistry(network, configDir string) *ContractRegistry

NewContractRegistry creates a new contract registry.

func (*ContractRegistry) GenerateEnvExports

func (r *ContractRegistry) GenerateEnvExports() string

GenerateEnvExports generates shell export commands for contract addresses.

func (*ContractRegistry) Get

func (r *ContractRegistry) Get(name string) *ContractInfo

Get returns the contract info for a given name.

func (*ContractRegistry) GetAddress

func (r *ContractRegistry) GetAddress(name string) string

GetAddress returns the contract address for a given name.

func (*ContractRegistry) GetAddresses

func (r *ContractRegistry) GetAddresses() ContractAddresses

GetAddresses returns ContractAddresses populated from the registry.

func (*ContractRegistry) List

func (r *ContractRegistry) List() []*ContractInfo

List returns all registered contracts.

func (*ContractRegistry) LoadFromEnv

func (r *ContractRegistry) LoadFromEnv()

LoadFromEnv loads contract addresses from environment variables.

func (*ContractRegistry) LoadFromFile

func (r *ContractRegistry) LoadFromFile(filename string) error

LoadFromFile loads contract addresses from a JSON file.

func (*ContractRegistry) RegisterDeployment

func (r *ContractRegistry) RegisterDeployment(name, address, version, txHash, deployer string)

RegisterDeployment records a new contract deployment.

func (*ContractRegistry) RegisterUpdate

func (r *ContractRegistry) RegisterUpdate(name, newAddress, newVersion, txHash string) error

RegisterUpdate records a contract update.

func (*ContractRegistry) SaveToFile

func (r *ContractRegistry) SaveToFile(filename string) error

SaveToFile saves contract addresses to a JSON file.

func (*ContractRegistry) Set

func (r *ContractRegistry) Set(name string, info *ContractInfo)

Set sets the contract info for a given name.

func (*ContractRegistry) SetAddress

func (r *ContractRegistry) SetAddress(name, address string)

SetAddress sets the contract address for a given name.

func (*ContractRegistry) Validate

func (r *ContractRegistry) Validate() []string

Validate checks if all required contracts are registered.

type DeployedContract

type DeployedContract struct {
	Name        string `json:"name,omitempty"`
	Hash        string `json:"hash"`
	Address     string `json:"address,omitempty"`
	TxHash      string `json:"tx_hash,omitempty"`
	GasConsumed string `json:"gas_consumed,omitempty"`
	State       string `json:"state,omitempty"`
	DeployedAt  string `json:"deployed_at,omitempty"`
}

DeployedContract represents a deployed smart contract.

type DeploymentResult

type DeploymentResult struct {
	Contracts []DeployedContract `json:"contracts"`
	Network   string             `json:"network,omitempty"`
	Deployer  string             `json:"deployer,omitempty"`
	SessionID string             `json:"session_id,omitempty"`
	Account   string             `json:"account,omitempty"`
	Timestamp string             `json:"timestamp,omitempty"`
}

DeploymentResult represents the result of a contract deployment operation.

type EventHandler

type EventHandler func(event *ContractEvent) error

EventHandler is a callback for contract events.

type EventListener

type EventListener struct {
	// contains filtered or unexported fields
}

EventListener listens for contract events on Neo N3.

func NewEventListener

func NewEventListener(cfg *ListenerConfig) *EventListener

NewEventListener creates a new event listener.

func (*EventListener) On

func (l *EventListener) On(eventName string, handler EventHandler)

On registers an event handler.

func (*EventListener) OnAny

func (l *EventListener) OnAny(handler EventHandler)

OnAny registers a handler for all contract events.

func (*EventListener) OnTransaction

func (l *EventListener) OnTransaction(handler TxHandler)

OnTransaction registers a transaction-level handler.

func (*EventListener) Start

func (l *EventListener) Start(ctx context.Context) error

Start starts the event listener.

func (*EventListener) Stop

func (l *EventListener) Stop()

Stop stops the event listener.

type Execution

type Execution struct {
	Trigger       string         `json:"trigger"`
	VMState       string         `json:"vmstate"`
	Exception     string         `json:"exception,omitempty"`
	GasConsumed   string         `json:"gasconsumed"`
	Stack         []StackItem    `json:"stack"`
	Notifications []Notification `json:"notifications"`
}

Execution represents a single execution in the application log.

type GlobalSignerSigner

type GlobalSignerSigner struct {
	// contains filtered or unexported fields
}

GlobalSignerSigner implements TEESigner using the GlobalSigner infrastructure marble. It never holds long-lived private key material locally.

func NewGlobalSignerSigner

func NewGlobalSignerSigner(ctx context.Context, client *gsclient.Client) (*GlobalSignerSigner, error)

NewGlobalSignerSigner constructs a signer backed by GlobalSigner. It fetches the active public key via /attestation to compute ScriptHash and verification script.

func (*GlobalSignerSigner) GetVerificationScript

func (s *GlobalSignerSigner) GetVerificationScript() []byte

func (*GlobalSignerSigner) ScriptHash

func (s *GlobalSignerSigner) ScriptHash() util.Uint160

func (*GlobalSignerSigner) Sign

func (s *GlobalSignerSigner) Sign(ctx context.Context, data []byte) ([]byte, error)

Sign signs an arbitrary payload using GlobalSigner raw signing.

func (*GlobalSignerSigner) SignTx

SignTx signs tx and updates its witnesses, matching neo-go's expected witness format. The transaction MUST already contain a signer entry for this signer's ScriptHash.

type InvokeResult

type InvokeResult struct {
	Script      string      `json:"script"`
	State       string      `json:"state"`
	GasConsumed string      `json:"gasconsumed"`
	Stack       []StackItem `json:"stack"`
	Exception   string      `json:"exception,omitempty"`
	Tx          string      `json:"tx,omitempty"`
}

InvokeResult represents the result of a contract invocation.

type ListenerConfig

type ListenerConfig struct {
	Client        *Client
	Contracts     ContractAddresses // All contract addresses to monitor
	PollInterval  time.Duration
	StartBlock    uint64
	Confirmations uint64
	Logger        *logging.Logger
	// MaxHandlerConcurrency limits concurrent handler goroutines. Use <0 for unlimited.
	MaxHandlerConcurrency int
}

ListenerConfig holds event listener configuration.

type LocalTEESigner

type LocalTEESigner struct {
	// contains filtered or unexported fields
}

LocalTEESigner implements TEESigner using a locally available private key. It is primarily intended for local development/testing or transitional setups.

func NewLocalTEESignerFromPrivateKeyHex

func NewLocalTEESignerFromPrivateKeyHex(privateKeyHex string) (*LocalTEESigner, error)

NewLocalTEESignerFromPrivateKeyHex constructs a local signer from a hex-encoded private key.

func (*LocalTEESigner) GetVerificationScript

func (s *LocalTEESigner) GetVerificationScript() []byte

func (*LocalTEESigner) ScriptHash

func (s *LocalTEESigner) ScriptHash() util.Uint160

func (*LocalTEESigner) Sign

func (s *LocalTEESigner) Sign(_ context.Context, data []byte) ([]byte, error)

func (*LocalTEESigner) SignTx

type MessageSigner

type MessageSigner interface {
	Sign(ctx context.Context, data []byte) ([]byte, error)
}

MessageSigner abstracts signing arbitrary byte payloads (typically used for on-chain parameter signatures verified by contracts).

type MiniAppMetricEvent

type MiniAppMetricEvent struct {
	AppID      string
	MetricName string
	Value      *big.Int
}

MiniAppMetricEvent represents a metric emitted by a MiniApp contract. Event: Platform_Metric(appId, metricName, value) Legacy event name: Metric

func ParseMiniAppMetricEvent

func ParseMiniAppMetricEvent(event *ContractEvent) (*MiniAppMetricEvent, error)

type MiniAppNotificationEvent

type MiniAppNotificationEvent struct {
	AppID            string
	Title            string
	Content          string
	NotificationType string
	Priority         int
}

MiniAppNotificationEvent represents a notification from a MiniApp contract. Event: Platform_Notification(appId, title, content, notificationType, priority) Legacy event name: Notification

func ParseMiniAppNotificationEvent

func ParseMiniAppNotificationEvent(event *ContractEvent) (*MiniAppNotificationEvent, error)

type Notification

type Notification struct {
	Contract  string    `json:"contract"`
	EventName string    `json:"eventname"`
	State     StackItem `json:"state"`
}

Notification represents a contract notification.

type PaymentReceivedEvent

type PaymentReceivedEvent struct {
	PaymentID     string
	AppID         string
	SenderAddress string
	Amount        string
	Memo          string
}

PaymentReceivedEvent represents a PaymentHub payment event. Event: PaymentReceived(paymentId, appId, sender, amount, memo)

func ParsePaymentReceivedEvent

func ParsePaymentReceivedEvent(event *ContractEvent) (*PaymentReceivedEvent, error)

type PriceFeedContract

type PriceFeedContract struct {
	// contains filtered or unexported fields
}

PriceFeedContract is a minimal wrapper for the platform PriceFeed contract. It anchors TEE-produced price updates on-chain.

func NewPriceFeedContract

func NewPriceFeedContract(client *Client, hash string) *PriceFeedContract

func (*PriceFeedContract) GetLatest

func (c *PriceFeedContract) GetLatest(ctx context.Context, symbol string) (*PriceFeedRecord, error)

GetLatest returns the latest anchored record for a symbol.

func (*PriceFeedContract) Hash

func (c *PriceFeedContract) Hash() string

func (*PriceFeedContract) Update

func (c *PriceFeedContract) Update(
	ctx context.Context,
	signer TxSigner,
	symbol string,
	roundID, price *big.Int,
	timestamp uint64,
	attestationHash []byte,
	sourceSetID *big.Int,
	wait bool,
) (*TxResult, error)

Update writes a new anchored record for a symbol.

type PriceFeedRecord

type PriceFeedRecord struct {
	RoundID         *big.Int
	Price           *big.Int
	Timestamp       uint64
	AttestationHash []byte
	SourceSetID     *big.Int
}

PriceFeedRecord mirrors the platform PriceFeed contract record layout. Fields are returned by the contract in this order: (round_id, price, timestamp, attestation_hash, sourceset_id).

type RPCEndpoint

type RPCEndpoint struct {
	URL              string        `json:"url"`
	Priority         int           `json:"priority"`
	Healthy          bool          `json:"healthy"`
	ConsecutiveFails int           `json:"consecutive_fails"`
	LastCheck        time.Time     `json:"last_check"`
	LastLatency      time.Duration `json:"last_latency"`
	AvgLatency       time.Duration `json:"avg_latency"`
}

RPCEndpoint represents a NEO N3 RPC endpoint with health tracking.

type RPCError

type RPCError struct {
	Code    int    `json:"code"`
	Message string `json:"message"`
	Data    string `json:"data,omitempty"`
}

RPCError represents a JSON-RPC error.

func (*RPCError) Error

func (e *RPCError) Error() string

type RPCPool

type RPCPool struct {
	// contains filtered or unexported fields
}

RPCPool manages multiple RPC endpoints with health checking and failover.

func NewRPCPool

func NewRPCPool(cfg *RPCPoolConfig) (*RPCPool, error)

NewRPCPool creates a new RPC pool from configuration.

func (*RPCPool) ExecuteWithFailover

func (p *RPCPool) ExecuteWithFailover(ctx context.Context, maxRetries int, fn func(url string) error) error

ExecuteWithFailover executes a function with automatic failover on failure. The function receives the endpoint URL and should return an error if failover is needed.

func (*RPCPool) GetBestEndpoint

func (p *RPCPool) GetBestEndpoint() (*RPCEndpoint, error)

GetBestEndpoint returns the best healthy endpoint.

func (*RPCPool) GetEndpoints

func (p *RPCPool) GetEndpoints() []RPCEndpoint

GetEndpoints returns a copy of all endpoints with their status.

func (*RPCPool) GetNextEndpoint

func (p *RPCPool) GetNextEndpoint() *RPCEndpoint

GetNextEndpoint returns the next endpoint in round-robin fashion (for failover).

func (*RPCPool) HealthyCount

func (p *RPCPool) HealthyCount() int

HealthyCount returns the number of healthy endpoints.

func (*RPCPool) MarkHealthy

func (p *RPCPool) MarkHealthy(url string, latency time.Duration)

MarkHealthy marks an endpoint as healthy after a successful request.

func (*RPCPool) MarkUnhealthy

func (p *RPCPool) MarkUnhealthy(url string)

MarkUnhealthy marks an endpoint as unhealthy after a failure.

func (*RPCPool) Start

func (p *RPCPool) Start(ctx context.Context)

Start begins the health check loop.

func (*RPCPool) Stop

func (p *RPCPool) Stop()

Stop stops the health check loop.

type RPCPoolConfig

type RPCPoolConfig struct {
	// Endpoints is a comma-separated list of RPC URLs or a slice.
	Endpoints []string

	// HealthCheckInterval is how often to check endpoint health.
	HealthCheckInterval time.Duration

	// HealthCheckTimeout is the timeout for health check requests.
	HealthCheckTimeout time.Duration

	// MaxConsecutiveFails marks an endpoint unhealthy after this many failures.
	MaxConsecutiveFails int

	// HTTPClient is the HTTP client to use (optional, for TEE external client).
	HTTPClient *http.Client
}

RPCPoolConfig holds configuration for the RPC pool.

func DefaultRPCPoolConfig

func DefaultRPCPoolConfig() *RPCPoolConfig

DefaultRPCPoolConfig returns sensible defaults.

type RPCRequest

type RPCRequest struct {
	JSONRPC string        `json:"jsonrpc"`
	Method  string        `json:"method"`
	Params  []interface{} `json:"params"`
	ID      int           `json:"id"`
}

RPCRequest represents a JSON-RPC request.

type RPCResponse

type RPCResponse struct {
	JSONRPC string          `json:"jsonrpc"`
	ID      int             `json:"id"`
	Result  json.RawMessage `json:"result,omitempty"`
	Error   *RPCError       `json:"error,omitempty"`
}

RPCResponse represents a JSON-RPC response.

type RandomnessLogContract

type RandomnessLogContract struct {
	// contains filtered or unexported fields
}

RandomnessLogContract is a minimal wrapper for the platform RandomnessLog contract. It anchors enclave-generated randomness on-chain along with an attestation hash.

func NewRandomnessLogContract

func NewRandomnessLogContract(client *Client, hash string) *RandomnessLogContract

func (*RandomnessLogContract) Hash

func (c *RandomnessLogContract) Hash() string

func (*RandomnessLogContract) Record

func (c *RandomnessLogContract) Record(
	ctx context.Context,
	signer TxSigner,
	requestID string,
	randomness, attestationHash []byte,
	timestamp uint64,
	wait bool,
) (*TxResult, error)

Record writes a randomness record to the on-chain RandomnessLog contract.

func (*RandomnessLogContract) SetUpdater

func (c *RandomnessLogContract) SetUpdater(ctx context.Context, signer TxSigner, updaterHash160 string, wait bool) (*TxResult, error)

SetUpdater sets the authorized updater account for on-chain anchoring.

type ScheduleData

type ScheduleData struct {
	TriggerType     string
	Schedule        string
	IntervalSeconds *big.Int
	LastExecution   *big.Int
	NextExecution   *big.Int
	Paused          bool
}

ScheduleData mirrors the contract's ScheduleData struct.

type ServiceFulfilledEvent

type ServiceFulfilledEvent struct {
	RequestID string
	Success   bool
	Result    []byte
	Error     string
}

ServiceFulfilledEvent represents a ServiceFulfilled event. Event: ServiceFulfilled(requestId, success, result, error)

func ParseServiceFulfilledEvent

func ParseServiceFulfilledEvent(event *ContractEvent) (*ServiceFulfilledEvent, error)

type ServiceLayerGatewayContract

type ServiceLayerGatewayContract struct {
	// contains filtered or unexported fields
}

ServiceLayerGatewayContract is a minimal wrapper for the ServiceLayerGateway contract. It coordinates on-chain service requests and callbacks to MiniApp contracts.

func NewServiceLayerGatewayContract

func NewServiceLayerGatewayContract(client *Client, contractAddress string) *ServiceLayerGatewayContract

func (*ServiceLayerGatewayContract) Address

func (c *ServiceLayerGatewayContract) Address() string

func (*ServiceLayerGatewayContract) FulfillRequest

func (c *ServiceLayerGatewayContract) FulfillRequest(
	ctx context.Context,
	signer TxSigner,
	requestID *big.Int,
	success bool,
	result []byte,
	errorMessage string,
	wait bool,
) (*TxResult, error)

FulfillRequest finalizes a pending service request and triggers the callback.

func (*ServiceLayerGatewayContract) RequestService

func (c *ServiceLayerGatewayContract) RequestService(
	ctx context.Context,
	signer TxSigner,
	appID, serviceType string,
	payload []byte,
	callbackContractAddress, callbackMethod string,
	wait bool,
) (*TxResult, error)

RequestService submits a service request (primarily for testing; normally called by MiniApp contracts).

func (*ServiceLayerGatewayContract) SetUpdater

func (c *ServiceLayerGatewayContract) SetUpdater(ctx context.Context, signer TxSigner, updaterAddress string, wait bool) (*TxResult, error)

SetUpdater sets the authorized updater address for fulfillment calls.

type ServiceRequestedEvent

type ServiceRequestedEvent struct {
	RequestID        string
	AppID            string
	ServiceType      string
	Requester        string
	CallbackContract string
	CallbackMethod   string
	Payload          []byte
}

ServiceRequestedEvent represents a ServiceRequested event. Event: ServiceRequested(requestId, appId, serviceType, requester, callbackContract, callbackMethod, payload)

func ParseServiceRequestedEvent

func ParseServiceRequestedEvent(event *ContractEvent) (*ServiceRequestedEvent, error)

type Signer

type Signer struct {
	Account          string   `json:"account"`
	Scopes           string   `json:"scopes"`
	AllowedContracts []string `json:"allowedcontracts,omitempty"`
	AllowedGroups    []string `json:"allowedgroups,omitempty"`
}

Signer represents a transaction signer.

type StackItem

type StackItem struct {
	Type  string          `json:"type"`
	Value json.RawMessage `json:"value"`
}

StackItem represents a stack item from contract execution.

func ParseArray

func ParseArray(item StackItem) ([]StackItem, error)

ParseArray extracts an array of StackItems from a parent StackItem.

type TEESigner

type TEESigner interface {
	TxSigner
	MessageSigner
}

TEESigner is the combined signer used by TEE components that both submit chain transactions and produce contract-verifiable signatures.

type Transaction

type Transaction struct {
	Hash            string        `json:"hash"`
	Size            int           `json:"size"`
	Version         int           `json:"version"`
	Nonce           uint32        `json:"nonce"`
	Sender          string        `json:"sender"`
	SystemFee       string        `json:"sysfee"`
	NetworkFee      string        `json:"netfee"`
	ValidUntilBlock uint64        `json:"validuntilblock"`
	Signers         []Signer      `json:"signers"`
	Attributes      []TxAttribute `json:"attributes"`
	Script          string        `json:"script"`
	Witnesses       []Witness     `json:"witnesses"`
}

Transaction represents a Neo N3 transaction.

type TransactionEvent

type TransactionEvent struct {
	TxHash     string
	BlockIndex uint64
	BlockHash  string
	Sender     string
	Timestamp  time.Time
	Script     string
	Contracts  []string
}

TransactionEvent represents a transaction invocation.

type TxAttribute

type TxAttribute struct {
	Type string `json:"type"`
}

TxAttribute represents a transaction attribute.

type TxBuilder

type TxBuilder struct {
	// contains filtered or unexported fields
}

TxBuilder builds and signs Neo N3 transactions.

func NewTxBuilder

func NewTxBuilder(client *Client, networkID uint32) *TxBuilder

NewTxBuilder creates a new transaction builder.

func (*TxBuilder) BroadcastAndWait

func (b *TxBuilder) BroadcastAndWait(
	ctx context.Context,
	tx *transaction.Transaction,
	pollInterval, timeout time.Duration,
) (*ApplicationLog, error)

BroadcastAndWait broadcasts a transaction and waits for its application log.

func (*TxBuilder) BroadcastTx

func (b *TxBuilder) BroadcastTx(ctx context.Context, tx *transaction.Transaction) (util.Uint256, error)

BroadcastTx broadcasts a signed transaction and returns the transaction hash.

func (*TxBuilder) BuildAndSignTx

func (b *TxBuilder) BuildAndSignTx(
	ctx context.Context,
	invokeResult *InvokeResult,
	account TxSigner,
	signerScopes transaction.WitnessScope,
) (*transaction.Transaction, error)

BuildAndSignTx builds a transaction from an invoke simulation and signs it. Parameters:

  • ctx: context for RPC calls
  • invokeResult: result from InvokeFunction simulation
  • account: neo-go wallet account for signing
  • signerScopes: witness scope for the signer

type TxHandler

type TxHandler func(event *TransactionEvent) error

TxHandler is a callback for transaction-level events.

type TxResult

type TxResult struct {
	TxHash  string          // Transaction hash
	AppLog  *ApplicationLog // Application log (nil if wait=false)
	VMState string          // VM state from execution (HALT = success)
}

TxResult represents the result of a transaction execution.

type TxSigner

type TxSigner interface {
	ScriptHash() util.Uint160
	GetVerificationScript() []byte
	SignTx(net netmode.Magic, tx *transaction.Transaction) error
}

TxSigner abstracts Neo N3 transaction signing.

It is intentionally compatible with `neo-go/pkg/wallet.Account` to allow using a local private key signer while also supporting remote/TEE signers.

type Wallet

type Wallet struct {
	// contains filtered or unexported fields
}

Wallet represents a Neo N3 wallet for signing transactions.

func NewWallet

func NewWallet(privateKeyHex string) (*Wallet, error)

NewWallet creates a new wallet from a private key.

func (*Wallet) Address

func (w *Wallet) Address() string

Address returns the wallet address.

func (*Wallet) PublicKey

func (w *Wallet) PublicKey() []byte

PublicKey returns the wallet public key.

func (*Wallet) ScriptHash

func (w *Wallet) ScriptHash() []byte

ScriptHash returns the wallet script hash.

func (*Wallet) ScriptHashHex

func (w *Wallet) ScriptHashHex() string

ScriptHashHex returns the wallet script hash as hex string.

func (*Wallet) Sign

func (w *Wallet) Sign(data []byte) ([]byte, error)

Sign signs data with the wallet's private key.

type Witness

type Witness struct {
	Invocation   string `json:"invocation"`
	Verification string `json:"verification"`
}

Witness represents a transaction witness.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL