pyth

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

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

Go to latest
Published: Apr 14, 2025 License: Apache-2.0 Imports: 21 Imported by: 0

README

Pyth Network Go client

Access high-fidelity market data on Solana

Go Reference unit tests

Summary

Pyth Network delivers real-time market data to the Solana blockchain.

This library allows you to query, stream and publish price data using the Go programming language.

Getting Started

Add the Pyth client to your project using the Go CLI.

go get github.com/go-enols/go-pyth

Find docs and usage examples on pkg.go.dev.

Attributions

说明

  • 此库从原版分支后对gosolana进行了扩展以支持自定义的http代理
  • 对代码注释进行了中文翻译对国内用户较为友好

Documentation

Index

Examples

Constants

View Source
const (
	AccountTypeUnknown = uint32(iota)
	AccountTypeMapping
	AccountTypeProduct
	AccountTypePrice
)

Account类型枚举标识每个Pyth账户存储的内容

View Source
const (
	PriceStatusUnknown = uint32(iota)
	PriceStatusTrading
	PriceStatusHalted
	PriceStatusAuction
)

Price status.

View Source
const (
	Instruction_InitMapping = int32(iota)
	Instruction_AddMapping
	Instruction_AddProduct
	Instruction_UpdProduct
	Instruction_AddPrice
	Instruction_AddPublisher
	Instruction_DelPublisher
	Instruction_UpdPrice
	Instruction_AggPrice
	Instruction_InitPrice
	Instruction_InitTest
	Instruction_UpdTest
	Instruction_SetMinPub
	Instruction_UpdPriceNoFailOnError
)

Pyth程序指令

View Source
const Magic = uint32(0xa1b2c3d4)

Magic 是每个账户前缀的32位数字

View Source
const ProductAccountHeaderLen = 48

ProductAccountHeaderLen 是RawProductAccount中AttrsData字段的二进制偏移量

View Source
const V2 = uint32(2)

V2 标识账户中存储的版本2数据格式

Variables

View Source
var Devnet = Env{
	Program: solana.MustPublicKeyFromBase58("gSbePebfvPy7tRqimPoVecS2UsBvYv46ynrzWocc92s"),
	Mapping: solana.MustPublicKeyFromBase58("BmA9Z6FjioHJPpjT39QazZyhDRUdZy2ezwx4GiDdE2u2"),
}

Devnet 是Solana devnet集群上的Pyth程序

View Source
var Mainnet = Env{
	Program: solana.MustPublicKeyFromBase58("FsJ3A3u2vn5cTVofAjvy6y5kwABJAqYWpe4975bi2epH"),
	Mapping: solana.MustPublicKeyFromBase58("AHtgzX45WTKfkPG53L6WYhGEXwQkN1BVknET3sVsLL8J"),
}

Mainnet 是Solana主网集群上的Pyth程序

View Source
var Testnet = Env{
	Program: solana.MustPublicKeyFromBase58("8tfDNiaEyrV6Q1U4DEXrEigs9DoDtkugzFbybENEbCDz"),
	Mapping: solana.MustPublicKeyFromBase58("AFmdnt9ng1uVxqCmqwQJDAYC5cKTkw8gJKSM5PnzuF6z"),
}

Testnet 是Solana testnet集群上的Pyth程序

Functions

func InstructionIDToName

func InstructionIDToName(id int32) string

InstructionIDToName 返回Pyth指令类型的人类可读名称

func PeekAccount

func PeekAccount(data []byte) uint32

PeekAccount 根据账户的数据字节确定账户类型

Types

type AccountHeader

type AccountHeader struct {
	Magic       uint32 // set exactly to 0xa1b2c3d4
	Version     uint32 // currently V2
	AccountType uint32 // account type following the header
	Size        uint32 // size of the account including the header
}

AccountHeader 是每个账户类型开头的16字节头部

func (AccountHeader) Valid

func (h AccountHeader) Valid() bool

Valid 对账户执行基本检查

type AttrsMap

type AttrsMap struct {
	Pairs [][2]string
}

AttrsMap 是一个具有稳定顺序的字符串键值对列表

func NewAttrsMap

func NewAttrsMap(fromGo map[string]string) (out AttrsMap, err error)

NewAttrsMap 返回一个新的属性映射,初始顺序是任意的

提供的Go映射可以为nil

func ReadAttrsMapFromBinary

func ReadAttrsMapFromBinary(rd *bytes.Reader) (out AttrsMap, n int, err error)

ReadAttrsMapFromBinary 从二进制读取器消耗所有字节, 返回一个AttrsMap和读取的字节数

func (AttrsMap) BinaryLen

func (a AttrsMap) BinaryLen() (size int)

BinaryLen 返回此AttrsMap在二进制编码中的长度

func (AttrsMap) KVs

func (a AttrsMap) KVs() map[string]string

KVs 将AttrsMap作为无序的Go映射返回

func (AttrsMap) MarshalBinary

func (a AttrsMap) MarshalBinary() ([]byte, error)

MarshalBinary 将AttrsMap编码为其链上格式

func (*AttrsMap) MarshalJSON

func (a *AttrsMap) MarshalJSON() ([]byte, error)

MarshalJSON 返回JSON字符串映射

func (AttrsMap) Sort

func (a AttrsMap) Sort()

Sort 按字典序对AttrsMap的键进行排序

func (*AttrsMap) UnmarshalBinary

func (a *AttrsMap) UnmarshalBinary(data []byte) (err error)

UnmarshalBinary 从链上格式解码AttrsMap

如果无法消耗整个提供的字节切片,将返回错误

func (*AttrsMap) UnmarshalJSON

func (a *AttrsMap) UnmarshalJSON(data []byte) (err error)

UnmarshalJSON 加载JSON字符串映射

type CallbackHandle

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

CallbackHandle 跟踪回调注册的生命周期

func (CallbackHandle) Unsubscribe

func (c CallbackHandle) Unsubscribe()

Unsubscribe 从处理器中注销回调

调用Unsubscribe是可选的 当底层流关闭时处理器会自动调用它

type Client

type Client struct {
	Env      Env
	RPC      *rpc.Client
	WSClient *ws.Client
	Log      *zap.Logger

	AccountsBatchSize int // number of accounts to get with getMultipleAccounts()
}

Client 通过Solana的JSON-RPC API与Pyth交互

不要直接实例化Client,请使用NewClient代替

func NewClient

func NewClient(env Env, rpcClient *rpc.Client, WSClient *ws.Client) *Client

NewClient 创建一个新的Pyth链上程序客户端

func (*Client) GetAllPriceAccounts

func (c *Client) GetAllPriceAccounts(ctx context.Context, commitment rpc.CommitmentType) ([]PriceAccountEntry, error)

GetAllPriceAccounts 返回所有价格账户

如果获取任何产品账户失败,则中止并返回错误

func (*Client) GetAllProductAccounts

func (c *Client) GetAllProductAccounts(ctx context.Context, commitment rpc.CommitmentType) ([]ProductAccountEntry, error)

GetAllProductAccounts 返回所有产品账户

如果获取任何产品账户失败,则中止并返回错误

Example
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
wallet, err := gosolana.NewWallet(ctx, gosolana.Option{
	RpcUrl: rpc.DevNet_RPC,
	WsUrl:  rpc.DevNet_WS,
})
if err != nil {
	log.Fatalf("Failed to create wallet: %v", err)
}

// 连接到Solana devnet上的Pyth
client := NewClient(Devnet, wallet.GetClient(), wallet.GetWsClient())

products, _ := client.GetAllProductAccounts(context.TODO(), rpc.CommitmentProcessed)
// Print first product as JSON.
products[0].Slot = 1234
jsonData, _ := json.MarshalIndent(&products[0], "", "  ")
fmt.Println(string(jsonData))
Output:

{
  "first_price": "4EQrNZYk5KR1RnjyzbaaRbHsv8VqZWzSUtvx58wLsZbj",
  "attrs": {
    "asset_type": "Crypto",
    "base": "BCH",
    "description": "BCH/USD",
    "generic_symbol": "BCHUSD",
    "quote_currency": "USD",
    "symbol": "Crypto.BCH/USD"
  },
  "pubkey": "89GseEmvNkzAMMEXcW9oTYzqRPXTsJ3BmNerXmgA1osV",
  "slot": 1234
}

func (*Client) GetAllProductKeys

func (c *Client) GetAllProductKeys(ctx context.Context, commitment rpc.CommitmentType) ([]solana.PublicKey, error)

GetAllProductKeys 列出所有产品账户公钥的映射账户

Example
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
wallet, err := gosolana.NewWallet(ctx, gosolana.Option{
	RpcUrl: rpc.DevNet_RPC,
	WsUrl:  rpc.DevNet_WS,
})
if err != nil {
	log.Fatalf("Failed to create wallet: %v", err)
}

// 连接到Solana devnet上的Pyth
client := NewClient(Devnet, wallet.GetClient(), wallet.GetWsClient())

products, _ := client.GetAllProductKeys(context.TODO(), rpc.CommitmentProcessed)
// Print first 5 product account pubkeys.
for _, key := range products[:5] {
	fmt.Println(key)
}
Output:

89GseEmvNkzAMMEXcW9oTYzqRPXTsJ3BmNerXmgA1osV
JCnD5WiurZfoeVPEi2AXVgacg73Wd2iRDDjZDbSwdr9D
G89jkM5wFLpmnbvRbeePUumxsJyzoXaRfgBVjyx2CPzQ
GaBJpKtnyUbyKe34XuyegR7W98a9PT5cg985G974NY8R
Fwosgw2ikRvdzgKcQJwMacyczk3nXgoW3AtVtyVvXSAb

func (*Client) GetMappingAccount

func (c *Client) GetMappingAccount(ctx context.Context, mappingKey solana.PublicKey, commitment rpc.CommitmentType) (MappingAccountEntry, error)

GetMappingAccount 从区块链获取单个映射账户

func (*Client) GetPriceAccount

func (c *Client) GetPriceAccount(ctx context.Context, priceKey solana.PublicKey, commitment rpc.CommitmentType) (PriceAccountEntry, error)

GetPriceAccount 从区块链获取价格账户

func (*Client) GetPriceAccountsRecursive

func (c *Client) GetPriceAccountsRecursive(ctx context.Context, commitment rpc.CommitmentType, priceKeys ...solana.PublicKey) ([]PriceAccountEntry, error)

GetPriceAccountsRecursive 递归获取给定公钥的价格账户

如果这些价格账户有后继者,也会递归获取它们的内容 当使用ProductAccountHeader.FirstPrice调用时,将获取产品的所有价格账户

func (*Client) GetProductAccount

func (c *Client) GetProductAccount(ctx context.Context, productKey solana.PublicKey, commitment rpc.CommitmentType) (ProductAccountEntry, error)

GetProductAccount 从区块链获取产品账户

Example
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
wallet, err := gosolana.NewWallet(ctx, gosolana.Option{
	RpcUrl: rpc.DevNet_RPC,
	WsUrl:  rpc.DevNet_WS,
})
if err != nil {
	log.Fatalf("Failed to create wallet: %v", err)
}

// 连接到Solana devnet上的Pyth
client := NewClient(Devnet, wallet.GetClient(), wallet.GetWsClient())

productPubkey := solana.MustPublicKeyFromBase58("EWxGfxoPQSNA2744AYdAKmsQZ8F9o9M7oKkvL3VM1dko")
product, _ := client.GetProductAccount(context.TODO(), productPubkey, rpc.CommitmentProcessed)
product.Slot = 1234
// Print first product as JSON.
jsonData, _ := json.MarshalIndent(product, "", "  ")
fmt.Println(string(jsonData))
Output:

{
  "first_price": "E36MyBbavhYKHVLWR79GiReNNnBDiHj6nWA7htbkNZbh",
  "attrs": {
    "asset_type": "FX",
    "base": "EUR",
    "description": "EUR/USD",
    "generic_symbol": "EURUSD",
    "quote_currency": "USD",
    "symbol": "FX.EUR/USD",
    "tenor": "Spot"
  },
  "pubkey": "EWxGfxoPQSNA2744AYdAKmsQZ8F9o9M7oKkvL3VM1dko",
  "slot": 1234
}

func (*Client) StreamPriceAccounts

func (c *Client) StreamPriceAccounts() *PriceAccountStream

StreamPriceAccounts 创建价格账户更新的新流

如果WebSocket连接中断或停滞,它将自动重新连接

Example
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
wallet, err := gosolana.NewWallet(ctx, gosolana.Option{
	RpcUrl: rpc.DevNet_RPC,
	WsUrl:  rpc.DevNet_WS,
})
if err != nil {
	log.Fatalf("Failed to create wallet: %v", err)
}

// 连接到Solana devnet上的Pyth
client := NewClient(Devnet, wallet.GetClient(), wallet.GetWsClient())

stream := client.StreamPriceAccounts()
// Close stream after a while.
go func() {
	<-time.After(3 * time.Second)
	stream.Close()
}()
// Print updates.
for update := range stream.Updates() {
	fmt.Println(update.Agg.Price)
}
Output:

type CommandAddPrice

type CommandAddPrice struct {
	Exponent  int32
	PriceType uint32
}

CommandAddPrice 是Instruction_AddPrice的负载

type CommandAddPublisher

type CommandAddPublisher struct {
	Publisher solana.PublicKey
}

CommandAddPublisher 是Instruction_AddPublisher的负载

type CommandDelPublisher

type CommandDelPublisher struct {
	Publisher solana.PublicKey
}

CommandDelPublisher 是Instruction_DelPublisher的负载

type CommandHeader

type CommandHeader struct {
	Version uint32 // currently V2
	Cmd     int32
}

CommandHeader 是任何指令数据开头的8字节头部

func (*CommandHeader) Valid

func (h *CommandHeader) Valid() bool

Valid 对指令数据执行基本检查

type CommandInitPrice

type CommandInitPrice struct {
	Exponent  int32
	PriceType uint32
}

CommandInitPrice 是Instruction_InitPrice的负载

type CommandSetMinPub

type CommandSetMinPub struct {
	MinPub  uint8
	Padding [3]byte
}

CommandSetMinPub 是Instruction_SetMinPub的负载

type CommandUpdPrice

type CommandUpdPrice struct {
	Status  uint32
	Unused  uint32
	Price   int64
	Conf    uint64
	PubSlot uint64
}

CommandUpdPrice 是Instruction_UpdPrice或Instruction_UpdPriceNoFailOnError的负载

type CommandUpdProduct

type CommandUpdProduct struct {
	AttrsMap
}

CommandUpdProduct 是Instruction_UpdProduct的负载

type CommandUpdTest

type CommandUpdTest struct {
	Exponent int32
	SlotDiff [32]int8
	Price    [32]int64
	Conf     [32]uint64
}

CommandUpdTest 是Instruction_UpdTest的负载

type Ema

type Ema struct {
	Val   int64
	Numer int64
	Denom int64
}

Ema 是指数加权移动平均

type Env

type Env struct {
	Program solana.PublicKey // Program ID
	Mapping solana.PublicKey // Root mapping key
}

Env 标识Pyth链上程序的部署环境

type Instruction

type Instruction struct {
	Header  CommandHeader
	Payload interface{}
	// contains filtered or unexported fields
}

func DecodeInstruction

func DecodeInstruction(
	programKey solana.PublicKey,
	accounts []*solana.AccountMeta,
	data []byte,
) (*Instruction, error)

DecodeInstruction 尝试从链上指令重建Pyth命令

安全性说明

请注意,此函数的行为可能与Pyth链上程序不同。 特别是边缘情况和无效输入的处理是基于"尽力而为"原则。

此函数也不执行账户所有权或权限检查。

最好仅在程序执行成功时使用此指令。

func (*Instruction) Accounts

func (inst *Instruction) Accounts() []*solana.AccountMeta

func (*Instruction) Data

func (inst *Instruction) Data() ([]byte, error)

func (*Instruction) ProgramID

func (inst *Instruction) ProgramID() solana.PublicKey

type InstructionBuilder

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

InstructionBuilder 创建与Pyth链上程序交互的新指令

func NewInstructionBuilder

func NewInstructionBuilder(programKey solana.PublicKey) *InstructionBuilder

NewInstructionBuilder 创建一个新的InstructionBuilder,针对给定的Pyth程序

func (*InstructionBuilder) AddMapping

func (i *InstructionBuilder) AddMapping(
	fundingKey solana.PublicKey,
	tailMappingKey solana.PublicKey,
	newMappingKey solana.PublicKey,
) *Instruction

AddMapping 初始化并添加新的映射账户到列表

func (*InstructionBuilder) AddPrice

func (i *InstructionBuilder) AddPrice(
	fundingKey solana.PublicKey,
	productKey solana.PublicKey,
	priceKey solana.PublicKey,
	payload CommandAddPrice,
) *Instruction

AddPrice 向产品账户添加新的价格账户

func (*InstructionBuilder) AddProduct

func (i *InstructionBuilder) AddProduct(
	fundingKey solana.PublicKey,
	mappingKey solana.PublicKey,
	productKey solana.PublicKey,
) *Instruction

AddProduct 初始化并添加新的产品参考数据账户

func (*InstructionBuilder) AddPublisher

func (i *InstructionBuilder) AddPublisher(
	fundingKey solana.PublicKey,
	priceKey solana.PublicKey,
	payload CommandAddPublisher,
) *Instruction

AddPublisher 向价格账户添加发布者

func (*InstructionBuilder) AggPrice

func (i *InstructionBuilder) AggPrice(
	fundingKey solana.PublicKey,
	priceKey solana.PublicKey,
) *Instruction

AggPrice 计算产品账户的聚合价格

func (*InstructionBuilder) DelPublisher

func (i *InstructionBuilder) DelPublisher(
	fundingKey solana.PublicKey,
	priceKey solana.PublicKey,
	payload CommandDelPublisher,
) *Instruction

DelPublisher 从价格账户删除发布者

func (*InstructionBuilder) InitMapping

func (i *InstructionBuilder) InitMapping(
	fundingKey solana.PublicKey,
	mappingKey solana.PublicKey,
) *Instruction

InitMapping 初始化第一个映射列表账户

func (*InstructionBuilder) InitPrice

func (i *InstructionBuilder) InitPrice(
	fundingKey solana.PublicKey,
	priceKey solana.PublicKey,
	payload CommandInitPrice,
) *Instruction

InitPrice (重新)初始化价格账户

func (*InstructionBuilder) InitTest

func (i *InstructionBuilder) InitTest(
	fundingKey solana.PublicKey,
	testKey solana.PublicKey,
) *Instruction

InitTest 初始化测试账户

func (*InstructionBuilder) SetMinPub

func (i *InstructionBuilder) SetMinPub(
	fundingKey solana.PublicKey,
	priceKey solana.PublicKey,
	payload CommandSetMinPub,
) *Instruction

SetMinPub 设置价格账户的最小发布者数量

func (*InstructionBuilder) UpdPrice

func (i *InstructionBuilder) UpdPrice(
	fundingKey solana.PublicKey,
	priceKey solana.PublicKey,
	payload CommandUpdPrice,
) *Instruction

UpdPrice 向价格账户发布新的组件价格

func (*InstructionBuilder) UpdPriceNoFailOnError

func (i *InstructionBuilder) UpdPriceNoFailOnError(
	fundingKey solana.PublicKey,
	priceKey solana.PublicKey,
	payload CommandUpdPrice,
) *Instruction

UpdPriceNoFailOnError 向价格账户发布新的组件价格,忽略错误

func (*InstructionBuilder) UpdProduct

func (i *InstructionBuilder) UpdProduct(
	fundingKey solana.PublicKey,
	productKey solana.PublicKey,
	payload CommandUpdProduct,
) *Instruction

UpdProduct 更新产品账户

func (*InstructionBuilder) UpdTest

func (i *InstructionBuilder) UpdTest(
	fundingKey solana.PublicKey,
	testKey solana.PublicKey,
	payload CommandUpdTest,
) *Instruction

UpdTest 运行聚合价格测试

type MappingAccount

type MappingAccount struct {
	AccountHeader
	Num      uint32           // number of keys
	Pad1     uint32           // reserved field
	Next     solana.PublicKey // pubkey of next mapping account
	Products [640]solana.PublicKey
}

MappingAccount 是Pyth上所有产品的单向链表的一部分

func (*MappingAccount) ProductKeys

func (m *MappingAccount) ProductKeys() []solana.PublicKey

ProductKeys 返回此映射引用的产品密钥切片,不包括空条目

func (*MappingAccount) UnmarshalBinary

func (m *MappingAccount) UnmarshalBinary(buf []byte) error

UnmarshalBinary 从链上格式解码映射账户

type MappingAccountEntry

type MappingAccountEntry struct {
	*MappingAccount
	Pubkey solana.PublicKey `json:"pubkey"`
	Slot   uint64           `json:"slot"`
}

MappingAccountEntry is a versioned mapping account and its pubkey.

type PriceAccount

type PriceAccount struct {
	AccountHeader
	PriceType  uint32           // price or calculation type
	Exponent   int32            // price exponent
	Num        uint32           // number of component prices
	NumQt      uint32           // number of quoters that make up aggregate
	LastSlot   uint64           // slot of last valid (not unknown) aggregate price
	ValidSlot  uint64           // valid slot of aggregate price
	Twap       Ema              // exponential moving average price
	Twac       Ema              // exponential moving confidence interval
	Drv1, Drv2 int64            // reserved for future use
	Product    solana.PublicKey // ProductAccount key
	Next       solana.PublicKey // next PriceAccount key in linked list
	PrevSlot   uint64           // valid slot of previous update
	PrevPrice  int64            // aggregate price of previous update
	PrevConf   uint64           // confidence interval of previous update
	Drv3       int64            // reserved for future use
	Agg        PriceInfo        // aggregate price info
	Components [32]PriceComp    // price components for each quoter
}

PriceAccount 表示产品的持续更新价格源

func (*PriceAccount) GetComponent

func (p *PriceAccount) GetComponent(publisher *solana.PublicKey) *PriceComp

GetComponent 返回具有给定发布者密钥的第一个价格组件。可能返回nil

func (*PriceAccount) UnmarshalBinary

func (p *PriceAccount) UnmarshalBinary(buf []byte) error

UnmarshalBinary 从链上格式解码价格账户

type PriceAccountEntry

type PriceAccountEntry struct {
	*PriceAccount
	Pubkey solana.PublicKey `json:"pubkey"`
	Slot   uint64           `json:"slot"`
}

PriceAccountEntry is a versioned price account and its pubkey.

type PriceAccountStream

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

PriceAccountStream 是链上价格账户更新的持续流

func (*PriceAccountStream) Close

func (p *PriceAccountStream) Close()

Close 当不再需要更新时必须调用

func (*PriceAccountStream) Err

func (p *PriceAccountStream) Err() error

Err 返回价格账户流关闭的原因 会阻塞直到流实际关闭 如果关闭是预期的则返回nil

func (*PriceAccountStream) Updates

func (p *PriceAccountStream) Updates() <-chan PriceAccountEntry

Updates 返回包含新价格账户更新的通道

type PriceComp

type PriceComp struct {
	Publisher solana.PublicKey // key of contributing publisher
	Agg       PriceInfo        // price used to compute the current aggregate price
	Latest    PriceInfo        // latest price of publisher
}

PriceComp 包含特定发布者贡献的价格和置信度

type PriceEventHandler

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

PriceEventHandler 提供Pyth更新的回调式接口

Example
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
wallet, err := gosolana.NewWallet(ctx, gosolana.Option{
	RpcUrl: rpc.DevNet_RPC,
	WsUrl:  rpc.DevNet_WS,
})
if err != nil {
	log.Fatalf("Failed to create wallet: %v", err)
}

// 连接到Solana devnet上的Pyth
client := NewClient(Devnet, wallet.GetClient(), wallet.GetWsClient())

// 打开新的事件流
stream := client.StreamPriceAccounts()
handler := NewPriceEventHandler(stream)

// 订阅价格账户变更
priceKey := solana.MustPublicKeyFromBase58("J83w4HKfqxwcq3BEMMkPFSppX3gqekLyLJBexebFVkix")
handler.OnPriceChange(priceKey, func(info PriceUpdate) {
	price, conf, ok := info.Current()
	if ok {
		log.Printf("Price change: $%s ± $%s", price, conf)
	}
})

// 一段时间后关闭流
<-time.After(10 * time.Second)
stream.Close()
Output:

func NewPriceEventHandler

func NewPriceEventHandler(stream *PriceAccountStream) *PriceEventHandler

NewPriceEventHandler 创建一个新的流事件处理器

注意:不能在事件处理器之间重用同一个流

func (*PriceEventHandler) Err

func (p *PriceEventHandler) Err() error

Err 返回底层价格账户流关闭的原因

会阻塞直到流实际关闭 如果关闭是预期的则返回nil

此函数返回后事件处理器将不再发送任何回调 可以用此函数作为与回调相关的清理任务的屏障

func (*PriceEventHandler) OnComponentChange

func (p *PriceEventHandler) OnComponentChange(priceKey solana.PublicKey, publisher solana.PublicKey, callback func(PriceUpdate)) CallbackHandle

OnComponentChange 注册一个回调函数,当给定(价格账户,发布者账户)对的价格组件变化时调用

func (*PriceEventHandler) OnPriceChange

func (p *PriceEventHandler) OnPriceChange(priceKey solana.PublicKey, callback func(PriceUpdate)) CallbackHandle

OnPriceChange 注册一个回调函数,当指定价格账户的聚合价格变化时调用

type PriceInfo

type PriceInfo struct {
	Price   int64  // current price
	Conf    uint64 // confidence interval around the price
	Status  uint32 // status of price
	CorpAct uint32
	PubSlot uint64 // valid publishing slot
}

PriceInfo 包含特定slot的价格和置信度

此结构可以表示发布者的贡献或价格聚合的结果

func (*PriceInfo) HasChanged

func (p *PriceInfo) HasChanged(other *PriceInfo) bool

HasChanged 返回此价格信息与另一个价格信息之间是否有变化

func (*PriceInfo) IsZero

func (p *PriceInfo) IsZero() bool

func (*PriceInfo) Value

func (p *PriceInfo) Value(exponent int32) (price decimal.Decimal, conf decimal.Decimal, ok bool)

Value 返回解析后的价格和置信度值

如果ok为false,则该值无效

type PriceUpdate

type PriceUpdate struct {
	Account      *PriceAccount
	PreviousInfo *PriceInfo
	CurrentInfo  *PriceInfo
}

PriceUpdate 当聚合价格或组件价格更新时返回给回调函数

func (PriceUpdate) Current

func (p PriceUpdate) Current() (price decimal.Decimal, conf decimal.Decimal, ok bool)

Current 返回最后一次价格更新的值

如果ok为false,则该值无效

func (PriceUpdate) Previous

func (p PriceUpdate) Previous() (price decimal.Decimal, conf decimal.Decimal, ok bool)

Previous 返回之前看到的价格更新值

如果ok为false,则该值无效

type ProductAccount

type ProductAccount struct {
	ProductAccountHeader
	Attrs AttrsMap `json:"attrs"` // key-value string pairs of additional data
}

ProductAccount 包含单个产品的元数据, 例如其符号和基础/报价货币

func (*ProductAccount) UnmarshalBinary

func (p *ProductAccount) UnmarshalBinary(buf []byte) error

UnmarshalBinary 从链上格式解码产品账户

func (*ProductAccount) UnmarshalJSON

func (p *ProductAccount) UnmarshalJSON(buf []byte) error

UnmarshalJSON 从JSON解码产品账户内容

type ProductAccountEntry

type ProductAccountEntry struct {
	*ProductAccount
	Pubkey solana.PublicKey `json:"pubkey"`
	Slot   uint64           `json:"slot"`
}

ProductAccountEntry is a versioned product account and its pubkey.

type ProductAccountHeader

type ProductAccountHeader struct {
	AccountHeader `json:"-"`
	FirstPrice    solana.PublicKey `json:"first_price"` // first price account in list
}

type RawProductAccount

type RawProductAccount struct {
	ProductAccountHeader
	AttrsData [464]byte
}

Jump to

Keyboard shortcuts

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