client

package module
v0.0.0-...-1945114 Latest Latest
Warning

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

Go to latest
Published: Dec 6, 2025 License: MIT Imports: 33 Imported by: 0

README

Massa Go Client

A comprehensive Go client library for interacting with the Massa blockchain. This client provides full access to blockchain data, smart contract deployment and interaction, transaction broadcasting, and real-time event monitoring.

🚀 Features

  • Blockchain Data Retrieval: Access blocks, transactions, balances, and node information
  • Smart Contract Deployment: Deploy single or multiple contracts with constructor support
  • Smart Contract Interaction: Call contract functions and read contract state
  • Transaction Broadcasting: Send transfers, buy/sell rolls, and other operations
  • Event Monitoring: Real-time event subscription via WebSocket and polling
  • Connection Management: Automatic reconnection, retry logic, and connection pooling
  • Network Support: Mainnet, testnet, and custom network configurations

📦 Installation

go get github.com/nafsilabs/massa-go/client

🔧 Dependencies

  • github.com/gorilla/websocket - WebSocket client
  • github.com/nafsilabs/massa-go/wallet - Wallet functionality
  • golang.org/x/crypto - Cryptographic functions

📖 Quick Start

Basic Client Setup
package main

import (
    "fmt"
    "log"
    
    "github.com/nafsilabs/massa-go/client"
)

func main() {
    // Create a client for testnet
    massaClient, err := client.NewTestnetClient()
    if err != nil {
        log.Fatal(err)
    }
    defer massaClient.Close()
    
    // Get node status
    status, err := massaClient.GetNodeStatus()
    if err != nil {
        log.Fatal(err)
    }
    
    fmt.Printf("Connected to Massa node: %s\n", status.NodeID)
    fmt.Printf("Current slot: %d\n", status.CurrentSlot)
}
Client Builder Pattern
// Create a custom client with specific configuration
client, err := client.NewClientBuilder().
    WithTestnet().
    WithTimeout(60 * time.Second).
    WithRetryCount(5).
    WithAPIKey("your-api-key").
    BuildAndConnect()

🌐 Network Configurations

Predefined Networks
// Mainnet
client, err := client.NewMainnetClient()

// Testnet  
client, err := client.NewTestnetClient()

// Local development node
client, err := client.NewLocalnetClient()
Custom Networks
customNetwork := &client.NetworkConfig{
    Name:      "custom",
    ChainID:   12345,
    RPCURL:    "https://your-node.com/api/v2",
    WSURL:     "wss://your-node.com/ws",
    PublicAPI: "https://your-node.com/api/v2",
}

client := client.NewClient(client.DefaultClientConfig(customNetwork))

🔍 Blockchain Data Retrieval

Node Information
// Get node status
status, err := client.GetNodeStatus()
fmt.Printf("Current slot: %d\n", status.CurrentSlot)

// Get node configuration
config, err := client.GetNodeInfo()
fmt.Printf("Chain ID: %d\n", config.ChainID)
Blocks and Operations
// Get block by ID
block, err := client.GetBlock("block_id_here")

// Get multiple blocks
blocks, err := client.GetBlocks([]string{"id1", "id2"})

// Get blocks by slot numbers
blocks, err := client.GetBlocksBySlots([]uint64{100, 101, 102})

// Get operation information
operation, err := client.GetOperation("operation_id_here")
Account Information
// Get account balance
balance, err := client.GetBalance("AU1234...")
fmt.Printf("Final balance: %s MAS\n", balance.Final)

// Get multiple balances
addresses := []string{"AU1234...", "AU5678..."}
balances, err := client.GetBalances(addresses)

💼 Smart Contract Operations

Contract Deployment
// Deploy a single contract
deployRequest := &client.ContractDeploymentRequest{
    Bytecode: contractBytecode,
    MaxGas:   1000000,
    Coins:    "0",
    Datastore: map[string][]byte{
        "initial_value": []byte("Hello, Massa!"),
    },
    Constructor: &client.ConstructorCall{
        Function:  "constructor",
        Parameter: []byte(`{"owner": "AU1234..."}`),
        Coins:     "0",
    },
}

result, err := client.DeployContract(deployRequest, account, "password")
fmt.Printf("Contract deployed at: %s\n", result.ContractAddress)
Multiple Contract Deployment
// Deploy multiple contracts in one transaction
multiRequest := &client.MultiContractDeploymentRequest{
    Contracts: []client.ContractDeploymentRequest{
        {Bytecode: contract1Bytecode, MaxGas: 500000, Coins: "0"},
        {Bytecode: contract2Bytecode, MaxGas: 500000, Coins: "0"},
    },
    MaxGas: 1000000,
}

result, err := client.DeployMultipleContracts(multiRequest, account, "password")
fmt.Printf("Deployed %d contracts\n", len(result.ContractAddresses))
Contract Interaction
// Call a contract function
callResult, err := client.CallContract(
    "AS1234...",                    // contract address
    "transfer",                     // function name
    []byte(`{"to": "AU5678...", "amount": 1000}`), // parameters
    100000,                         // max gas
    "0",                           // coins to send
    account,                       // signing account
    "password",                    // account password
)

// Read contract state (no transaction required)
readResult, err := client.ReadContract(
    "AS1234...",                    // contract address
    "get_balance",                  // function name
    []byte(`{"address": "AU1234..."}`), // parameters
    "AU1234...",                   // caller address
)
fmt.Printf("Contract returned: %s\n", string(readResult.Result))

💸 Transaction Operations

Coin Transfers
// Transfer coins
result, err := client.TransferCoins(
    "AU1234...",    // from address
    "AU5678...",    // to address
    "1000000000",   // amount in nanoMAS (1 MAS)
    account,        // signing account
    "password",     // account password
)

fmt.Printf("Transfer transaction: %s\n", result.OperationID)
Validator Operations
// Buy validator rolls
result, err := client.BuyRolls(
    "AU1234...",    // from address
    5,              // number of rolls
    account,        // signing account
    "password",     // account password
)

// Sell validator rolls
result, err := client.SellRolls(
    "AU1234...",    // from address
    2,              // number of rolls
    account,        // signing account
    "password",     // account password
)
Batch Transactions
// Send multiple transactions
operations := []*client.Operation{
    {
        Creator: account.Address.String(),
        Fee: "1000000",
        ExpirePeriod: 5,
        Type: "Transfer",
        Content: &client.TransferOperation{
            Recipient: "AU5678...",
            Amount: "500000000",
        },
    },
    // ... more operations
}

ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()

results, err := client.BatchTransactions(ctx, operations, account, "password")

📡 Event Monitoring

WebSocket Event Subscription
// Subscribe to all events
eventHandler := func(event *client.Event) {
    fmt.Printf("Event from slot %d: %s\n", event.Context.Slot, event.Data)
}

subscriptionID, err := client.SubscribeToEvents(&client.EventFilter{}, eventHandler)

// Subscribe to contract-specific events
subscriptionID, err := client.SubscribeToContractEvents("AS1234...", eventHandler)

// Subscribe to address-specific events
subscriptionID, err := client.SubscribeToAddressEvents("AU1234...", eventHandler)

// Unsubscribe when done
err = client.UnsubscribeFromEvents(subscriptionID)
Event Filtering
// Filter events by slot range
startSlot := uint64(1000)
endSlot := uint64(2000)
filter := &client.EventFilter{
    Start:   &startSlot,
    End:     &endSlot,
    Emitter: &contractAddress,
}

events, err := client.GetEvents(filter)
Channel-Based Event Streaming
// Create an event stream
stream, err := client.NewEventStream(&client.EventFilter{})
if err != nil {
    log.Fatal(err)
}
defer stream.Close()

// Listen to events
for {
    select {
    case event := <-stream.Events():
        fmt.Printf("Received event: %+v\n", event)
    case err := <-stream.Errors():
        fmt.Printf("Stream error: %v\n", err)
    case <-time.After(30 * time.Second):
        return // Timeout
    }
}
Polling-Based Event Monitoring
// For environments without WebSocket support
poller := client.NewEventPoller(
    &client.EventFilter{},
    5*time.Second,  // polling interval
    eventHandler,
)

poller.Start()
defer poller.Stop()

🔄 Connection Management

Connection Pool
// Create multiple client configurations for load balancing
configs := []*client.ClientConfig{
    client.DefaultClientConfig(client.MainnetConfig),
    client.DefaultClientConfig(client.MainnetConfig),
    client.DefaultClientConfig(client.MainnetConfig),
}

// Create client pool
pool, err := client.NewClientPool(configs)
if err != nil {
    log.Fatal(err)
}
defer pool.Close()

// Get a healthy client
ctx := context.Background()
healthyClient, err := pool.GetHealthyClient(ctx)
if err != nil {
    log.Fatal(err)
}

// Use the client
status, err := healthyClient.GetNodeStatus()
Health Monitoring
// Check client health
if client.IsConnected() {
    fmt.Println("Client is connected")
}

// Force reconnection
err := client.Reconnect()

// Pool health check
healthResults := pool.HealthCheck(context.Background())
for i, err := range healthResults {
    if err != nil {
        fmt.Printf("Client %d is unhealthy: %v\n", i, err)
    }
}

🛠️ Advanced Usage

Custom Request Handling
// Use retry wrapper for critical operations
ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second)
defer cancel()

err := client.WithRetry(ctx, 5, func() error {
    _, err := client.GetNodeStatus()
    return err
})
Configuration Management
// Get current configuration
config := client.GetConfig()
fmt.Printf("Current network: %s\n", config.Network.Name)

// Update configuration
newConfig := client.DefaultClientConfig(client.MainnetConfig)
newConfig.Timeout = 60 * time.Second
err := client.SetConfig(newConfig)

📊 Monitoring and Debugging

Transaction Monitoring
// Wait for transaction completion
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()

result, err := client.WaitForTransaction(ctx, operationID)
if err != nil {
    log.Printf("Transaction failed: %v", err)
} else {
    fmt.Printf("Transaction completed with status: %s\n", result.Status)
}

// Get transaction receipt
receipt, err := client.GetTransactionReceipt(operationID)
fmt.Printf("Gas used: %d\n", receipt.GasUsed)
Error Handling
// Check for specific error types
if rpcErr, ok := err.(*client.RPCError); ok {
    fmt.Printf("RPC error code: %d, message: %s\n", rpcErr.Code, rpcErr.Message)
}

// Operation status checking
switch result.Status {
case client.OperationStatusSuccess:
    fmt.Println("Operation succeeded")
case client.OperationStatusFailed:
    fmt.Printf("Operation failed: %s\n", result.Error)
case client.OperationStatusPending:
    fmt.Println("Operation is pending")
}

🔐 Security Best Practices

  1. API Keys: Store API keys securely and never commit them to version control
  2. Password Management: Use secure password storage for wallet account passwords
  3. Network Validation: Always validate network configurations in production
  4. Error Handling: Implement proper error handling for all network operations
  5. Resource Cleanup: Always close clients and streams when done

🧪 Testing

Unit Testing
func TestClientConnection(t *testing.T) {
    client, err := client.NewTestnetClient()
    require.NoError(t, err)
    defer client.Close()
    
    status, err := client.GetNodeStatus()
    require.NoError(t, err)
    require.NotEmpty(t, status.NodeID)
}
Integration Testing
func TestSmartContractDeployment(t *testing.T) {
    client, err := client.NewTestnetClient()
    require.NoError(t, err)
    defer client.Close()
    
    // Deploy test contract
    deployRequest := &client.ContractDeploymentRequest{
        Bytecode: loadTestContract(),
        MaxGas:   1000000,
        Coins:    "0",
    }
    
    result, err := client.DeployContract(deployRequest, testAccount, "password")
    require.NoError(t, err)
    require.NotEmpty(t, result.ContractAddress)
}

📝 Examples

See the example directory for complete working examples:

  • Basic client usage
  • Smart contract deployment and interaction
  • Event monitoring and filtering
  • Transaction operations
  • Connection pooling
  • Error handling patterns

🤝 Contributing

  1. Fork the repository
  2. Create a feature branch
  3. Add tests for new functionality
  4. Ensure all tests pass
  5. Submit a pull request

📄 License

This project is licensed under the MIT License - see the LICENSE file for details.

🐛 Troubleshooting

Common Issues

Connection Errors

# Check if the node is running and accessible
curl -X POST -H "Content-Type: application/json" \
  -d '{"jsonrpc":"2.0","method":"get_status","id":1}' \
  https://test.massa.net/api/v2

WebSocket Issues

// Disable WebSocket if having connectivity issues
client := client.NewClientBuilder().
    WithTestnet().
    WithCustomWebSocket(""). // Empty WebSocket URL disables it
    Build()

Timeout Issues

// Increase timeout for slow connections
client := client.NewClientBuilder().
    WithTimeout(120 * time.Second).
    WithRetryCount(10).
    Build()

Built with ❤️ for the Massa ecosystem

Documentation

Overview

other gRPC client methods

Index

Constants

View Source
const (
	ConfigFile      = "config.yaml"
	MainnetURL      = "https://mainnet.massa.net/api/v2"
	MainnetChainID  = 77658377
	BuildnetURL     = "https://buildnet.massa.net/api/v2"
	BuildnetChainID = 77658366

	// Public API ports
	DEFAULT_GRPC_PORT     = "33037"
	DEFAULT_JSON_RPC_PORT = "33035"

	DEFAULT_PERIOD_OFFSET      uint64 = 5
	DEFAULT_READ_ONLY_CALL_FEE uint64 = 0.01 * 1e9
	MANTISSA_SCALE             uint32 = 9

	DEFAULT_TARGET_NUM_GRPC_AVAILABLE   uint32        = 3
	DEFAULT_GET_PROVIDER_MAX_RETRIES    uint32        = 3
	DEFAULT_GET_PROVIDER_RETRY_INTERVAL time.Duration = 5 * time.Second

	DEFAULT_KDF_ITER    = 600_000
	DEFAULT_KDF_KEY_LEN = 32

	SECRET_KEY_PREFIX              = "S"
	PUBLIC_KEY_PREFIX              = "P"
	ADDRESS_USER_PREFIX            = "AU"
	ADDRESS_CONTRACT_PREFIX        = "AS"
	OPERATION_ID_PREFIX            = "O"
	ADDRESS_PREIX_LENGTH    uint64 = 2
	KEYS_VERSION_NUMBER     uint64 = 0

	MAX_BLOCK_GAS = 4_294_967_295

	DEFAULT_MAINNET_JSON_RPC = "https://mainnet.massa.net/api/v2"
)
View Source
const (
	PercentageGasLimit = 10
)

Variables

This section is empty.

Functions

func EstimateGasCostCallSC

func EstimateGasCostCallSC(
	account *wallet.Account,
	password string,
	targetAddr string,
	callerAddr string,
	function string,
	parameter []byte,
	coins uint64,
	fee uint64,
	c *Client,
) (uint64, error)

func EstimateGasCostExecuteSC

func EstimateGasCostExecuteSC(
	account *wallet.Account,
	password string,
	callerAddress string,
	contract []byte,
	datastore []byte,
	maxCoins uint64,
	fee uint64,
	client *Client,
) (uint64, error)

func GetVersionDigits

func GetVersionDigits(status *State) (string, error)

GetVersionDigits extracts the version digits from the node version string. Example: "DEVN.1.2" -> "1.2" Example: "MAIN.6.6" -> "6.6"

func NextSlot

func NextSlot(c *Client) (uint64, error)

func ReadOnlyResultToBytes

func ReadOnlyResultToBytes(r *ReadOnlyResult) ([]byte, error)

ReadOnlyResultToBytes extracts the returned payload bytes from a ReadOnlyResult. It supports several JSON shapes returned by the node's `Ok` field: - top-level numeric array: Ok: [14,0,0,0] - nested numeric array: Ok: [[14,0,0,0]] - base64-encoded string: Ok: ["<base64>"] - raw string: Ok: ["raw"] - []byte when already decoded Returns an error if no payload is present or the shape is unsupported.

func SerializeDatastore

func SerializeDatastore(datastore []ContractDatastoreEntry) ([]byte, error)

SerializeDatastore serializes the datastore into a []byte array.

Types

type Address

type Address struct {
	Address                string   `json:"address"`
	BlockDraws             []string `json:"block_draws"`
	BlocksCreated          []string `json:"blocks_created"`
	CandidateBalance       string   `json:"candidate_balance"`
	CandidateDatastoreKeys [][]byte `json:"candidate_datastore_keys"`
	FinalBalance           string   `json:"final_balance"`
	FinalDatastoreKeys     [][]byte `json:"final_datastore_keys"`
}

func Addresses

func Addresses(client *Client, addr []string) ([]Address, error)

type Balance

type Balance struct {
	Candidate decimal.Decimal
	Final     decimal.Decimal
}

func FetchBalance

func FetchBalance(client *Client, address string) (*Balance, error)

FetchBalance returns as a decimal the candidate balance and final balance of an address.

type BitVecHeadInfo

type BitVecHeadInfo struct {
	Width int `json:"width"`
	Index int `json:"index"`
}

type ChangeSet

type ChangeSet struct {
	Set interface{} `json:"Set"` // Set can be of different types, using `interface{}`

}

type Client

type Client struct {
	RPCClient jsonrpc.RPCClient
	ChainID   utils.NetworkType
}

func NewClient

func NewClient(isMainnet bool) *Client

type ClientConfig

type ClientConfig struct {
	Address        string
	UseTLS         bool
	TLSConfig      *tls.Config
	DefaultTimeout time.Duration
	DialOptions    []grpc.DialOption
	ChainID        utils.NetworkType
	Account        *wallet.Account
}

ClientConfig holds configuration for the gRPC client

type Config

type Config struct {
	BlockReward             *string `json:"block_reward"`
	DeltaF0                 *uint   `json:"delta_f0"`
	EndTimeStamp            *uint   `json:"end_timestamp"`
	GenesisTimestamp        *uint   `json:"genesis_timestamp"`
	OperationValidityParios *uint   `json:"operation_validity_periods"`
	PeriodsPerCycle         *uint   `json:"periods_per_cycle"`
	PosLockCycles           *uint   `json:"pos_lock_cycles"`
	PosLookbackCycle        *uint   `json:"pos_lookback_cycles"`
	RollPrice               *string `json:"roll_price"`
	T0                      *uint   `json:"t0"`
	ThreadCount             *uint   `json:"thread_count"`
}

type ConsensusStats

type ConsensusStats struct {
	CliqueCount         *uint `json:"clique_count"`
	EndTimespan         *uint `json:"end_timespan"`
	FinalBlockCount     *uint `json:"final_block_count"`
	FinalOperationCount *uint `json:"final_operation_count"`
	StakerCount         *uint `json:"staker_count"`
	StaleBlockCount     *uint `json:"stale_block_count"`
	StartTimespan       *uint `json:"start_timespan"`
}

type ContractDatastore

type ContractDatastore struct {
	ByteCode []byte
	Args     []byte
	Coins    uint64
}

func DatastoreToDeployedContract

func DatastoreToDeployedContract(datastore []ContractDatastoreEntry) (
	contractDatastore ContractDatastore,
	isDeployDatastore bool,
)

DatastoreToDeployedContract If the datastore is a valid datastore for a deployed contract, it will return the contract's bytecode, args and coins If the datastore is not a valid datastore for a deployed contract, it will return an empty ContractDatastore and isDeployDatastore = false.

type ContractDatastoreEntry

type ContractDatastoreEntry struct {
	Key   []byte
	Value []byte
}

func DeserializeDatastore

func DeserializeDatastore(datastore []byte) ([]ContractDatastoreEntry, error)

type DatastoreEntryData

type DatastoreEntryData struct {
	Address string        `json:"address"`
	Key     JSONableSlice `json:"key"`
}

func NewDatastoreEntry

func NewDatastoreEntry(address string, key []byte) DatastoreEntryData

type DatastoreEntryResponse

type DatastoreEntryResponse struct {
	CandidateValue []byte `json:"candidate_value"`
	FinalValue     []byte `json:"final_value"`
}

func ContractDatastoreEntries

func ContractDatastoreEntries(client *Client, address string, keys [][]byte) ([]DatastoreEntryResponse, error)

func FetchDatastoreEntries

func FetchDatastoreEntries(client *Client, entries []DatastoreEntryData) ([]DatastoreEntryResponse, error)

func FetchDatastoreEntry

func FetchDatastoreEntry(client *Client, address string, key []byte) (*DatastoreEntryResponse, error)

type DeferredCreditsInfo

type DeferredCreditsInfo struct {
	Credits map[string]interface{} `json:"credits"` // Empty in provided JSON, assumed to be a map
}

type Event

type Event struct {
	Context EventContext `json:"context"`
	Data    string       `json:"data"`
}

func Events

func Events(client *Client, start *Slot, end *Slot,
	emitter *string, originalCaller *string,
	operationID *string,
) ([]Event, error)

*

  • Filters events based on given arguments. *
  • Research criterion are
  • - by slots:
  • * after => start
  • * before => end
  • - callstack address:
  • * last address in the callstack => emitter
  • * first address in the callstack => originaCaller
  • - operation id. *
  • All these criterion are optional.

func ListenEvents

func ListenEvents(
	client *Client,
	start *Slot, end *Slot,
	emitter *string,
	operationID *string,
	caller *string,
	failOnExecError bool,
) ([]Event, error)

type EventContext

type EventContext struct {
	Slot              Timestamp   `json:"slot"`
	Block             interface{} `json:"block"` // Assuming `null` can be represented as an `interface{}`
	ReadOnly          bool        `json:"read_only"`
	IndexInSlot       int         `json:"index_in_slot"`
	CallStack         []string    `json:"call_stack"`
	OriginOperationID interface{} `json:"origin_operation_id"` // Assuming `null` can be represented as an `interface{}`
	IsFinal           bool        `json:"is_final"`
	IsError           bool        `json:"is_error"`
}

type EventSearchCriteria

type EventSearchCriteria struct {
	Start                 *Slot   `json:"start"`
	End                   *Slot   `json:"end"`
	EmitterAddress        *string `json:"emitter_address"`
	OriginalCallerAddress *string `json:"original_caller_address"`
	OriginalOperationID   *string `json:"original_operation_id"`
}

type JSONableSlice

type JSONableSlice []byte

func (JSONableSlice) MarshalJSON

func (u JSONableSlice) MarshalJSON() ([]byte, error)

type LedgerEntryChange

type LedgerEntryChange struct {
	Update LedgerUpdate `json:"Update"`
}

type LedgerUpdate

type LedgerUpdate struct {
	Balance   ChangeSet     `json:"balance"`
	Bytecode  interface{}   `json:"bytecode"`
	Datastore []interface{} `json:"datastore"`
}

type MassaClient

type MassaClient struct {
	PublicClient  pb.PublicServiceClient
	PrivateClient pb.PrivateServiceClient

	ChainID utils.NetworkType
	Account *wallet.Account
	// contains filtered or unexported fields
}

MassaClient provides high-level methods for signing and sending operations using wallet accounts (automatic signing)

func NewMassaClient

func NewMassaClient(cfg *ClientConfig) (*MassaClient, error)

NewMassaClient creates a new wallet-integrated operation sender

func (*MassaClient) BuyRolls

func (c *MassaClient) BuyRolls(
	ctx context.Context,
	nickname string,
	password string,
	rollCount uint64,
	fee float64,
) (string, error)

BuyRolls is a convenience method for buying rolls using wallet

func (*MassaClient) CallSC

func (c *MassaClient) CallSC(
	ctx context.Context,
	nickname string,
	password string,
	targetAddress string,
	targetFunction string,
	parameters []byte,
	maxGas float64,
	coins float64,
	fee float64,
) (string, error)

CallSC is a convenience method for calling smart contracts using wallet

func (*MassaClient) Close

func (c *MassaClient) Close() error

func (*MassaClient) ExecuteSC

func (c *MassaClient) ExecuteSC(
	ctx context.Context,
	nickname string,
	password string,
	bytecode []byte,
	maxGas float64,
	maxCoins float64,
	datastore []byte,
	fee float64,
) (string, error)

SendExecuteSCWithWallet is a convenience method for deploying smart contracts using wallet

func (*MassaClient) GetContext

func (c *MassaClient) GetContext() (context.Context, context.CancelFunc)

GetContext returns a context with the default timeout

func (*MassaClient) GetContextWithTimeout

func (c *MassaClient) GetContextWithTimeout(timeout time.Duration) (context.Context, context.CancelFunc)

GetContextWithTimeout returns a context with a custom timeout

func (*MassaClient) GetDatastoreEntries

func (c *MassaClient) GetDatastoreEntries(ctx context.Context, address string, keys [][]byte) ([]*model.DatastoreEntry, error)

GetDatastoreEntries fetches datastore entries for a given contract address and a list of keys. It returns the protobuf model DatastoreEntry objects (which contain candidate and final values).

func (*MassaClient) NewBlocksServerStream

func (c *MassaClient) NewBlocksServerStream(ctx context.Context, req *pb.NewBlocksServerRequest, handler StreamHandler[pb.NewBlocksServerResponse]) error

NewBlocksServerStream creates a server streaming connection for new blocks

func (*MassaClient) NewBlocksStream

NewBlocksStream creates a bidirectional stream for new blocks

func (*MassaClient) NewEndorsementsServerStream

NewEndorsementsServerStream creates a server streaming connection for new endorsements

func (*MassaClient) NewEndorsementsStream

NewEndorsementsStream creates a bidirectional stream for new endorsements

func (*MassaClient) NewFilledBlocksServerStream

NewFilledBlocksServerStream creates a server streaming connection for new filled blocks

func (*MassaClient) NewFilledBlocksStream

NewFilledBlocksStream creates a bidirectional stream for new filled blocks

func (*MassaClient) NewOperationsServerStream

func (c *MassaClient) NewOperationsServerStream(ctx context.Context, req *pb.NewOperationsServerRequest, handler StreamHandler[pb.NewOperationsServerResponse]) error

NewOperationsServerStream creates a server streaming connection for new operations

func (*MassaClient) NewOperationsStream

NewOperationsStream creates a bidirectional stream for new operations

func (*MassaClient) NewSlotABICallStacksStream

NewSlotABICallStacksStream creates a bidirectional stream for slot ABI call stacks

func (*MassaClient) NewSlotExecutionOutputsServerStream

NewSlotExecutionOutputsServerStream creates a server streaming connection for slot execution outputs

func (*MassaClient) NewSlotExecutionOutputsStream

NewSlotExecutionOutputsStream creates a bidirectional stream for slot execution outputs

func (*MassaClient) NewSlotTransfersStream

NewSlotTransfersStream creates a bidirectional stream for slot transfers

func (*MassaClient) NewTransfersInfoServerStream

NewTransfersInfoServerStream creates a server streaming connection for transfers info

func (*MassaClient) ReadOnlyCallSC

func (c *MassaClient) ReadOnlyCallSC(
	ctx context.Context,
	targetAddress string,
	targetFunction string,
	parameters []byte,
	coins float64,
	fee float64,
	callerAddress string,
) (*model.ReadOnlyExecutionOutput, error)

ReadOnlyCallSC performs a read-only smart contract call (no signature required) It uses the node JSON-RPC "execute_read_only_call" under the hood and returns the result. If callerAddress is empty and the MassaClient was created with a wallet account, the caller address will be taken from the wallet account.

func (*MassaClient) SellRolls

func (c *MassaClient) SellRolls(
	ctx context.Context,
	nickname string,
	password string,
	rollCount uint64,
	fee float64) (string, error)

SellRolls is a conven`ience method for selling rolls using wallet

func (*MassaClient) SendBlocksStream

SendBlocksStream creates a bidirectional stream for sending blocks

func (*MassaClient) SendEndorsementsStream

SendEndorsementsStream creates a bidirectional stream for sending endorsements

func (*MassaClient) SendOperation

func (c *MassaClient) SendOperation(
	ctx context.Context,
	nickname string,
	password string,
	op sendoperation.Operation,
	fee uint64,
) (string, error)

SendOperationWithWallet signs and sends a single operation using a wallet account Parameters:

  • ctx: Context for the request
  • nickname: Account nickname in the wallet
  • password: Account password
  • op: The operation to send
  • fee: Fee amount in NanoMassa
  • expirePeriod: Period after which the operation expires

Returns:

  • operationID: The ID of the sent operation
  • error: Any error that occurred

func (*MassaClient) SendOperationsStream

SendOperationsStream creates a bidirectional stream for sending operations

func (*MassaClient) SendTransaction

func (c *MassaClient) SendTransaction(
	ctx context.Context,
	nickname string,
	password string,
	recipientAddress string,
	amount float64,
	fee float64,
) (string, error)

SendTransaction is a convenience method for sending a transaction using wallet

func (*MassaClient) TransactionsThroughputServerStream

TransactionsThroughputServerStream creates a server streaming connection for transactions throughput

func (*MassaClient) TransactionsThroughputStream

TransactionsThroughputStream creates a bidirectional stream for transactions throughput

type NetworkStats

type NetworkStats struct {
	ActiveNodeCount    *uint `json:"active_node_count"`
	BannedPeerCount    *uint `json:"banned_peer_count"`
	InConnectionCount  *uint `json:"in_connection_count"`
	KnowPeerCount      *uint `json:"known_peer_count"`
	OutConnectionCount *uint `json:"out_connection_count"`
}

type PosChanges

type PosChanges struct {
	SeedBits        SeedBitsInfo           `json:"seed_bits"`
	RollChanges     map[string]interface{} `json:"roll_changes"`     // Empty in provided JSON, assumed to be a map
	ProductionStats map[string]interface{} `json:"production_stats"` // Empty in provided JSON, assumed to be a map
	DeferredCredits DeferredCreditsInfo    `json:"deferred_credits"`
}

type ReadOnlyCallParams

type ReadOnlyCallParams struct {
	MaxGas         int           `json:"max_gas"`
	Coins          string        `json:"coins"`
	Fee            string        `json:"fee"`
	TargetAddress  string        `json:"target_address"`
	TargetFunction string        `json:"target_function"`
	Parameter      JSONableSlice `json:"parameter"`
	CallerAddress  string        `json:"caller_address"`
}

ReadOnlyCallParams is the struct used to send a read only callSC to the node.

type ReadOnlyExecuteParams

type ReadOnlyExecuteParams struct {
	MaxGas             int           `json:"max_gas"`
	Coins              string        `json:"coins"`
	Fee                string        `json:"fee"`
	Address            string        `json:"address"`
	Bytecode           JSONableSlice `json:"bytecode"`
	OperationDatastore JSONableSlice `json:"operation_datastore"`
}

ReadOnlyExecuteParams is the struct used to send a read only executeSC to the node.

type ReadOnlyResult

type ReadOnlyResult struct {
	ExecutedAt   Timestamp   `json:"executed_at"`
	Result       Result      `json:"result"`
	OutputEvents []Event     `json:"output_events"`
	GasCost      int         `json:"gas_cost"`
	StateChanges StateChange `json:"state_changes"`
}

func ReadOnlyCallSC

func ReadOnlyCallSC(
	targetAddr string,
	function string,
	parameter []byte,
	coins string,
	fee string,
	callerAddr string,
	c *Client,
) (*ReadOnlyResult, error)

ReadOnlyCallSC calls execute_read_only_call jsonrpc method. coins and fee must be in MAS.

func ReadOnlyExecuteSC

func ReadOnlyExecuteSC(
	contract []byte,
	datastore []byte,
	coins string,
	fee string,
	callerAddr string,
	client *Client,
) (*ReadOnlyResult, error)

ReadOnlyExecuteSC calls execute_read_only_bytecode jsonrpc method. coins and fee must be in MAS.

type Result

type Result struct {
	Ok    []interface{} `json:"Ok,omitempty"`
	Error string        `json:"Error,omitempty"`
}

Result is a struct that can hold both 'Ok' and 'Error' fields.

func (*Result) UnmarshalJSON

func (r *Result) UnmarshalJSON(data []byte) error

Custom UnmarshalJSON to handle both cases for the Result field.

type SeedBitsInfo

type SeedBitsInfo struct {
	Order string         `json:"order"`
	Head  BitVecHeadInfo `json:"head"`
	Bits  int            `json:"bits"`
	Data  []interface{}  `json:"data"` // Empty array in provided JSON
}

type Slot

type Slot struct {
	Period int `json:"period"`
	Thread int `json:"thread"`
}

func NewSlot

func NewSlot(period int, thread int) *Slot

type State

type State struct {
	Config         *Config         `json:"config"`
	ConsensusStats *ConsensusStats `json:"consensus_stats"`
	CurrentCycle   *uint           `json:"current_cycle"`
	CurrentTime    *uint           `json:"current_time"`
	LastSlot       *Slot           `json:"last_slot"`
	NetworkStats   *NetworkStats   `json:"network_stats"`
	NextSlot       *Slot           `json:"next_slot"`
	NodeID         *string         `json:"node_id"`
	NodeIP         *string         `json:"node_ip"`
	PoolStats      *[]uint         `json:"pool_stats"`
	Version        *string         `json:"version"`
	ChainID        *uint           `json:"chain_id"`
	MinimalFees    *string         `json:"minimal_fees"`
}

func Status

func Status(client *Client) (*State, error)

type StateChange

type StateChange struct {
	LedgerChanges                map[string]LedgerEntryChange `json:"ledger_changes"`
	AsyncPoolChanges             []interface{}                `json:"async_pool_changes"` // Empty in provided JSON, assumed to be a map
	PosChanges                   PosChanges                   `json:"pos_changes"`
	ExecutedOpsChanges           map[string]interface{}       `json:"executed_ops_changes"`
	ExecutedDenunciationsChanges []interface{}                `json:"executed_denunciations_changes"` // Empty array in provided JSON
	ExecutionTrailHashChange     interface{}                  `json:"execution_trail_hash_change"`
}

type StreamHandler

type StreamHandler[T any] func(msg *T) error

StreamHandler is a generic handler for processing stream responses

type Timestamp

type Timestamp struct {
	Period int `json:"period"`
	Thread int `json:"thread"`
}

Jump to

Keyboard shortcuts

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