Documentation
¶
Overview ¶
Package rpcclient implements NEO-specific JSON-RPC 2.0 client.
This package itself is designed to be a thin layer on top of the regular JSON-RPC interface provided by Neo implementations. Therefore the set of methods provided by clients is exactly the same as available from servers and they use data types that directly correspond to JSON data exchanged. While this is the most powerful and direct interface, it at the same time is not very convenient for many purposes, like the most popular one --- performing test invocations and creating/sending transactions that will do something to the chain. Please check subpackages for more convenient APIs.
Subpackages ¶
The overall structure can be seen as a number of layers built on top of rpcclient and on top of each other with each package and each layer solving different problems.
These layers are:
Basic RPC API, rpcclient package itself.
Generic invocation/transaction API represented by invoker, unwrap (auxiliary, but very convenient) and actor packages. These allow to perform test invocations with plain Go types, use historic states for these invocations, get the execution results from reader functions and create/send transactions that change something on-chain.
Standard-specific wrappers that are implemented in nep11 and nep17 packages (with common methods in neptoken). They implement the respective NEP-11 and NEP-17 APIs both for safe (read-only) and state-changing methods. Safe methods require an Invoker to be called, while Actor is used to create/send transactions.
Contract-specific wrappers for native contracts that include management, gas, neo, oracle, policy and rolemgmt packages for the respective native contracts. Complete contract functionality is exposed (reusing nep17 package for gas and neo).
Notary actor and contract, a bit special since it's a NeoGo protocol extension, but notary package provides both the notary native contract wrapper and a notary-specific actor implementation that allows to easily wrap any transaction into a notary request.
Non-native contract-specific wrappers, currently partially provided only for NNS contract (it's still in development), at the moment that's mostly an example of how contract-specific wrappers can be built for other dApps (reusing invoker/actor layers it's pretty easy).
Client ¶
After creating a client instance with or without a ClientConfig you can interact with the NEO blockchain by its exposed methods.
Supported methods
calculatenetworkfee findstates getapplicationlog getbestblockhash getblock getblockcount getblockhash getblockheader getblockheadercount getcommittee getconnectioncount getcontractstate getnativecontracts getnep11balances getnep11properties getnep11transfers getnep17balances getnep17transfers getpeers getrawmempool getrawtransaction getstate getstateheight getstateroot getstorage gettransactionheight getunclaimedgas getnextblockvalidators getversion invokefunction invokescript invokecontractverify sendrawtransaction submitblock submitoracleresponse terminatesession traverseiterator validateaddress
Extensions:
getblocksysfee getrawnotarypool getrawnotarytransaction submitnotaryrequest
Unsupported methods
canceltransaction claimgas dumpprivkey getbalance getmetricblocktimestamp getnewaddress getwalletheight importprivkey listaddress listplugins sendfrom sendmany sendtoaddress
Example ¶
package main import ( "context" "fmt" "os" "github.com/nspcc-dev/neo-go/pkg/encoding/address" "github.com/nspcc-dev/neo-go/pkg/rpcclient" ) func main() { endpoint := "http://seed5.bridgeprotocol.io:10332" opts := rpcclient.Options{} c, err := rpcclient.New(context.TODO(), endpoint, opts) if err != nil { fmt.Println(err) os.Exit(1) } err = c.Init() if err != nil { fmt.Println(err) os.Exit(1) } if err := c.Ping(); err != nil { fmt.Println(err) os.Exit(1) } addr, err := address.StringToUint160("ATySFJAbLW7QHsZGHScLhxq6EyNBxx3eFP") if err != nil { fmt.Println(err) os.Exit(1) } resp, err := c.GetNEP17Balances(addr) if err != nil { fmt.Println(err) os.Exit(1) } fmt.Println(resp.Address) fmt.Println(resp.Balances) }
Output:
Index ¶
- Variables
- type Client
- func (c *Client) CalculateNetworkFee(tx *transaction.Transaction) (int64, error)
- func (c *Client) Close()
- func (c *Client) Context() context.Context
- func (c *Client) Endpoint() string
- func (c *Client) FindStates(stateroot util.Uint256, historicalContractHash util.Uint160, ...) (result.FindStates, error)
- func (c *Client) FindStorageByHash(contractHash util.Uint160, prefix []byte, start *int) (result.FindStorage, error)
- func (c *Client) FindStorageByHashHistoric(stateroot util.Uint256, historicalContractHash util.Uint160, ...) (result.FindStorage, error)
- func (c *Client) FindStorageByID(contractID int32, prefix []byte, start *int) (result.FindStorage, error)
- func (c *Client) FindStorageByIDHistoric(stateroot util.Uint256, historicalContractID int32, historicalPrefix []byte, ...) (result.FindStorage, error)
- func (c *Client) GetApplicationLog(hash util.Uint256, trig *trigger.Type) (*result.ApplicationLog, error)
- func (c *Client) GetBestBlockHash() (util.Uint256, error)
- func (c *Client) GetBlockByHash(hash util.Uint256) (*block.Block, error)
- func (c *Client) GetBlockByHashVerbose(hash util.Uint256) (*result.Block, error)
- func (c *Client) GetBlockByIndex(index uint32) (*block.Block, error)
- func (c *Client) GetBlockByIndexVerbose(index uint32) (*result.Block, error)
- func (c *Client) GetBlockCount() (uint32, error)
- func (c *Client) GetBlockHash(index uint32) (util.Uint256, error)
- func (c *Client) GetBlockHeader(hash util.Uint256) (*block.Header, error)
- func (c *Client) GetBlockHeaderCount() (uint32, error)
- func (c *Client) GetBlockHeaderVerbose(hash util.Uint256) (*result.Header, error)
- func (c *Client) GetBlockSysFee(index uint32) (fixedn.Fixed8, error)
- func (c *Client) GetCandidates() ([]result.Candidate, error)
- func (c *Client) GetCommittee() (keys.PublicKeys, error)
- func (c *Client) GetConnectionCount() (int, error)
- func (c *Client) GetContractStateByAddressOrName(addressOrName string) (*state.Contract, error)
- func (c *Client) GetContractStateByHash(hash util.Uint160) (*state.Contract, error)
- func (c *Client) GetContractStateByID(id int32) (*state.Contract, error)
- func (c *Client) GetNEP11Balances(address util.Uint160) (*result.NEP11Balances, error)
- func (c *Client) GetNEP11Properties(asset util.Uint160, token []byte) (map[string]any, error)
- func (c *Client) GetNEP11Transfers(address util.Uint160, start, stop *uint64, limit, page *int) (*result.NEP11Transfers, error)
- func (c *Client) GetNEP17Balances(address util.Uint160) (*result.NEP17Balances, error)
- func (c *Client) GetNEP17Transfers(address util.Uint160, start, stop *uint64, limit, page *int) (*result.NEP17Transfers, error)
- func (c *Client) GetNativeContracts() ([]state.NativeContract, error)
- func (c *Client) GetNextBlockValidators() ([]result.Validator, error)
- func (c *Client) GetPeers() (*result.GetPeers, error)
- func (c *Client) GetProof(stateroot util.Uint256, historicalContractHash util.Uint160, ...) (*result.ProofWithKey, error)
- func (c *Client) GetRawMemPool() ([]util.Uint256, error)
- func (c *Client) GetRawNotaryPool() (*result.RawNotaryPool, error)
- func (c *Client) GetRawNotaryTransaction(hash util.Uint256) (*transaction.Transaction, error)
- func (c *Client) GetRawNotaryTransactionVerbose(hash util.Uint256) (*transaction.Transaction, error)
- func (c *Client) GetRawTransaction(hash util.Uint256) (*transaction.Transaction, error)
- func (c *Client) GetRawTransactionVerbose(hash util.Uint256) (*result.TransactionOutputRaw, error)
- func (c *Client) GetState(stateroot util.Uint256, historicalContractHash util.Uint160, ...) ([]byte, error)
- func (c *Client) GetStateHeight() (*result.StateHeight, error)
- func (c *Client) GetStateRootByBlockHash(hash util.Uint256) (*state.MPTRoot, error)
- func (c *Client) GetStateRootByHeight(height uint32) (*state.MPTRoot, error)
- func (c *Client) GetStorageByHash(hash util.Uint160, key []byte) ([]byte, error)
- func (c *Client) GetStorageByHashHistoric(root util.Uint256, hash util.Uint160, key []byte) ([]byte, error)
- func (c *Client) GetStorageByID(id int32, key []byte) ([]byte, error)
- func (c *Client) GetStorageByIDHistoric(root util.Uint256, id int32, key []byte) ([]byte, error)
- func (c *Client) GetTransactionHeight(hash util.Uint256) (uint32, error)
- func (c *Client) GetUnclaimedGas(address string) (result.UnclaimedGas, error)
- func (c *Client) GetVersion() (*result.Version, error)
- func (c *Client) Init() error
- func (c *Client) InvokeContractVerify(contract util.Uint160, params []smartcontract.Parameter, ...) (*result.Invoke, error)
- func (c *Client) InvokeContractVerifyAtHeight(height uint32, contract util.Uint160, params []smartcontract.Parameter, ...) (*result.Invoke, error)
- func (c *Client) InvokeContractVerifyWithState(stateOrBlock util.Uint256, contract util.Uint160, ...) (*result.Invoke, error)
- func (c *Client) InvokeFunction(contract util.Uint160, operation string, params []smartcontract.Parameter, ...) (*result.Invoke, error)
- func (c *Client) InvokeFunctionAtHeight(height uint32, contract util.Uint160, operation string, ...) (*result.Invoke, error)
- func (c *Client) InvokeFunctionWithState(stateOrBlock util.Uint256, contract util.Uint160, operation string, ...) (*result.Invoke, error)
- func (c *Client) InvokeScript(script []byte, signers []transaction.Signer) (*result.Invoke, error)
- func (c *Client) InvokeScriptAtHeight(height uint32, script []byte, signers []transaction.Signer) (*result.Invoke, error)
- func (c *Client) InvokeScriptWithState(stateOrBlock util.Uint256, script []byte, signers []transaction.Signer) (*result.Invoke, error)
- func (c *Client) Ping() error
- func (c *Client) SendRawTransaction(rawTX *transaction.Transaction) (util.Uint256, error)
- func (c *Client) SubmitBlock(b block.Block) (util.Uint256, error)
- func (c *Client) SubmitP2PNotaryRequest(req *payload.P2PNotaryRequest) (util.Uint256, error)
- func (c *Client) SubmitRawOracleResponse(ps []any) error
- func (c *Client) TerminateSession(sessionID uuid.UUID) (bool, error)
- func (c *Client) TraverseIterator(sessionID, iteratorID uuid.UUID, maxItemsCount int) ([]stackitem.Item, error)
- func (c *Client) ValidateAddress(address string) error
- func (c *Client) VerifyProof(stateroot util.Uint256, proof *result.ProofWithKey) ([]byte, error)
- type Internal
- type InternalHook
- type Notification
- type Options
- type WSClient
- func (c *WSClient) Close()
- func (c *WSClient) Context() context.Context
- func (c *WSClient) GetError() error
- func (c *WSClient) ReceiveBlocks(flt *neorpc.BlockFilter, rcvr chan<- *block.Block) (string, error)
- func (c *WSClient) ReceiveExecutionNotifications(flt *neorpc.NotificationFilter, rcvr chan<- *state.ContainedNotificationEvent) (string, error)
- func (c *WSClient) ReceiveExecutions(flt *neorpc.ExecutionFilter, rcvr chan<- *state.AppExecResult) (string, error)
- func (c *WSClient) ReceiveHeadersOfAddedBlocks(flt *neorpc.BlockFilter, rcvr chan<- *block.Header) (string, error)
- func (c *WSClient) ReceiveNotaryRequests(flt *neorpc.NotaryRequestFilter, rcvr chan<- *result.NotaryRequestEvent) (string, error)
- func (c *WSClient) ReceiveTransactions(flt *neorpc.TxFilter, rcvr chan<- *transaction.Transaction) (string, error)
- func (c *WSClient) Unsubscribe(id string) error
- func (c *WSClient) UnsubscribeAll() error
- type WSOptions
Examples ¶
Constants ¶
This section is empty.
Variables ¶
var ErrNilNotificationReceiver = errors.New("nil notification receiver")
ErrNilNotificationReceiver is returned when notification receiver channel is nil.
var ErrWSConnLost = errors.New("connection lost")
ErrWSConnLost is a WSClient-specific error that will be returned for any requests after disconnection (including intentional ones via (*WSClient).Close).
Functions ¶
This section is empty.
Types ¶
type Client ¶
type Client struct {
// contains filtered or unexported fields
}
Client represents the middleman for executing JSON RPC calls to remote NEO RPC nodes. Client is thread-safe and can be used from multiple goroutines.
func New ¶
New returns a new Client ready to use. You should call Init method to initialize stateroot setting for the network the client is operating on if you plan using GetBlock*.
func (*Client) CalculateNetworkFee ¶
func (c *Client) CalculateNetworkFee(tx *transaction.Transaction) (int64, error)
CalculateNetworkFee calculates network fee for the transaction. The transaction may have empty witnesses for contract signers and may have only verification scripts filled for standard sig/multisig signers.
func (*Client) Close ¶
func (c *Client) Close()
Close closes unused underlying networks connections.
func (*Client) FindStates ¶
func (c *Client) FindStates(stateroot util.Uint256, historicalContractHash util.Uint160, historicalPrefix []byte, start []byte, maxCount *int) (result.FindStates, error)
FindStates returns historical contract storage item states by the given stateroot, historical contract hash and historical prefix. If `start` path is specified, items starting from `start` path are being returned (excluding item located at the start path). If `maxCount` specified, the maximum number of items to be returned equals to `maxCount`.
func (*Client) FindStorageByHash ¶ added in v0.102.0
func (c *Client) FindStorageByHash(contractHash util.Uint160, prefix []byte, start *int) (result.FindStorage, error)
FindStorageByHash returns contract storage items by the given contract hash and prefix. If `start` index is specified, items starting from `start` index are being returned (including item located at the start index).
func (*Client) FindStorageByHashHistoric ¶ added in v0.102.0
func (c *Client) FindStorageByHashHistoric(stateroot util.Uint256, historicalContractHash util.Uint160, historicalPrefix []byte, start *int) (result.FindStorage, error)
FindStorageByHashHistoric returns historical contract storage items by the given stateroot, historical contract hash and historical prefix. If `start` index is specified, then items starting from `start` index are being returned (including item located at the start index).
func (*Client) FindStorageByID ¶ added in v0.102.0
func (c *Client) FindStorageByID(contractID int32, prefix []byte, start *int) (result.FindStorage, error)
FindStorageByID returns contract storage items by the given contract ID and prefix. If `start` index is specified, items starting from `start` index are being returned (including item located at the start index).
func (*Client) FindStorageByIDHistoric ¶ added in v0.102.0
func (c *Client) FindStorageByIDHistoric(stateroot util.Uint256, historicalContractID int32, historicalPrefix []byte, start *int) (result.FindStorage, error)
FindStorageByIDHistoric returns historical contract storage items by the given stateroot, historical contract ID and historical prefix. If `start` index is specified, then items starting from `start` index are being returned (including item located at the start index).
func (*Client) GetApplicationLog ¶
func (c *Client) GetApplicationLog(hash util.Uint256, trig *trigger.Type) (*result.ApplicationLog, error)
GetApplicationLog returns a contract log based on the specified txid.
func (*Client) GetBestBlockHash ¶
GetBestBlockHash returns the hash of the tallest block in the blockchain.
func (*Client) GetBlockByHash ¶
GetBlockByHash returns a block by its hash. In-header stateroot option must be initialized with Init before calling this method.
func (*Client) GetBlockByHashVerbose ¶
GetBlockByHashVerbose returns a block wrapper with additional metadata by its hash. In-header stateroot option must be initialized with Init before calling this method.
func (*Client) GetBlockByIndex ¶
GetBlockByIndex returns a block by its height. In-header stateroot option must be initialized with Init before calling this method.
func (*Client) GetBlockByIndexVerbose ¶
GetBlockByIndexVerbose returns a block wrapper with additional metadata by its height. In-header stateroot option must be initialized with Init before calling this method. NOTE: to get transaction.ID and transaction.Size, use t.Hash() and io.GetVarSize(t) respectively.
func (*Client) GetBlockCount ¶
GetBlockCount returns the number of blocks in the blockchain.
func (*Client) GetBlockHash ¶
GetBlockHash returns the hash value of the corresponding block based on the specified index.
func (*Client) GetBlockHeader ¶
GetBlockHeader returns the corresponding block header information from a serialized hex string according to the specified script hash. In-header stateroot option must be initialized with Init before calling this method.
func (*Client) GetBlockHeaderCount ¶
GetBlockHeaderCount returns the number of headers in the main chain.
func (*Client) GetBlockHeaderVerbose ¶
GetBlockHeaderVerbose returns the corresponding block header information from a Json format string according to the specified script hash. In-header stateroot option must be initialized with Init before calling this method.
func (*Client) GetBlockSysFee ¶
GetBlockSysFee returns the system fees of the block based on the specified index. This method is only supported by NeoGo servers.
func (*Client) GetCandidates ¶
GetCandidates returns the current list of NEO candidate node with voting data and validator status.
func (*Client) GetCommittee ¶
func (c *Client) GetCommittee() (keys.PublicKeys, error)
GetCommittee returns the current public keys of NEO nodes in the committee.
func (*Client) GetConnectionCount ¶
GetConnectionCount returns the current number of the connections for the node.
func (*Client) GetContractStateByAddressOrName ¶
GetContractStateByAddressOrName queries contract information using the contract address or name. Notice that name-based queries work only for native contracts, non-native ones can't be requested this way.
func (*Client) GetContractStateByHash ¶
GetContractStateByHash queries contract information according to the contract script hash.
func (*Client) GetContractStateByID ¶
GetContractStateByID queries contract information according to the contract ID. Notice that this is supported by all servers only for native contracts, non-native ones can be requested only from NeoGo servers.
func (*Client) GetNEP11Balances ¶
GetNEP11Balances is a wrapper for getnep11balances RPC.
func (*Client) GetNEP11Properties ¶
GetNEP11Properties is a wrapper for getnep11properties RPC. We recommend using nep11 package and Properties method there to receive proper VM types and work with them. This method is provided mostly for the sake of completeness. For well-known attributes like "description", "image", "name" and "tokenURI" it returns strings, while for all others []byte (which can be nil).
func (*Client) GetNEP11Transfers ¶
func (c *Client) GetNEP11Transfers(address util.Uint160, start, stop *uint64, limit, page *int) (*result.NEP11Transfers, error)
GetNEP11Transfers is a wrapper for getnep11transfers RPC. Address parameter is mandatory, while all others are optional. Limit and page parameters are only supported by NeoGo servers and can only be specified with start and stop.
func (*Client) GetNEP17Balances ¶
GetNEP17Balances is a wrapper for getnep17balances RPC.
func (*Client) GetNEP17Transfers ¶
func (c *Client) GetNEP17Transfers(address util.Uint160, start, stop *uint64, limit, page *int) (*result.NEP17Transfers, error)
GetNEP17Transfers is a wrapper for getnep17transfers RPC. Address parameter is mandatory while all the others are optional. Start and stop parameters are supported since neo-go 0.77.0 and limit and page since neo-go 0.78.0. These parameters are positional in the JSON-RPC call. For example, you can't specify the limit without specifying start/stop first.
func (*Client) GetNativeContracts ¶
func (c *Client) GetNativeContracts() ([]state.NativeContract, error)
GetNativeContracts queries information about native contracts.
func (*Client) GetNextBlockValidators ¶
GetNextBlockValidators returns the current NEO consensus nodes information and voting data.
func (*Client) GetPeers ¶
GetPeers returns a list of the nodes that the node is currently connected to/disconnected from.
func (*Client) GetProof ¶ added in v0.102.0
func (c *Client) GetProof(stateroot util.Uint256, historicalContractHash util.Uint160, historicalKey []byte) (*result.ProofWithKey, error)
GetProof returns existence proof of storage item state by the given stateroot historical contract hash and historical item key.
func (*Client) GetRawMemPool ¶
GetRawMemPool returns a list of unconfirmed transactions in the memory.
func (*Client) GetRawNotaryPool ¶ added in v0.102.0
func (c *Client) GetRawNotaryPool() (*result.RawNotaryPool, error)
GetRawNotaryPool returns hashes of main P2PNotaryRequest transactions that are currently in the RPC node's notary request pool with the corresponding hashes of fallback transactions.
func (*Client) GetRawNotaryTransaction ¶ added in v0.102.0
func (c *Client) GetRawNotaryTransaction(hash util.Uint256) (*transaction.Transaction, error)
GetRawNotaryTransaction returns main or fallback transaction from the RPC node's notary request pool.
func (*Client) GetRawNotaryTransactionVerbose ¶ added in v0.102.0
func (c *Client) GetRawNotaryTransactionVerbose(hash util.Uint256) (*transaction.Transaction, error)
GetRawNotaryTransactionVerbose returns main or fallback transaction from the RPC node's notary request pool. NOTE: to get transaction.ID and transaction.Size, use t.Hash() and io.GetVarSize(t) respectively.
func (*Client) GetRawTransaction ¶
func (c *Client) GetRawTransaction(hash util.Uint256) (*transaction.Transaction, error)
GetRawTransaction returns a transaction by hash.
func (*Client) GetRawTransactionVerbose ¶
GetRawTransactionVerbose returns a transaction wrapper with additional metadata by transaction's hash. NOTE: to get transaction.ID and transaction.Size, use t.Hash() and io.GetVarSize(t) respectively.
func (*Client) GetState ¶
func (c *Client) GetState(stateroot util.Uint256, historicalContractHash util.Uint160, historicalKey []byte) ([]byte, error)
GetState returns historical contract storage item state by the given stateroot, historical contract hash and historical item key.
func (*Client) GetStateHeight ¶
func (c *Client) GetStateHeight() (*result.StateHeight, error)
GetStateHeight returns the current validated and local node state height.
func (*Client) GetStateRootByBlockHash ¶
GetStateRootByBlockHash returns the state root for the block with the specified hash.
func (*Client) GetStateRootByHeight ¶
GetStateRootByHeight returns the state root for the specified height.
func (*Client) GetStorageByHash ¶
GetStorageByHash returns the stored value according to the contract script hash and the stored key.
func (*Client) GetStorageByHashHistoric ¶ added in v0.102.0
func (c *Client) GetStorageByHashHistoric(root util.Uint256, hash util.Uint160, key []byte) ([]byte, error)
GetStorageByHashHistoric returns the historical stored value according to the contract script hash, the stored key and specified stateroot.
func (*Client) GetStorageByID ¶
GetStorageByID returns the stored value according to the contract ID and the stored key.
func (*Client) GetStorageByIDHistoric ¶ added in v0.102.0
GetStorageByIDHistoric returns the historical stored value according to the contract ID and, stored key and specified stateroot.
func (*Client) GetTransactionHeight ¶
GetTransactionHeight returns the block index where the transaction is found.
func (*Client) GetUnclaimedGas ¶
func (c *Client) GetUnclaimedGas(address string) (result.UnclaimedGas, error)
GetUnclaimedGas returns the unclaimed GAS amount for the specified address.
func (*Client) GetVersion ¶
GetVersion returns the version information about the queried node.
func (*Client) Init ¶
Init sets magic of the network client connected to, stateRootInHeader option and native NEO, GAS and Policy contracts scripthashes. This method should be called before any header- or block-related requests in order to deserialize responses properly.
func (*Client) InvokeContractVerify ¶
func (c *Client) InvokeContractVerify(contract util.Uint160, params []smartcontract.Parameter, signers []transaction.Signer, witnesses ...transaction.Witness) (*result.Invoke, error)
InvokeContractVerify returns the results after calling `verify` method of the smart contract with the given parameters under verification trigger type. NOTE: this is test invoke and will not affect the blockchain.
func (*Client) InvokeContractVerifyAtHeight ¶
func (c *Client) InvokeContractVerifyAtHeight(height uint32, contract util.Uint160, params []smartcontract.Parameter, signers []transaction.Signer, witnesses ...transaction.Witness) (*result.Invoke, error)
InvokeContractVerifyAtHeight returns the results after calling `verify` method of the smart contract with the given parameters under verification trigger type at the blockchain state specified by the blockchain height. NOTE: this is test invoke and will not affect the blockchain.
func (*Client) InvokeContractVerifyWithState ¶
func (c *Client) InvokeContractVerifyWithState(stateOrBlock util.Uint256, contract util.Uint160, params []smartcontract.Parameter, signers []transaction.Signer, witnesses ...transaction.Witness) (*result.Invoke, error)
InvokeContractVerifyWithState returns the results after calling `verify` method of the smart contract with the given parameters under verification trigger type at the blockchain state specified by the state root or block hash. NOTE: this is test invoke and will not affect the blockchain.
func (*Client) InvokeFunction ¶
func (c *Client) InvokeFunction(contract util.Uint160, operation string, params []smartcontract.Parameter, signers []transaction.Signer) (*result.Invoke, error)
InvokeFunction returns the results after calling the smart contract scripthash with the given operation and parameters. NOTE: this is test invoke and will not affect the blockchain.
func (*Client) InvokeFunctionAtHeight ¶
func (c *Client) InvokeFunctionAtHeight(height uint32, contract util.Uint160, operation string, params []smartcontract.Parameter, signers []transaction.Signer) (*result.Invoke, error)
InvokeFunctionAtHeight returns the results after calling the smart contract with the given operation and parameters at the given blockchain state specified by the blockchain height. NOTE: this is test invoke and will not affect the blockchain.
func (*Client) InvokeFunctionWithState ¶
func (c *Client) InvokeFunctionWithState(stateOrBlock util.Uint256, contract util.Uint160, operation string, params []smartcontract.Parameter, signers []transaction.Signer) (*result.Invoke, error)
InvokeFunctionWithState returns the results after calling the smart contract with the given operation and parameters at the given blockchain state defined by the specified state root or block hash. NOTE: this is test invoke and will not affect the blockchain.
func (*Client) InvokeScript ¶
InvokeScript returns the result of the given script after running it true the VM. NOTE: This is a test invoke and will not affect the blockchain.
func (*Client) InvokeScriptAtHeight ¶
func (c *Client) InvokeScriptAtHeight(height uint32, script []byte, signers []transaction.Signer) (*result.Invoke, error)
InvokeScriptAtHeight returns the result of the given script after running it true the VM using the provided chain state retrieved from the specified chain height. NOTE: This is a test invoke and will not affect the blockchain.
func (*Client) InvokeScriptWithState ¶
func (c *Client) InvokeScriptWithState(stateOrBlock util.Uint256, script []byte, signers []transaction.Signer) (*result.Invoke, error)
InvokeScriptWithState returns the result of the given script after running it true the VM using the provided chain state retrieved from the specified state root or block hash. NOTE: This is a test invoke and will not affect the blockchain.
func (*Client) Ping ¶
Ping attempts to create a connection to the endpoint and returns an error if there is any.
func (*Client) SendRawTransaction ¶
func (c *Client) SendRawTransaction(rawTX *transaction.Transaction) (util.Uint256, error)
SendRawTransaction broadcasts the given transaction to the Neo network. It always returns transaction hash, when successful (no error) this is the hash returned from server, when not it's a locally calculated rawTX hash.
func (*Client) SubmitBlock ¶
SubmitBlock broadcasts a raw block over the NEO network.
func (*Client) SubmitP2PNotaryRequest ¶
SubmitP2PNotaryRequest submits given P2PNotaryRequest payload to the RPC node. It returns fallback transaction hash.
func (*Client) SubmitRawOracleResponse ¶
SubmitRawOracleResponse submits a raw oracle response to the oracle node. Raw params are used to avoid excessive marshalling.
func (*Client) TerminateSession ¶
TerminateSession tries to terminate the specified session and returns `true` iff the specified session was found on server.
func (*Client) TraverseIterator ¶
func (c *Client) TraverseIterator(sessionID, iteratorID uuid.UUID, maxItemsCount int) ([]stackitem.Item, error)
TraverseIterator returns a set of iterator values (maxItemsCount at max) for the specified iterator and session. If result contains no elements, then either Iterator has no elements or session was expired and terminated by the server. If maxItemsCount is non-positive, then config.DefaultMaxIteratorResultItems iterator values will be returned using single `traverseiterator` call. Note that iterator session lifetime is restricted by the RPC-server configuration and is being reset each time iterator is accessed. If session won't be accessed within session expiration time, then it will be terminated by the RPC-server automatically.
func (*Client) ValidateAddress ¶
ValidateAddress verifies that the address is a correct NEO address. Consider using [address] package instead to do it locally.
func (*Client) VerifyProof ¶ added in v0.102.0
VerifyProof returns value by the given stateroot and proof.
type Internal ¶ added in v0.101.1
type Internal struct { WSClient // contains filtered or unexported fields }
Internal is an experimental "local" client that does not connect to RPC via network. It's made for deeply integrated applications like NeoFS that have blockchain running in the same process, so use it only if you know what you're doing. It provides the same interface WSClient does.
func NewInternal ¶ added in v0.101.1
func NewInternal(ctx context.Context, register InternalHook) (*Internal, error)
NewInternal creates an instance of internal client. It accepts a method provided by RPC server.
type InternalHook ¶ added in v0.101.1
type InternalHook func(context.Context, chan<- neorpc.Notification) func(*neorpc.Request) (*neorpc.Response, error)
InternalHook is a function signature that is required to create a local client (see NewInternal). It performs registration of local client's event channel and returns a request handler function.
type Notification ¶
Notification represents a server-generated notification for client subscriptions. Value can be one of *block.Block, *state.AppExecResult, *state.ContainedNotificationEvent *transaction.Transaction or *subscriptions.NotaryRequestEvent based on Type.
func (Notification) EventID ¶ added in v0.99.5
func (n Notification) EventID() neorpc.EventID
EventID implements Container interface and returns notification ID.
func (Notification) EventPayload ¶ added in v0.99.5
func (n Notification) EventPayload() any
EventPayload implements Container interface and returns notification object.
type Options ¶
type Options struct { // Cert is a client-side certificate, it doesn't work at the moment along // with the other two options below. Cert string Key string CACert string DialTimeout time.Duration RequestTimeout time.Duration // Limit total number of connections per host. No limit by default. MaxConnsPerHost int }
Options defines options for the RPC client. All values are optional. If any duration is not specified, a default of 4 seconds will be used.
type WSClient ¶
type WSClient struct { Client // contains filtered or unexported fields }
WSClient is a websocket-enabled RPC client that can be used with appropriate servers. It's supposed to be faster than Client because it has persistent connection to the server and at the same time it exposes some functionality that is only provided via websockets (like event subscription mechanism). WSClient is thread-safe and can be used from multiple goroutines to perform RPC requests.
It exposes a set of Receive* methods with the same behaviour pattern that is caused by the fact that the client itself receives every message from the server via a single channel. This includes any subscriptions and any replies to ordinary requests at the same. The client then routes these messages to channels provided on subscription (passed to Receive*) or to the respective receivers (API callers) if it's an ordinary JSON-RPC reply. While synchronous API users are blocked during their calls and wake up on reply, subscription channels must be read from to avoid blocking the client. Failure to do so will make WSClient wait for the channel reader to get the event and while it waits every other messages (subscription-related or request replies) will be blocked. This also means that subscription channel must be properly drained after unsubscription. If CloseNotificationChannelIfFull option is on then the receiver channel will be closed immediately in case if a subsequent notification can't be sent to it, which means WSClient's operations are unblocking in this mode. No unsubscription is performed in this case, so it's still the user responsibility to unsubscribe.
All Receive* methods provide notifications ordering and persistence guarantees. See https://github.com/nspcc-dev/neo-go/blob/master/docs/notifications.md#ordering-and-persistence-guarantees for more details on this topic.
Any received subscription items (blocks/transactions/nofitications) are passed via pointers for efficiency, but the actual structures MUST NOT be changed, as it may affect the functionality of other notification receivers. If multiple subscriptions share the same receiver channel, then matching notification is only sent once per channel. The receiver channel will be closed by the WSClient immediately after MissedEvent is received from the server; no unsubscription is performed in this case, so it's the user responsibility to unsubscribe. It will also be closed on disconnection from server or on situation when it's impossible to send a subsequent notification to the subscriber's channel and CloseNotificationChannelIfFull option is on.
func NewWS ¶
NewWS returns a new WSClient ready to use (with established websocket connection). You need to use websocket URL for it like `ws://1.2.3.4/ws`. You should call Init method to initialize the network magic the client is operating on.
func (*WSClient) Close ¶
func (c *WSClient) Close()
Close closes connection to the remote side rendering this client instance unusable.
func (*WSClient) Context ¶ added in v0.99.5
Context returns WSClient Cancel context that will be terminated on Client shutdown.
func (*WSClient) GetError ¶
GetError returns the reason of WS connection closing. It returns nil in case if connection was closed by the use via Close() method calling.
func (*WSClient) ReceiveBlocks ¶ added in v0.99.5
ReceiveBlocks registers provided channel as a receiver for the new block events. Events can be filtered by the given BlockFilter, nil value doesn't add any filter. See WSClient comments for generic Receive* behaviour details.
func (*WSClient) ReceiveExecutionNotifications ¶ added in v0.99.5
func (c *WSClient) ReceiveExecutionNotifications(flt *neorpc.NotificationFilter, rcvr chan<- *state.ContainedNotificationEvent) (string, error)
ReceiveExecutionNotifications registers provided channel as a receiver for execution events. Events can be filtered by the given NotificationFilter, nil value doesn't add any filter. See WSClient comments for generic Receive* behaviour details.
func (*WSClient) ReceiveExecutions ¶ added in v0.99.5
func (c *WSClient) ReceiveExecutions(flt *neorpc.ExecutionFilter, rcvr chan<- *state.AppExecResult) (string, error)
ReceiveExecutions registers provided channel as a receiver for application execution result events generated during transaction execution. Events can be filtered by the given ExecutionFilter, nil value doesn't add any filter. See WSClient comments for generic Receive* behaviour details.
func (*WSClient) ReceiveHeadersOfAddedBlocks ¶ added in v0.105.0
func (c *WSClient) ReceiveHeadersOfAddedBlocks(flt *neorpc.BlockFilter, rcvr chan<- *block.Header) (string, error)
ReceiveHeadersOfAddedBlocks registers provided channel as a receiver for new block's header events. Events can be filtered by the given neorpc.BlockFilter, nil value doesn't add any filter. See WSClient comments for generic Receive* behaviour details.
func (*WSClient) ReceiveNotaryRequests ¶ added in v0.99.5
func (c *WSClient) ReceiveNotaryRequests(flt *neorpc.NotaryRequestFilter, rcvr chan<- *result.NotaryRequestEvent) (string, error)
ReceiveNotaryRequests registers provided channel as a receiver for notary request payload addition or removal events. Events can be filtered by the given NotaryRequestFilter where sender corresponds to notary request sender (the second fallback transaction signer), signer corresponds to main transaction signers and type corresponds to the [mempoolevent.Type] and denotes whether notary request was added to or removed from the notary request pool. nil value doesn't add any filter. See WSClient comments for generic Receive* behaviour details.
func (*WSClient) ReceiveTransactions ¶ added in v0.99.5
func (c *WSClient) ReceiveTransactions(flt *neorpc.TxFilter, rcvr chan<- *transaction.Transaction) (string, error)
ReceiveTransactions registers provided channel as a receiver for new transaction events. Events can be filtered by the given TxFilter, nil value doesn't add any filter. See WSClient comments for generic Receive* behaviour details.
func (*WSClient) Unsubscribe ¶
Unsubscribe removes subscription for the given event stream. It will return an error in case if there's no subscription with the provided ID. Call to Unsubscribe doesn't block notifications receive process for given subscriber, thus, ensure that subscriber channel is properly drained while unsubscription is being performed. Failing to do so will cause WSClient to block even regular requests. You may probably need to run unsubscription process in a separate routine (in parallel with notification receiver routine) to avoid Client's notification dispatcher blocking.
func (*WSClient) UnsubscribeAll ¶
UnsubscribeAll removes all active subscriptions of the current client. It copies the list of subscribers in order not to hold the lock for the whole execution time and tries to unsubscribe from us many feeds as possible returning the chunk of unsubscription errors afterwards. Call to UnsubscribeAll doesn't block notifications receive process for given subscribers, thus, ensure that subscribers channels are properly drained while unsubscription is being performed. Failing to do so will cause WSClient to block even regular requests. You may probably need to run unsubscription process in a separate routine (in parallel with notification receiver routines) to avoid Client's notification dispatcher blocking.
type WSOptions ¶ added in v0.102.0
type WSOptions struct { Options // CloseNotificationChannelIfFull allows WSClient to close a subscriber's // receive channel in case if the channel isn't read properly and no more // events can be pushed to it. This option, if set, allows to avoid WSClient // blocking on a subsequent notification dispatch. However, if enabled, the // corresponding subscription is kept even after receiver's channel closing, // thus it's still the caller's duty to call Unsubscribe() for this // subscription. CloseNotificationChannelIfFull bool }
WSOptions defines options for the web-socket RPC client. It contains a set of options for the underlying standard RPC client as far as WSClient-specific options. See Options documentation for more details.
Directories
¶
Path | Synopsis |
---|---|
Package actor provides a way to change chain state via RPC client.
|
Package actor provides a way to change chain state via RPC client. |
Package gas provides a convenience wrapper for GAS contract to use it via RPC.
|
Package gas provides a convenience wrapper for GAS contract to use it via RPC. |
Package invoker provides a convenient wrapper to perform test calls via RPC client.
|
Package invoker provides a convenient wrapper to perform test calls via RPC client. |
Package management provides an RPC wrapper for the native ContractManagement contract.
|
Package management provides an RPC wrapper for the native ContractManagement contract. |
Package neo provides an RPC-based wrapper for the NEOToken contract.
|
Package neo provides an RPC-based wrapper for the NEOToken contract. |
Package nep11 contains RPC wrappers for NEP-11 contracts.
|
Package nep11 contains RPC wrappers for NEP-11 contracts. |
Package nep17 contains RPC wrappers to work with NEP-17 contracts.
|
Package nep17 contains RPC wrappers to work with NEP-17 contracts. |
Package neptoken contains RPC wrapper for common NEP-11 and NEP-17 methods.
|
Package neptoken contains RPC wrapper for common NEP-11 and NEP-17 methods. |
Package nns provide some RPC wrappers for the non-native NNS contract.
|
Package nns provide some RPC wrappers for the non-native NNS contract. |
Package notary provides an RPC-based wrapper for the Notary subsystem.
|
Package notary provides an RPC-based wrapper for the Notary subsystem. |
Package oracle allows to work with the native OracleContract contract via RPC.
|
Package oracle allows to work with the native OracleContract contract via RPC. |
Package policy allows to work with the native PolicyContract contract via RPC.
|
Package policy allows to work with the native PolicyContract contract via RPC. |
Package rolemgmt allows to work with the native RoleManagement contract via RPC.
|
Package rolemgmt allows to work with the native RoleManagement contract via RPC. |
Package unwrap provides a set of proxy methods to process invocation results.
|
Package unwrap provides a set of proxy methods to process invocation results. |