From 5c74a31c0162fd8b35fdf4fe2ffd9e443bed1c15 Mon Sep 17 00:00:00 2001 From: Marko Kungla Date: Sun, 25 Feb 2024 15:13:35 +0200 Subject: [PATCH 01/65] feat: EnableRequestsStats replaces CollectRequestsStats CollectRequestsStats is marked deprecated and will be removed in v5 Signed-off-by: Marko Kungla --- options.go | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/options.go b/options.go index 3bcd540..453843d 100644 --- a/options.go +++ b/options.go @@ -154,10 +154,19 @@ func Origin(origin string) Option { // CollectRequestsStats when enabled uses httptrace is used // to collect detailed timing information about the request. +// +// Deprecated: Use EnableRequestsStats instead. +// CollectRequestsStats will be removed in v5.0.0 func CollectRequestsStats(enabled bool) Option { + return EnableRequestsStats(enabled) +} + +// EnableRequestsStats when enabled uses httptrace is used +// to collect detailed timing information about the request. +func EnableRequestsStats(enable bool) Option { return Option{ apply: func(c *Client) error { - c.reqStatsEnabled = enabled + c.reqStatsEnabled = enable return nil }, } From 95e8c74aada4988eb1a2d22f9668b6ea144d48c6 Mon Sep 17 00:00:00 2001 From: Marko Kungla Date: Sun, 25 Feb 2024 15:33:11 +0200 Subject: [PATCH 02/65] feat!: upgrade to v4 and min go1.22 BREAKING CHANGE: Default koios api base is /v1 Signed-off-by: Marko Kungla --- README.md | 12 ++++++------ Taskfile.yaml | 2 +- account_test.go | 2 +- address_test.go | 2 +- assets_test.go | 2 +- block_test.go | 2 +- epoch_test.go | 2 +- go.mod | 10 +++++----- go.sum | 19 ++++++------------- koios.go | 4 ++-- koios_test.go | 2 +- network_test.go | 2 +- pool_test.go | 2 +- script_test.go | 2 +- transaction_test.go | 2 +- 15 files changed, 30 insertions(+), 37 deletions(-) diff --git a/README.md b/README.md index 65299a5..2c2a06d 100644 --- a/README.md +++ b/README.md @@ -10,16 +10,16 @@ **[Koios API] Client Library for Go** -[![PkgGoDev](https://pkg.go.dev/badge/github.com/cardano-community/koios-go-client/v3)](https://pkg.go.dev/github.com/cardano-community/koios-go-client/v3) +[![PkgGoDev](https://pkg.go.dev/badge/github.com/cardano-community/koios-go-client/v4)](https://pkg.go.dev/github.com/cardano-community/koios-go-client/v4) ```shell -go get github.com/cardano-community/koios-go-client/v3 +go get github.com/cardano-community/koios-go-client/v4 ``` ```go ... import ( - "github.com/cardano-community/koios-go-client/v3" // imports as package "koios" + "github.com/cardano-community/koios-go-client/v4" // imports as package "koios" ) ... ``` @@ -47,7 +47,7 @@ import ( [![codecov](https://codecov.io/gh/cardano-community/koios-go-client/branch/main/graph/badge.svg?token=FA1KGG6ZQ5)](https://codecov.io/gh/cardano-community/koios-go-client) [![codeql](https://github.com/cardano-community/koios-go-client/workflows/codeql/badge.svg)](https://github.com/cardano-community/koios-go-client/actions/workflows/codeql.yml) [![misspell](https://github.com/cardano-community/koios-go-client/workflows/misspell/badge.svg)](https://github.com/cardano-community/koios-go-client/actions/workflows/misspell.yml) -[![Go Report Card](https://goreportcard.com/badge/github.com/cardano-community/koios-go-client/v3)](https://goreportcard.com/report/github.com/cardano-community/koios-go-client/v3) +[![Go Report Card](https://goreportcard.com/badge/github.com/cardano-community/koios-go-client/v4)](https://goreportcard.com/report/github.com/cardano-community/koios-go-client/v4) --- @@ -81,7 +81,7 @@ import ( ## Usage -See Godoc [![PkgGoDev](https://pkg.go.dev/badge/github.com/cardano-community/koios-go-client/v3)](https://pkg.go.dev/github.com/cardano-community/koios-go-client/v3) +See Godoc [![PkgGoDev](https://pkg.go.dev/badge/github.com/cardano-community/koios-go-client/v4)](https://pkg.go.dev/github.com/cardano-community/koios-go-client/v4) Additionally you can find all usecases by looking source of `koio-cli` Command-line application [koios-cli] which utilizes entire API of this library. @@ -100,7 +100,7 @@ import ( "fmt" "log" - koios "github.com/cardano-community/koios-go-client/v3" + koios "github.com/cardano-community/koios-go-client/v4" ) func main() { diff --git a/Taskfile.yaml b/Taskfile.yaml index d8f83a2..2ac2168 100644 --- a/Taskfile.yaml +++ b/Taskfile.yaml @@ -60,7 +60,7 @@ tasks: SNAPSHOT: sh: 'if [[ $(git describe --exact-match HEAD) != v* ]]; then echo "--snapshot"; fi' cmds: - - goreleaser release --rm-dist {{.SNAPSHOT}} + - goreleaser release --clean {{.SNAPSHOT}} setup: desc: Setup development env. diff --git a/account_test.go b/account_test.go index 2baa5bc..35a866f 100644 --- a/account_test.go +++ b/account_test.go @@ -22,7 +22,7 @@ import ( "strings" "testing" - "github.com/cardano-community/koios-go-client/v3" + "github.com/cardano-community/koios-go-client/v4" "github.com/stretchr/testify/assert" ) diff --git a/address_test.go b/address_test.go index e38bb07..fe178c2 100644 --- a/address_test.go +++ b/address_test.go @@ -21,7 +21,7 @@ import ( "fmt" "testing" - "github.com/cardano-community/koios-go-client/v3" + "github.com/cardano-community/koios-go-client/v4" "github.com/stretchr/testify/assert" ) diff --git a/assets_test.go b/assets_test.go index 2fb5c81..42b0efe 100644 --- a/assets_test.go +++ b/assets_test.go @@ -21,7 +21,7 @@ import ( "fmt" "testing" - "github.com/cardano-community/koios-go-client/v3" + "github.com/cardano-community/koios-go-client/v4" "github.com/stretchr/testify/assert" ) diff --git a/block_test.go b/block_test.go index 30f835b..58333bd 100644 --- a/block_test.go +++ b/block_test.go @@ -21,7 +21,7 @@ import ( "fmt" "testing" - "github.com/cardano-community/koios-go-client/v3" + "github.com/cardano-community/koios-go-client/v4" "github.com/stretchr/testify/assert" ) diff --git a/epoch_test.go b/epoch_test.go index 5dcdd55..d1d415a 100644 --- a/epoch_test.go +++ b/epoch_test.go @@ -21,7 +21,7 @@ import ( "fmt" "testing" - "github.com/cardano-community/koios-go-client/v3" + "github.com/cardano-community/koios-go-client/v4" "github.com/stretchr/testify/assert" ) diff --git a/go.mod b/go.mod index 1e416fd..37c03ba 100644 --- a/go.mod +++ b/go.mod @@ -1,12 +1,12 @@ -module github.com/cardano-community/koios-go-client/v3 // imports as package "koios" +module github.com/cardano-community/koios-go-client/v4 // imports as package "koios" -go 1.18 +go 1.22 require ( github.com/shopspring/decimal v1.3.1 - github.com/stretchr/testify v1.8.1 - golang.org/x/text v0.5.0 - golang.org/x/time v0.2.0 + github.com/stretchr/testify v1.8.4 + golang.org/x/text v0.14.0 + golang.org/x/time v0.5.0 ) require ( diff --git a/go.sum b/go.sum index 15d6a73..b07c171 100644 --- a/go.sum +++ b/go.sum @@ -1,23 +1,16 @@ -github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= github.com/shopspring/decimal v1.3.1 h1:2Usl1nmF/WZucqkFZhnfFYxxxu8LG21F6nPQBE5gKV8= github.com/shopspring/decimal v1.3.1/go.mod h1:DKyhrW/HYNuLGql+MJL6WCR6knT2jwCFRcu2hWCYk4o= -github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= -github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw= -github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo= -github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= -github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU= -github.com/stretchr/testify v1.8.1 h1:w7B6lhMri9wdJUVmEZPGGhZzrYTPvgJArz7wNPgYKsk= -github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4= -golang.org/x/text v0.5.0 h1:OLmvp0KP+FVG99Ct/qFiL/Fhk4zp4QQnZ7b2U+5piUM= -golang.org/x/text v0.5.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8= -golang.org/x/time v0.2.0 h1:52I/1L54xyEQAYdtcSuxtiT84KGYTBGXwayxmIpNJhE= -golang.org/x/time v0.2.0/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= +github.com/stretchr/testify v1.8.4 h1:CcVxjf3Q8PM0mHUKJCdn+eZZtm5yQwehR5yeSVQQcUk= +github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo= +golang.org/x/text v0.14.0 h1:ScX5w1eTa3QqT8oi6+ziP7dTV1S2+ALU0bI+0zXKWiQ= +golang.org/x/text v0.14.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU= +golang.org/x/time v0.5.0 h1:o7cqy6amK/52YcAKIPlM3a+Fpj35zvRj2TP+e1xFSfk= +golang.org/x/time v0.5.0/go.mod h1:3BpzKBy/shNhVucY/MWOyx10tF3SFh9QdLuxbVysPQM= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= -gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/koios.go b/koios.go index c7f6c53..debd61f 100644 --- a/koios.go +++ b/koios.go @@ -40,12 +40,12 @@ const ( GuildHost = "guild.koios.rest" PreviewHost = "preview.koios.rest" PreProdHost = "preprod.koios.rest" - DefaultAPIVersion = "v0" + DefaultAPIVersion = "v1" DefaultPort uint16 = 443 DefaultScheme = "https" LibraryVersion = "v0" DefaultRateLimit int = 10 // https://api.koios.rest/#overview--limits - DefaultOrigin = "https://github.com/cardano-community/koios-go-client" + DefaultOrigin = "koios-go-client/v4" PageSize uint = 1000 ) diff --git a/koios_test.go b/koios_test.go index a94d026..23b88c2 100644 --- a/koios_test.go +++ b/koios_test.go @@ -21,7 +21,7 @@ import ( "fmt" "os" - "github.com/cardano-community/koios-go-client/v3" + "github.com/cardano-community/koios-go-client/v4" "github.com/shopspring/decimal" "github.com/stretchr/testify/assert" ) diff --git a/network_test.go b/network_test.go index be7a469..5f56e18 100644 --- a/network_test.go +++ b/network_test.go @@ -20,7 +20,7 @@ import ( "context" "testing" - "github.com/cardano-community/koios-go-client/v3" + "github.com/cardano-community/koios-go-client/v4" "github.com/stretchr/testify/assert" ) diff --git a/pool_test.go b/pool_test.go index 57e58df..f83a0dc 100644 --- a/pool_test.go +++ b/pool_test.go @@ -21,7 +21,7 @@ import ( "fmt" "testing" - "github.com/cardano-community/koios-go-client/v3" + "github.com/cardano-community/koios-go-client/v4" "github.com/stretchr/testify/assert" ) diff --git a/script_test.go b/script_test.go index 52d3677..9bb2be3 100644 --- a/script_test.go +++ b/script_test.go @@ -20,7 +20,7 @@ import ( "context" "testing" - "github.com/cardano-community/koios-go-client/v3" + "github.com/cardano-community/koios-go-client/v4" "github.com/stretchr/testify/assert" ) diff --git a/transaction_test.go b/transaction_test.go index 24f0d18..c7a36f2 100644 --- a/transaction_test.go +++ b/transaction_test.go @@ -21,7 +21,7 @@ import ( "fmt" "testing" - "github.com/cardano-community/koios-go-client/v3" + "github.com/cardano-community/koios-go-client/v4" "github.com/stretchr/testify/assert" ) From 453fefc7a2a096870c27786006efc2b3accf622c Mon Sep 17 00:00:00 2001 From: Marko Kungla Date: Mon, 26 Feb 2024 17:47:56 +0200 Subject: [PATCH 03/65] fix: update default DefaultOrigin chore: reorganize /network endpoint related code Signed-off-by: Marko Kungla --- block.go | 1 - koios.go | 28 ++++++++- network.go | 173 ++++++++++++++++++++++++++++++++++++++++++----------- 3 files changed, 164 insertions(+), 38 deletions(-) diff --git a/block.go b/block.go index bc0ae72..9f611c1 100644 --- a/block.go +++ b/block.go @@ -26,7 +26,6 @@ import ( ) type ( - BlockNo int // Block defines model for block. Block struct { // Hash block hash diff --git a/koios.go b/koios.go index debd61f..7c10859 100644 --- a/koios.go +++ b/koios.go @@ -45,7 +45,7 @@ const ( DefaultScheme = "https" LibraryVersion = "v0" DefaultRateLimit int = 10 // https://api.koios.rest/#overview--limits - DefaultOrigin = "koios-go-client/v4" + DefaultOrigin = "https://github.com/cardano-community/koios-go-client@v4" PageSize uint = 1000 ) @@ -77,7 +77,9 @@ var ( // introduces breaking change since v1.3.0 type ( - Slot int + Slot uint + + BlockNo uint // PaymentCredential type def. PaymentCredential string @@ -276,9 +278,11 @@ func (v PolicyID) String() string { } func (t *Timestamp) UnmarshalJSON(b []byte) error { + if string(b) == "null" { + return nil + } q, err := strconv.ParseInt(string(b), 10, 64) if err != nil { - // time.IsZero = true return nil } t.Time = time.Unix(q, 0) @@ -287,5 +291,23 @@ func (t *Timestamp) UnmarshalJSON(b []byte) error { // MarshalJSON turns our time.Time back into an int. func (t Timestamp) MarshalJSON() ([]byte, error) { + if t.IsZero() { + return []byte("null"), nil + } return []byte(strconv.FormatInt(t.Time.Unix(), 10)), nil } + +func (b BlockNo) String() string { + return fmt.Sprintf("%d", b) +} + +func (s Slot) String() string { + return fmt.Sprintf("%d", s) +} + +func (h BlockHash) MarshalJSON() ([]byte, error) { + if len(h) == 0 { + return []byte("null"), nil + } + return []byte(fmt.Sprintf("%q", h)), nil +} diff --git a/network.go b/network.go index 74b76ba..bc8be84 100644 --- a/network.go +++ b/network.go @@ -23,8 +23,6 @@ import ( "github.com/shopspring/decimal" ) -// introduces breaking change since v1.3.0 - type ( // Tip defines model for tip. Tip struct { @@ -52,7 +50,27 @@ type ( Response Data Tip `json:"data"` } +) + +// GetTip returns the tip info about the latest block seen by chain. +func (c *Client) GetTip( + ctx context.Context, + opts *RequestOptions, +) (res *TipResponse, err error) { + res = &TipResponse{} + rsp, err := c.request(ctx, &res.Response, "GET", "/tip", nil, opts) + if err != nil { + return res, err + } + tips := []Tip{} + err = ReadAndUnmarshalResponse(rsp, &res.Response, &tips) + if len(tips) == 1 { + res.Data = tips[0] + } + return res, err +} +type ( // Genesis defines model for genesis. Genesis struct { // Active Slot Co-Efficient (f) - determines the _probability_ of number of @@ -107,6 +125,27 @@ type ( Response Data Genesis `json:"data"` } +) + +// GetGenesis returns the Genesis parameters used to start specific era on chain. +func (c *Client) GetGenesis( + ctx context.Context, + opts *RequestOptions, +) (*GenesisResponse, error) { + res := &GenesisResponse{} + rsp, err := c.request(ctx, &res.Response, "GET", "/genesis", nil, opts) + if err != nil { + return res, err + } + genesisres := []Genesis{} + err = ReadAndUnmarshalResponse(rsp, &res.Response, &genesisres) + if len(genesisres) == 1 { + res.Data = genesisres[0] + } + return res, err +} + +type ( // Totals defines model for totals. Totals struct { @@ -138,57 +177,90 @@ type ( } ) -// GetTip returns the tip info about the latest block seen by chain. -func (c *Client) GetTip( +// GetTotals returns the circulating utxo, treasury, rewards, supply and +// reserves in lovelace for specified epoch, all epochs if empty. +func (c *Client) GetTotals( ctx context.Context, + epoch *EpochNo, opts *RequestOptions, -) (res *TipResponse, err error) { - res = &TipResponse{} - rsp, err := c.request(ctx, &res.Response, "GET", "/tip", nil, opts) +) (*TotalsResponse, error) { + if opts == nil { + opts = c.NewRequestOptions() + } + if epoch != nil { + opts.QuerySet("_epoch_no", epoch.String()) + } + res := &TotalsResponse{} + rsp, err := c.request(ctx, &res.Response, "GET", "/totals", nil, opts) if err != nil { return res, err } - tips := []Tip{} - err = ReadAndUnmarshalResponse(rsp, &res.Response, &tips) - if len(tips) == 1 { - res.Data = tips[0] - } - return res, err + return res, ReadAndUnmarshalResponse(rsp, &res.Response, &res.Data) } -// GetGenesis returns the Genesis parameters used to start specific era on chain. -func (c *Client) GetGenesis( +type ( + // ParamUpdate defines model for param update. + ParamUpdate struct { + // Epoch number. + TxHash TxHash `json:"tx_hash"` + BlockHeight BlockNo `json:"block_height"` + BlockTime Timestamp `json:"block_time"` + EpochNo EpochNo `json:"epoch_no"` + Data json.RawMessage `json:"data"` + } + + // ParamUpdatesResponse represents response from `/param_updates` endpoint. + ParamUpdatesResponse struct { + Response + Data []ParamUpdate `json:"data"` + } +) + +// GetParamUpdates returns the parameter updates for the network. +func (c *Client) GetParamUpdates( ctx context.Context, opts *RequestOptions, -) (*GenesisResponse, error) { - res := &GenesisResponse{} - rsp, err := c.request(ctx, &res.Response, "GET", "/genesis", nil, opts) +) (*ParamUpdatesResponse, error) { + if opts == nil { + opts = c.NewRequestOptions() + } + res := &ParamUpdatesResponse{} + rsp, err := c.request(ctx, &res.Response, "GET", "/param_updates", nil, opts) if err != nil { return res, err } - genesisres := []Genesis{} - err = ReadAndUnmarshalResponse(rsp, &res.Response, &genesisres) - if len(genesisres) == 1 { - res.Data = genesisres[0] - } - return res, err + return res, ReadAndUnmarshalResponse(rsp, &res.Response, &res.Data) } -// GetTotals returns the circulating utxo, treasury, rewards, supply and -// reserves in lovelace for specified epoch, all epochs if empty. -func (c *Client) GetTotals( +type ( + // ReserveWithdrawal defines model for reserve withdrawal. + ReserveWithdrawal struct { + EpochNo EpochNo `json:"epoch_no"` + EpochSlot Slot `json:"epoch_slot"` + TxHash TxHash `json:"tx_hash"` + BlockHash BlockHash `json:"block_hash"` + BlockHeight BlockNo `json:"block_height"` + Amount decimal.Decimal `json:"amount"` + StakeAddress Address `json:"stake_address"` + } + + // ReserveWithdrawalsResponse represents response from `/reserve_withdrawals` endpoint. + ReserveWithdrawalsResponse struct { + Response + Data []ReserveWithdrawal `json:"data"` + } +) + +func (c *Client) GetReserveWithdrawals( ctx context.Context, - epoch *EpochNo, opts *RequestOptions, -) (*TotalsResponse, error) { +) (*ReserveWithdrawalsResponse, error) { if opts == nil { opts = c.NewRequestOptions() } - if epoch != nil { - opts.QuerySet("_epoch_no", epoch.String()) - } - res := &TotalsResponse{} - rsp, err := c.request(ctx, &res.Response, "GET", "/totals", nil, opts) + + res := &ReserveWithdrawalsResponse{} + rsp, err := c.request(ctx, &res.Response, "GET", "/reserve_withdrawals", nil, opts) if err != nil { return res, err } @@ -202,3 +274,36 @@ func (g *Genesis) AlonzoGenesisMap() (map[string]any, error) { } return data, nil } + +type ( + // TreasuryWithdrawal defines model for treasury withdrawal. + TreasuryWithdrawal struct { + EpochNo EpochNo `json:"epoch_no"` + EpochSlot Slot `json:"epoch_slot"` + TxHash TxHash `json:"tx_hash"` + BlockHash BlockHash `json:"block_hash"` + BlockHeight BlockNo `json:"block_height"` + Amount decimal.Decimal `json:"amount"` + StakeAddress Address `json:"stake_address"` + } + TreasuryWithdrawalsResponse struct { + Response + Data []TreasuryWithdrawal `json:"data"` + } +) + +func (c *Client) GetTreasuryWithdrawals( + ctx context.Context, + opts *RequestOptions, +) (*TreasuryWithdrawalsResponse, error) { + if opts == nil { + opts = c.NewRequestOptions() + } + + res := &TreasuryWithdrawalsResponse{} + rsp, err := c.request(ctx, &res.Response, "GET", "/treasury_withdrawals", nil, opts) + if err != nil { + return res, err + } + return res, ReadAndUnmarshalResponse(rsp, &res.Response, &res.Data) +} From f2fb1b79e1bc1734dc8102f4fd01a4d1f45932dd Mon Sep 17 00:00:00 2001 From: Marko Kungla Date: Tue, 27 Feb 2024 00:57:54 +0200 Subject: [PATCH 04/65] ci: update github actions config Signed-off-by: Marko Kungla --- .github/workflows/codeql.yml | 6 +-- .github/workflows/linux.yml | 12 ++--- .github/workflows/macos.yml | 6 +-- .github/workflows/semantic-pull-request.yml | 2 +- .github/workflows/test-guild.yml | 54 ++++++++++----------- .github/workflows/test-mainnet.yml | 54 ++++++++++----------- .github/workflows/test-preprod.yml | 54 ++++++++++----------- .github/workflows/test-preview.yml | 54 ++++++++++----------- .github/workflows/windows.yml | 6 +-- 9 files changed, 124 insertions(+), 124 deletions(-) diff --git a/.github/workflows/codeql.yml b/.github/workflows/codeql.yml index b577ad0..2cdeb92 100644 --- a/.github/workflows/codeql.yml +++ b/.github/workflows/codeql.yml @@ -5,10 +5,10 @@ permissions: {} on: push: - branches: [ master ] + branches: [ main ] pull_request: # The branches below must be a subset of the branches above - branches: [ master ] + branches: [ main ] schedule: - cron: '30 5 * * 4' @@ -28,7 +28,7 @@ jobs: steps: - name: Checkout repository - uses: actions/checkout@v3 + uses: actions/checkout@v4 # Initializes the CodeQL tools for scanning. - name: Initialize CodeQL diff --git a/.github/workflows/linux.yml b/.github/workflows/linux.yml index f0b180d..24ff75a 100644 --- a/.github/workflows/linux.yml +++ b/.github/workflows/linux.yml @@ -11,10 +11,10 @@ jobs: lint: runs-on: ubuntu-latest steps: - - uses: actions/setup-go@v3 + - uses: actions/setup-go@v5 with: go-version: 1.19 - - uses: actions/checkout@v3 + - uses: actions/checkout@v4 - name: golangci-lint uses: golangci/golangci-lint-action@v3 @@ -24,19 +24,19 @@ jobs: - lint strategy: matrix: - go: ['1.18', '1.19'] + go: ['1.22', 'tip'] steps: - name: Set up Go - uses: actions/setup-go@v3 + uses: actions/setup-go@v5 with: go-version: ${{ matrix.go }} - name: Checkout code - uses: actions/checkout@v3 + uses: actions/checkout@v4 - name: Run tests run: | go test -v -race -covermode atomic -coverprofile=coverage.txt ./... - name: Upload coverage - uses: codecov/codecov-action@v3 + uses: codecov/codecov-action@v4 with: flags: linux,local fail_ci_if_error: true diff --git a/.github/workflows/macos.yml b/.github/workflows/macos.yml index 8050907..48be3ea 100644 --- a/.github/workflows/macos.yml +++ b/.github/workflows/macos.yml @@ -14,16 +14,16 @@ jobs: go: ['1.18', '1.19'] steps: - name: Set up Go - uses: actions/setup-go@v3 + uses: actions/setup-go@v5 with: go-version: ${{ matrix.go }} - name: Checkout code - uses: actions/checkout@v3 + uses: actions/checkout@v4 - name: Run tests run: | go test -v -race -covermode atomic -coverprofile=coverage.txt ./... - name: Upload coverage - uses: codecov/codecov-action@v3 + uses: codecov/codecov-action@v4 with: flags: macos,local fail_ci_if_error: true diff --git a/.github/workflows/semantic-pull-request.yml b/.github/workflows/semantic-pull-request.yml index e55691b..8f2c520 100644 --- a/.github/workflows/semantic-pull-request.yml +++ b/.github/workflows/semantic-pull-request.yml @@ -12,7 +12,7 @@ jobs: name: Validate PR title runs-on: ubuntu-latest steps: - - uses: amannn/action-semantic-pull-request@v4 + - uses: amannn/action-semantic-pull-request@v5 env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} with: diff --git a/.github/workflows/test-guild.yml b/.github/workflows/test-guild.yml index 9f163f0..37bd0e4 100644 --- a/.github/workflows/test-guild.yml +++ b/.github/workflows/test-guild.yml @@ -23,13 +23,13 @@ jobs: - NetworkGenesis - NetworkTotals steps: - - uses: actions/setup-go@v3 + - uses: actions/setup-go@v5 with: go-version: 1.19 - - uses: actions/checkout@v3 + - uses: actions/checkout@v4 - run: go test -v -covermode atomic -coverprofile coverage.txt -run ^Test${{ matrix.test }}$ - name: Upload coverage - uses: codecov/codecov-action@v3 + uses: codecov/codecov-action@v4 with: flags: "${{ env.KOIOS_NETWORK }},${{ github.job }},${{ matrix.test }}" name: "${{ env.KOIOS_NETWORK }}-${{ github.job }}-${{ matrix.test }}" @@ -45,13 +45,13 @@ jobs: - EpochParams - EpochBlockProtocols steps: - - uses: actions/setup-go@v3 + - uses: actions/setup-go@v5 with: go-version: 1.19 - - uses: actions/checkout@v3 + - uses: actions/checkout@v4 - run: go test -v -covermode atomic -coverprofile coverage.txt -run ^Test${{ matrix.test }}$ - name: Upload coverage - uses: codecov/codecov-action@v3 + uses: codecov/codecov-action@v4 with: flags: "${{ env.KOIOS_NETWORK }},${{ github.job }},${{ matrix.test }}" name: "${{ env.KOIOS_NETWORK }}-${{ github.job }}-${{ matrix.test }}" @@ -67,13 +67,13 @@ jobs: - BlockInfo - BlockTxs steps: - - uses: actions/setup-go@v3 + - uses: actions/setup-go@v5 with: go-version: 1.19 - - uses: actions/checkout@v3 + - uses: actions/checkout@v4 - run: go test -v -covermode atomic -coverprofile coverage.txt -run ^Test${{ matrix.test }}$ - name: Upload coverage - uses: codecov/codecov-action@v3 + uses: codecov/codecov-action@v4 with: flags: "${{ env.KOIOS_NETWORK }},${{ github.job }},${{ matrix.test }}" name: "${{ env.KOIOS_NETWORK }}-${{ github.job }}-${{ matrix.test }}" @@ -91,13 +91,13 @@ jobs: - TxMetaLabels - TxStatus steps: - - uses: actions/setup-go@v3 + - uses: actions/setup-go@v5 with: go-version: 1.19 - - uses: actions/checkout@v3 + - uses: actions/checkout@v4 - run: go test -v -covermode atomic -coverprofile coverage.txt -run ^Test${{ matrix.test }}$ - name: Upload coverage - uses: codecov/codecov-action@v3 + uses: codecov/codecov-action@v4 with: flags: "${{ env.KOIOS_NETWORK }},${{ github.job }},${{ matrix.test }}" name: "${{ env.KOIOS_NETWORK }}-${{ github.job }}-${{ matrix.test }}" @@ -117,13 +117,13 @@ jobs: - AddressAssets - CredentialTxs steps: - - uses: actions/setup-go@v3 + - uses: actions/setup-go@v5 with: go-version: 1.19 - - uses: actions/checkout@v3 + - uses: actions/checkout@v4 - run: go test -v -covermode atomic -coverprofile coverage.txt -run ^Test${{ matrix.test }}$ - name: Upload coverage - uses: codecov/codecov-action@v3 + uses: codecov/codecov-action@v4 with: flags: "${{ env.KOIOS_NETWORK }},${{ github.job }},${{ matrix.test }}" name: "${{ env.KOIOS_NETWORK }}-${{ github.job }}-${{ matrix.test }}" @@ -147,13 +147,13 @@ jobs: - AccountAssets - AccountHistory steps: - - uses: actions/setup-go@v3 + - uses: actions/setup-go@v5 with: go-version: 1.19 - - uses: actions/checkout@v3 + - uses: actions/checkout@v4 - run: go test -v -covermode atomic -coverprofile coverage.txt -run ^Test${{ matrix.test }}$ - name: Upload coverage - uses: codecov/codecov-action@v3 + uses: codecov/codecov-action@v4 with: flags: "${{ env.KOIOS_NETWORK }},${{ github.job }},${{ matrix.test }}" name: "${{ env.KOIOS_NETWORK }}-${{ github.job }}-${{ matrix.test }}" @@ -176,13 +176,13 @@ jobs: - AssetSummary - AssetTxs steps: - - uses: actions/setup-go@v3 + - uses: actions/setup-go@v5 with: go-version: 1.19 - - uses: actions/checkout@v3 + - uses: actions/checkout@v4 - run: go test -v -covermode atomic -coverprofile coverage.txt -run ^Test${{ matrix.test }}$ - name: Upload coverage - uses: codecov/codecov-action@v3 + uses: codecov/codecov-action@v4 with: flags: "${{ env.KOIOS_NETWORK }},${{ github.job }},${{ matrix.test }}" name: "${{ env.KOIOS_NETWORK }}-${{ github.job }}-${{ matrix.test }}" @@ -208,13 +208,13 @@ jobs: - PoolRelays - PoolMetadata steps: - - uses: actions/setup-go@v3 + - uses: actions/setup-go@v5 with: go-version: 1.19 - - uses: actions/checkout@v3 + - uses: actions/checkout@v4 - run: go test -v -covermode atomic -coverprofile coverage.txt -run ^Test${{ matrix.test }}$ - name: Upload coverage - uses: codecov/codecov-action@v3 + uses: codecov/codecov-action@v4 with: flags: "${{ env.KOIOS_NETWORK }},${{ github.job }},${{ matrix.test }}" name: "${{ env.KOIOS_NETWORK }}-${{ github.job }}-${{ matrix.test }}" @@ -234,13 +234,13 @@ jobs: - ScriptRedeemers - DatumInfo steps: - - uses: actions/setup-go@v3 + - uses: actions/setup-go@v5 with: go-version: 1.19 - - uses: actions/checkout@v3 + - uses: actions/checkout@v4 - run: go test -v -covermode atomic -coverprofile coverage.txt -run ^Test${{ matrix.test }}$ - name: Upload coverage - uses: codecov/codecov-action@v3 + uses: codecov/codecov-action@v4 with: flags: "${{ env.KOIOS_NETWORK }},${{ github.job }},${{ matrix.test }}" name: "${{ env.KOIOS_NETWORK }}-${{ github.job }}-${{ matrix.test }}" diff --git a/.github/workflows/test-mainnet.yml b/.github/workflows/test-mainnet.yml index 423429e..428d18b 100644 --- a/.github/workflows/test-mainnet.yml +++ b/.github/workflows/test-mainnet.yml @@ -23,13 +23,13 @@ jobs: - NetworkGenesis - NetworkTotals steps: - - uses: actions/setup-go@v3 + - uses: actions/setup-go@v5 with: go-version: 1.19 - - uses: actions/checkout@v3 + - uses: actions/checkout@v4 - run: go test -v -covermode atomic -coverprofile coverage.txt -run ^Test${{ matrix.test }}$ - name: Upload coverage - uses: codecov/codecov-action@v3 + uses: codecov/codecov-action@v4 with: flags: "${{ env.KOIOS_NETWORK }},${{ github.job }},${{ matrix.test }}" name: "${{ env.KOIOS_NETWORK }}-${{ github.job }}-${{ matrix.test }}" @@ -45,13 +45,13 @@ jobs: - EpochParams - EpochBlockProtocols steps: - - uses: actions/setup-go@v3 + - uses: actions/setup-go@v5 with: go-version: 1.19 - - uses: actions/checkout@v3 + - uses: actions/checkout@v4 - run: go test -v -covermode atomic -coverprofile coverage.txt -run ^Test${{ matrix.test }}$ - name: Upload coverage - uses: codecov/codecov-action@v3 + uses: codecov/codecov-action@v4 with: flags: "${{ env.KOIOS_NETWORK }},${{ github.job }},${{ matrix.test }}" name: "${{ env.KOIOS_NETWORK }}-${{ github.job }}-${{ matrix.test }}" @@ -67,13 +67,13 @@ jobs: - BlockInfo - BlockTxs steps: - - uses: actions/setup-go@v3 + - uses: actions/setup-go@v5 with: go-version: 1.19 - - uses: actions/checkout@v3 + - uses: actions/checkout@v4 - run: go test -v -covermode atomic -coverprofile coverage.txt -run ^Test${{ matrix.test }}$ - name: Upload coverage - uses: codecov/codecov-action@v3 + uses: codecov/codecov-action@v4 with: flags: "${{ env.KOIOS_NETWORK }},${{ github.job }},${{ matrix.test }}" name: "${{ env.KOIOS_NETWORK }}-${{ github.job }}-${{ matrix.test }}" @@ -91,13 +91,13 @@ jobs: - TxMetaLabels - TxStatus steps: - - uses: actions/setup-go@v3 + - uses: actions/setup-go@v5 with: go-version: 1.19 - - uses: actions/checkout@v3 + - uses: actions/checkout@v4 - run: go test -v -covermode atomic -coverprofile coverage.txt -run ^Test${{ matrix.test }}$ - name: Upload coverage - uses: codecov/codecov-action@v3 + uses: codecov/codecov-action@v4 with: flags: "${{ env.KOIOS_NETWORK }},${{ github.job }},${{ matrix.test }}" name: "${{ env.KOIOS_NETWORK }}-${{ github.job }}-${{ matrix.test }}" @@ -117,13 +117,13 @@ jobs: - AddressAssets - CredentialTxs steps: - - uses: actions/setup-go@v3 + - uses: actions/setup-go@v5 with: go-version: 1.19 - - uses: actions/checkout@v3 + - uses: actions/checkout@v4 - run: go test -v -covermode atomic -coverprofile coverage.txt -run ^Test${{ matrix.test }}$ - name: Upload coverage - uses: codecov/codecov-action@v3 + uses: codecov/codecov-action@v4 with: flags: "${{ env.KOIOS_NETWORK }},${{ github.job }},${{ matrix.test }}" name: "${{ env.KOIOS_NETWORK }}-${{ github.job }}-${{ matrix.test }}" @@ -147,13 +147,13 @@ jobs: - AccountAssets - AccountHistory steps: - - uses: actions/setup-go@v3 + - uses: actions/setup-go@v5 with: go-version: 1.19 - - uses: actions/checkout@v3 + - uses: actions/checkout@v4 - run: go test -v -covermode atomic -coverprofile coverage.txt -run ^Test${{ matrix.test }}$ - name: Upload coverage - uses: codecov/codecov-action@v3 + uses: codecov/codecov-action@v4 with: flags: "${{ env.KOIOS_NETWORK }},${{ github.job }},${{ matrix.test }}" name: "${{ env.KOIOS_NETWORK }}-${{ github.job }}-${{ matrix.test }}" @@ -176,13 +176,13 @@ jobs: - AssetSummary - AssetTxs steps: - - uses: actions/setup-go@v3 + - uses: actions/setup-go@v5 with: go-version: 1.19 - - uses: actions/checkout@v3 + - uses: actions/checkout@v4 - run: go test -v -covermode atomic -coverprofile coverage.txt -run ^Test${{ matrix.test }}$ - name: Upload coverage - uses: codecov/codecov-action@v3 + uses: codecov/codecov-action@v4 with: flags: "${{ env.KOIOS_NETWORK }},${{ github.job }},${{ matrix.test }}" name: "${{ env.KOIOS_NETWORK }}-${{ github.job }}-${{ matrix.test }}" @@ -208,13 +208,13 @@ jobs: - PoolRelays - PoolMetadata steps: - - uses: actions/setup-go@v3 + - uses: actions/setup-go@v5 with: go-version: 1.19 - - uses: actions/checkout@v3 + - uses: actions/checkout@v4 - run: go test -v -covermode atomic -coverprofile coverage.txt -run ^Test${{ matrix.test }}$ - name: Upload coverage - uses: codecov/codecov-action@v3 + uses: codecov/codecov-action@v4 with: flags: "${{ env.KOIOS_NETWORK }},${{ github.job }},${{ matrix.test }}" name: "${{ env.KOIOS_NETWORK }}-${{ github.job }}-${{ matrix.test }}" @@ -234,13 +234,13 @@ jobs: - ScriptRedeemers - DatumInfo steps: - - uses: actions/setup-go@v3 + - uses: actions/setup-go@v5 with: go-version: 1.19 - - uses: actions/checkout@v3 + - uses: actions/checkout@v4 - run: go test -v -covermode atomic -coverprofile coverage.txt -run ^Test${{ matrix.test }}$ - name: Upload coverage - uses: codecov/codecov-action@v3 + uses: codecov/codecov-action@v4 with: flags: "${{ env.KOIOS_NETWORK }},${{ github.job }},${{ matrix.test }}" name: "${{ env.KOIOS_NETWORK }}-${{ github.job }}-${{ matrix.test }}" diff --git a/.github/workflows/test-preprod.yml b/.github/workflows/test-preprod.yml index cf9cb24..8a99c52 100644 --- a/.github/workflows/test-preprod.yml +++ b/.github/workflows/test-preprod.yml @@ -23,13 +23,13 @@ jobs: - NetworkGenesis - NetworkTotals steps: - - uses: actions/setup-go@v3 + - uses: actions/setup-go@v5 with: go-version: 1.19 - - uses: actions/checkout@v3 + - uses: actions/checkout@v4 - run: go test -v -covermode atomic -coverprofile coverage.txt -run ^Test${{ matrix.test }}$ - name: Upload coverage - uses: codecov/codecov-action@v3 + uses: codecov/codecov-action@v4 with: flags: "${{ env.KOIOS_NETWORK }},${{ github.job }},${{ matrix.test }}" name: "${{ env.KOIOS_NETWORK }}-${{ github.job }}-${{ matrix.test }}" @@ -45,13 +45,13 @@ jobs: - EpochParams - EpochBlockProtocols steps: - - uses: actions/setup-go@v3 + - uses: actions/setup-go@v5 with: go-version: 1.19 - - uses: actions/checkout@v3 + - uses: actions/checkout@v4 - run: go test -v -covermode atomic -coverprofile coverage.txt -run ^Test${{ matrix.test }}$ - name: Upload coverage - uses: codecov/codecov-action@v3 + uses: codecov/codecov-action@v4 with: flags: "${{ env.KOIOS_NETWORK }},${{ github.job }},${{ matrix.test }}" name: "${{ env.KOIOS_NETWORK }}-${{ github.job }}-${{ matrix.test }}" @@ -67,13 +67,13 @@ jobs: - BlockInfo - BlockTxs steps: - - uses: actions/setup-go@v3 + - uses: actions/setup-go@v5 with: go-version: 1.19 - - uses: actions/checkout@v3 + - uses: actions/checkout@v4 - run: go test -v -covermode atomic -coverprofile coverage.txt -run ^Test${{ matrix.test }}$ - name: Upload coverage - uses: codecov/codecov-action@v3 + uses: codecov/codecov-action@v4 with: flags: "${{ env.KOIOS_NETWORK }},${{ github.job }},${{ matrix.test }}" name: "${{ env.KOIOS_NETWORK }}-${{ github.job }}-${{ matrix.test }}" @@ -91,13 +91,13 @@ jobs: - TxMetaLabels - TxStatus steps: - - uses: actions/setup-go@v3 + - uses: actions/setup-go@v5 with: go-version: 1.19 - - uses: actions/checkout@v3 + - uses: actions/checkout@v4 - run: go test -v -covermode atomic -coverprofile coverage.txt -run ^Test${{ matrix.test }}$ - name: Upload coverage - uses: codecov/codecov-action@v3 + uses: codecov/codecov-action@v4 with: flags: "${{ env.KOIOS_NETWORK }},${{ github.job }},${{ matrix.test }}" name: "${{ env.KOIOS_NETWORK }}-${{ github.job }}-${{ matrix.test }}" @@ -117,13 +117,13 @@ jobs: - AddressAssets - CredentialTxs steps: - - uses: actions/setup-go@v3 + - uses: actions/setup-go@v5 with: go-version: 1.19 - - uses: actions/checkout@v3 + - uses: actions/checkout@v4 - run: go test -v -covermode atomic -coverprofile coverage.txt -run ^Test${{ matrix.test }}$ - name: Upload coverage - uses: codecov/codecov-action@v3 + uses: codecov/codecov-action@v4 with: flags: "${{ env.KOIOS_NETWORK }},${{ github.job }},${{ matrix.test }}" name: "${{ env.KOIOS_NETWORK }}-${{ github.job }}-${{ matrix.test }}" @@ -147,13 +147,13 @@ jobs: - AccountAssets - AccountHistory steps: - - uses: actions/setup-go@v3 + - uses: actions/setup-go@v5 with: go-version: 1.19 - - uses: actions/checkout@v3 + - uses: actions/checkout@v4 - run: go test -v -covermode atomic -coverprofile coverage.txt -run ^Test${{ matrix.test }}$ - name: Upload coverage - uses: codecov/codecov-action@v3 + uses: codecov/codecov-action@v4 with: flags: "${{ env.KOIOS_NETWORK }},${{ github.job }},${{ matrix.test }}" name: "${{ env.KOIOS_NETWORK }}-${{ github.job }}-${{ matrix.test }}" @@ -176,13 +176,13 @@ jobs: - AssetSummary - AssetTxs steps: - - uses: actions/setup-go@v3 + - uses: actions/setup-go@v5 with: go-version: 1.19 - - uses: actions/checkout@v3 + - uses: actions/checkout@v4 - run: go test -v -covermode atomic -coverprofile coverage.txt -run ^Test${{ matrix.test }}$ - name: Upload coverage - uses: codecov/codecov-action@v3 + uses: codecov/codecov-action@v4 with: flags: "${{ env.KOIOS_NETWORK }},${{ github.job }},${{ matrix.test }}" name: "${{ env.KOIOS_NETWORK }}-${{ github.job }}-${{ matrix.test }}" @@ -208,13 +208,13 @@ jobs: - PoolRelays - PoolMetadata steps: - - uses: actions/setup-go@v3 + - uses: actions/setup-go@v5 with: go-version: 1.19 - - uses: actions/checkout@v3 + - uses: actions/checkout@v4 - run: go test -v -covermode atomic -coverprofile coverage.txt -run ^Test${{ matrix.test }}$ - name: Upload coverage - uses: codecov/codecov-action@v3 + uses: codecov/codecov-action@v4 with: flags: "${{ env.KOIOS_NETWORK }},${{ github.job }},${{ matrix.test }}" name: "${{ env.KOIOS_NETWORK }}-${{ github.job }}-${{ matrix.test }}" @@ -234,13 +234,13 @@ jobs: - ScriptRedeemers - DatumInfo steps: - - uses: actions/setup-go@v3 + - uses: actions/setup-go@v5 with: go-version: 1.19 - - uses: actions/checkout@v3 + - uses: actions/checkout@v4 - run: go test -v -covermode atomic -coverprofile coverage.txt -run ^Test${{ matrix.test }}$ - name: Upload coverage - uses: codecov/codecov-action@v3 + uses: codecov/codecov-action@v4 with: flags: "${{ env.KOIOS_NETWORK }},${{ github.job }},${{ matrix.test }}" name: "${{ env.KOIOS_NETWORK }}-${{ github.job }}-${{ matrix.test }}" diff --git a/.github/workflows/test-preview.yml b/.github/workflows/test-preview.yml index 302d097..35f5c66 100644 --- a/.github/workflows/test-preview.yml +++ b/.github/workflows/test-preview.yml @@ -23,13 +23,13 @@ jobs: - NetworkGenesis - NetworkTotals steps: - - uses: actions/setup-go@v3 + - uses: actions/setup-go@v5 with: go-version: 1.19 - - uses: actions/checkout@v3 + - uses: actions/checkout@v4 - run: go test -v -covermode atomic -coverprofile coverage.txt -run ^Test${{ matrix.test }}$ - name: Upload coverage - uses: codecov/codecov-action@v3 + uses: codecov/codecov-action@v4 with: flags: "${{ env.KOIOS_NETWORK }},${{ github.job }},${{ matrix.test }}" name: "${{ env.KOIOS_NETWORK }}-${{ github.job }}-${{ matrix.test }}" @@ -45,13 +45,13 @@ jobs: - EpochParams - EpochBlockProtocols steps: - - uses: actions/setup-go@v3 + - uses: actions/setup-go@v5 with: go-version: 1.19 - - uses: actions/checkout@v3 + - uses: actions/checkout@v4 - run: go test -v -covermode atomic -coverprofile coverage.txt -run ^Test${{ matrix.test }}$ - name: Upload coverage - uses: codecov/codecov-action@v3 + uses: codecov/codecov-action@v4 with: flags: "${{ env.KOIOS_NETWORK }},${{ github.job }},${{ matrix.test }}" name: "${{ env.KOIOS_NETWORK }}-${{ github.job }}-${{ matrix.test }}" @@ -67,13 +67,13 @@ jobs: - BlockInfo - BlockTxs steps: - - uses: actions/setup-go@v3 + - uses: actions/setup-go@v5 with: go-version: 1.19 - - uses: actions/checkout@v3 + - uses: actions/checkout@v4 - run: go test -v -covermode atomic -coverprofile coverage.txt -run ^Test${{ matrix.test }}$ - name: Upload coverage - uses: codecov/codecov-action@v3 + uses: codecov/codecov-action@v4 with: flags: "${{ env.KOIOS_NETWORK }},${{ github.job }},${{ matrix.test }}" name: "${{ env.KOIOS_NETWORK }}-${{ github.job }}-${{ matrix.test }}" @@ -91,13 +91,13 @@ jobs: - TxMetaLabels - TxStatus steps: - - uses: actions/setup-go@v3 + - uses: actions/setup-go@v5 with: go-version: 1.19 - - uses: actions/checkout@v3 + - uses: actions/checkout@v4 - run: go test -v -covermode atomic -coverprofile coverage.txt -run ^Test${{ matrix.test }}$ - name: Upload coverage - uses: codecov/codecov-action@v3 + uses: codecov/codecov-action@v4 with: flags: "${{ env.KOIOS_NETWORK }},${{ github.job }},${{ matrix.test }}" name: "${{ env.KOIOS_NETWORK }}-${{ github.job }}-${{ matrix.test }}" @@ -117,13 +117,13 @@ jobs: - AddressAssets - CredentialTxs steps: - - uses: actions/setup-go@v3 + - uses: actions/setup-go@v5 with: go-version: 1.19 - - uses: actions/checkout@v3 + - uses: actions/checkout@v4 - run: go test -v -covermode atomic -coverprofile coverage.txt -run ^Test${{ matrix.test }}$ - name: Upload coverage - uses: codecov/codecov-action@v3 + uses: codecov/codecov-action@v4 with: flags: "${{ env.KOIOS_NETWORK }},${{ github.job }},${{ matrix.test }}" name: "${{ env.KOIOS_NETWORK }}-${{ github.job }}-${{ matrix.test }}" @@ -147,13 +147,13 @@ jobs: - AccountAssets - AccountHistory steps: - - uses: actions/setup-go@v3 + - uses: actions/setup-go@v5 with: go-version: 1.19 - - uses: actions/checkout@v3 + - uses: actions/checkout@v4 - run: go test -v -covermode atomic -coverprofile coverage.txt -run ^Test${{ matrix.test }}$ - name: Upload coverage - uses: codecov/codecov-action@v3 + uses: codecov/codecov-action@v4 with: flags: "${{ env.KOIOS_NETWORK }},${{ github.job }},${{ matrix.test }}" name: "${{ env.KOIOS_NETWORK }}-${{ github.job }}-${{ matrix.test }}" @@ -176,13 +176,13 @@ jobs: - AssetSummary - AssetTxs steps: - - uses: actions/setup-go@v3 + - uses: actions/setup-go@v5 with: go-version: 1.19 - - uses: actions/checkout@v3 + - uses: actions/checkout@v4 - run: go test -v -covermode atomic -coverprofile coverage.txt -run ^Test${{ matrix.test }}$ - name: Upload coverage - uses: codecov/codecov-action@v3 + uses: codecov/codecov-action@v4 with: flags: "${{ env.KOIOS_NETWORK }},${{ github.job }},${{ matrix.test }}" name: "${{ env.KOIOS_NETWORK }}-${{ github.job }}-${{ matrix.test }}" @@ -208,13 +208,13 @@ jobs: - PoolRelays - PoolMetadata steps: - - uses: actions/setup-go@v3 + - uses: actions/setup-go@v5 with: go-version: 1.19 - - uses: actions/checkout@v3 + - uses: actions/checkout@v4 - run: go test -v -covermode atomic -coverprofile coverage.txt -run ^Test${{ matrix.test }}$ - name: Upload coverage - uses: codecov/codecov-action@v3 + uses: codecov/codecov-action@v4 with: flags: "${{ env.KOIOS_NETWORK }},${{ github.job }},${{ matrix.test }}" name: "${{ env.KOIOS_NETWORK }}-${{ github.job }}-${{ matrix.test }}" @@ -234,13 +234,13 @@ jobs: - ScriptRedeemers - DatumInfo steps: - - uses: actions/setup-go@v3 + - uses: actions/setup-go@v5 with: go-version: 1.19 - - uses: actions/checkout@v3 + - uses: actions/checkout@v4 - run: go test -v -covermode atomic -coverprofile coverage.txt -run ^Test${{ matrix.test }}$ - name: Upload coverage - uses: codecov/codecov-action@v3 + uses: codecov/codecov-action@v4 with: flags: "${{ env.KOIOS_NETWORK }},${{ github.job }},${{ matrix.test }}" name: "${{ env.KOIOS_NETWORK }}-${{ github.job }}-${{ matrix.test }}" diff --git a/.github/workflows/windows.yml b/.github/workflows/windows.yml index 34117ac..716223d 100644 --- a/.github/workflows/windows.yml +++ b/.github/workflows/windows.yml @@ -14,17 +14,17 @@ jobs: go: ['1.18', '1.19'] steps: - name: Set up Go - uses: actions/setup-go@v3 + uses: actions/setup-go@v5 with: go-version: ${{ matrix.go }} - name: Checkout code - uses: actions/checkout@v3 + uses: actions/checkout@v4 - name: Run tests run: | go mod download -x go test -v -race -coverprofile coverage.coverprofile -covermode atomic ./... - name: Upload coverage - uses: codecov/codecov-action@v3 + uses: codecov/codecov-action@v4 with: flags: windows,local fail_ci_if_error: true From f468c2f39623d842fc6c26fcd8ea64c53d8e04bd Mon Sep 17 00:00:00 2001 From: Marko Kungla Date: Tue, 27 Feb 2024 19:21:51 +0200 Subject: [PATCH 05/65] ci: init v2 github actions Signed-off-by: Marko Kungla --- .github/workflows/codeql.yml | 45 ---- .github/workflows/linux.yml | 43 ---- .github/workflows/macos.yml | 30 --- .github/workflows/main.yml | 46 ++++ .github/workflows/semantic-pull-request.yml | 68 ------ .github/workflows/test-guild.yml | 248 -------------------- .github/workflows/test-mainnet.yml | 248 -------------------- .github/workflows/test-preprod.yml | 248 -------------------- .github/workflows/test-preview.yml | 248 -------------------- .github/workflows/windows.yml | 31 --- 10 files changed, 46 insertions(+), 1209 deletions(-) delete mode 100644 .github/workflows/codeql.yml delete mode 100644 .github/workflows/linux.yml delete mode 100644 .github/workflows/macos.yml create mode 100644 .github/workflows/main.yml delete mode 100644 .github/workflows/semantic-pull-request.yml delete mode 100644 .github/workflows/test-guild.yml delete mode 100644 .github/workflows/test-mainnet.yml delete mode 100644 .github/workflows/test-preprod.yml delete mode 100644 .github/workflows/test-preview.yml delete mode 100644 .github/workflows/windows.yml diff --git a/.github/workflows/codeql.yml b/.github/workflows/codeql.yml deleted file mode 100644 index 2cdeb92..0000000 --- a/.github/workflows/codeql.yml +++ /dev/null @@ -1,45 +0,0 @@ -name: "CodeQL" - -# Remove default permissions -permissions: {} - -on: - push: - branches: [ main ] - pull_request: - # The branches below must be a subset of the branches above - branches: [ main ] - schedule: - - cron: '30 5 * * 4' - -jobs: - analyze: - name: Analyze - runs-on: ubuntu-latest - permissions: - actions: read - contents: read - security-events: write - - strategy: - fail-fast: false - matrix: - language: [ 'go' ] - - steps: - - name: Checkout repository - uses: actions/checkout@v4 - - # Initializes the CodeQL tools for scanning. - - name: Initialize CodeQL - uses: github/codeql-action/init@v2 - with: - languages: ${{ matrix.language }} - - # Autobuild attempts to build any compiled languages (C/C++, C#, or Java). - # If this step fails, then you should remove it and run the build manually (see below) - - name: Autobuild - uses: github/codeql-action/autobuild@v2 - - - name: Perform CodeQL Analysis - uses: github/codeql-action/analyze@v2 diff --git a/.github/workflows/linux.yml b/.github/workflows/linux.yml deleted file mode 100644 index 24ff75a..0000000 --- a/.github/workflows/linux.yml +++ /dev/null @@ -1,43 +0,0 @@ -name: linux - -on: - push: - branches: - - main - pull_request: - -jobs: - # lint - lint: - runs-on: ubuntu-latest - steps: - - uses: actions/setup-go@v5 - with: - go-version: 1.19 - - uses: actions/checkout@v4 - - name: golangci-lint - uses: golangci/golangci-lint-action@v3 - - test: - runs-on: ubuntu-latest - needs: - - lint - strategy: - matrix: - go: ['1.22', 'tip'] - steps: - - name: Set up Go - uses: actions/setup-go@v5 - with: - go-version: ${{ matrix.go }} - - name: Checkout code - uses: actions/checkout@v4 - - name: Run tests - run: | - go test -v -race -covermode atomic -coverprofile=coverage.txt ./... - - name: Upload coverage - uses: codecov/codecov-action@v4 - with: - flags: linux,local - fail_ci_if_error: true - files: ./coverage.txt diff --git a/.github/workflows/macos.yml b/.github/workflows/macos.yml deleted file mode 100644 index 48be3ea..0000000 --- a/.github/workflows/macos.yml +++ /dev/null @@ -1,30 +0,0 @@ -name: macos - -on: - push: - branches: - - main - pull_request: - -jobs: - test: - runs-on: macos-latest - strategy: - matrix: - go: ['1.18', '1.19'] - steps: - - name: Set up Go - uses: actions/setup-go@v5 - with: - go-version: ${{ matrix.go }} - - name: Checkout code - uses: actions/checkout@v4 - - name: Run tests - run: | - go test -v -race -covermode atomic -coverprofile=coverage.txt ./... - - name: Upload coverage - uses: codecov/codecov-action@v4 - with: - flags: macos,local - fail_ci_if_error: true - files: ./coverage.txt diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml new file mode 100644 index 0000000..0be1487 --- /dev/null +++ b/.github/workflows/main.yml @@ -0,0 +1,46 @@ +name: CI/CD Workflow + +concurrency: + group: main-${{ github.ref }} + cancel-in-progress: true + +on: + push: + branches: + - main + pull_request: + branches: + - main + +jobs: +############################################################################### +# PREREQUISITES + lint: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-go@v5 + with: + go-version: '1.22' + cache: false + - name: golangci-lint + uses: golangci/golangci-lint-action@v4 + with: + version: 'latest' + codeql: + runs-on: ubuntu-latest + timeout-minutes: 60 + permissions: + security-events: write + actions: read + contents: read + steps: + - uses: actions/checkout@v4 + - uses: github/codeql-action/init@v3 + with: + languages: go + - uses: github/codeql-action/autobuild@v3 + - uses: github/codeql-action/analyze@v3 + +############################################################################### +# ... other jobs ... diff --git a/.github/workflows/semantic-pull-request.yml b/.github/workflows/semantic-pull-request.yml deleted file mode 100644 index 8f2c520..0000000 --- a/.github/workflows/semantic-pull-request.yml +++ /dev/null @@ -1,68 +0,0 @@ -name: "Lint PR Conventional Commits" - -on: - pull_request_target: - types: - - opened - - edited - - synchronize - -jobs: - main: - name: Validate PR title - runs-on: ubuntu-latest - steps: - - uses: amannn/action-semantic-pull-request@v5 - env: - GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} - with: - # Configure which types are allowed. - # Default: https://github.com/commitizen/conventional-commit-types - types: | - build - chore - ci - dep - docs - feat - fix - perf - refactor - revert - style - test - # Configure which scopes are allowed. - scopes: | - cli - client - endpoint - godoc - markdown - packaging - # Configure that a scope must always be provided. - requireScope: false - # Configure additional validation for the subject based on a regex. - # This example ensures the subject doesn't start with an uppercase character. - subjectPattern: ^(?![A-Z]).+$ - # If `subjectPattern` is configured, you can use this property to override - # the default error message that is shown when the pattern doesn't match. - # The variables `subject` and `title` can be used within the message. - subjectPatternError: | - The subject "{subject}" found in the pull request title "{title}" - didn't match the configured pattern. Please ensure that the subject - doesn't start with an uppercase character. - # For work-in-progress PRs you can typically use draft pull requests - # from Github. However, private repositories on the free plan don't have - # this option and therefore this action allows you to opt-in to using the - # special "[WIP]" prefix to indicate this state. This will avoid the - # validation of the PR title and the pull request checks remain pending. - # Note that a second check will be reported if this is enabled. - wip: true - # When using "Squash and merge" on a PR with only one commit, GitHub - # will suggest using that commit message instead of the PR title for the - # merge commit, and it's easy to commit this by mistake. Enable this option - # to also validate the commit message for one commit PRs. - validateSingleCommit: true - # Related to `validateSingleCommit` you can opt-in to validate that the PR - # title matches a single commit to avoid confusion. - validateSingleCommitMatchesPrTitle: true diff --git a/.github/workflows/test-guild.yml b/.github/workflows/test-guild.yml deleted file mode 100644 index 37bd0e4..0000000 --- a/.github/workflows/test-guild.yml +++ /dev/null @@ -1,248 +0,0 @@ -name: guild - -on: - push: - branches: - - main - schedule: - - cron: '0 0 * * *' # every day at midnight - -env: - KOIOS_NETWORK: guild - -jobs: - network: - runs-on: ubuntu-latest - needs: - # just to limit concurrent check groups to 3 - - transactions - strategy: - matrix: - test: - - NetworkTip - - NetworkGenesis - - NetworkTotals - steps: - - uses: actions/setup-go@v5 - with: - go-version: 1.19 - - uses: actions/checkout@v4 - - run: go test -v -covermode atomic -coverprofile coverage.txt -run ^Test${{ matrix.test }}$ - - name: Upload coverage - uses: codecov/codecov-action@v4 - with: - flags: "${{ env.KOIOS_NETWORK }},${{ github.job }},${{ matrix.test }}" - name: "${{ env.KOIOS_NETWORK }}-${{ github.job }}-${{ matrix.test }}" - files: ./coverage.txt - env_vars: KOIOS_NETWORK - - epoch: - runs-on: ubuntu-latest - strategy: - matrix: - test: - - EpochInfo - - EpochParams - - EpochBlockProtocols - steps: - - uses: actions/setup-go@v5 - with: - go-version: 1.19 - - uses: actions/checkout@v4 - - run: go test -v -covermode atomic -coverprofile coverage.txt -run ^Test${{ matrix.test }}$ - - name: Upload coverage - uses: codecov/codecov-action@v4 - with: - flags: "${{ env.KOIOS_NETWORK }},${{ github.job }},${{ matrix.test }}" - name: "${{ env.KOIOS_NETWORK }}-${{ github.job }}-${{ matrix.test }}" - files: ./coverage.txt - env_vars: KOIOS_NETWORK - - blocks: - runs-on: ubuntu-latest - strategy: - matrix: - test: - - Blocks - - BlockInfo - - BlockTxs - steps: - - uses: actions/setup-go@v5 - with: - go-version: 1.19 - - uses: actions/checkout@v4 - - run: go test -v -covermode atomic -coverprofile coverage.txt -run ^Test${{ matrix.test }}$ - - name: Upload coverage - uses: codecov/codecov-action@v4 - with: - flags: "${{ env.KOIOS_NETWORK }},${{ github.job }},${{ matrix.test }}" - name: "${{ env.KOIOS_NETWORK }}-${{ github.job }}-${{ matrix.test }}" - files: ./coverage.txt - env_vars: KOIOS_NETWORK - - transactions: - runs-on: ubuntu-latest - strategy: - matrix: - test: - - TxInfo - - TxUTxO - - TxMetadata - - TxMetaLabels - - TxStatus - steps: - - uses: actions/setup-go@v5 - with: - go-version: 1.19 - - uses: actions/checkout@v4 - - run: go test -v -covermode atomic -coverprofile coverage.txt -run ^Test${{ matrix.test }}$ - - name: Upload coverage - uses: codecov/codecov-action@v4 - with: - flags: "${{ env.KOIOS_NETWORK }},${{ github.job }},${{ matrix.test }}" - name: "${{ env.KOIOS_NETWORK }}-${{ github.job }}-${{ matrix.test }}" - files: ./coverage.txt - env_vars: KOIOS_NETWORK - - address: - runs-on: ubuntu-latest - needs: - # just to limit concurrent check groups to 3 - - epoch - strategy: - matrix: - test: - - AddressInfo - - AddressTxs - - AddressAssets - - CredentialTxs - steps: - - uses: actions/setup-go@v5 - with: - go-version: 1.19 - - uses: actions/checkout@v4 - - run: go test -v -covermode atomic -coverprofile coverage.txt -run ^Test${{ matrix.test }}$ - - name: Upload coverage - uses: codecov/codecov-action@v4 - with: - flags: "${{ env.KOIOS_NETWORK }},${{ github.job }},${{ matrix.test }}" - name: "${{ env.KOIOS_NETWORK }}-${{ github.job }}-${{ matrix.test }}" - files: ./coverage.txt - env_vars: KOIOS_NETWORK - - account: - runs-on: ubuntu-latest - needs: - # just to limit concurrent check groups to 3 - - blocks - strategy: - matrix: - test: - - Accounts - - AccountInfo - - AccountInfoCached - - AccountRewards - - AccountUpdates - - AccountAddresses - - AccountAssets - - AccountHistory - steps: - - uses: actions/setup-go@v5 - with: - go-version: 1.19 - - uses: actions/checkout@v4 - - run: go test -v -covermode atomic -coverprofile coverage.txt -run ^Test${{ matrix.test }}$ - - name: Upload coverage - uses: codecov/codecov-action@v4 - with: - flags: "${{ env.KOIOS_NETWORK }},${{ github.job }},${{ matrix.test }}" - name: "${{ env.KOIOS_NETWORK }}-${{ github.job }}-${{ matrix.test }}" - files: ./coverage.txt - env_vars: KOIOS_NETWORK - - assets: - runs-on: ubuntu-latest - needs: - # just to limit concurrent check groups to 3 - - account - strategy: - matrix: - test: - - Assets - - AssetAddresses - - AssetInfo - - AssetHistory - - AssetPolicyInfo - - AssetSummary - - AssetTxs - steps: - - uses: actions/setup-go@v5 - with: - go-version: 1.19 - - uses: actions/checkout@v4 - - run: go test -v -covermode atomic -coverprofile coverage.txt -run ^Test${{ matrix.test }}$ - - name: Upload coverage - uses: codecov/codecov-action@v4 - with: - flags: "${{ env.KOIOS_NETWORK }},${{ github.job }},${{ matrix.test }}" - name: "${{ env.KOIOS_NETWORK }}-${{ github.job }}-${{ matrix.test }}" - files: ./coverage.txt - env_vars: KOIOS_NETWORK - - pool: - runs-on: ubuntu-latest - needs: - # just to limit concurrent check groups to 3 - - address - strategy: - matrix: - test: - - Pools - - PoolInfo - - PoolSnapshot - - PoolDelegators - - PoolDelegatorsHistory - - PoolBlocks - - PoolHistory - - PoolUpdates - - PoolRelays - - PoolMetadata - steps: - - uses: actions/setup-go@v5 - with: - go-version: 1.19 - - uses: actions/checkout@v4 - - run: go test -v -covermode atomic -coverprofile coverage.txt -run ^Test${{ matrix.test }}$ - - name: Upload coverage - uses: codecov/codecov-action@v4 - with: - flags: "${{ env.KOIOS_NETWORK }},${{ github.job }},${{ matrix.test }}" - name: "${{ env.KOIOS_NETWORK }}-${{ github.job }}-${{ matrix.test }}" - files: ./coverage.txt - env_vars: KOIOS_NETWORK - - scripts: - runs-on: ubuntu-latest - needs: - # just to limit concurrent check groups to 3 - - address - strategy: - matrix: - test: - - NativeScriptList - - PlutusScriptList - - ScriptRedeemers - - DatumInfo - steps: - - uses: actions/setup-go@v5 - with: - go-version: 1.19 - - uses: actions/checkout@v4 - - run: go test -v -covermode atomic -coverprofile coverage.txt -run ^Test${{ matrix.test }}$ - - name: Upload coverage - uses: codecov/codecov-action@v4 - with: - flags: "${{ env.KOIOS_NETWORK }},${{ github.job }},${{ matrix.test }}" - name: "${{ env.KOIOS_NETWORK }}-${{ github.job }}-${{ matrix.test }}" - files: ./coverage.txt - env_vars: KOIOS_NETWORK diff --git a/.github/workflows/test-mainnet.yml b/.github/workflows/test-mainnet.yml deleted file mode 100644 index 428d18b..0000000 --- a/.github/workflows/test-mainnet.yml +++ /dev/null @@ -1,248 +0,0 @@ -name: mainnet - -on: - push: - branches: - - main - schedule: - - cron: '0 0 * * *' # every day at midnight - -env: - KOIOS_NETWORK: mainnet - -jobs: - network: - runs-on: ubuntu-latest - needs: - # just to limit concurrent check groups to 3 - - transactions - strategy: - matrix: - test: - - NetworkTip - - NetworkGenesis - - NetworkTotals - steps: - - uses: actions/setup-go@v5 - with: - go-version: 1.19 - - uses: actions/checkout@v4 - - run: go test -v -covermode atomic -coverprofile coverage.txt -run ^Test${{ matrix.test }}$ - - name: Upload coverage - uses: codecov/codecov-action@v4 - with: - flags: "${{ env.KOIOS_NETWORK }},${{ github.job }},${{ matrix.test }}" - name: "${{ env.KOIOS_NETWORK }}-${{ github.job }}-${{ matrix.test }}" - files: ./coverage.txt - env_vars: KOIOS_NETWORK - - epoch: - runs-on: ubuntu-latest - strategy: - matrix: - test: - - EpochInfo - - EpochParams - - EpochBlockProtocols - steps: - - uses: actions/setup-go@v5 - with: - go-version: 1.19 - - uses: actions/checkout@v4 - - run: go test -v -covermode atomic -coverprofile coverage.txt -run ^Test${{ matrix.test }}$ - - name: Upload coverage - uses: codecov/codecov-action@v4 - with: - flags: "${{ env.KOIOS_NETWORK }},${{ github.job }},${{ matrix.test }}" - name: "${{ env.KOIOS_NETWORK }}-${{ github.job }}-${{ matrix.test }}" - files: ./coverage.txt - env_vars: KOIOS_NETWORK - - blocks: - runs-on: ubuntu-latest - strategy: - matrix: - test: - - Blocks - - BlockInfo - - BlockTxs - steps: - - uses: actions/setup-go@v5 - with: - go-version: 1.19 - - uses: actions/checkout@v4 - - run: go test -v -covermode atomic -coverprofile coverage.txt -run ^Test${{ matrix.test }}$ - - name: Upload coverage - uses: codecov/codecov-action@v4 - with: - flags: "${{ env.KOIOS_NETWORK }},${{ github.job }},${{ matrix.test }}" - name: "${{ env.KOIOS_NETWORK }}-${{ github.job }}-${{ matrix.test }}" - files: ./coverage.txt - env_vars: KOIOS_NETWORK - - transactions: - runs-on: ubuntu-latest - strategy: - matrix: - test: - - TxInfo - - TxUTxO - - TxMetadata - - TxMetaLabels - - TxStatus - steps: - - uses: actions/setup-go@v5 - with: - go-version: 1.19 - - uses: actions/checkout@v4 - - run: go test -v -covermode atomic -coverprofile coverage.txt -run ^Test${{ matrix.test }}$ - - name: Upload coverage - uses: codecov/codecov-action@v4 - with: - flags: "${{ env.KOIOS_NETWORK }},${{ github.job }},${{ matrix.test }}" - name: "${{ env.KOIOS_NETWORK }}-${{ github.job }}-${{ matrix.test }}" - files: ./coverage.txt - env_vars: KOIOS_NETWORK - - address: - runs-on: ubuntu-latest - needs: - # just to limit concurrent check groups to 3 - - epoch - strategy: - matrix: - test: - - AddressInfo - - AddressTxs - - AddressAssets - - CredentialTxs - steps: - - uses: actions/setup-go@v5 - with: - go-version: 1.19 - - uses: actions/checkout@v4 - - run: go test -v -covermode atomic -coverprofile coverage.txt -run ^Test${{ matrix.test }}$ - - name: Upload coverage - uses: codecov/codecov-action@v4 - with: - flags: "${{ env.KOIOS_NETWORK }},${{ github.job }},${{ matrix.test }}" - name: "${{ env.KOIOS_NETWORK }}-${{ github.job }}-${{ matrix.test }}" - files: ./coverage.txt - env_vars: KOIOS_NETWORK - - account: - runs-on: ubuntu-latest - needs: - # just to limit concurrent check groups to 3 - - blocks - strategy: - matrix: - test: - - Accounts - - AccountInfo - - AccountInfoCached - - AccountRewards - - AccountUpdates - - AccountAddresses - - AccountAssets - - AccountHistory - steps: - - uses: actions/setup-go@v5 - with: - go-version: 1.19 - - uses: actions/checkout@v4 - - run: go test -v -covermode atomic -coverprofile coverage.txt -run ^Test${{ matrix.test }}$ - - name: Upload coverage - uses: codecov/codecov-action@v4 - with: - flags: "${{ env.KOIOS_NETWORK }},${{ github.job }},${{ matrix.test }}" - name: "${{ env.KOIOS_NETWORK }}-${{ github.job }}-${{ matrix.test }}" - files: ./coverage.txt - env_vars: KOIOS_NETWORK - - assets: - runs-on: ubuntu-latest - needs: - # just to limit concurrent check groups to 3 - - account - strategy: - matrix: - test: - - Assets - - AssetAddresses - - AssetInfo - - AssetHistory - - AssetPolicyInfo - - AssetSummary - - AssetTxs - steps: - - uses: actions/setup-go@v5 - with: - go-version: 1.19 - - uses: actions/checkout@v4 - - run: go test -v -covermode atomic -coverprofile coverage.txt -run ^Test${{ matrix.test }}$ - - name: Upload coverage - uses: codecov/codecov-action@v4 - with: - flags: "${{ env.KOIOS_NETWORK }},${{ github.job }},${{ matrix.test }}" - name: "${{ env.KOIOS_NETWORK }}-${{ github.job }}-${{ matrix.test }}" - files: ./coverage.txt - env_vars: KOIOS_NETWORK - - pool: - runs-on: ubuntu-latest - needs: - # just to limit concurrent check groups to 3 - - address - strategy: - matrix: - test: - - Pools - - PoolInfo - - PoolSnapshot - - PoolDelegators - - PoolDelegatorsHistory - - PoolBlocks - - PoolHistory - - PoolUpdates - - PoolRelays - - PoolMetadata - steps: - - uses: actions/setup-go@v5 - with: - go-version: 1.19 - - uses: actions/checkout@v4 - - run: go test -v -covermode atomic -coverprofile coverage.txt -run ^Test${{ matrix.test }}$ - - name: Upload coverage - uses: codecov/codecov-action@v4 - with: - flags: "${{ env.KOIOS_NETWORK }},${{ github.job }},${{ matrix.test }}" - name: "${{ env.KOIOS_NETWORK }}-${{ github.job }}-${{ matrix.test }}" - files: ./coverage.txt - env_vars: KOIOS_NETWORK - - scripts: - runs-on: ubuntu-latest - needs: - # just to limit concurrent check groups to 3 - - address - strategy: - matrix: - test: - - NativeScriptList - - PlutusScriptList - - ScriptRedeemers - - DatumInfo - steps: - - uses: actions/setup-go@v5 - with: - go-version: 1.19 - - uses: actions/checkout@v4 - - run: go test -v -covermode atomic -coverprofile coverage.txt -run ^Test${{ matrix.test }}$ - - name: Upload coverage - uses: codecov/codecov-action@v4 - with: - flags: "${{ env.KOIOS_NETWORK }},${{ github.job }},${{ matrix.test }}" - name: "${{ env.KOIOS_NETWORK }}-${{ github.job }}-${{ matrix.test }}" - files: ./coverage.txt - env_vars: KOIOS_NETWORK diff --git a/.github/workflows/test-preprod.yml b/.github/workflows/test-preprod.yml deleted file mode 100644 index 8a99c52..0000000 --- a/.github/workflows/test-preprod.yml +++ /dev/null @@ -1,248 +0,0 @@ -name: preprod - -on: - push: - branches: - - main - schedule: - - cron: '0 0 * * *' # every day at midnight - -env: - KOIOS_NETWORK: preprod - -jobs: - network: - runs-on: ubuntu-latest - needs: - # just to limit concurrent check groups to 3 - - transactions - strategy: - matrix: - test: - - NetworkTip - - NetworkGenesis - - NetworkTotals - steps: - - uses: actions/setup-go@v5 - with: - go-version: 1.19 - - uses: actions/checkout@v4 - - run: go test -v -covermode atomic -coverprofile coverage.txt -run ^Test${{ matrix.test }}$ - - name: Upload coverage - uses: codecov/codecov-action@v4 - with: - flags: "${{ env.KOIOS_NETWORK }},${{ github.job }},${{ matrix.test }}" - name: "${{ env.KOIOS_NETWORK }}-${{ github.job }}-${{ matrix.test }}" - files: ./coverage.txt - env_vars: KOIOS_NETWORK - - epoch: - runs-on: ubuntu-latest - strategy: - matrix: - test: - - EpochInfo - - EpochParams - - EpochBlockProtocols - steps: - - uses: actions/setup-go@v5 - with: - go-version: 1.19 - - uses: actions/checkout@v4 - - run: go test -v -covermode atomic -coverprofile coverage.txt -run ^Test${{ matrix.test }}$ - - name: Upload coverage - uses: codecov/codecov-action@v4 - with: - flags: "${{ env.KOIOS_NETWORK }},${{ github.job }},${{ matrix.test }}" - name: "${{ env.KOIOS_NETWORK }}-${{ github.job }}-${{ matrix.test }}" - files: ./coverage.txt - env_vars: KOIOS_NETWORK - - blocks: - runs-on: ubuntu-latest - strategy: - matrix: - test: - - Blocks - - BlockInfo - - BlockTxs - steps: - - uses: actions/setup-go@v5 - with: - go-version: 1.19 - - uses: actions/checkout@v4 - - run: go test -v -covermode atomic -coverprofile coverage.txt -run ^Test${{ matrix.test }}$ - - name: Upload coverage - uses: codecov/codecov-action@v4 - with: - flags: "${{ env.KOIOS_NETWORK }},${{ github.job }},${{ matrix.test }}" - name: "${{ env.KOIOS_NETWORK }}-${{ github.job }}-${{ matrix.test }}" - files: ./coverage.txt - env_vars: KOIOS_NETWORK - - transactions: - runs-on: ubuntu-latest - strategy: - matrix: - test: - - TxInfo - - TxUTxO - - TxMetadata - - TxMetaLabels - - TxStatus - steps: - - uses: actions/setup-go@v5 - with: - go-version: 1.19 - - uses: actions/checkout@v4 - - run: go test -v -covermode atomic -coverprofile coverage.txt -run ^Test${{ matrix.test }}$ - - name: Upload coverage - uses: codecov/codecov-action@v4 - with: - flags: "${{ env.KOIOS_NETWORK }},${{ github.job }},${{ matrix.test }}" - name: "${{ env.KOIOS_NETWORK }}-${{ github.job }}-${{ matrix.test }}" - files: ./coverage.txt - env_vars: KOIOS_NETWORK - - address: - runs-on: ubuntu-latest - needs: - # just to limit concurrent check groups to 3 - - epoch - strategy: - matrix: - test: - - AddressInfo - - AddressTxs - - AddressAssets - - CredentialTxs - steps: - - uses: actions/setup-go@v5 - with: - go-version: 1.19 - - uses: actions/checkout@v4 - - run: go test -v -covermode atomic -coverprofile coverage.txt -run ^Test${{ matrix.test }}$ - - name: Upload coverage - uses: codecov/codecov-action@v4 - with: - flags: "${{ env.KOIOS_NETWORK }},${{ github.job }},${{ matrix.test }}" - name: "${{ env.KOIOS_NETWORK }}-${{ github.job }}-${{ matrix.test }}" - files: ./coverage.txt - env_vars: KOIOS_NETWORK - - account: - runs-on: ubuntu-latest - needs: - # just to limit concurrent check groups to 3 - - blocks - strategy: - matrix: - test: - - Accounts - - AccountInfo - - AccountInfoCached - - AccountRewards - - AccountUpdates - - AccountAddresses - - AccountAssets - - AccountHistory - steps: - - uses: actions/setup-go@v5 - with: - go-version: 1.19 - - uses: actions/checkout@v4 - - run: go test -v -covermode atomic -coverprofile coverage.txt -run ^Test${{ matrix.test }}$ - - name: Upload coverage - uses: codecov/codecov-action@v4 - with: - flags: "${{ env.KOIOS_NETWORK }},${{ github.job }},${{ matrix.test }}" - name: "${{ env.KOIOS_NETWORK }}-${{ github.job }}-${{ matrix.test }}" - files: ./coverage.txt - env_vars: KOIOS_NETWORK - - assets: - runs-on: ubuntu-latest - needs: - # just to limit concurrent check groups to 3 - - account - strategy: - matrix: - test: - - Assets - - AssetAddresses - - AssetInfo - - AssetHistory - - AssetPolicyInfo - - AssetSummary - - AssetTxs - steps: - - uses: actions/setup-go@v5 - with: - go-version: 1.19 - - uses: actions/checkout@v4 - - run: go test -v -covermode atomic -coverprofile coverage.txt -run ^Test${{ matrix.test }}$ - - name: Upload coverage - uses: codecov/codecov-action@v4 - with: - flags: "${{ env.KOIOS_NETWORK }},${{ github.job }},${{ matrix.test }}" - name: "${{ env.KOIOS_NETWORK }}-${{ github.job }}-${{ matrix.test }}" - files: ./coverage.txt - env_vars: KOIOS_NETWORK - - pool: - runs-on: ubuntu-latest - needs: - # just to limit concurrent check groups to 3 - - address - strategy: - matrix: - test: - - Pools - - PoolInfo - - PoolSnapshot - - PoolDelegators - - PoolDelegatorsHistory - - PoolBlocks - - PoolHistory - - PoolUpdates - - PoolRelays - - PoolMetadata - steps: - - uses: actions/setup-go@v5 - with: - go-version: 1.19 - - uses: actions/checkout@v4 - - run: go test -v -covermode atomic -coverprofile coverage.txt -run ^Test${{ matrix.test }}$ - - name: Upload coverage - uses: codecov/codecov-action@v4 - with: - flags: "${{ env.KOIOS_NETWORK }},${{ github.job }},${{ matrix.test }}" - name: "${{ env.KOIOS_NETWORK }}-${{ github.job }}-${{ matrix.test }}" - files: ./coverage.txt - env_vars: KOIOS_NETWORK - - scripts: - runs-on: ubuntu-latest - needs: - # just to limit concurrent check groups to 3 - - address - strategy: - matrix: - test: - - NativeScriptList - - PlutusScriptList - - ScriptRedeemers - - DatumInfo - steps: - - uses: actions/setup-go@v5 - with: - go-version: 1.19 - - uses: actions/checkout@v4 - - run: go test -v -covermode atomic -coverprofile coverage.txt -run ^Test${{ matrix.test }}$ - - name: Upload coverage - uses: codecov/codecov-action@v4 - with: - flags: "${{ env.KOIOS_NETWORK }},${{ github.job }},${{ matrix.test }}" - name: "${{ env.KOIOS_NETWORK }}-${{ github.job }}-${{ matrix.test }}" - files: ./coverage.txt - env_vars: KOIOS_NETWORK diff --git a/.github/workflows/test-preview.yml b/.github/workflows/test-preview.yml deleted file mode 100644 index 35f5c66..0000000 --- a/.github/workflows/test-preview.yml +++ /dev/null @@ -1,248 +0,0 @@ -name: preview - -on: - push: - branches: - - main - schedule: - - cron: '0 0 * * *' # every day at midnight - -env: - KOIOS_NETWORK: preview - -jobs: - network: - runs-on: ubuntu-latest - needs: - # just to limit concurrent check groups to 3 - - transactions - strategy: - matrix: - test: - - NetworkTip - - NetworkGenesis - - NetworkTotals - steps: - - uses: actions/setup-go@v5 - with: - go-version: 1.19 - - uses: actions/checkout@v4 - - run: go test -v -covermode atomic -coverprofile coverage.txt -run ^Test${{ matrix.test }}$ - - name: Upload coverage - uses: codecov/codecov-action@v4 - with: - flags: "${{ env.KOIOS_NETWORK }},${{ github.job }},${{ matrix.test }}" - name: "${{ env.KOIOS_NETWORK }}-${{ github.job }}-${{ matrix.test }}" - files: ./coverage.txt - env_vars: KOIOS_NETWORK - - epoch: - runs-on: ubuntu-latest - strategy: - matrix: - test: - - EpochInfo - - EpochParams - - EpochBlockProtocols - steps: - - uses: actions/setup-go@v5 - with: - go-version: 1.19 - - uses: actions/checkout@v4 - - run: go test -v -covermode atomic -coverprofile coverage.txt -run ^Test${{ matrix.test }}$ - - name: Upload coverage - uses: codecov/codecov-action@v4 - with: - flags: "${{ env.KOIOS_NETWORK }},${{ github.job }},${{ matrix.test }}" - name: "${{ env.KOIOS_NETWORK }}-${{ github.job }}-${{ matrix.test }}" - files: ./coverage.txt - env_vars: KOIOS_NETWORK - - blocks: - runs-on: ubuntu-latest - strategy: - matrix: - test: - - Blocks - - BlockInfo - - BlockTxs - steps: - - uses: actions/setup-go@v5 - with: - go-version: 1.19 - - uses: actions/checkout@v4 - - run: go test -v -covermode atomic -coverprofile coverage.txt -run ^Test${{ matrix.test }}$ - - name: Upload coverage - uses: codecov/codecov-action@v4 - with: - flags: "${{ env.KOIOS_NETWORK }},${{ github.job }},${{ matrix.test }}" - name: "${{ env.KOIOS_NETWORK }}-${{ github.job }}-${{ matrix.test }}" - files: ./coverage.txt - env_vars: KOIOS_NETWORK - - transactions: - runs-on: ubuntu-latest - strategy: - matrix: - test: - - TxInfo - - TxUTxO - - TxMetadata - - TxMetaLabels - - TxStatus - steps: - - uses: actions/setup-go@v5 - with: - go-version: 1.19 - - uses: actions/checkout@v4 - - run: go test -v -covermode atomic -coverprofile coverage.txt -run ^Test${{ matrix.test }}$ - - name: Upload coverage - uses: codecov/codecov-action@v4 - with: - flags: "${{ env.KOIOS_NETWORK }},${{ github.job }},${{ matrix.test }}" - name: "${{ env.KOIOS_NETWORK }}-${{ github.job }}-${{ matrix.test }}" - files: ./coverage.txt - env_vars: KOIOS_NETWORK - - address: - runs-on: ubuntu-latest - needs: - # just to limit concurrent check groups to 3 - - epoch - strategy: - matrix: - test: - - AddressInfo - - AddressTxs - - AddressAssets - - CredentialTxs - steps: - - uses: actions/setup-go@v5 - with: - go-version: 1.19 - - uses: actions/checkout@v4 - - run: go test -v -covermode atomic -coverprofile coverage.txt -run ^Test${{ matrix.test }}$ - - name: Upload coverage - uses: codecov/codecov-action@v4 - with: - flags: "${{ env.KOIOS_NETWORK }},${{ github.job }},${{ matrix.test }}" - name: "${{ env.KOIOS_NETWORK }}-${{ github.job }}-${{ matrix.test }}" - files: ./coverage.txt - env_vars: KOIOS_NETWORK - - account: - runs-on: ubuntu-latest - needs: - # just to limit concurrent check groups to 3 - - blocks - strategy: - matrix: - test: - - Accounts - - AccountInfo - - AccountInfoCached - - AccountRewards - - AccountUpdates - - AccountAddresses - - AccountAssets - - AccountHistory - steps: - - uses: actions/setup-go@v5 - with: - go-version: 1.19 - - uses: actions/checkout@v4 - - run: go test -v -covermode atomic -coverprofile coverage.txt -run ^Test${{ matrix.test }}$ - - name: Upload coverage - uses: codecov/codecov-action@v4 - with: - flags: "${{ env.KOIOS_NETWORK }},${{ github.job }},${{ matrix.test }}" - name: "${{ env.KOIOS_NETWORK }}-${{ github.job }}-${{ matrix.test }}" - files: ./coverage.txt - env_vars: KOIOS_NETWORK - - assets: - runs-on: ubuntu-latest - needs: - # just to limit concurrent check groups to 3 - - account - strategy: - matrix: - test: - - Assets - - AssetAddresses - - AssetInfo - - AssetHistory - - AssetPolicyInfo - - AssetSummary - - AssetTxs - steps: - - uses: actions/setup-go@v5 - with: - go-version: 1.19 - - uses: actions/checkout@v4 - - run: go test -v -covermode atomic -coverprofile coverage.txt -run ^Test${{ matrix.test }}$ - - name: Upload coverage - uses: codecov/codecov-action@v4 - with: - flags: "${{ env.KOIOS_NETWORK }},${{ github.job }},${{ matrix.test }}" - name: "${{ env.KOIOS_NETWORK }}-${{ github.job }}-${{ matrix.test }}" - files: ./coverage.txt - env_vars: KOIOS_NETWORK - - pool: - runs-on: ubuntu-latest - needs: - # just to limit concurrent check groups to 3 - - address - strategy: - matrix: - test: - - Pools - - PoolInfo - - PoolSnapshot - - PoolDelegators - - PoolDelegatorsHistory - - PoolBlocks - - PoolHistory - - PoolUpdates - - PoolRelays - - PoolMetadata - steps: - - uses: actions/setup-go@v5 - with: - go-version: 1.19 - - uses: actions/checkout@v4 - - run: go test -v -covermode atomic -coverprofile coverage.txt -run ^Test${{ matrix.test }}$ - - name: Upload coverage - uses: codecov/codecov-action@v4 - with: - flags: "${{ env.KOIOS_NETWORK }},${{ github.job }},${{ matrix.test }}" - name: "${{ env.KOIOS_NETWORK }}-${{ github.job }}-${{ matrix.test }}" - files: ./coverage.txt - env_vars: KOIOS_NETWORK - - scripts: - runs-on: ubuntu-latest - needs: - # just to limit concurrent check groups to 3 - - address - strategy: - matrix: - test: - - NativeScriptList - - PlutusScriptList - - ScriptRedeemers - - DatumInfo - steps: - - uses: actions/setup-go@v5 - with: - go-version: 1.19 - - uses: actions/checkout@v4 - - run: go test -v -covermode atomic -coverprofile coverage.txt -run ^Test${{ matrix.test }}$ - - name: Upload coverage - uses: codecov/codecov-action@v4 - with: - flags: "${{ env.KOIOS_NETWORK }},${{ github.job }},${{ matrix.test }}" - name: "${{ env.KOIOS_NETWORK }}-${{ github.job }}-${{ matrix.test }}" - files: ./coverage.txt - env_vars: KOIOS_NETWORK diff --git a/.github/workflows/windows.yml b/.github/workflows/windows.yml deleted file mode 100644 index 716223d..0000000 --- a/.github/workflows/windows.yml +++ /dev/null @@ -1,31 +0,0 @@ -name: windows - -on: - push: - branches: - - main - pull_request: - -jobs: - test: - runs-on: windows-latest - strategy: - matrix: - go: ['1.18', '1.19'] - steps: - - name: Set up Go - uses: actions/setup-go@v5 - with: - go-version: ${{ matrix.go }} - - name: Checkout code - uses: actions/checkout@v4 - - name: Run tests - run: | - go mod download -x - go test -v -race -coverprofile coverage.coverprofile -covermode atomic ./... - - name: Upload coverage - uses: codecov/codecov-action@v4 - with: - flags: windows,local - fail_ci_if_error: true - files: ./coverage.coverprofile From 00a4051eb925a5bb0984f5b360291953046e0370 Mon Sep 17 00:00:00 2001 From: Marko Kungla Date: Tue, 27 Feb 2024 19:23:02 +0200 Subject: [PATCH 06/65] feat: replace LibraryVersion with Version() to get library version sets library version from package version instead of hardcoded const Signed-off-by: Marko Kungla --- go.mod | 2 ++ go.sum | 4 ++++ koios.go | 61 ++++++++++++++++++++++++++++++--------------------- koios_test.go | 5 +++++ 4 files changed, 47 insertions(+), 25 deletions(-) diff --git a/go.mod b/go.mod index 37c03ba..91543f0 100644 --- a/go.mod +++ b/go.mod @@ -3,6 +3,7 @@ module github.com/cardano-community/koios-go-client/v4 // imports as package "ko go 1.22 require ( + github.com/happy-sdk/happy/pkg/version v0.1.2 github.com/shopspring/decimal v1.3.1 github.com/stretchr/testify v1.8.4 golang.org/x/text v0.14.0 @@ -12,5 +13,6 @@ require ( require ( github.com/davecgh/go-spew v1.1.1 // indirect github.com/pmezard/go-difflib v1.0.0 // indirect + golang.org/x/mod v0.15.0 // indirect gopkg.in/yaml.v3 v3.0.1 // indirect ) diff --git a/go.sum b/go.sum index b07c171..3958049 100644 --- a/go.sum +++ b/go.sum @@ -1,11 +1,15 @@ github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/happy-sdk/happy/pkg/version v0.1.2 h1:8DJ0afkEVW2fdm1uEScTS4wPgGe0Tmls3QPuX7jrbhY= +github.com/happy-sdk/happy/pkg/version v0.1.2/go.mod h1:mFhI4DRvXZ8Ls8D5/aXIqcMnjCUBNtI3Ye9ilYL2Bz0= github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= github.com/shopspring/decimal v1.3.1 h1:2Usl1nmF/WZucqkFZhnfFYxxxu8LG21F6nPQBE5gKV8= github.com/shopspring/decimal v1.3.1/go.mod h1:DKyhrW/HYNuLGql+MJL6WCR6knT2jwCFRcu2hWCYk4o= github.com/stretchr/testify v1.8.4 h1:CcVxjf3Q8PM0mHUKJCdn+eZZtm5yQwehR5yeSVQQcUk= github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo= +golang.org/x/mod v0.15.0 h1:SernR4v+D55NyBH2QiEQrlBAnj1ECL6AGrA5+dPaMY8= +golang.org/x/mod v0.15.0/go.mod h1:hTbmBsO62+eylJbnUtE2MGJUyE7QWk4xUqPFrRgJ+7c= golang.org/x/text v0.14.0 h1:ScX5w1eTa3QqT8oi6+ziP7dTV1S2+ALU0bI+0zXKWiQ= golang.org/x/text v0.14.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU= golang.org/x/time v0.5.0 h1:o7cqy6amK/52YcAKIPlM3a+Fpj35zvRj2TP+e1xFSfk= diff --git a/koios.go b/koios.go index 7c10859..63bbf61 100644 --- a/koios.go +++ b/koios.go @@ -19,34 +19,35 @@ import ( "strings" "time" + "github.com/happy-sdk/happy/pkg/version" "github.com/shopspring/decimal" "golang.org/x/text/cases" "golang.org/x/text/language" ) -// MainnetHost : is primay and default api host. -// GuildnetHost : is Guild network host. -// PreviewHost : is Preview network host. -// PreProdHost : is Pre Production network host. -// DefaultAPIVersion : is openapi spec version e.g. /v0. -// DefaultPort : default port used by api client. -// DefaultSchema : default schema used by api client. -// LibraryVersion : koios go library version. -// DefaultRateLimit : is default rate limit used by api client. -// DefaultOrigin : is default origin header used by api client. const ( - MainnetHost = "api.koios.rest" - MainnetHostEU = "eu-api.koios.rest" - GuildHost = "guild.koios.rest" - PreviewHost = "preview.koios.rest" - PreProdHost = "preprod.koios.rest" - DefaultAPIVersion = "v1" - DefaultPort uint16 = 443 - DefaultScheme = "https" - LibraryVersion = "v0" - DefaultRateLimit int = 10 // https://api.koios.rest/#overview--limits - DefaultOrigin = "https://github.com/cardano-community/koios-go-client@v4" - PageSize uint = 1000 + // MainnetHost is primay and default api host. + MainnetHost = "api.koios.rest" + // MainnetHostEU is main net api host in EU. + MainnetHostEU = "eu-api.koios.rest" + // GuildnetHost is Guild network host. + GuildHost = "guild.koios.rest" + // PreviewHost is Preview network host. + PreviewHost = "preview.koios.rest" + // PreProdHost is Pre Production network host. + PreProdHost = "preprod.koios.rest" + // DefaultAPIVersion is openapi spec version e.g. /v1. + DefaultAPIVersion = "v1" + // DefaultPort default port used by api client. + DefaultPort uint16 = 443 + // DefaultSchema default schema used by api client. + DefaultScheme = "https" + // DefaultRateLimit is default rate limit used by api client. + DefaultRateLimit int = 10 // https://api.koios.rest/#overview--limits + // DefaultOrigin is default origin header used by api client. + DefaultOrigin = "https://github.com/cardano-community/koios-go-client/v4" + // PageSize is default page size used by api client. + PageSize uint = 1000 ) // Predefined errors used by the library. @@ -74,8 +75,6 @@ var ( ZeroCoin = decimal.Zero.Copy() //nolint: gochecknoglobals ) -// introduces breaking change since v1.3.0 - type ( Slot uint @@ -212,7 +211,7 @@ func New(opts ...Option) (*Client, error) { "User-Agent", fmt.Sprintf( "go-koios/%s (%s %s) %s/%s https://github.com/cardano-community/go-koios", - LibraryVersion, + Version(), cases.Title(language.English).String(runtime.GOOS), runtime.GOARCH, runtime.GOOS, @@ -247,6 +246,18 @@ func New(opts ...Option) (*Client, error) { return c, nil } +// Version returns koios go library version +func Version() string { + return libraryVersion +} + +var libraryVersion string + +func init() { + v := version.Current() + libraryVersion = v.String() +} + // String returns PaymentCredential as string. func (v PaymentCredential) String() string { return string(v) diff --git a/koios_test.go b/koios_test.go index 23b88c2..c1cb00f 100644 --- a/koios_test.go +++ b/koios_test.go @@ -20,6 +20,7 @@ import ( "errors" "fmt" "os" + "testing" "github.com/cardano-community/koios-go-client/v4" "github.com/shopspring/decimal" @@ -414,3 +415,7 @@ func testIsLocal(t TestingT, err error) bool { t.Error(err) return false } + +func TestVersion(t *testing.T) { + assertNotEmpty(t, koios.Version(), "koios.Version()") +} From 5d4832bcd49acc717a400775730b38cf74e8450f Mon Sep 17 00:00:00 2001 From: Marko Kungla Date: Tue, 27 Feb 2024 19:36:38 +0200 Subject: [PATCH 07/65] test: disable obsolete tests Signed-off-by: Marko Kungla --- .github/workflows/{main.yml => ci.yml} | 2 +- account_test.go | 430 +++++++------ address_test.go | 205 +++---- asset_test.go | 190 ++++++ assets_test.go | 211 ------- block_test.go | 195 +++--- client_test.go | 247 ++++---- epoch_test.go | 203 +++---- koios_test.go | 809 ++++++++++++------------- network_test.go | 150 ++--- pool_test.go | 545 ++++++++--------- script_test.go | 210 +++---- transaction_test.go | 359 ++++++----- 13 files changed, 1761 insertions(+), 1995 deletions(-) rename .github/workflows/{main.yml => ci.yml} (97%) create mode 100644 asset_test.go delete mode 100644 assets_test.go diff --git a/.github/workflows/main.yml b/.github/workflows/ci.yml similarity index 97% rename from .github/workflows/main.yml rename to .github/workflows/ci.yml index 0be1487..3e72b90 100644 --- a/.github/workflows/main.yml +++ b/.github/workflows/ci.yml @@ -1,4 +1,4 @@ -name: CI/CD Workflow +name: CI concurrency: group: main-${{ github.ref }} diff --git a/account_test.go b/account_test.go index 35a866f..19fec80 100644 --- a/account_test.go +++ b/account_test.go @@ -1,231 +1,209 @@ -// Copyright 2022 The Cardano Community Authors // SPDX-License-Identifier: Apache-2.0 // -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at: -// -// http://www.apache.org/licenses/LICENSE-2.0 -// or LICENSE file in repository root. -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. +// Copyright © 2022 The Cardano Community Authors package koios_test -import ( - "context" - "fmt" - "strings" - "testing" - - "github.com/cardano-community/koios-go-client/v4" - "github.com/stretchr/testify/assert" -) - -func TestAccounts(t *testing.T) { - client, err := getLiveClient() - if testIsLocal(t, err) { - return - } - - accountsTest(t, client) -} - -func accountsTest(t TestingT, client *koios.Client) { - - opts := client.NewRequestOptions() - opts.SetPageSize(10) - res, err := client.GetAccounts(context.Background(), opts) - if !assert.NoError(t, err) { - return - } - assertEqual(t, 10, len(res.Data), "total blocks returned") - - for _, addr := range res.Data { - assert.True( - t, - strings.HasPrefix(addr.String(), "stake"), - fmt.Sprintf("account list returned %s", addr)) - } -} - -func TestAccountInfo(t *testing.T) { - client, err := getLiveClient() - if testIsLocal(t, err) { - return - } - accountInfoTest(t, networkAccounts(), false, client) -} - -func TestAccountInfoCached(t *testing.T) { - client, err := getLiveClient() - if testIsLocal(t, err) { - return - } - accountInfoTest(t, networkAccounts(), true, client) -} - -func accountInfoTest(t TestingT, accs []koios.Address, cached bool, client *koios.Client) { - - res, err := client.GetAccountsInfo(context.Background(), accs, cached, nil) - if !assert.NoError(t, err) { - return - } - - if !cached { - assertEqual(t, len(accs), len(res.Data), "total account infos returned") - } - - for i, account := range res.Data { - label := fmt.Sprintf("account[%d]", i) - assertNotEmpty(t, account.StakeAddress, label+".stake_address") - assertNotEmpty(t, account.Status, label+".status") - if account.DelegatedPool != nil { - assertNotEmpty(t, account.DelegatedPool, label+".delegated_pool") - } - // assertIsPositive(t, account.TotalBalance, label+".total_balance") - // assertIsPositive(t, account.UTxO, label+".utxo") - // assertIsPositive(t, account.Rewards, label+".rewards") - // assertIsPositive(t, account.Withdrawals, label+".withdrawals") - // assertIsPositive(t, account.RewardsAvailable, label+".rewards_available") - // assertIsPositive(t, account.Reserves, label+".reserves") - // assertIsPositive(t, account.Treasury, label+".treasury") - } -} - -func TestAccountRewards(t *testing.T) { - client, err := getLiveClient() - if testIsLocal(t, err) { - return - } - epoch := networkEpoch() - accountRewardsTest(t, networkAccounts(), &epoch, client) -} - -func accountRewardsTest(t TestingT, accs []koios.Address, epoch *koios.EpochNo, client *koios.Client) { - res, err := client.GetAccountsRewards(context.Background(), accs, epoch, nil) - if !assert.NoError(t, err) { - return - } - - for i, account := range res.Data { - label := fmt.Sprintf("account[%d]", i) - assertNotEmpty(t, account.StakeAddress, label+".stake_address") - for _, reward := range account.Rewards { - label := fmt.Sprintf("account[%s][%d]", account.StakeAddress, reward.EarnedEpoch) - assertGreater(t, reward.EarnedEpoch, 0, label+".earned_epoch") - assertGreater(t, reward.SpendableEpoch, 0, label+".spendable_epoch") - assertIsPositive(t, reward.Amount, label+".amount") - assertNotEmpty(t, reward.Type, label+".type") - assertNotEmpty(t, reward.PoolID, label+".pool_id") - } - } -} - -func TestAccountUpdates(t *testing.T) { - client, err := getLiveClient() - if testIsLocal(t, err) { - return - } - accountUpdatesTest(t, networkAccounts(), client) -} - -func accountUpdatesTest(t TestingT, accs []koios.Address, client *koios.Client) { - res, err := client.GetAccountsUpdates(context.Background(), accs, nil) - if !assert.NoError(t, err) { - return - } - for i, account := range res.Data { - label := fmt.Sprintf("account[%d]", i) - assertNotEmpty(t, account.StakeAddress, label+".stake_address") - for j, update := range account.Updates { - label := fmt.Sprintf("account[%s].updates[%d]", account.StakeAddress, j) - assertNotEmpty(t, update.TxHash, label+".tx_hash") - assertGreater(t, update.EpochNo, 0, label+".epoch_no") - assertGreater(t, update.EpochSlot, 0, label+".epoch_slot") - assertGreater(t, update.AbsoluteSlot, 0, label+".absolute_slot") - assertTimeNotZero(t, update.BlockTime, label+".block_time") - } - } -} - -func TestAccountAddresses(t *testing.T) { - client, err := getLiveClient() - if testIsLocal(t, err) { - return - } - accountAddressesTest(t, networkAccounts(), client) -} - -func accountAddressesTest(t TestingT, accs []koios.Address, client *koios.Client) { - res, err := client.GetAccountsAddresses(context.Background(), accs, nil) - if !assert.NoError(t, err) { - return - } - - for i, account := range res.Data { - label := fmt.Sprintf("stake_address[%d]", i) - assertNotEmpty(t, account.StakeAddress, label) - for j, addr := range account.Addresses { - assertNotEmpty(t, addr, fmt.Sprintf("stake_address[%d].addresses[%d]", i, j)) - } - } -} - -func TestAccountAssets(t *testing.T) { - client, err := getLiveClient() - if testIsLocal(t, err) { - return - } - accountAssetsTest(t, networkAccounts(), client) -} - -func accountAssetsTest(t TestingT, accs []koios.Address, client *koios.Client) { - res, err := client.GetAccountsAssets(context.Background(), accs, nil) - if !assert.NoError(t, err) { - return - } - - for i, account := range res.Data { - label := fmt.Sprintf("acc[%d]", i) - assertNotEmpty(t, account.StakeAddress, label) - for j, asset := range account.Assets { - assertNotEmpty(t, asset.PolicyID, fmt.Sprintf("acc[%d].assets[%d].policy_id", i, j)) - // asset name can be empty - if len(asset.AssetName) > 0 { - assertNotEmpty(t, asset.AssetName, fmt.Sprintf("acc[%d].assets[%d].asset_name", i, j)) - } - assertNotEmpty(t, asset.Fingerprint, fmt.Sprintf("acc[%d].assets[%d].fingerprint", i, j)) - assertIsPositive(t, asset.Quantity, fmt.Sprintf("acc[%d].assets[%d].quantity", i, j)) - } - } -} - -func TestAccountHistory(t *testing.T) { - client, err := getLiveClient() - if testIsLocal(t, err) { - return - } - accountHistoryTest(t, networkAccounts(), client) -} - -func accountHistoryTest(t TestingT, accs []koios.Address, client *koios.Client) { - res, err := client.GetAccountsHistory(context.Background(), accs, nil) - if !assert.NoError(t, err) { - return - } - for _, account := range res.Data { - label := fmt.Sprintf("acc[%s].stake_address", account.StakeAddress) - assertNotEmpty(t, account.StakeAddress, label) - for i, history := range account.History { - label = fmt.Sprintf("%s.history[%d]", label, i) - assertNotEmpty(t, history.PoolID, label+".pool_id") - assertGreater(t, history.EpochNo, 0, label+".epoch_no") - assertIsPositive(t, history.ActiveStake, label+".active_stake") - } - } -} +// func TestAccounts(t *testing.T) { +// client, err := getLiveClient() +// if testIsLocal(t, err) { +// return +// } + +// accountsTest(t, client) +// } + +// func accountsTest(t TestingT, client *koios.Client) { + +// opts := client.NewRequestOptions() +// opts.SetPageSize(10) +// res, err := client.GetAccounts(context.Background(), opts) +// if !assert.NoError(t, err) { +// return +// } +// assertEqual(t, 10, len(res.Data), "total blocks returned") + +// for _, addr := range res.Data { +// assert.True( +// t, +// strings.HasPrefix(addr.String(), "stake"), +// fmt.Sprintf("account list returned %s", addr)) +// } +// } + +// func TestAccountInfo(t *testing.T) { +// client, err := getLiveClient() +// if testIsLocal(t, err) { +// return +// } +// accountInfoTest(t, networkAccounts(), false, client) +// } + +// func TestAccountInfoCached(t *testing.T) { +// client, err := getLiveClient() +// if testIsLocal(t, err) { +// return +// } +// accountInfoTest(t, networkAccounts(), true, client) +// } + +// func accountInfoTest(t TestingT, accs []koios.Address, cached bool, client *koios.Client) { + +// res, err := client.GetAccountsInfo(context.Background(), accs, cached, nil) +// if !assert.NoError(t, err) { +// return +// } + +// if !cached { +// assertEqual(t, len(accs), len(res.Data), "total account infos returned") +// } + +// for i, account := range res.Data { +// label := fmt.Sprintf("account[%d]", i) +// assertNotEmpty(t, account.StakeAddress, label+".stake_address") +// assertNotEmpty(t, account.Status, label+".status") +// if account.DelegatedPool != nil { +// assertNotEmpty(t, account.DelegatedPool, label+".delegated_pool") +// } +// // assertIsPositive(t, account.TotalBalance, label+".total_balance") +// // assertIsPositive(t, account.UTxO, label+".utxo") +// // assertIsPositive(t, account.Rewards, label+".rewards") +// // assertIsPositive(t, account.Withdrawals, label+".withdrawals") +// // assertIsPositive(t, account.RewardsAvailable, label+".rewards_available") +// // assertIsPositive(t, account.Reserves, label+".reserves") +// // assertIsPositive(t, account.Treasury, label+".treasury") +// } +// } + +// func TestAccountRewards(t *testing.T) { +// client, err := getLiveClient() +// if testIsLocal(t, err) { +// return +// } +// epoch := networkEpoch() +// accountRewardsTest(t, networkAccounts(), &epoch, client) +// } + +// func accountRewardsTest(t TestingT, accs []koios.Address, epoch *koios.EpochNo, client *koios.Client) { +// res, err := client.GetAccountsRewards(context.Background(), accs, epoch, nil) +// if !assert.NoError(t, err) { +// return +// } + +// for i, account := range res.Data { +// label := fmt.Sprintf("account[%d]", i) +// assertNotEmpty(t, account.StakeAddress, label+".stake_address") +// for _, reward := range account.Rewards { +// label := fmt.Sprintf("account[%s][%d]", account.StakeAddress, reward.EarnedEpoch) +// assertGreater(t, reward.EarnedEpoch, 0, label+".earned_epoch") +// assertGreater(t, reward.SpendableEpoch, 0, label+".spendable_epoch") +// assertIsPositive(t, reward.Amount, label+".amount") +// assertNotEmpty(t, reward.Type, label+".type") +// assertNotEmpty(t, reward.PoolID, label+".pool_id") +// } +// } +// } + +// func TestAccountUpdates(t *testing.T) { +// client, err := getLiveClient() +// if testIsLocal(t, err) { +// return +// } +// accountUpdatesTest(t, networkAccounts(), client) +// } + +// func accountUpdatesTest(t TestingT, accs []koios.Address, client *koios.Client) { +// res, err := client.GetAccountsUpdates(context.Background(), accs, nil) +// if !assert.NoError(t, err) { +// return +// } +// for i, account := range res.Data { +// label := fmt.Sprintf("account[%d]", i) +// assertNotEmpty(t, account.StakeAddress, label+".stake_address") +// for j, update := range account.Updates { +// label := fmt.Sprintf("account[%s].updates[%d]", account.StakeAddress, j) +// assertNotEmpty(t, update.TxHash, label+".tx_hash") +// assertGreater(t, update.EpochNo, 0, label+".epoch_no") +// assertGreater(t, update.EpochSlot, 0, label+".epoch_slot") +// assertGreater(t, update.AbsoluteSlot, 0, label+".absolute_slot") +// assertTimeNotZero(t, update.BlockTime, label+".block_time") +// } +// } +// } + +// func TestAccountAddresses(t *testing.T) { +// client, err := getLiveClient() +// if testIsLocal(t, err) { +// return +// } +// accountAddressesTest(t, networkAccounts(), client) +// } + +// func accountAddressesTest(t TestingT, accs []koios.Address, client *koios.Client) { +// res, err := client.GetAccountsAddresses(context.Background(), accs, nil) +// if !assert.NoError(t, err) { +// return +// } + +// for i, account := range res.Data { +// label := fmt.Sprintf("stake_address[%d]", i) +// assertNotEmpty(t, account.StakeAddress, label) +// for j, addr := range account.Addresses { +// assertNotEmpty(t, addr, fmt.Sprintf("stake_address[%d].addresses[%d]", i, j)) +// } +// } +// } + +// func TestAccountAssets(t *testing.T) { +// client, err := getLiveClient() +// if testIsLocal(t, err) { +// return +// } +// accountAssetsTest(t, networkAccounts(), client) +// } + +// func accountAssetsTest(t TestingT, accs []koios.Address, client *koios.Client) { +// res, err := client.GetAccountsAssets(context.Background(), accs, nil) +// if !assert.NoError(t, err) { +// return +// } + +// for i, account := range res.Data { +// label := fmt.Sprintf("acc[%d]", i) +// assertNotEmpty(t, account.StakeAddress, label) +// for j, asset := range account.Assets { +// assertNotEmpty(t, asset.PolicyID, fmt.Sprintf("acc[%d].assets[%d].policy_id", i, j)) +// // asset name can be empty +// if len(asset.AssetName) > 0 { +// assertNotEmpty(t, asset.AssetName, fmt.Sprintf("acc[%d].assets[%d].asset_name", i, j)) +// } +// assertNotEmpty(t, asset.Fingerprint, fmt.Sprintf("acc[%d].assets[%d].fingerprint", i, j)) +// assertIsPositive(t, asset.Quantity, fmt.Sprintf("acc[%d].assets[%d].quantity", i, j)) +// } +// } +// } + +// func TestAccountHistory(t *testing.T) { +// client, err := getLiveClient() +// if testIsLocal(t, err) { +// return +// } +// accountHistoryTest(t, networkAccounts(), client) +// } + +// func accountHistoryTest(t TestingT, accs []koios.Address, client *koios.Client) { +// res, err := client.GetAccountsHistory(context.Background(), accs, nil) +// if !assert.NoError(t, err) { +// return +// } +// for _, account := range res.Data { +// label := fmt.Sprintf("acc[%s].stake_address", account.StakeAddress) +// assertNotEmpty(t, account.StakeAddress, label) +// for i, history := range account.History { +// label = fmt.Sprintf("%s.history[%d]", label, i) +// assertNotEmpty(t, history.PoolID, label+".pool_id") +// assertGreater(t, history.EpochNo, 0, label+".epoch_no") +// assertIsPositive(t, history.ActiveStake, label+".active_stake") +// } +// } +// } diff --git a/address_test.go b/address_test.go index fe178c2..a440af4 100644 --- a/address_test.go +++ b/address_test.go @@ -1,128 +1,107 @@ -// Copyright 2022 The Cardano Community Authors // SPDX-License-Identifier: Apache-2.0 // -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at: -// -// http://www.apache.org/licenses/LICENSE-2.0 -// or LICENSE file in repository root. -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. +// Copyright © 2022 The Cardano Community Authors package koios_test -import ( - "context" - "fmt" - "testing" - - "github.com/cardano-community/koios-go-client/v4" - "github.com/stretchr/testify/assert" -) - -func TestAddressInfo(t *testing.T) { - client, err := getLiveClient() - if testIsLocal(t, err) { - return - } - addressInfoTest(t, networkAddresses(), client) -} +// func TestAddressInfo(t *testing.T) { +// client, err := getLiveClient() +// if testIsLocal(t, err) { +// return +// } +// addressInfoTest(t, networkAddresses(), client) +// } -func addressInfoTest(t TestingT, addrs []koios.Address, client *koios.Client) { - res, err := client.GetAddressesInfo(context.Background(), addrs, nil) - if !assert.NoError(t, err) { - return - } - for i, addr := range res.Data { - assertNotEmpty(t, addr.Address, fmt.Sprintf("info[%d].address", i)) - assertIsPositive(t, addr.Balance, fmt.Sprintf("status[%d].balance", i)) - assert.False(t, addr.ScriptAddress, fmt.Sprintf("status[%d].script_address", i)) - for i, utxo := range addr.UTxOs { - assertUTxO(t, utxo, fmt.Sprintf("add[%s].utxo_set[%d]", addr.Address, i)) - } - } -} +// func addressInfoTest(t TestingT, addrs []koios.Address, client *koios.Client) { +// res, err := client.GetAddressesInfo(context.Background(), addrs, nil) +// if !assert.NoError(t, err) { +// return +// } +// for i, addr := range res.Data { +// assertNotEmpty(t, addr.Address, fmt.Sprintf("info[%d].address", i)) +// assertIsPositive(t, addr.Balance, fmt.Sprintf("status[%d].balance", i)) +// assert.False(t, addr.ScriptAddress, fmt.Sprintf("status[%d].script_address", i)) +// for i, utxo := range addr.UTxOs { +// assertUTxO(t, utxo, fmt.Sprintf("add[%s].utxo_set[%d]", addr.Address, i)) +// } +// } +// } -func TestAddressTxs(t *testing.T) { - client, err := getLiveClient() - if testIsLocal(t, err) { - return - } - addressTxsTest(t, networkAddresses(), client) -} +// func TestAddressTxs(t *testing.T) { +// client, err := getLiveClient() +// if testIsLocal(t, err) { +// return +// } +// addressTxsTest(t, networkAddresses(), client) +// } -func addressTxsTest(t TestingT, addrs []koios.Address, client *koios.Client) { - res, err := client.GetAddressTxs(context.Background(), addrs, 0, nil) - if !assert.NoError(t, err) { - return - } +// func addressTxsTest(t TestingT, addrs []koios.Address, client *koios.Client) { +// res, err := client.GetAddressTxs(context.Background(), addrs, 0, nil) +// if !assert.NoError(t, err) { +// return +// } - assertGreater(t, len(res.Data), 10, "expected transactions list") - for i, tx := range res.Data { - assertNotEmpty(t, tx.TxHash, fmt.Sprintf("tx[%d].tx_hash", i)) - assertNotEmpty(t, tx.EpochNo, fmt.Sprintf("tx[%d].epoch_no", i)) - assertNotEmpty(t, tx.BlockHeight, fmt.Sprintf("tx[%d].block_height", i)) - assertTimeNotZero(t, tx.BlockTime, fmt.Sprintf("tx[%d].block_time", i)) - } -} +// assertGreater(t, len(res.Data), 10, "expected transactions list") +// for i, tx := range res.Data { +// assertNotEmpty(t, tx.TxHash, fmt.Sprintf("tx[%d].tx_hash", i)) +// assertNotEmpty(t, tx.EpochNo, fmt.Sprintf("tx[%d].epoch_no", i)) +// assertNotEmpty(t, tx.BlockHeight, fmt.Sprintf("tx[%d].block_height", i)) +// assertTimeNotZero(t, tx.BlockTime, fmt.Sprintf("tx[%d].block_time", i)) +// } +// } -func TestAddressAssets(t *testing.T) { - client, err := getLiveClient() - if testIsLocal(t, err) { - return - } - addressAssetsTest(t, networkAddresses(), client) -} +// func TestAddressAssets(t *testing.T) { +// client, err := getLiveClient() +// if testIsLocal(t, err) { +// return +// } +// addressAssetsTest(t, networkAddresses(), client) +// } -func addressAssetsTest(t TestingT, addrs []koios.Address, client *koios.Client) { - res, err := client.GetAddressesAssets(context.Background(), addrs, nil) - if err != nil { - if assert.ErrorIs(t, err, koios.ErrNoData) { - githubActionWarning("AddressAssets", err.Error()) - return - } - assert.NoError(t, err) - return - } +// func addressAssetsTest(t TestingT, addrs []koios.Address, client *koios.Client) { +// res, err := client.GetAddressesAssets(context.Background(), addrs, nil) +// if err != nil { +// if assert.ErrorIs(t, err, koios.ErrNoData) { +// githubActionWarning("AddressAssets", err.Error()) +// return +// } +// assert.NoError(t, err) +// return +// } - for _, addrcol := range res.Data { - assertNotEmpty(t, addrcol.Address, "address") - for i, asset := range addrcol.AssetList { - label := fmt.Sprintf("address[%s].assets[%d]", addrcol.Address, i) - assertNotEmpty(t, asset.PolicyID, label+".ploicy_id") - if len(asset.AssetName) > 0 { - assertNotEmpty(t, asset.AssetName, label+"asset_name") - } - assertNotEmpty(t, asset.Fingerprint, label+"fingerprint") - assertIsPositive(t, asset.Quantity, label+"quantity") - } - } -} +// for _, addrcol := range res.Data { +// assertNotEmpty(t, addrcol.Address, "address") +// for i, asset := range addrcol.AssetList { +// label := fmt.Sprintf("address[%s].assets[%d]", addrcol.Address, i) +// assertNotEmpty(t, asset.PolicyID, label+".ploicy_id") +// if len(asset.AssetName) > 0 { +// assertNotEmpty(t, asset.AssetName, label+"asset_name") +// } +// assertNotEmpty(t, asset.Fingerprint, label+"fingerprint") +// assertIsPositive(t, asset.Quantity, label+"quantity") +// } +// } +// } -func TestCredentialTxs(t *testing.T) { - client, err := getLiveClient() - if testIsLocal(t, err) { - return - } - credentialTxsTest(t, networkPaymentCredentials(), client) -} +// func TestCredentialTxs(t *testing.T) { +// client, err := getLiveClient() +// if testIsLocal(t, err) { +// return +// } +// credentialTxsTest(t, networkPaymentCredentials(), client) +// } -func credentialTxsTest(t TestingT, creds []koios.PaymentCredential, client *koios.Client) { - res, err := client.GetCredentialTxs(context.Background(), creds, 0, nil) - if !assert.NoError(t, err) { - return - } +// func credentialTxsTest(t TestingT, creds []koios.PaymentCredential, client *koios.Client) { +// res, err := client.GetCredentialTxs(context.Background(), creds, 0, nil) +// if !assert.NoError(t, err) { +// return +// } - assertGreater(t, len(res.Data), 2, "expected transactions list") - for i, tx := range res.Data { - assertNotEmpty(t, tx.TxHash, fmt.Sprintf("tx[%d].tx_hash", i)) - assertNotEmpty(t, tx.EpochNo, fmt.Sprintf("tx[%d].epoch_no", i)) - assertNotEmpty(t, tx.BlockHeight, fmt.Sprintf("tx[%d].block_height", i)) - assertTimeNotZero(t, tx.BlockTime, fmt.Sprintf("tx[%d].block_time", i)) - } -} +// assertGreater(t, len(res.Data), 2, "expected transactions list") +// for i, tx := range res.Data { +// assertNotEmpty(t, tx.TxHash, fmt.Sprintf("tx[%d].tx_hash", i)) +// assertNotEmpty(t, tx.EpochNo, fmt.Sprintf("tx[%d].epoch_no", i)) +// assertNotEmpty(t, tx.BlockHeight, fmt.Sprintf("tx[%d].block_height", i)) +// assertTimeNotZero(t, tx.BlockTime, fmt.Sprintf("tx[%d].block_time", i)) +// } +// } diff --git a/asset_test.go b/asset_test.go new file mode 100644 index 0000000..0cbbfa6 --- /dev/null +++ b/asset_test.go @@ -0,0 +1,190 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// Copyright © 2022 The Cardano Community Authors + +package koios_test + +// func TestAssets(t *testing.T) { +// client, err := getLiveClient() +// if testIsLocal(t, err) { +// return +// } +// assetsTest(t, client) +// } + +// func assetsTest(t TestingT, client *koios.Client) { +// opts := client.NewRequestOptions() +// opts.SetPageSize(10) +// res, err := client.GetAssets(context.Background(), opts) +// if !assert.NoError(t, err) { +// return +// } +// assertEqual(t, 10, len(res.Data), "total blocks returned") + +// for _, item := range res.Data { +// assertNotEmpty(t, item.PolicyID, "policy_id") +// assertGreater(t, len(item.Fingerprint), 0, item.PolicyID.String()+" fingerprint") +// } +// } + +// func TestAssetAddresses(t *testing.T) { +// client, err := getLiveClient() +// if testIsLocal(t, err) { +// return +// } +// policyID, assetName, _, _ := networkPolicyAsset() +// assetAddressesTest(t, client, policyID, assetName) +// } + +// func assetAddressesTest(t TestingT, client *koios.Client, policyID koios.PolicyID, assetName koios.AssetName) { +// res, err := client.GetAssetAddresses(context.Background(), policyID, assetName, nil) +// if !assert.NoError(t, err) { +// return +// } + +// for _, holder := range res.Data { +// assertNotEmpty(t, holder.PaymentAddress, "payment_address") +// assertIsPositive(t, holder.Quantity, "quantity") +// } +// } + +// func TestAssetInfo(t *testing.T) { +// client, err := getLiveClient() +// if testIsLocal(t, err) { +// return +// } +// policyID, assetName, _, _ := networkPolicyAsset() +// assetInfoTest(t, client, policyID, assetName) +// } + +// func assetInfoTest(t TestingT, client *koios.Client, policyID koios.PolicyID, assetName koios.AssetName) { +// res, err := client.GetAssetInfo(context.Background(), policyID, assetName, nil) +// if !assert.NoError(t, err) { +// return +// } + +// assertNotEmpty(t, res.Data.PolicyID, "policy_id") +// if len(res.Data.AssetName) > 0 { +// assertNotEmpty(t, res.Data.AssetNameASCII, "asset_name_ascii") +// } +// assertNotEmpty(t, res.Data.Fingerprint, "fingerprint") +// assertNotEmpty(t, res.Data.MintingTxHash, "minting_tx_hash") +// assertIsPositive(t, res.Data.TotalSupply, "total_supply") +// assertGreater(t, res.Data.MintCnt, 0, "mint_cnt") +// // assertGreater(t, res.Data.BurnCnt, 0, "burn_cnt") +// assertTimeNotZero(t, res.Data.CreationTime, "creation_time") +// // assertNotEmpty(t, res.Data.MintingTxMetadata, "minting_tx_metadata") +// // assertNotEmpty(t, res.Data.TokenRegistryMetadata, "token_registry_metadata") +// } + +// func TestAssetHistory(t *testing.T) { +// client, err := getLiveClient() +// if testIsLocal(t, err) { +// return +// } +// policyID, assetName, _, _ := networkPolicyAsset() +// assetHistoryTest(t, client, policyID, assetName) +// } + +// func assetHistoryTest(t TestingT, client *koios.Client, policyID koios.PolicyID, assetName koios.AssetName) { +// res, err := client.GetAssetHistory(context.Background(), policyID, assetName, nil) +// if !assert.NoError(t, err) { +// return +// } +// assertNotEmpty(t, res.Data.PolicyID, "policy_id") +// assertNotEmpty(t, res.Data.Fingerprint, "fingerprint") +// for _, minttx := range res.Data.MintingTXs { +// assertNotEmpty(t, minttx.TxHash, "tx_hash") +// assertNotEmpty(t, minttx.BlockTime, "block_time") +// assertCoinNotZero(t, minttx.Quantity, "quantity") +// assertTxMetadata(t, minttx.Metadata, fmt.Sprintf("policy[%s].metadata", policyID)) +// } +// } + +// func TestAssetPolicyInfo(t *testing.T) { +// client, err := getLiveClient() +// if testIsLocal(t, err) { +// return +// } +// policyID, _, _, _ := networkPolicyAsset() +// assetPolicyInfoTest(t, client, policyID) +// } + +// func assetPolicyInfoTest(t TestingT, client *koios.Client, policyID koios.PolicyID) { +// res, err := client.GetAssetPolicyInfo(context.Background(), policyID, nil) +// if !assert.NoError(t, err) { +// return +// } + +// for i, asset := range res.Data { +// label := fmt.Sprintf("policy[%s][%d]", policyID, i) +// assertNotEmpty(t, asset.PolicyID, label+".policy_id") +// if len(asset.AssetName) > 0 { +// assertNotEmpty(t, asset.AssetNameASCII, label+".asset_name_ascii") +// } +// assertNotEmpty(t, asset.Fingerprint, label+".fingerprint") +// // assertNotEmpty(t, asset.MintingTxHash, label+".minting_tx_hash") +// assertIsPositive(t, asset.TotalSupply, label+".total_supply") +// // assertGreater(t, asset.MintCnt, 0, label+".mint_cnt") +// // assertGreater(t, res.Data.BurnCnt, 0, "burn_cnt") +// assertTimeNotZero(t, asset.CreationTime, label+".creation_time") +// // assertNotEmpty(t, res.Data.MintingTxMetadata, "minting_tx_metadata") +// // assertNotEmpty(t, res.Data.TokenRegistryMetadata, "token_registry_metadata") +// } +// } + +// func TestAssetSummary(t *testing.T) { +// client, err := getLiveClient() +// if testIsLocal(t, err) { +// return +// } +// policyID, asset, _, _ := networkPolicyAsset() +// testAssetSummaryTest(t, client, policyID, asset) +// } + +// func testAssetSummaryTest(t TestingT, client *koios.Client, policyID koios.PolicyID, asset koios.AssetName) { +// res, err := client.GetAssetSummary(context.Background(), policyID, asset, nil) +// if !assert.NoError(t, err) { +// return +// } + +// for _, summary := range res.Data { +// assertNotEmpty(t, summary.PolicyID, "policy_id") +// // assertNotEmpty(t, summary.AssetName, "asset_name") +// assertGreater(t, summary.TotalTransactions, 0, "total_transactions") +// if summary.StakedWallets == 0 { +// githubActionWarning("AssetSummary", "staked_wallets is 0") +// } +// // assertGreater(t, summary.UnstakedAddresses, 0, "unstaked_addresses") +// } +// } + +// func TestAssetTxs(t *testing.T) { +// client, err := getLiveClient() +// if testIsLocal(t, err) { +// return +// } +// policyID, asset, abh, history := networkPolicyAsset() +// assetTxsTest(t, client, policyID, asset, abh, history) +// } + +// func assetTxsTest( +// t TestingT, +// client *koios.Client, +// policyID koios.PolicyID, +// asset koios.AssetName, +// abh int, +// history bool, +// ) { +// res, err := client.GetAssetTxs(context.Background(), policyID, asset, abh, history, nil) +// if !assert.NoError(t, err) { +// return +// } + +// for i, tx := range res.Data { +// assertNotEmpty(t, tx.TxHash, fmt.Sprintf("tx[%d].tx_hash", i)) +// assertNotEmpty(t, tx.EpochNo, fmt.Sprintf("tx[%d].epoch_no", i)) +// assertNotEmpty(t, tx.BlockHeight, fmt.Sprintf("tx[%d].block_height", i)) +// assertTimeNotZero(t, tx.BlockTime, fmt.Sprintf("tx[%d].block_time", i)) +// } +// } diff --git a/assets_test.go b/assets_test.go deleted file mode 100644 index 42b0efe..0000000 --- a/assets_test.go +++ /dev/null @@ -1,211 +0,0 @@ -// Copyright 2022 The Cardano Community Authors -// SPDX-License-Identifier: Apache-2.0 -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at: -// -// http://www.apache.org/licenses/LICENSE-2.0 -// or LICENSE file in repository root. -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package koios_test - -import ( - "context" - "fmt" - "testing" - - "github.com/cardano-community/koios-go-client/v4" - "github.com/stretchr/testify/assert" -) - -func TestAssets(t *testing.T) { - client, err := getLiveClient() - if testIsLocal(t, err) { - return - } - assetsTest(t, client) -} - -func assetsTest(t TestingT, client *koios.Client) { - opts := client.NewRequestOptions() - opts.SetPageSize(10) - res, err := client.GetAssets(context.Background(), opts) - if !assert.NoError(t, err) { - return - } - assertEqual(t, 10, len(res.Data), "total blocks returned") - - for _, item := range res.Data { - assertNotEmpty(t, item.PolicyID, "policy_id") - assertGreater(t, len(item.Fingerprint), 0, item.PolicyID.String()+" fingerprint") - } -} - -func TestAssetAddresses(t *testing.T) { - client, err := getLiveClient() - if testIsLocal(t, err) { - return - } - policyID, assetName, _, _ := networkPolicyAsset() - assetAddressesTest(t, client, policyID, assetName) -} - -func assetAddressesTest(t TestingT, client *koios.Client, policyID koios.PolicyID, assetName koios.AssetName) { - res, err := client.GetAssetAddresses(context.Background(), policyID, assetName, nil) - if !assert.NoError(t, err) { - return - } - - for _, holder := range res.Data { - assertNotEmpty(t, holder.PaymentAddress, "payment_address") - assertIsPositive(t, holder.Quantity, "quantity") - } -} - -func TestAssetInfo(t *testing.T) { - client, err := getLiveClient() - if testIsLocal(t, err) { - return - } - policyID, assetName, _, _ := networkPolicyAsset() - assetInfoTest(t, client, policyID, assetName) -} - -func assetInfoTest(t TestingT, client *koios.Client, policyID koios.PolicyID, assetName koios.AssetName) { - res, err := client.GetAssetInfo(context.Background(), policyID, assetName, nil) - if !assert.NoError(t, err) { - return - } - - assertNotEmpty(t, res.Data.PolicyID, "policy_id") - if len(res.Data.AssetName) > 0 { - assertNotEmpty(t, res.Data.AssetNameASCII, "asset_name_ascii") - } - assertNotEmpty(t, res.Data.Fingerprint, "fingerprint") - assertNotEmpty(t, res.Data.MintingTxHash, "minting_tx_hash") - assertIsPositive(t, res.Data.TotalSupply, "total_supply") - assertGreater(t, res.Data.MintCnt, 0, "mint_cnt") - // assertGreater(t, res.Data.BurnCnt, 0, "burn_cnt") - assertTimeNotZero(t, res.Data.CreationTime, "creation_time") - // assertNotEmpty(t, res.Data.MintingTxMetadata, "minting_tx_metadata") - // assertNotEmpty(t, res.Data.TokenRegistryMetadata, "token_registry_metadata") -} - -func TestAssetHistory(t *testing.T) { - client, err := getLiveClient() - if testIsLocal(t, err) { - return - } - policyID, assetName, _, _ := networkPolicyAsset() - assetHistoryTest(t, client, policyID, assetName) -} - -func assetHistoryTest(t TestingT, client *koios.Client, policyID koios.PolicyID, assetName koios.AssetName) { - res, err := client.GetAssetHistory(context.Background(), policyID, assetName, nil) - if !assert.NoError(t, err) { - return - } - assertNotEmpty(t, res.Data.PolicyID, "policy_id") - assertNotEmpty(t, res.Data.Fingerprint, "fingerprint") - for _, minttx := range res.Data.MintingTXs { - assertNotEmpty(t, minttx.TxHash, "tx_hash") - assertNotEmpty(t, minttx.BlockTime, "block_time") - assertCoinNotZero(t, minttx.Quantity, "quantity") - assertTxMetadata(t, minttx.Metadata, fmt.Sprintf("policy[%s].metadata", policyID)) - } -} - -func TestAssetPolicyInfo(t *testing.T) { - client, err := getLiveClient() - if testIsLocal(t, err) { - return - } - policyID, _, _, _ := networkPolicyAsset() - assetPolicyInfoTest(t, client, policyID) -} - -func assetPolicyInfoTest(t TestingT, client *koios.Client, policyID koios.PolicyID) { - res, err := client.GetAssetPolicyInfo(context.Background(), policyID, nil) - if !assert.NoError(t, err) { - return - } - - for i, asset := range res.Data { - label := fmt.Sprintf("policy[%s][%d]", policyID, i) - assertNotEmpty(t, asset.PolicyID, label+".policy_id") - if len(asset.AssetName) > 0 { - assertNotEmpty(t, asset.AssetNameASCII, label+".asset_name_ascii") - } - assertNotEmpty(t, asset.Fingerprint, label+".fingerprint") - // assertNotEmpty(t, asset.MintingTxHash, label+".minting_tx_hash") - assertIsPositive(t, asset.TotalSupply, label+".total_supply") - // assertGreater(t, asset.MintCnt, 0, label+".mint_cnt") - // assertGreater(t, res.Data.BurnCnt, 0, "burn_cnt") - assertTimeNotZero(t, asset.CreationTime, label+".creation_time") - // assertNotEmpty(t, res.Data.MintingTxMetadata, "minting_tx_metadata") - // assertNotEmpty(t, res.Data.TokenRegistryMetadata, "token_registry_metadata") - } -} - -func TestAssetSummary(t *testing.T) { - client, err := getLiveClient() - if testIsLocal(t, err) { - return - } - policyID, asset, _, _ := networkPolicyAsset() - testAssetSummaryTest(t, client, policyID, asset) -} - -func testAssetSummaryTest(t TestingT, client *koios.Client, policyID koios.PolicyID, asset koios.AssetName) { - res, err := client.GetAssetSummary(context.Background(), policyID, asset, nil) - if !assert.NoError(t, err) { - return - } - - for _, summary := range res.Data { - assertNotEmpty(t, summary.PolicyID, "policy_id") - // assertNotEmpty(t, summary.AssetName, "asset_name") - assertGreater(t, summary.TotalTransactions, 0, "total_transactions") - if summary.StakedWallets == 0 { - githubActionWarning("AssetSummary", "staked_wallets is 0") - } - // assertGreater(t, summary.UnstakedAddresses, 0, "unstaked_addresses") - } -} - -func TestAssetTxs(t *testing.T) { - client, err := getLiveClient() - if testIsLocal(t, err) { - return - } - policyID, asset, abh, history := networkPolicyAsset() - assetTxsTest(t, client, policyID, asset, abh, history) -} - -func assetTxsTest( - t TestingT, - client *koios.Client, - policyID koios.PolicyID, - asset koios.AssetName, - abh int, - history bool, -) { - res, err := client.GetAssetTxs(context.Background(), policyID, asset, abh, history, nil) - if !assert.NoError(t, err) { - return - } - - for i, tx := range res.Data { - assertNotEmpty(t, tx.TxHash, fmt.Sprintf("tx[%d].tx_hash", i)) - assertNotEmpty(t, tx.EpochNo, fmt.Sprintf("tx[%d].epoch_no", i)) - assertNotEmpty(t, tx.BlockHeight, fmt.Sprintf("tx[%d].block_height", i)) - assertTimeNotZero(t, tx.BlockTime, fmt.Sprintf("tx[%d].block_time", i)) - } -} diff --git a/block_test.go b/block_test.go index 58333bd..b4b51e3 100644 --- a/block_test.go +++ b/block_test.go @@ -1,124 +1,103 @@ -// Copyright 2022 The Cardano Community Authors // SPDX-License-Identifier: Apache-2.0 // -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at: -// -// http://www.apache.org/licenses/LICENSE-2.0 -// or LICENSE file in repository root. -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. +// Copyright © 2022 The Cardano Community Authors package koios_test -import ( - "context" - "fmt" - "testing" - - "github.com/cardano-community/koios-go-client/v4" - "github.com/stretchr/testify/assert" -) - -func TestBlocks(t *testing.T) { - client, err := getLiveClient() - if testIsLocal(t, err) { - return - } - blocksTest(t, client) -} +// func TestBlocks(t *testing.T) { +// client, err := getLiveClient() +// if testIsLocal(t, err) { +// return +// } +// blocksTest(t, client) +// } -func blocksTest(t TestingT, client *koios.Client) { +// func blocksTest(t TestingT, client *koios.Client) { - opts := client.NewRequestOptions() - opts.SetPageSize(10) - res, err := client.GetBlocks(context.Background(), opts) - if !assert.NoError(t, err) { - return - } - assertEqual(t, 10, len(res.Data), "total blocks returned") +// opts := client.NewRequestOptions() +// opts.SetPageSize(10) +// res, err := client.GetBlocks(context.Background(), opts) +// if !assert.NoError(t, err) { +// return +// } +// assertEqual(t, 10, len(res.Data), "total blocks returned") - assertNotEmpty(t, res.Data[0].Hash, "hash") - assertGreater(t, res.Data[0].EpochNo, koios.EpochNo(0), "epoch_no") - assertGreater(t, res.Data[0].AbsSlot, koios.Slot(0), "abs_slot") - assertGreater(t, res.Data[0].EpochSlot, koios.Slot(0), "epoch_slot") - assertGreater(t, res.Data[0].Height, 0, "block_height") - assertGreater(t, res.Data[0].Size, 0, "block_size") - assertTimeNotZero(t, res.Data[0].Time, "block_time") - if res.Data[0].TxCount == 0 { - githubActionWarning("/blocks", fmt.Sprintf("block(%s) tx count is 0", res.Data[0].Hash)) - } - assertNotEmpty(t, res.Data[0].VrfKey, "vrf_key") - assertNotEmpty(t, res.Data[0].Pool, "pool") - // assertGreater(t, res.Data[0].OpCertCounter, 0, "op_cert_counter") - assertGreater(t, res.Data[0].ProtoMajor, 0, "proto_major") - // assertGreater(t, res.Data[0].ProtoMinor, 0, "proto_minor") -} +// assertNotEmpty(t, res.Data[0].Hash, "hash") +// assertGreater(t, res.Data[0].EpochNo, koios.EpochNo(0), "epoch_no") +// assertGreater(t, res.Data[0].AbsSlot, koios.Slot(0), "abs_slot") +// assertGreater(t, res.Data[0].EpochSlot, koios.Slot(0), "epoch_slot") +// assertGreater(t, res.Data[0].Height, 0, "block_height") +// assertGreater(t, res.Data[0].Size, 0, "block_size") +// assertTimeNotZero(t, res.Data[0].Time, "block_time") +// if res.Data[0].TxCount == 0 { +// githubActionWarning("/blocks", fmt.Sprintf("block(%s) tx count is 0", res.Data[0].Hash)) +// } +// assertNotEmpty(t, res.Data[0].VrfKey, "vrf_key") +// assertNotEmpty(t, res.Data[0].Pool, "pool") +// // assertGreater(t, res.Data[0].OpCertCounter, 0, "op_cert_counter") +// assertGreater(t, res.Data[0].ProtoMajor, 0, "proto_major") +// // assertGreater(t, res.Data[0].ProtoMinor, 0, "proto_minor") +// } -func TestBlockInfo(t *testing.T) { - client, err := getLiveClient() - if testIsLocal(t, err) { - return - } - blockInfoTest(t, networkBlockHash(), client) -} +// func TestBlockInfo(t *testing.T) { +// client, err := getLiveClient() +// if testIsLocal(t, err) { +// return +// } +// blockInfoTest(t, networkBlockHash(), client) +// } -func blockInfoTest(t TestingT, hash koios.BlockHash, client *koios.Client) { - res, err := client.GetBlockInfo(context.Background(), hash, nil) - if !assert.NoError(t, err) { - return - } +// func blockInfoTest(t TestingT, hash koios.BlockHash, client *koios.Client) { +// res, err := client.GetBlockInfo(context.Background(), hash, nil) +// if !assert.NoError(t, err) { +// return +// } - assertNotEmpty(t, res.Data.Hash, "hash") - assertGreater(t, res.Data.EpochNo, koios.EpochNo(0), "epoch_no") - assertGreater(t, res.Data.AbsSlot, koios.Slot(0), "abs_slot") - assertGreater(t, res.Data.EpochSlot, koios.Slot(0), "epoch_slot") - assertGreater(t, res.Data.Height, 0, "block_height") - assertGreater(t, res.Data.Size, 0, "block_size") - assertTimeNotZero(t, res.Data.Time, "block_time") +// assertNotEmpty(t, res.Data.Hash, "hash") +// assertGreater(t, res.Data.EpochNo, koios.EpochNo(0), "epoch_no") +// assertGreater(t, res.Data.AbsSlot, koios.Slot(0), "abs_slot") +// assertGreater(t, res.Data.EpochSlot, koios.Slot(0), "epoch_slot") +// assertGreater(t, res.Data.Height, 0, "block_height") +// assertGreater(t, res.Data.Size, 0, "block_size") +// assertTimeNotZero(t, res.Data.Time, "block_time") - if res.Data.TxCount == 0 { - githubActionWarning("/block_info", fmt.Sprintf("block(%s) tx count is 0", res.Data.Hash)) - } else { - assertIsPositive(t, res.Data.TotalOutput, "total_output") - assertIsPositive(t, res.Data.TotalFees, "total_fees") - } +// if res.Data.TxCount == 0 { +// githubActionWarning("/block_info", fmt.Sprintf("block(%s) tx count is 0", res.Data.Hash)) +// } else { +// assertIsPositive(t, res.Data.TotalOutput, "total_output") +// assertIsPositive(t, res.Data.TotalFees, "total_fees") +// } - assertNotEmpty(t, res.Data.VrfKey, "vrf_key") - assertNotEmpty(t, res.Data.OpCert, "op_cert") - // assertGreater(t, res.Data.OpCertCounter, 0, "op_cert_counter") - assertNotEmpty(t, res.Data.Pool, "pool") - assertGreater(t, res.Data.ProtoMajor, 0, "proto_major") - // assertGreater(t, res.Data.ProtoMinor, 0, "proto_minor") +// assertNotEmpty(t, res.Data.VrfKey, "vrf_key") +// assertNotEmpty(t, res.Data.OpCert, "op_cert") +// // assertGreater(t, res.Data.OpCertCounter, 0, "op_cert_counter") +// assertNotEmpty(t, res.Data.Pool, "pool") +// assertGreater(t, res.Data.ProtoMajor, 0, "proto_major") +// // assertGreater(t, res.Data.ProtoMinor, 0, "proto_minor") - assertGreater(t, res.Data.Confirmations, 0, "num_confirmations") - assertNotEmpty(t, res.Data.ParentHash, "parent_hash") - assertNotEmpty(t, res.Data.ChildHash, "child_hash") -} +// assertGreater(t, res.Data.Confirmations, 0, "num_confirmations") +// assertNotEmpty(t, res.Data.ParentHash, "parent_hash") +// assertNotEmpty(t, res.Data.ChildHash, "child_hash") +// } -func TestBlockTxs(t *testing.T) { - client, err := getLiveClient() - if testIsLocal(t, err) { - return - } - blockTxsTest(t, networkBlockHash(), client) -} +// func TestBlockTxs(t *testing.T) { +// client, err := getLiveClient() +// if testIsLocal(t, err) { +// return +// } +// blockTxsTest(t, networkBlockHash(), client) +// } -func blockTxsTest(t TestingT, hash koios.BlockHash, client *koios.Client) { - res, err := client.GetBlockTxs(context.Background(), hash, nil) - if err != nil { - if assert.ErrorIs(t, err, koios.ErrNoData) { - githubActionWarning("BlockTxs", err.Error()) - return - } - assert.NoError(t, err) - return - } - assertEqual(t, hash, res.Data.BlockHash, "req/res block hashes do not match") - assertGreater(t, len(res.Data.TxHashes), 0, "tx_hashes") -} +// func blockTxsTest(t TestingT, hash koios.BlockHash, client *koios.Client) { +// res, err := client.GetBlockTxs(context.Background(), hash, nil) +// if err != nil { +// if assert.ErrorIs(t, err, koios.ErrNoData) { +// githubActionWarning("BlockTxs", err.Error()) +// return +// } +// assert.NoError(t, err) +// return +// } +// assertEqual(t, hash, res.Data.BlockHash, "req/res block hashes do not match") +// assertGreater(t, len(res.Data.TxHashes), 0, "tx_hashes") +// } diff --git a/client_test.go b/client_test.go index 300c9af..64458d7 100644 --- a/client_test.go +++ b/client_test.go @@ -1,140 +1,117 @@ -// Copyright 2022 The Cardano Community Authors // SPDX-License-Identifier: Apache-2.0 // -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at: -// -// http://www.apache.org/licenses/LICENSE-2.0 -// or LICENSE file in repository root. -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. +// Copyright © 2022 The Cardano Community Authors package koios -import ( - "errors" - "fmt" - "net/http" - "net/url" - "testing" - "time" - - "github.com/stretchr/testify/assert" -) - -func TestNewDefaults(t *testing.T) { - api, err := New() - assert.NoError(t, err) - if assert.NotNil(t, api) { - raw := fmt.Sprintf( - "%s://%s/api/%s/", - DefaultScheme, - MainnetHost, - DefaultAPIVersion, - ) - u, err := url.ParseRequestURI(raw) - assert.NoError(t, err, "default url can not be constructed") - assert.Equal(t, u.String(), api.BaseURL(), "invalid default base url") - } -} - -func TestOptions(t *testing.T) { - api, err := New( - Host("localhost"), - APIVersion("v1"), - Port(8080), - Scheme("http"), - RateLimit(100), - Origin("http://localhost.localdomain"), - CollectRequestsStats(true), - ) - assert.NoError(t, err) - if assert.NotNil(t, api) { - assert.Equal(t, "http://localhost:8080/api/v1/", api.BaseURL(), "invalid default base url") - } - - api2, err2 := New(Scheme("ws")) - assert.EqualError(t, err2, "scheme must be http or https") - assert.Nil(t, api2) -} - -func TestOptionErrs(t *testing.T) { - client, _ := New() - assert.Error(t, HTTPClient(http.DefaultClient).apply(client), - "should not allow changing http client.") - assert.Error(t, RateLimit(0).apply(client), - "should not unlimited requests p/s") - assert.Error(t, Origin("localhost").apply(client), - "origin should be valid http origin") - _, err := New(Origin("localhost.localdomain")) - assert.Error(t, err, "New should return err when option is invalid") -} - -func TestHTTPClient(t *testing.T) { - client, err := New(HTTPClient(http.DefaultClient)) - assert.NotEqual(t, http.DefaultClient, client) - assert.Error(t, err) -} - -func TestReadResponseBody(t *testing.T) { - // enure that readResponseBody behaves consistently - nil1, nil2 := ReadResponseBody(nil) - assert.Nil(t, nil1) - assert.Nil(t, nil2) -} - -func TestNewClients(t *testing.T) { - c1, err := New() - assert.NoError(t, err) - assert.NotNil(t, c1) - - client := http.DefaultClient - client.Timeout = 10 * time.Second - c2, err2 := New(HTTPClient(client)) - assert.NoError(t, err2) - assert.NotNil(t, c2) - - c3, err := c1.WithOptions(HTTPClient(client)) - assert.NoError(t, err) - assert.NotNil(t, c3) -} - -var errApply = errors.New("apply error") - -func TestApplyError(t *testing.T) { - res := &Response{} - - res.applyError([]byte( - "{hint:\"the-hint\",details:\"the-details\",code:101,message:\"the-message\"}"), - errApply, - ) - assert.Equal(t, "apply error: invalid character 'h' looking for beginning of object key string", res.Error.Message) - - res.applyError( - []byte("{\"hint\":\"the-hint\",\"details\":\"the-details\",\"code\":\"101\",\"message\":\"the-message\"}"), - errApply, - ) - assert.Equal(t, "the-hint", res.Error.Hint) - assert.Equal(t, "apply error: the-message", res.Error.Message) - assert.Equal(t, ErrorCode("101"), res.Error.Code) - assert.Equal(t, "the-details", res.Error.Details) -} - -func TestBaseURL(t *testing.T) { - api, _ := New() - err := api.setBaseURL("http", "localhost", "v2", 9000) - assert.NoError(t, err) - assert.Equal(t, "http://localhost:9000/api/v2/", api.url.String()) - - err2 := api.setBaseURL("http", "localhost\\invalid", "v2", 9000) - assert.EqualError( - t, - err2, - "parse \"http://localhost\\\\invalid:9000/api/v2/\": invalid character \"\\\\\" in host name", - ) -} +// func TestNewDefaults(t *testing.T) { +// api, err := New() +// assert.NoError(t, err) +// if assert.NotNil(t, api) { +// raw := fmt.Sprintf( +// "%s://%s/api/%s/", +// DefaultScheme, +// MainnetHost, +// DefaultAPIVersion, +// ) +// u, err := url.ParseRequestURI(raw) +// assert.NoError(t, err, "default url can not be constructed") +// assert.Equal(t, u.String(), api.BaseURL(), "invalid default base url") +// } +// } + +// func TestOptions(t *testing.T) { +// api, err := New( +// Host("localhost"), +// APIVersion("v1"), +// Port(8080), +// Scheme("http"), +// RateLimit(100), +// Origin("http://localhost.localdomain"), +// CollectRequestsStats(true), +// ) +// assert.NoError(t, err) +// if assert.NotNil(t, api) { +// assert.Equal(t, "http://localhost:8080/api/v1/", api.BaseURL(), "invalid default base url") +// } + +// api2, err2 := New(Scheme("ws")) +// assert.EqualError(t, err2, "scheme must be http or https") +// assert.Nil(t, api2) +// } + +// func TestOptionErrs(t *testing.T) { +// client, _ := New() +// assert.Error(t, HTTPClient(http.DefaultClient).apply(client), +// "should not allow changing http client.") +// assert.Error(t, RateLimit(0).apply(client), +// "should not unlimited requests p/s") +// assert.Error(t, Origin("localhost").apply(client), +// "origin should be valid http origin") +// _, err := New(Origin("localhost.localdomain")) +// assert.Error(t, err, "New should return err when option is invalid") +// } + +// func TestHTTPClient(t *testing.T) { +// client, err := New(HTTPClient(http.DefaultClient)) +// assert.NotEqual(t, http.DefaultClient, client) +// assert.Error(t, err) +// } + +// func TestReadResponseBody(t *testing.T) { +// // enure that readResponseBody behaves consistently +// nil1, nil2 := ReadResponseBody(nil) +// assert.Nil(t, nil1) +// assert.Nil(t, nil2) +// } + +// func TestNewClients(t *testing.T) { +// c1, err := New() +// assert.NoError(t, err) +// assert.NotNil(t, c1) + +// client := http.DefaultClient +// client.Timeout = 10 * time.Second +// c2, err2 := New(HTTPClient(client)) +// assert.NoError(t, err2) +// assert.NotNil(t, c2) + +// c3, err := c1.WithOptions(HTTPClient(client)) +// assert.NoError(t, err) +// assert.NotNil(t, c3) +// } + +// var errApply = errors.New("apply error") + +// func TestApplyError(t *testing.T) { +// res := &Response{} + +// res.applyError([]byte( +// "{hint:\"the-hint\",details:\"the-details\",code:101,message:\"the-message\"}"), +// errApply, +// ) +// assert.Equal(t, "apply error: invalid character 'h' looking for beginning of object key string", res.Error.Message) + +// res.applyError( +// []byte("{\"hint\":\"the-hint\",\"details\":\"the-details\",\"code\":\"101\",\"message\":\"the-message\"}"), +// errApply, +// ) +// assert.Equal(t, "the-hint", res.Error.Hint) +// assert.Equal(t, "apply error: the-message", res.Error.Message) +// assert.Equal(t, ErrorCode("101"), res.Error.Code) +// assert.Equal(t, "the-details", res.Error.Details) +// } + +// func TestBaseURL(t *testing.T) { +// api, _ := New() +// err := api.setBaseURL("http", "localhost", "v2", 9000) +// assert.NoError(t, err) +// assert.Equal(t, "http://localhost:9000/api/v2/", api.url.String()) + +// err2 := api.setBaseURL("http", "localhost\\invalid", "v2", 9000) +// assert.EqualError( +// t, +// err2, +// "parse \"http://localhost\\\\invalid:9000/api/v2/\": invalid character \"\\\\\" in host name", +// ) +// } diff --git a/epoch_test.go b/epoch_test.go index d1d415a..f5a25f8 100644 --- a/epoch_test.go +++ b/epoch_test.go @@ -1,128 +1,107 @@ -// Copyright 2022 The Cardano Community Authors // SPDX-License-Identifier: Apache-2.0 // -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at: -// -// http://www.apache.org/licenses/LICENSE-2.0 -// or LICENSE file in repository root. -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. +// Copyright © 2022 The Cardano Community Authors package koios_test -import ( - "context" - "fmt" - "testing" - - "github.com/cardano-community/koios-go-client/v4" - "github.com/stretchr/testify/assert" -) - -func TestEpochInfo(t *testing.T) { - client, err := getLiveClient() - if testIsLocal(t, err) { - return - } - epochInfoTest(t, networkEpoch(), client) -} +// func TestEpochInfo(t *testing.T) { +// client, err := getLiveClient() +// if testIsLocal(t, err) { +// return +// } +// epochInfoTest(t, networkEpoch(), client) +// } -func epochInfoTest(t TestingT, epoch koios.EpochNo, client *koios.Client) { - res, err := client.GetEpochInfo(context.Background(), &epoch, nil) - if !assert.NoError(t, err) { - return - } - assertEqual(t, epoch, res.Data[0].EpochNo, "epoch_no") +// func epochInfoTest(t TestingT, epoch koios.EpochNo, client *koios.Client) { +// res, err := client.GetEpochInfo(context.Background(), &epoch, nil) +// if !assert.NoError(t, err) { +// return +// } +// assertEqual(t, epoch, res.Data[0].EpochNo, "epoch_no") - if res.Data[0].TxCount == 0 { - githubActionWarning("/epoch_info", fmt.Sprintf("epoch(%d) tx count is 0", res.Data[0].EpochNo)) - } else { - assertIsPositive(t, res.Data[0].Fees, "fees") - assertIsPositive(t, res.Data[0].OutSum, "out_sum") - } +// if res.Data[0].TxCount == 0 { +// githubActionWarning("/epoch_info", fmt.Sprintf("epoch(%d) tx count is 0", res.Data[0].EpochNo)) +// } else { +// assertIsPositive(t, res.Data[0].Fees, "fees") +// assertIsPositive(t, res.Data[0].OutSum, "out_sum") +// } - assertGreater(t, res.Data[0].BlkCount, 0, "blk_count") - assertTimeNotZero(t, res.Data[0].StartTime, "start_time") - assertTimeNotZero(t, res.Data[0].EndTime, "end_time") - assertTimeNotZero(t, res.Data[0].FirstBlockTime, "first_block_time") - assertTimeNotZero(t, res.Data[0].LastBlockTime, "last_block_time") - assertIsPositive(t, res.Data[0].ActiveStake, "active_stake") - assertIsPositive(t, res.Data[0].TotalRewards, "total_rewards") - assertIsPositive(t, res.Data[0].AvgBlkReward, "avg_blk_reward") -} +// assertGreater(t, res.Data[0].BlkCount, 0, "blk_count") +// assertTimeNotZero(t, res.Data[0].StartTime, "start_time") +// assertTimeNotZero(t, res.Data[0].EndTime, "end_time") +// assertTimeNotZero(t, res.Data[0].FirstBlockTime, "first_block_time") +// assertTimeNotZero(t, res.Data[0].LastBlockTime, "last_block_time") +// assertIsPositive(t, res.Data[0].ActiveStake, "active_stake") +// assertIsPositive(t, res.Data[0].TotalRewards, "total_rewards") +// assertIsPositive(t, res.Data[0].AvgBlkReward, "avg_blk_reward") +// } -func TestEpochParams(t *testing.T) { - client, err := getLiveClient() - if testIsLocal(t, err) { - return - } - epochParamsTest(t, networkEpoch(), client) +// func TestEpochParams(t *testing.T) { +// client, err := getLiveClient() +// if testIsLocal(t, err) { +// return +// } +// epochParamsTest(t, networkEpoch(), client) -} +// } -func epochParamsTest(t TestingT, epoch koios.EpochNo, client *koios.Client) { - res, err := client.GetEpochParams(context.Background(), &epoch, nil) - if !assert.NoError(t, err) { - return - } +// func epochParamsTest(t TestingT, epoch koios.EpochNo, client *koios.Client) { +// res, err := client.GetEpochParams(context.Background(), &epoch, nil) +// if !assert.NoError(t, err) { +// return +// } - // assertGreater(t, res.Data[0].Decentralisation, 0, "decentralisation") - // assertNotEmpty(t, res.Data[0].ExtraEntropy, "extra_entropy") - // assertGreater(t, res.Data[0].ProtocolMinor, 0, "protocol_minor") +// // assertGreater(t, res.Data[0].Decentralisation, 0, "decentralisation") +// // assertNotEmpty(t, res.Data[0].ExtraEntropy, "extra_entropy") +// // assertGreater(t, res.Data[0].ProtocolMinor, 0, "protocol_minor") - assertEqual(t, epoch, res.Data[0].EpochNo, "epoch_no") - assertIsPositive(t, res.Data[0].MinFeeA, "min_fee_a") - assertIsPositive(t, res.Data[0].MinFeeB, "min_fee_b") - assertGreater(t, res.Data[0].MaxBlockSize, 0, "max_block_size") - assertGreater(t, res.Data[0].MaxTxSize, 0, "max_tx_size") - assertGreater(t, res.Data[0].MaxBhSize, 0, "max_bh_size") - assertNotEmpty(t, res.Data[0].KeyDeposit, "key_deposit") - assertNotEmpty(t, res.Data[0].PoolDeposit, "pool_deposit") - assertGreater(t, res.Data[0].MaxEpoch, 0, "max_epoch") - assertGreater(t, res.Data[0].OptimalPoolCount, 0, "optimal_pool_count") - assertGreater(t, res.Data[0].Influence, 0, "influence") - assertGreater(t, res.Data[0].MonetaryExpandRate, 0, "monetary_expand_rate") - assertGreater(t, res.Data[0].TreasuryGrowthRate, 0, "treasury_growth_rate") - assertGreater(t, res.Data[0].ProtocolMajor, 0, "protocol_major") - assertIsPositive(t, res.Data[0].MinUtxoValue, "min_utxo_value") - assertIsPositive(t, res.Data[0].MinPoolCost, "min_pool_cost") - assertNotEmpty(t, res.Data[0].Nonce, "nonce") - assertNotEmpty(t, res.Data[0].BlockHash.String(), "block_hash") - assertNotEmpty(t, res.Data[0].CostModels, "cost_models") - assertIsPositive(t, res.Data[0].PriceMem, "price_mem") - assertIsPositive(t, res.Data[0].PriceStep, "price_step") - assertGreater(t, res.Data[0].MaxTxExMem, 0, "max_tx_ex_mem") - assertGreater(t, res.Data[0].MaxTxExSteps, 0, "max_tx_ex_steps") - assertGreater(t, res.Data[0].MaxBlockExMem, 0, "max_block_ex_mem") - assertGreater(t, res.Data[0].MaxBlockExSteps, 0, "max_block_ex_steps") - assertGreater(t, res.Data[0].MaxValSize, 0, "max_val_size") - assertGreater(t, res.Data[0].CollateralPercent, 0, "collateral_percent") - assertGreater(t, res.Data[0].MaxCollateralInputs, 0, "max_collateral_inputs") - assertIsPositive(t, res.Data[0].CoinsPerUtxoSize, "coins_per_utxo_size") - assertIsPositive(t, res.Data[0].CoinsPerUtxoSize, "coins_per_utxo_size") -} +// assertEqual(t, epoch, res.Data[0].EpochNo, "epoch_no") +// assertIsPositive(t, res.Data[0].MinFeeA, "min_fee_a") +// assertIsPositive(t, res.Data[0].MinFeeB, "min_fee_b") +// assertGreater(t, res.Data[0].MaxBlockSize, 0, "max_block_size") +// assertGreater(t, res.Data[0].MaxTxSize, 0, "max_tx_size") +// assertGreater(t, res.Data[0].MaxBhSize, 0, "max_bh_size") +// assertNotEmpty(t, res.Data[0].KeyDeposit, "key_deposit") +// assertNotEmpty(t, res.Data[0].PoolDeposit, "pool_deposit") +// assertGreater(t, res.Data[0].MaxEpoch, 0, "max_epoch") +// assertGreater(t, res.Data[0].OptimalPoolCount, 0, "optimal_pool_count") +// assertGreater(t, res.Data[0].Influence, 0, "influence") +// assertGreater(t, res.Data[0].MonetaryExpandRate, 0, "monetary_expand_rate") +// assertGreater(t, res.Data[0].TreasuryGrowthRate, 0, "treasury_growth_rate") +// assertGreater(t, res.Data[0].ProtocolMajor, 0, "protocol_major") +// assertIsPositive(t, res.Data[0].MinUtxoValue, "min_utxo_value") +// assertIsPositive(t, res.Data[0].MinPoolCost, "min_pool_cost") +// assertNotEmpty(t, res.Data[0].Nonce, "nonce") +// assertNotEmpty(t, res.Data[0].BlockHash.String(), "block_hash") +// assertNotEmpty(t, res.Data[0].CostModels, "cost_models") +// assertIsPositive(t, res.Data[0].PriceMem, "price_mem") +// assertIsPositive(t, res.Data[0].PriceStep, "price_step") +// assertGreater(t, res.Data[0].MaxTxExMem, 0, "max_tx_ex_mem") +// assertGreater(t, res.Data[0].MaxTxExSteps, 0, "max_tx_ex_steps") +// assertGreater(t, res.Data[0].MaxBlockExMem, 0, "max_block_ex_mem") +// assertGreater(t, res.Data[0].MaxBlockExSteps, 0, "max_block_ex_steps") +// assertGreater(t, res.Data[0].MaxValSize, 0, "max_val_size") +// assertGreater(t, res.Data[0].CollateralPercent, 0, "collateral_percent") +// assertGreater(t, res.Data[0].MaxCollateralInputs, 0, "max_collateral_inputs") +// assertIsPositive(t, res.Data[0].CoinsPerUtxoSize, "coins_per_utxo_size") +// assertIsPositive(t, res.Data[0].CoinsPerUtxoSize, "coins_per_utxo_size") +// } -func TestEpochBlockProtocols(t *testing.T) { - client, err := getLiveClient() - if testIsLocal(t, err) { - return - } - epochBlockProtocolsTest(t, networkEpoch(), client) +// func TestEpochBlockProtocols(t *testing.T) { +// client, err := getLiveClient() +// if testIsLocal(t, err) { +// return +// } +// epochBlockProtocolsTest(t, networkEpoch(), client) -} +// } -func epochBlockProtocolsTest(t TestingT, epoch koios.EpochNo, client *koios.Client) { - res, err := client.GetEpochBlockProtocols(context.Background(), &epoch, nil) - if !assert.NoError(t, err) { - return - } - assertGreater(t, res.Data[0].ProtoMajor, 0, "proto_major") - // assertGreater(t, res.Data[0].ProtoMinor, 0, "proto_minor") - assertGreater(t, res.Data[0].Blocks, 0, "blocks") -} +// func epochBlockProtocolsTest(t TestingT, epoch koios.EpochNo, client *koios.Client) { +// res, err := client.GetEpochBlockProtocols(context.Background(), &epoch, nil) +// if !assert.NoError(t, err) { +// return +// } +// assertGreater(t, res.Data[0].ProtoMajor, 0, "proto_major") +// // assertGreater(t, res.Data[0].ProtoMinor, 0, "proto_minor") +// assertGreater(t, res.Data[0].Blocks, 0, "blocks") +// } diff --git a/koios_test.go b/koios_test.go index c1cb00f..ec0d453 100644 --- a/koios_test.go +++ b/koios_test.go @@ -1,421 +1,398 @@ -// Copyright 2022 The Cardano Community Authors // SPDX-License-Identifier: Apache-2.0 // -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at: -// -// http://www.apache.org/licenses/LICENSE-2.0 -// or LICENSE file in repository root. -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. +// Copyright © 2022 The Cardano Community Authors package koios_test -import ( - "errors" - "fmt" - "os" - "testing" - - "github.com/cardano-community/koios-go-client/v4" - "github.com/shopspring/decimal" - "github.com/stretchr/testify/assert" -) - -// TestingT is an interface wrapper around *testing.T -type TestingT interface { - Errorf(format string, args ...any) - Error(args ...any) - SkipNow() -} - -var errLocalClient = errors.New("local client is used") - -func networkEpoch() koios.EpochNo { - var epoch koios.EpochNo - switch os.Getenv("KOIOS_NETWORK") { - case "guild": - epoch = koios.EpochNo(1950) - case "mainnet": - epoch = koios.EpochNo(320) - case "preprod": - epoch = koios.EpochNo(31) - case "preview": - epoch = koios.EpochNo(12) - default: - // local - epoch = koios.EpochNo(0) - } - return epoch -} - -func networkBlockHash() koios.BlockHash { - var hash koios.BlockHash - switch os.Getenv("KOIOS_NETWORK") { - case "guild": - hash = koios.BlockHash("bddbbc6df0ad09567a513349bafd56d8ec5c8fcd9ee9db12173624b896350d57") - case "mainnet": - hash = koios.BlockHash("fb9087c9f1408a7bbd7b022fd294ab565fec8dd3a8ef091567482722a1fa4e30") - case "preprod": - hash = koios.BlockHash("2abeb8d1c1227139763be30ddb7a2fd79abd7d44195fca87a7c836a510b2802d") - case "preview": - hash = koios.BlockHash("a4504e2495ed03b48be36676f430c54dca0769d29f72ebf18d493abf42d2167b") - default: - // mainnet - hash = koios.BlockHash("") - } - return hash -} - -func networkTxHashes() []koios.TxHash { - var hash []koios.TxHash - switch os.Getenv("KOIOS_NETWORK") { - case "guild": - hash = []koios.TxHash{ - "bf04578d452dd3acb7c70fbac32dc972cb69f932f804171cfb4268f5af0228e7", - "63b716064012f858450731cb5f960c100c6cb639ec1ec999b898c604451f116a", - } - case "mainnet": - hash = []koios.TxHash{ - "f144a8264acf4bdfe2e1241170969c930d64ab6b0996a4a45237b623f1dd670e", - "0b8ba3bed976fa4913f19adc9f6dd9063138db5b4dd29cecde369456b5155e94", - } - case "preprod": - hash = []koios.TxHash{ - "d10133964da9e443b303917fd0b7644ae3d01c133deff85b4f59416c2d00f530", - "145688d3619e7524510ea64c0ec6363b77a9b8da179ef9bb0273a0940d57d576", - } - case "preview": - hash = []koios.TxHash{ - "f1592b29b79ae85d753913dd25644c60925a4a0683979faa33832fead4b4bd9c", - "206f6da5b0b0de45605a95f5ce7e172be9674550f7dde3838c45cbf24bab8b00", - } - default: - // local - hash = []koios.TxHash{} - } - return hash -} - -func networkPoolID() koios.PoolID { - switch os.Getenv("KOIOS_NETWORK") { - case "guild": - return "pool1xc9eywck4e20tydz4yvh5vfe0ep8whawvwz8wqkc9k046a2ypp4" - case "mainnet": - return "pool155efqn9xpcf73pphkk88cmlkdwx4ulkg606tne970qswczg3asc" - case "preprod": - return "pool1ext7qrwjzaxcdfhdnkq5mth59ukuu2atcg6tgqpmevpt7ratkta" - case "preview": - return "pool1p90428kec03mjdya3k4gv5d20w7lmed7ca0snknef5j977l3y8l" - default: - // local - return "" - } -} - -func networkScriptHash() koios.ScriptHash { - switch os.Getenv("KOIOS_NETWORK") { - case "guild": - return "160301a01ee86d8e46cbe3aef1e3bf69bfa28c65d5be2dde56a37af8" - case "mainnet": - return "d8480dc869b94b80e81ec91b0abe307279311fe0e7001a9488f61ff8" - case "preprod": - return "590555d7b5760e98ae2bdd29b356247776251dfab0a207bfce98a485" - case "preview": - return "f758cf422ca0cbed7d9d6fad1eb5a3c70537d62e661ad450dd2a3810" - default: - // local - return "" - } -} - -func networkDatumHash() koios.DatumHash { - switch os.Getenv("KOIOS_NETWORK") { - case "guild": - return "45b0cfc220ceec5b7c1c62c4d4193d38e4eba48e8815729ce75f9c0ab0e4c1c0" - case "preprod": - return "5571e2c3549f15934a38382d1318707a86751fb70827f4cbd29b104480f1be9b" - case "preview": - return "6181b3dc623cd8812caf027a3507e9b3095388a7cf3db65983e1fddd3a84c88c" - case "mainnet": - return "818ee3db3bbbd04f9f2ce21778cac3ac605802a4fcb00c8b3a58ee2dafc17d46" - default: - // local - return "" - } -} - -func networkAddresses() []koios.Address { - var addrs []koios.Address - switch os.Getenv("KOIOS_NETWORK") { - case "guild": - addrs = []koios.Address{ - "addr_test1qzmtfv43a8ncx6ve92ja6yy25npn9raz9pu5a2tfxsqv9gy9ktf0pu6yu4zjh9r37fzx3h4tsxqdjhu3t4d5ffdsfz9s6ska3z", - "addr_test1vq67g5u8ls4vm4wdvs0r8xvsuej66nvaqedyrj2tcz6tuycz275pu", - } - case "mainnet": - addrs = []koios.Address{ - "addr1qyp9kz50sh9c53hpmk3l4ewj9ur794t2hdqpngsjn3wkc5sztv9glpwt3frwrhdrltjaytc8ut2k4w6qrx3p98zad3fq07xe9g", - "addr1qyfldpcvte8nkfpyv0jdc8e026cz5qedx7tajvupdu2724tlj8sypsq6p90hl40ya97xamkm9fwsppus2ru8zf6j8g9sm578cu", - } - case "preprod": - addrs = []koios.Address{ - "addr_test1vzpwq95z3xyum8vqndgdd9mdnmafh3djcxnc6jemlgdmswcve6tkw", - "addr_test1vpfwv0ezc5g8a4mkku8hhy3y3vp92t7s3ul8g778g5yegsgalc6gc", - } - case "preview": - addrs = []koios.Address{ - "addr_test1vpfwv0ezc5g8a4mkku8hhy3y3vp92t7s3ul8g778g5yegsgalc6gc", - "addr_test1vqneq3v0dqh3x3muv6ee3lt8e5729xymnxuavx6tndcjc2cv24ef9", - } - default: - // mainnet - addrs = []koios.Address{} - } - return addrs -} - -func networkPaymentCredentials() []koios.PaymentCredential { - var creds []koios.PaymentCredential - switch os.Getenv("KOIOS_NETWORK") { - case "guild": - creds = []koios.PaymentCredential{ - "b6b4b2b1e9e78369992aa5dd108aa4c3328fa228794ea9693400c2a0", - "35e45387fc2acdd5cd641e339990e665ad4d9d065a41c94bc0b4be13", - } - case "mainnet": - creds = []koios.PaymentCredential{ - "025b0a8f85cb8a46e1dda3fae5d22f07e2d56abb4019a2129c5d6c52", - "13f6870c5e4f3b242463e4dc1f2f56b02a032d3797d933816f15e555", - } - case "preprod": - creds = []koios.PaymentCredential{ - "b429738bd6cc58b5c7932d001aa2bd05cfea47020a556c8c753d4436", - "82e016828989cd9d809b50d6976d9efa9bc5b2c1a78d4b3bfa1bb83b", - } - case "preview": - creds = []koios.PaymentCredential{ - "33c378cee41b2e15ac848f7f6f1d2f78155ab12d93b713de898d855f", - "52e63f22c5107ed776b70f7b92248b02552fd08f3e747bc745099441", - } - default: - // local - creds = []koios.PaymentCredential{} - - } - return creds -} - -func networkAccounts() []koios.Address { - var accs []koios.Address - switch os.Getenv("KOIOS_NETWORK") { - case "guild": - accs = []koios.Address{ - "stake_test17zt9x005zkd2usz2vhvktyzqsuwz25gmgnaqdka5hcj9m2qfg2py2", - "stake_test1uzzm95hs7dzw23ftj3cly3rgm64crqxet7g46k6y5kcy3zcs3mpjd", - } - case "mainnet": - accs = []koios.Address{ - "stake1uyfmzu5qqy70a8kq4c8rw09q0w0ktfcxppwujejnsh6tyrg5c774g", - "stake1uydhlh7f2kkw9eazct5zyzlrvj32gjnkmt2v5qf6t8rut4qwch8ey", - } - case "preprod": - accs = []koios.Address{ - "stake_test1urq4rcynzj4uxqc74c852zky7wa6epgmn9r6k3j3gv7502q8jks0l", - "stake_test1ur4t5nhceyn2amfuj7z74uxmmj8jf9fmgd2egqw8c98ve3cp2g4wx", - } - case "preview": - accs = []koios.Address{ - "stake_test1upv7n2x0lxepkyx8ux2gjt74ecaa39tjgaccxl6hw5fwzngpzf5zt", - "stake_test1up6wqzrw2h9vvjy5zfkjn0dwtymy5r29zyhf8fyhm6fat9c2am5hl", - } - default: - // local - accs = []koios.Address{} - } - return accs -} - -func networkPolicyAsset() (koios.PolicyID, koios.AssetName, int, bool) { - switch os.Getenv("KOIOS_NETWORK") { - case "guild": - return "313534a537bc476c86ff7c57ec511bd7f24a9d15654091b24e9c606e", "41484c636f696e", 63487, true - case "mainnet": - return "d3501d9531fcc25e3ca4b6429318c2cc374dbdbcf5e99c1c1e5da1ff", "444f4e545350414d", 63487, true - case "preprod": - return "c6e65ba7878b2f8ea0ad39287d3e2fd256dc5c4160fc19bdf4c4d87e", "7447454e53", 50000, true - case "preview": - return "065270479316f1d92e00f7f9f095ebeaac9d009c878dc35ce36d3404", "433374", 50000, true - default: - // mainnet - return "", "", 0, false - } -} - -func getLiveClient() (client *koios.Client, err error) { - net, ok := os.LookupEnv("KOIOS_NETWORK") - if !ok { - return nil, fmt.Errorf("%w: KOIOS_NETWORK not set", errLocalClient) - } - var host string - switch net { - case "mainnet": - host = koios.MainnetHost - case "guild": - host = koios.GuildHost - case "preprod": - host = koios.PreProdHost - case "preview": - host = koios.PreviewHost - default: - return nil, fmt.Errorf("invalid KOIOS_NETWORK=%q", net) - } - return koios.New(koios.Host(host)) -} - -func assertEqual[V comparable](t TestingT, want, got V, tag string) bool { - msg := fmt.Sprintf("%s: want(%v) got(%v)", tag, want, got) - return assert.Equal(t, want, got, msg) -} - -func assertIsPositive(t TestingT, in decimal.Decimal, tag string) bool { - msg := fmt.Sprintf("%s: should be positive got %s", tag, in.String()) - return assert.True(t, in.IsPositive(), msg) -} - -func assertCoinNotZero(t TestingT, in decimal.Decimal, tag string) bool { - msg := fmt.Sprintf("%s: should not be 0", tag) - return assert.True(t, !in.IsZero(), msg) -} - -func assertGreater[V any](t TestingT, count, min V, tag string) bool { - msg := fmt.Sprintf("%s: should be greater than %v", tag, min) - return assert.Greater(t, count, min, msg) -} - -func assertNotEmpty(t TestingT, in any, tag string) bool { - msg := fmt.Sprintf("%s: in(%v)", tag, in) - return assert.NotEmpty(t, in, msg) -} - -func assertTimeNotZero(t TestingT, in koios.Timestamp, tag string) bool { - msg := fmt.Sprintf("%s: time is empty or not parsed from return value", tag) - return assert.False(t, in.Time.IsZero(), msg) -} - -func assertEUTxO(t TestingT, eutxo koios.EUTxO, tag string) { - assertNotEmpty(t, eutxo.TxHash, fmt.Sprintf("eutxo[%s].tx_hash", eutxo.TxHash)) - for i, utxo := range eutxo.Inputs { - assertUTxO(t, utxo, fmt.Sprintf("eutxo[%s].inputs[%d]", eutxo.TxHash, i)) - } - for i, utxo := range eutxo.Inputs { - assertUTxO(t, utxo, fmt.Sprintf("eutxo[%s].outputs[%d]", eutxo.TxHash, i)) - } -} - -func assertUTxO(t TestingT, utxo koios.UTxO, tag string) { - assertNotEmpty(t, utxo.TxHash, fmt.Sprintf("%s.tx_hash", tag)) - assertGreater(t, utxo.TxIndex, -1, fmt.Sprintf("%s.tx_index", tag)) - - if utxo.PaymentAddr != nil { - assertNotEmpty(t, utxo.PaymentAddr.Bech32, fmt.Sprintf("%s.payment_addr.bech32", tag)) - assertNotEmpty(t, utxo.PaymentAddr.Cred, fmt.Sprintf("%s.payment_addr.cred", tag)) - } - if utxo.StakeAddress != nil { - assertNotEmpty(t, utxo.StakeAddress, fmt.Sprintf("%s.stake_addr", tag)) - } - // assertGreater(t, utxo.BlockHeight, 0, fmt.Sprintf("%s.block_height", tag)) - // assertTimeNotZero(t, utxo.BlockTime, fmt.Sprintf("%s.block_time", tag)) - assertIsPositive(t, utxo.Value, fmt.Sprintf("%s.value", tag)) - - // assertNotEmpty(t, utxo.DatumHash, fmt.Sprintf("%s.datum_hash", tag)) - - if utxo.InlineDatum != nil { - assertNotEmpty(t, "", fmt.Sprintf("%s.inline_datum", tag)) - } - if utxo.ReferenceScript != nil { - assertNotEmpty(t, "", fmt.Sprintf("%s.reference_script", tag)) - } - if len(utxo.AssetList) > 0 { - for i, asset := range utxo.AssetList { - assertAsset(t, asset, fmt.Sprintf("%s.asset_list[%d]", tag, i)) - } - } -} - -func assertAsset(t TestingT, asset koios.Asset, tag string) { - // assertNotEmpty(t, asset.Name, fmt.Sprintf("%s.asset_name", tag)) - // assertNotEmpty(t, asset.Fingerprint, fmt.Sprintf("%s.fingerprint", tag)) - assertNotEmpty(t, asset.PolicyID, fmt.Sprintf("%s.policy_id", tag)) - assertIsPositive(t, asset.Quantity, fmt.Sprintf("%s.quantity", tag)) -} - -func assertTxMetadata(t TestingT, metadata koios.TxMetadata, tag string) { - if len(metadata) == 0 { - return - } - for key, json := range metadata { - assertNotEmpty(t, key, fmt.Sprintf("%s[%s]", tag, key)) - assertNotEmpty(t, json, fmt.Sprintf("%s[%s]", tag, json)) - } -} - -func assertCertificates(t TestingT, certs []koios.Certificate, tag string) { - for i, cert := range certs { - // assertGreater(t, cert.Index, 0, fmt.Sprintf("%s[%d].index", tag, i)) - assertNotEmpty(t, cert.Type, fmt.Sprintf("%s[%d].type", tag, i)) - assertNotEmpty(t, cert.Info, fmt.Sprintf("%s[%d].info", tag, i)) - } -} - -func assertNativeScripts(t TestingT, nscripts []koios.NativeScript, tag string) { - for i, nscript := range nscripts { - assertNotEmpty(t, nscript.CreationTxHash, fmt.Sprintf("%s[%d].creation_tx_hash", tag, i)) - assertNotEmpty(t, nscript.ScriptHash, fmt.Sprintf("%s[%d].script_hash", tag, i)) - assertNotEmpty(t, nscript.Type, fmt.Sprintf("%s[%d].type", tag, i)) - assertNotEmpty(t, nscript.Script.Type, fmt.Sprintf("%s[%d].script.type", tag, i)) - - for j, script := range nscript.Script.Scripts { - assertNotEmpty(t, script, fmt.Sprintf("%s[%d].scripts[%d]", tag, i, j)) - } - } -} - -func assertPlutusContracts(t TestingT, contracts []koios.PlutusContract, tag string) { - for i, contract := range contracts { - assertNotEmpty(t, contract.Address, fmt.Sprintf("%s[%d].address", tag, i)) - assertNotEmpty(t, contract.ScriptHash, fmt.Sprintf("%s[%d].script_hash", tag, i)) - assertNotEmpty(t, contract.ByteCode, fmt.Sprintf("%s[%d].bytecode", tag, i)) - assertGreater(t, contract.Size, 0, fmt.Sprintf("%s[%d].size", tag, i)) - assert.True(t, contract.ValidContract, 0, fmt.Sprintf("%s[%d].valid_contract", tag, i)) - } -} - -func githubActionWarning(title, msg string) { - fmt.Printf( - "::warning title=%s::%q\n", - title, - msg, - ) -} - -func testIsLocal(t TestingT, err error) bool { - if err == nil { - return false - } - if errors.Is(err, errLocalClient) { - t.SkipNow() - return true - } - t.Error(err) - return false -} - -func TestVersion(t *testing.T) { - assertNotEmpty(t, koios.Version(), "koios.Version()") -} +// // TestingT is an interface wrapper around *testing.T +// type TestingT interface { +// Errorf(format string, args ...any) +// Error(args ...any) +// SkipNow() +// } + +// var errLocalClient = errors.New("local client is used") + +// func networkEpoch() koios.EpochNo { +// var epoch koios.EpochNo +// switch os.Getenv("KOIOS_NETWORK") { +// case "guild": +// epoch = koios.EpochNo(1950) +// case "mainnet": +// epoch = koios.EpochNo(320) +// case "preprod": +// epoch = koios.EpochNo(31) +// case "preview": +// epoch = koios.EpochNo(12) +// default: +// // local +// epoch = koios.EpochNo(0) +// } +// return epoch +// } + +// func networkBlockHash() koios.BlockHash { +// var hash koios.BlockHash +// switch os.Getenv("KOIOS_NETWORK") { +// case "guild": +// hash = koios.BlockHash("bddbbc6df0ad09567a513349bafd56d8ec5c8fcd9ee9db12173624b896350d57") +// case "mainnet": +// hash = koios.BlockHash("fb9087c9f1408a7bbd7b022fd294ab565fec8dd3a8ef091567482722a1fa4e30") +// case "preprod": +// hash = koios.BlockHash("2abeb8d1c1227139763be30ddb7a2fd79abd7d44195fca87a7c836a510b2802d") +// case "preview": +// hash = koios.BlockHash("a4504e2495ed03b48be36676f430c54dca0769d29f72ebf18d493abf42d2167b") +// default: +// // mainnet +// hash = koios.BlockHash("") +// } +// return hash +// } + +// func networkTxHashes() []koios.TxHash { +// var hash []koios.TxHash +// switch os.Getenv("KOIOS_NETWORK") { +// case "guild": +// hash = []koios.TxHash{ +// "bf04578d452dd3acb7c70fbac32dc972cb69f932f804171cfb4268f5af0228e7", +// "63b716064012f858450731cb5f960c100c6cb639ec1ec999b898c604451f116a", +// } +// case "mainnet": +// hash = []koios.TxHash{ +// "f144a8264acf4bdfe2e1241170969c930d64ab6b0996a4a45237b623f1dd670e", +// "0b8ba3bed976fa4913f19adc9f6dd9063138db5b4dd29cecde369456b5155e94", +// } +// case "preprod": +// hash = []koios.TxHash{ +// "d10133964da9e443b303917fd0b7644ae3d01c133deff85b4f59416c2d00f530", +// "145688d3619e7524510ea64c0ec6363b77a9b8da179ef9bb0273a0940d57d576", +// } +// case "preview": +// hash = []koios.TxHash{ +// "f1592b29b79ae85d753913dd25644c60925a4a0683979faa33832fead4b4bd9c", +// "206f6da5b0b0de45605a95f5ce7e172be9674550f7dde3838c45cbf24bab8b00", +// } +// default: +// // local +// hash = []koios.TxHash{} +// } +// return hash +// } + +// func networkPoolID() koios.PoolID { +// switch os.Getenv("KOIOS_NETWORK") { +// case "guild": +// return "pool1xc9eywck4e20tydz4yvh5vfe0ep8whawvwz8wqkc9k046a2ypp4" +// case "mainnet": +// return "pool155efqn9xpcf73pphkk88cmlkdwx4ulkg606tne970qswczg3asc" +// case "preprod": +// return "pool1ext7qrwjzaxcdfhdnkq5mth59ukuu2atcg6tgqpmevpt7ratkta" +// case "preview": +// return "pool1p90428kec03mjdya3k4gv5d20w7lmed7ca0snknef5j977l3y8l" +// default: +// // local +// return "" +// } +// } + +// func networkScriptHash() koios.ScriptHash { +// switch os.Getenv("KOIOS_NETWORK") { +// case "guild": +// return "160301a01ee86d8e46cbe3aef1e3bf69bfa28c65d5be2dde56a37af8" +// case "mainnet": +// return "d8480dc869b94b80e81ec91b0abe307279311fe0e7001a9488f61ff8" +// case "preprod": +// return "590555d7b5760e98ae2bdd29b356247776251dfab0a207bfce98a485" +// case "preview": +// return "f758cf422ca0cbed7d9d6fad1eb5a3c70537d62e661ad450dd2a3810" +// default: +// // local +// return "" +// } +// } + +// func networkDatumHash() koios.DatumHash { +// switch os.Getenv("KOIOS_NETWORK") { +// case "guild": +// return "45b0cfc220ceec5b7c1c62c4d4193d38e4eba48e8815729ce75f9c0ab0e4c1c0" +// case "preprod": +// return "5571e2c3549f15934a38382d1318707a86751fb70827f4cbd29b104480f1be9b" +// case "preview": +// return "6181b3dc623cd8812caf027a3507e9b3095388a7cf3db65983e1fddd3a84c88c" +// case "mainnet": +// return "818ee3db3bbbd04f9f2ce21778cac3ac605802a4fcb00c8b3a58ee2dafc17d46" +// default: +// // local +// return "" +// } +// } + +// func networkAddresses() []koios.Address { +// var addrs []koios.Address +// switch os.Getenv("KOIOS_NETWORK") { +// case "guild": +// addrs = []koios.Address{ +// "addr_test1qzmtfv43a8ncx6ve92ja6yy25npn9raz9pu5a2tfxsqv9gy9ktf0pu6yu4zjh9r37fzx3h4tsxqdjhu3t4d5ffdsfz9s6ska3z", +// "addr_test1vq67g5u8ls4vm4wdvs0r8xvsuej66nvaqedyrj2tcz6tuycz275pu", +// } +// case "mainnet": +// addrs = []koios.Address{ +// "addr1qyp9kz50sh9c53hpmk3l4ewj9ur794t2hdqpngsjn3wkc5sztv9glpwt3frwrhdrltjaytc8ut2k4w6qrx3p98zad3fq07xe9g", +// "addr1qyfldpcvte8nkfpyv0jdc8e026cz5qedx7tajvupdu2724tlj8sypsq6p90hl40ya97xamkm9fwsppus2ru8zf6j8g9sm578cu", +// } +// case "preprod": +// addrs = []koios.Address{ +// "addr_test1vzpwq95z3xyum8vqndgdd9mdnmafh3djcxnc6jemlgdmswcve6tkw", +// "addr_test1vpfwv0ezc5g8a4mkku8hhy3y3vp92t7s3ul8g778g5yegsgalc6gc", +// } +// case "preview": +// addrs = []koios.Address{ +// "addr_test1vpfwv0ezc5g8a4mkku8hhy3y3vp92t7s3ul8g778g5yegsgalc6gc", +// "addr_test1vqneq3v0dqh3x3muv6ee3lt8e5729xymnxuavx6tndcjc2cv24ef9", +// } +// default: +// // mainnet +// addrs = []koios.Address{} +// } +// return addrs +// } + +// func networkPaymentCredentials() []koios.PaymentCredential { +// var creds []koios.PaymentCredential +// switch os.Getenv("KOIOS_NETWORK") { +// case "guild": +// creds = []koios.PaymentCredential{ +// "b6b4b2b1e9e78369992aa5dd108aa4c3328fa228794ea9693400c2a0", +// "35e45387fc2acdd5cd641e339990e665ad4d9d065a41c94bc0b4be13", +// } +// case "mainnet": +// creds = []koios.PaymentCredential{ +// "025b0a8f85cb8a46e1dda3fae5d22f07e2d56abb4019a2129c5d6c52", +// "13f6870c5e4f3b242463e4dc1f2f56b02a032d3797d933816f15e555", +// } +// case "preprod": +// creds = []koios.PaymentCredential{ +// "b429738bd6cc58b5c7932d001aa2bd05cfea47020a556c8c753d4436", +// "82e016828989cd9d809b50d6976d9efa9bc5b2c1a78d4b3bfa1bb83b", +// } +// case "preview": +// creds = []koios.PaymentCredential{ +// "33c378cee41b2e15ac848f7f6f1d2f78155ab12d93b713de898d855f", +// "52e63f22c5107ed776b70f7b92248b02552fd08f3e747bc745099441", +// } +// default: +// // local +// creds = []koios.PaymentCredential{} + +// } +// return creds +// } + +// func networkAccounts() []koios.Address { +// var accs []koios.Address +// switch os.Getenv("KOIOS_NETWORK") { +// case "guild": +// accs = []koios.Address{ +// "stake_test17zt9x005zkd2usz2vhvktyzqsuwz25gmgnaqdka5hcj9m2qfg2py2", +// "stake_test1uzzm95hs7dzw23ftj3cly3rgm64crqxet7g46k6y5kcy3zcs3mpjd", +// } +// case "mainnet": +// accs = []koios.Address{ +// "stake1uyfmzu5qqy70a8kq4c8rw09q0w0ktfcxppwujejnsh6tyrg5c774g", +// "stake1uydhlh7f2kkw9eazct5zyzlrvj32gjnkmt2v5qf6t8rut4qwch8ey", +// } +// case "preprod": +// accs = []koios.Address{ +// "stake_test1urq4rcynzj4uxqc74c852zky7wa6epgmn9r6k3j3gv7502q8jks0l", +// "stake_test1ur4t5nhceyn2amfuj7z74uxmmj8jf9fmgd2egqw8c98ve3cp2g4wx", +// } +// case "preview": +// accs = []koios.Address{ +// "stake_test1upv7n2x0lxepkyx8ux2gjt74ecaa39tjgaccxl6hw5fwzngpzf5zt", +// "stake_test1up6wqzrw2h9vvjy5zfkjn0dwtymy5r29zyhf8fyhm6fat9c2am5hl", +// } +// default: +// // local +// accs = []koios.Address{} +// } +// return accs +// } + +// func networkPolicyAsset() (koios.PolicyID, koios.AssetName, int, bool) { +// switch os.Getenv("KOIOS_NETWORK") { +// case "guild": +// return "313534a537bc476c86ff7c57ec511bd7f24a9d15654091b24e9c606e", "41484c636f696e", 63487, true +// case "mainnet": +// return "d3501d9531fcc25e3ca4b6429318c2cc374dbdbcf5e99c1c1e5da1ff", "444f4e545350414d", 63487, true +// case "preprod": +// return "c6e65ba7878b2f8ea0ad39287d3e2fd256dc5c4160fc19bdf4c4d87e", "7447454e53", 50000, true +// case "preview": +// return "065270479316f1d92e00f7f9f095ebeaac9d009c878dc35ce36d3404", "433374", 50000, true +// default: +// // mainnet +// return "", "", 0, false +// } +// } + +// func getLiveClient() (client *koios.Client, err error) { +// net, ok := os.LookupEnv("KOIOS_NETWORK") +// if !ok { +// return nil, fmt.Errorf("%w: KOIOS_NETWORK not set", errLocalClient) +// } +// var host string +// switch net { +// case "mainnet": +// host = koios.MainnetHost +// case "guild": +// host = koios.GuildHost +// case "preprod": +// host = koios.PreProdHost +// case "preview": +// host = koios.PreviewHost +// default: +// return nil, fmt.Errorf("invalid KOIOS_NETWORK=%q", net) +// } +// return koios.New(koios.Host(host)) +// } + +// func assertEqual[V comparable](t TestingT, want, got V, tag string) bool { +// msg := fmt.Sprintf("%s: want(%v) got(%v)", tag, want, got) +// return assert.Equal(t, want, got, msg) +// } + +// func assertIsPositive(t TestingT, in decimal.Decimal, tag string) bool { +// msg := fmt.Sprintf("%s: should be positive got %s", tag, in.String()) +// return assert.True(t, in.IsPositive(), msg) +// } + +// func assertCoinNotZero(t TestingT, in decimal.Decimal, tag string) bool { +// msg := fmt.Sprintf("%s: should not be 0", tag) +// return assert.True(t, !in.IsZero(), msg) +// } + +// func assertGreater[V any](t TestingT, count, min V, tag string) bool { +// msg := fmt.Sprintf("%s: should be greater than %v", tag, min) +// return assert.Greater(t, count, min, msg) +// } + +// func assertNotEmpty(t TestingT, in any, tag string) bool { +// msg := fmt.Sprintf("%s: in(%v)", tag, in) +// return assert.NotEmpty(t, in, msg) +// } + +// func assertTimeNotZero(t TestingT, in koios.Timestamp, tag string) bool { +// msg := fmt.Sprintf("%s: time is empty or not parsed from return value", tag) +// return assert.False(t, in.Time.IsZero(), msg) +// } + +// func assertEUTxO(t TestingT, eutxo koios.EUTxO, tag string) { +// assertNotEmpty(t, eutxo.TxHash, fmt.Sprintf("eutxo[%s].tx_hash", eutxo.TxHash)) +// for i, utxo := range eutxo.Inputs { +// assertUTxO(t, utxo, fmt.Sprintf("eutxo[%s].inputs[%d]", eutxo.TxHash, i)) +// } +// for i, utxo := range eutxo.Inputs { +// assertUTxO(t, utxo, fmt.Sprintf("eutxo[%s].outputs[%d]", eutxo.TxHash, i)) +// } +// } + +// func assertUTxO(t TestingT, utxo koios.UTxO, tag string) { +// assertNotEmpty(t, utxo.TxHash, fmt.Sprintf("%s.tx_hash", tag)) +// assertGreater(t, utxo.TxIndex, -1, fmt.Sprintf("%s.tx_index", tag)) + +// if utxo.PaymentAddr != nil { +// assertNotEmpty(t, utxo.PaymentAddr.Bech32, fmt.Sprintf("%s.payment_addr.bech32", tag)) +// assertNotEmpty(t, utxo.PaymentAddr.Cred, fmt.Sprintf("%s.payment_addr.cred", tag)) +// } +// if utxo.StakeAddress != nil { +// assertNotEmpty(t, utxo.StakeAddress, fmt.Sprintf("%s.stake_addr", tag)) +// } +// // assertGreater(t, utxo.BlockHeight, 0, fmt.Sprintf("%s.block_height", tag)) +// // assertTimeNotZero(t, utxo.BlockTime, fmt.Sprintf("%s.block_time", tag)) +// assertIsPositive(t, utxo.Value, fmt.Sprintf("%s.value", tag)) + +// // assertNotEmpty(t, utxo.DatumHash, fmt.Sprintf("%s.datum_hash", tag)) + +// if utxo.InlineDatum != nil { +// assertNotEmpty(t, "", fmt.Sprintf("%s.inline_datum", tag)) +// } +// if utxo.ReferenceScript != nil { +// assertNotEmpty(t, "", fmt.Sprintf("%s.reference_script", tag)) +// } +// if len(utxo.AssetList) > 0 { +// for i, asset := range utxo.AssetList { +// assertAsset(t, asset, fmt.Sprintf("%s.asset_list[%d]", tag, i)) +// } +// } +// } + +// func assertAsset(t TestingT, asset koios.Asset, tag string) { +// // assertNotEmpty(t, asset.Name, fmt.Sprintf("%s.asset_name", tag)) +// // assertNotEmpty(t, asset.Fingerprint, fmt.Sprintf("%s.fingerprint", tag)) +// assertNotEmpty(t, asset.PolicyID, fmt.Sprintf("%s.policy_id", tag)) +// assertIsPositive(t, asset.Quantity, fmt.Sprintf("%s.quantity", tag)) +// } + +// func assertTxMetadata(t TestingT, metadata koios.TxMetadata, tag string) { +// if len(metadata) == 0 { +// return +// } +// for key, json := range metadata { +// assertNotEmpty(t, key, fmt.Sprintf("%s[%s]", tag, key)) +// assertNotEmpty(t, json, fmt.Sprintf("%s[%s]", tag, json)) +// } +// } + +// func assertCertificates(t TestingT, certs []koios.Certificate, tag string) { +// for i, cert := range certs { +// // assertGreater(t, cert.Index, 0, fmt.Sprintf("%s[%d].index", tag, i)) +// assertNotEmpty(t, cert.Type, fmt.Sprintf("%s[%d].type", tag, i)) +// assertNotEmpty(t, cert.Info, fmt.Sprintf("%s[%d].info", tag, i)) +// } +// } + +// func assertNativeScripts(t TestingT, nscripts []koios.NativeScript, tag string) { +// for i, nscript := range nscripts { +// assertNotEmpty(t, nscript.CreationTxHash, fmt.Sprintf("%s[%d].creation_tx_hash", tag, i)) +// assertNotEmpty(t, nscript.ScriptHash, fmt.Sprintf("%s[%d].script_hash", tag, i)) +// assertNotEmpty(t, nscript.Type, fmt.Sprintf("%s[%d].type", tag, i)) +// assertNotEmpty(t, nscript.Script.Type, fmt.Sprintf("%s[%d].script.type", tag, i)) + +// for j, script := range nscript.Script.Scripts { +// assertNotEmpty(t, script, fmt.Sprintf("%s[%d].scripts[%d]", tag, i, j)) +// } +// } +// } + +// func assertPlutusContracts(t TestingT, contracts []koios.PlutusContract, tag string) { +// for i, contract := range contracts { +// assertNotEmpty(t, contract.Address, fmt.Sprintf("%s[%d].address", tag, i)) +// assertNotEmpty(t, contract.ScriptHash, fmt.Sprintf("%s[%d].script_hash", tag, i)) +// assertNotEmpty(t, contract.ByteCode, fmt.Sprintf("%s[%d].bytecode", tag, i)) +// assertGreater(t, contract.Size, 0, fmt.Sprintf("%s[%d].size", tag, i)) +// assert.True(t, contract.ValidContract, 0, fmt.Sprintf("%s[%d].valid_contract", tag, i)) +// } +// } + +// func githubActionWarning(title, msg string) { +// fmt.Printf( +// "::warning title=%s::%q\n", +// title, +// msg, +// ) +// } + +// func testIsLocal(t TestingT, err error) bool { +// if err == nil { +// return false +// } +// if errors.Is(err, errLocalClient) { +// t.SkipNow() +// return true +// } +// t.Error(err) +// return false +// } + +// func TestVersion(t *testing.T) { +// assertNotEmpty(t, koios.Version(), "koios.Version()") +// } diff --git a/network_test.go b/network_test.go index 5f56e18..519e005 100644 --- a/network_test.go +++ b/network_test.go @@ -1,95 +1,75 @@ -// Copyright 2022 The Cardano Community Authors // SPDX-License-Identifier: Apache-2.0 // -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at: -// -// http://www.apache.org/licenses/LICENSE-2.0 -// or LICENSE file in repository root. -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. +// Copyright © 2022 The Cardano Community Authors package koios_test -import ( - "context" - "testing" - - "github.com/cardano-community/koios-go-client/v4" - "github.com/stretchr/testify/assert" -) - -func TestNetworkTip(t *testing.T) { - client, err := getLiveClient() - if testIsLocal(t, err) { - return - } - networkTipTest(t, client) -} +// func TestNetworkTip(t *testing.T) { +// client, err := getLiveClient() +// if testIsLocal(t, err) { +// return +// } +// networkTipTest(t, client) +// } -func networkTipTest(t TestingT, client *koios.Client) { - tip, err := client.GetTip(context.Background(), nil) - if !assert.NoError(t, err) { - return - } - assertGreater(t, tip.Data.AbsSlot, koios.Slot(10000), "abs_slot") - assertGreater(t, tip.Data.BlockNo, koios.BlockNo(10000), "block_no") - assertGreater(t, tip.Data.EpochNo, koios.EpochNo(1), "epoch_no") - assertGreater(t, tip.Data.EpochSlot, koios.Slot(1), "epoch_slot") - assertNotEmpty(t, tip.Data.Hash, "hash") - assertTimeNotZero(t, tip.Data.BlockTime, "block_time") -} +// func networkTipTest(t TestingT, client *koios.Client) { +// tip, err := client.GetTip(context.Background(), nil) +// if !assert.NoError(t, err) { +// return +// } +// assertGreater(t, tip.Data.AbsSlot, koios.Slot(10000), "abs_slot") +// assertGreater(t, tip.Data.BlockNo, koios.BlockNo(10000), "block_no") +// assertGreater(t, tip.Data.EpochNo, koios.EpochNo(1), "epoch_no") +// assertGreater(t, tip.Data.EpochSlot, koios.Slot(1), "epoch_slot") +// assertNotEmpty(t, tip.Data.Hash, "hash") +// assertTimeNotZero(t, tip.Data.BlockTime, "block_time") +// } -func TestNetworkGenesis(t *testing.T) { - client, err := getLiveClient() - if testIsLocal(t, err) { - return - } - networkGenesisTest(t, client) -} +// func TestNetworkGenesis(t *testing.T) { +// client, err := getLiveClient() +// if testIsLocal(t, err) { +// return +// } +// networkGenesisTest(t, client) +// } -func networkGenesisTest(t TestingT, client *koios.Client) { - res, err := client.GetGenesis(context.Background(), nil) - if !assert.NoError(t, err) { - return - } - assertIsPositive(t, res.Data.NetworkMagic, "networkmagic") - assertNotEmpty(t, res.Data.NetworkID, "networkid") - assertIsPositive(t, res.Data.EpochLength, "epochlength") - assertIsPositive(t, res.Data.SlotLength, "slotlength") - assertIsPositive(t, res.Data.MaxLovelaceSupply, "maxlovelacesupply") - assertTimeNotZero(t, res.Data.SystemStart, "systemstart") - assertIsPositive(t, res.Data.ActiveSlotCoeff, "activeslotcoeff") - assertIsPositive(t, res.Data.SlotsPerKesPeriod, "slotsperkesperiod") - assertIsPositive(t, res.Data.MaxKesRevolutions, "maxkesrevolutions") - assertIsPositive(t, res.Data.SecurityParam, "securityparam") - assertIsPositive(t, res.Data.UpdateQuorum, "updatequorum") - assertNotEmpty(t, res.Data.AlonzoGenesis, "alonzogenesis") -} +// func networkGenesisTest(t TestingT, client *koios.Client) { +// res, err := client.GetGenesis(context.Background(), nil) +// if !assert.NoError(t, err) { +// return +// } +// assertIsPositive(t, res.Data.NetworkMagic, "networkmagic") +// assertNotEmpty(t, res.Data.NetworkID, "networkid") +// assertIsPositive(t, res.Data.EpochLength, "epochlength") +// assertIsPositive(t, res.Data.SlotLength, "slotlength") +// assertIsPositive(t, res.Data.MaxLovelaceSupply, "maxlovelacesupply") +// assertTimeNotZero(t, res.Data.SystemStart, "systemstart") +// assertIsPositive(t, res.Data.ActiveSlotCoeff, "activeslotcoeff") +// assertIsPositive(t, res.Data.SlotsPerKesPeriod, "slotsperkesperiod") +// assertIsPositive(t, res.Data.MaxKesRevolutions, "maxkesrevolutions") +// assertIsPositive(t, res.Data.SecurityParam, "securityparam") +// assertIsPositive(t, res.Data.UpdateQuorum, "updatequorum") +// assertNotEmpty(t, res.Data.AlonzoGenesis, "alonzogenesis") +// } -func TestNetworkTotals(t *testing.T) { - client, err := getLiveClient() - if testIsLocal(t, err) { - return - } - networkTotalsTest(t, networkEpoch(), client) -} +// func TestNetworkTotals(t *testing.T) { +// client, err := getLiveClient() +// if testIsLocal(t, err) { +// return +// } +// networkTotalsTest(t, networkEpoch(), client) +// } -func networkTotalsTest(t TestingT, epoch koios.EpochNo, client *koios.Client) { - res, err := client.GetTotals(context.Background(), &epoch, nil) - if !assert.NoError(t, err) { - return - } - zero := int64(0) - assertEqual(t, epoch, res.Data[0].EpochNo, "epoch_no") - assertGreater(t, res.Data[0].Circulation.IntPart(), zero, "circulation") - assertGreater(t, res.Data[0].Reserves.IntPart(), zero, "reserves") - assertGreater(t, res.Data[0].Reward.IntPart(), zero, "reward") - assertGreater(t, res.Data[0].Supply.IntPart(), zero, "supply") - assertGreater(t, res.Data[0].Treasury.IntPart(), zero, "treasury") -} +// func networkTotalsTest(t TestingT, epoch koios.EpochNo, client *koios.Client) { +// res, err := client.GetTotals(context.Background(), &epoch, nil) +// if !assert.NoError(t, err) { +// return +// } +// zero := int64(0) +// assertEqual(t, epoch, res.Data[0].EpochNo, "epoch_no") +// assertGreater(t, res.Data[0].Circulation.IntPart(), zero, "circulation") +// assertGreater(t, res.Data[0].Reserves.IntPart(), zero, "reserves") +// assertGreater(t, res.Data[0].Reward.IntPart(), zero, "reward") +// assertGreater(t, res.Data[0].Supply.IntPart(), zero, "supply") +// assertGreater(t, res.Data[0].Treasury.IntPart(), zero, "treasury") +// } diff --git a/pool_test.go b/pool_test.go index f83a0dc..9b0c41d 100644 --- a/pool_test.go +++ b/pool_test.go @@ -1,313 +1,292 @@ -// Copyright 2022 The Cardano Community Authors // SPDX-License-Identifier: Apache-2.0 // -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at: -// -// http://www.apache.org/licenses/LICENSE-2.0 -// or LICENSE file in repository root. -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. +// Copyright © 2022 The Cardano Community Authors package koios_test -import ( - "context" - "fmt" - "testing" - - "github.com/cardano-community/koios-go-client/v4" - "github.com/stretchr/testify/assert" -) - -func TestPools(t *testing.T) { - client, err := getLiveClient() - if testIsLocal(t, err) { - return - } - poolsTest(t, client) -} +// func TestPools(t *testing.T) { +// client, err := getLiveClient() +// if testIsLocal(t, err) { +// return +// } +// poolsTest(t, client) +// } -func poolsTest(t TestingT, client *koios.Client) { - opts := client.NewRequestOptions() - opts.SetPageSize(10) - res, err := client.GetPools(context.Background(), opts) - if !assert.NoError(t, err) { - return - } - assertEqual(t, 10, len(res.Data), "total blocks returned") +// func poolsTest(t TestingT, client *koios.Client) { +// opts := client.NewRequestOptions() +// opts.SetPageSize(10) +// res, err := client.GetPools(context.Background(), opts) +// if !assert.NoError(t, err) { +// return +// } +// assertEqual(t, 10, len(res.Data), "total blocks returned") - for _, pool := range res.Data { - assertNotEmpty(t, pool.PoolID, "pool_id_bech32") - // assertNotEmpty(t, pool.Ticker, "ticker") - } -} +// for _, pool := range res.Data { +// assertNotEmpty(t, pool.PoolID, "pool_id_bech32") +// // assertNotEmpty(t, pool.Ticker, "ticker") +// } +// } -func TestPoolSnapshot(t *testing.T) { - client, err := getLiveClient() - if testIsLocal(t, err) { - return - } - poolID := networkPoolID() - poolSnapshotTest(t, client, poolID) -} +// func TestPoolSnapshot(t *testing.T) { +// client, err := getLiveClient() +// if testIsLocal(t, err) { +// return +// } +// poolID := networkPoolID() +// poolSnapshotTest(t, client, poolID) +// } -func poolSnapshotTest(t TestingT, client *koios.Client, poolID koios.PoolID) { - opts := client.NewRequestOptions() - opts.SetPageSize(10) - res, err := client.GetPoolSnapshot(context.Background(), poolID, opts) - if !assert.NoError(t, err) { - return - } - assertEqual(t, 3, len(res.Data), "snapshots returned") +// func poolSnapshotTest(t TestingT, client *koios.Client, poolID koios.PoolID) { +// opts := client.NewRequestOptions() +// opts.SetPageSize(10) +// res, err := client.GetPoolSnapshot(context.Background(), poolID, opts) +// if !assert.NoError(t, err) { +// return +// } +// assertEqual(t, 3, len(res.Data), "snapshots returned") - for i, pool := range res.Data { - assertNotEmpty(t, pool.Snapshot, "snapshot") - if i < 2 { - assertNotEmpty(t, pool.Nonce, "nonce") - } - assertIsPositive(t, pool.PoolStake, "pool_stake") - assertIsPositive(t, pool.ActiveStake, "active_stake") - assertGreater(t, pool.EpochNo, 0, "epoch_no") - } -} +// for i, pool := range res.Data { +// assertNotEmpty(t, pool.Snapshot, "snapshot") +// if i < 2 { +// assertNotEmpty(t, pool.Nonce, "nonce") +// } +// assertIsPositive(t, pool.PoolStake, "pool_stake") +// assertIsPositive(t, pool.ActiveStake, "active_stake") +// assertGreater(t, pool.EpochNo, 0, "epoch_no") +// } +// } -func TestPoolInfo(t *testing.T) { - client, err := getLiveClient() - if testIsLocal(t, err) { - return - } - poolID := networkPoolID() - poolInfoTest(t, client, poolID) -} +// func TestPoolInfo(t *testing.T) { +// client, err := getLiveClient() +// if testIsLocal(t, err) { +// return +// } +// poolID := networkPoolID() +// poolInfoTest(t, client, poolID) +// } -func poolInfoTest(t TestingT, client *koios.Client, poolID koios.PoolID) { +// func poolInfoTest(t TestingT, client *koios.Client, poolID koios.PoolID) { - res, err := client.GetPoolInfo(context.Background(), poolID, nil) - if !assert.NoError(t, err) { - return - } - assertNotEmpty(t, res.Data.PoolID, "pool_id_bech32") - assertNotEmpty(t, res.Data.PoolIdHex, "pool_id_hex") - assertGreater(t, res.Data.ActiveEpoch, 0, "active_epoch_no") - assertNotEmpty(t, res.Data.VrfKeyHash, "vrf_key_hash") - assertGreater(t, res.Data.Margin, 0, "margin") - assertIsPositive(t, res.Data.FixedCost, "fixed_cost") - assertIsPositive(t, res.Data.Pledge, "pledge") - assertNotEmpty(t, res.Data.RewardAddr, "reward_addr") - for _, owner := range res.Data.Owners { - assertNotEmpty(t, owner, "owners") - } - // assertNotEmpty(t, res.Data.Relays, "relays") - assertNotEmpty(t, res.Data.MetaURL, "meta_url") - assertNotEmpty(t, res.Data.MetaHash, "meta_hash") - // assertNotEmpty(t, res.Data.MetaJSON, "meta_json") - assertNotEmpty(t, res.Data.PoolStatus, "pool_status") - // assertNotEmpty(t, res.Data.RetiringEpoch, "retiring_epoch") - // assertNotEmpty(t, res.Data.OpCert, "op_cert") - // assertNotEmpty(t, res.Data.OpCertCounter, "op_cert_counter") - assertNotEmpty(t, res.Data.ActiveStake, "active_stake") - // assertNotEmpty(t, res.Data.Sigma, "sigma") - // assertNotEmpty(t, res.Data.BlockCount, "block_count") - assertNotEmpty(t, res.Data.LivePledge, "live_pledge") - assertNotEmpty(t, res.Data.LiveStake, "live_stake") - assertNotEmpty(t, res.Data.LiveDelegators, "live_delegators") - assertNotEmpty(t, res.Data.LiveSaturation, "live_saturation") -} +// res, err := client.GetPoolInfo(context.Background(), poolID, nil) +// if !assert.NoError(t, err) { +// return +// } +// assertNotEmpty(t, res.Data.PoolID, "pool_id_bech32") +// assertNotEmpty(t, res.Data.PoolIdHex, "pool_id_hex") +// assertGreater(t, res.Data.ActiveEpoch, 0, "active_epoch_no") +// assertNotEmpty(t, res.Data.VrfKeyHash, "vrf_key_hash") +// assertGreater(t, res.Data.Margin, 0, "margin") +// assertIsPositive(t, res.Data.FixedCost, "fixed_cost") +// assertIsPositive(t, res.Data.Pledge, "pledge") +// assertNotEmpty(t, res.Data.RewardAddr, "reward_addr") +// for _, owner := range res.Data.Owners { +// assertNotEmpty(t, owner, "owners") +// } +// // assertNotEmpty(t, res.Data.Relays, "relays") +// assertNotEmpty(t, res.Data.MetaURL, "meta_url") +// assertNotEmpty(t, res.Data.MetaHash, "meta_hash") +// // assertNotEmpty(t, res.Data.MetaJSON, "meta_json") +// assertNotEmpty(t, res.Data.PoolStatus, "pool_status") +// // assertNotEmpty(t, res.Data.RetiringEpoch, "retiring_epoch") +// // assertNotEmpty(t, res.Data.OpCert, "op_cert") +// // assertNotEmpty(t, res.Data.OpCertCounter, "op_cert_counter") +// assertNotEmpty(t, res.Data.ActiveStake, "active_stake") +// // assertNotEmpty(t, res.Data.Sigma, "sigma") +// // assertNotEmpty(t, res.Data.BlockCount, "block_count") +// assertNotEmpty(t, res.Data.LivePledge, "live_pledge") +// assertNotEmpty(t, res.Data.LiveStake, "live_stake") +// assertNotEmpty(t, res.Data.LiveDelegators, "live_delegators") +// assertNotEmpty(t, res.Data.LiveSaturation, "live_saturation") +// } -func TestPoolDelegators(t *testing.T) { - client, err := getLiveClient() - if testIsLocal(t, err) { - return - } - poolID := networkPoolID() - poolDelegatorsTest(t, client, poolID) -} +// func TestPoolDelegators(t *testing.T) { +// client, err := getLiveClient() +// if testIsLocal(t, err) { +// return +// } +// poolID := networkPoolID() +// poolDelegatorsTest(t, client, poolID) +// } -func poolDelegatorsTest(t TestingT, client *koios.Client, poolID koios.PoolID) { - res, err := client.GetPoolDelegators(context.Background(), poolID, nil) - if !assert.NoError(t, err) { - return - } +// func poolDelegatorsTest(t TestingT, client *koios.Client, poolID koios.PoolID) { +// res, err := client.GetPoolDelegators(context.Background(), poolID, nil) +// if !assert.NoError(t, err) { +// return +// } - for _, d := range res.Data { - assertNotEmpty(t, d.StakeAddress, "stake_address") - assertIsPositive(t, d.Amount, "amount") - assertGreater(t, d.ActiveEpochNo, 0, "active_epoch_no") - assertNotEmpty(t, d.LatestDelegationTxHash, "latest_delegation_tx_hash") - } -} +// for _, d := range res.Data { +// assertNotEmpty(t, d.StakeAddress, "stake_address") +// assertIsPositive(t, d.Amount, "amount") +// assertGreater(t, d.ActiveEpochNo, 0, "active_epoch_no") +// assertNotEmpty(t, d.LatestDelegationTxHash, "latest_delegation_tx_hash") +// } +// } -func TestPoolDelegatorsHistory(t *testing.T) { - client, err := getLiveClient() - if testIsLocal(t, err) { - return - } - poolID := networkPoolID() - epoch := networkEpoch() - poolDelegatorsHistoryTest(t, client, poolID, &epoch) -} +// func TestPoolDelegatorsHistory(t *testing.T) { +// client, err := getLiveClient() +// if testIsLocal(t, err) { +// return +// } +// poolID := networkPoolID() +// epoch := networkEpoch() +// poolDelegatorsHistoryTest(t, client, poolID, &epoch) +// } -func poolDelegatorsHistoryTest(t TestingT, client *koios.Client, poolID koios.PoolID, epoch *koios.EpochNo) { - res, err := client.GetPoolDelegatorsHistory(context.Background(), poolID, epoch, nil) - if !assert.NoError(t, err) { - return - } +// func poolDelegatorsHistoryTest(t TestingT, client *koios.Client, poolID koios.PoolID, epoch *koios.EpochNo) { +// res, err := client.GetPoolDelegatorsHistory(context.Background(), poolID, epoch, nil) +// if !assert.NoError(t, err) { +// return +// } - for _, d := range res.Data { - assertNotEmpty(t, d.StakeAddress, "stake_address") - assertIsPositive(t, d.Amount, "amount") - assertGreater(t, d.EpochNo, 0, "epoch_no") - } -} +// for _, d := range res.Data { +// assertNotEmpty(t, d.StakeAddress, "stake_address") +// assertIsPositive(t, d.Amount, "amount") +// assertGreater(t, d.EpochNo, 0, "epoch_no") +// } +// } -func TestPoolBlocks(t *testing.T) { - client, err := getLiveClient() - if testIsLocal(t, err) { - return - } - poolID := networkPoolID() - epoch := networkEpoch() - poolBlocksTest(t, client, poolID, &epoch) -} +// func TestPoolBlocks(t *testing.T) { +// client, err := getLiveClient() +// if testIsLocal(t, err) { +// return +// } +// poolID := networkPoolID() +// epoch := networkEpoch() +// poolBlocksTest(t, client, poolID, &epoch) +// } -func poolBlocksTest(t TestingT, client *koios.Client, poolID koios.PoolID, epoch *koios.EpochNo) { - res, err := client.GetPoolBlocks(context.Background(), poolID, epoch, nil) - if !assert.NoError(t, err) { - return - } +// func poolBlocksTest(t TestingT, client *koios.Client, poolID koios.PoolID, epoch *koios.EpochNo) { +// res, err := client.GetPoolBlocks(context.Background(), poolID, epoch, nil) +// if !assert.NoError(t, err) { +// return +// } - for _, d := range res.Data { - assertNotEmpty(t, d.BlockHash, "block_hash") - assertGreater(t, d.AbsSlot, 0, "abs_slot") - assertGreater(t, d.EpochNo, 0, "epoch_no") - assertGreater(t, d.BlockHeight, 0, "block_height") - assertTimeNotZero(t, d.BlockTime, "block_time") - } -} +// for _, d := range res.Data { +// assertNotEmpty(t, d.BlockHash, "block_hash") +// assertGreater(t, d.AbsSlot, 0, "abs_slot") +// assertGreater(t, d.EpochNo, 0, "epoch_no") +// assertGreater(t, d.BlockHeight, 0, "block_height") +// assertTimeNotZero(t, d.BlockTime, "block_time") +// } +// } -func TestPoolHistory(t *testing.T) { - client, err := getLiveClient() - if testIsLocal(t, err) { - return - } - poolID := networkPoolID() - epoch := networkEpoch() - poolHistoryTest(t, client, poolID, &epoch) -} +// func TestPoolHistory(t *testing.T) { +// client, err := getLiveClient() +// if testIsLocal(t, err) { +// return +// } +// poolID := networkPoolID() +// epoch := networkEpoch() +// poolHistoryTest(t, client, poolID, &epoch) +// } -func poolHistoryTest(t TestingT, client *koios.Client, poolID koios.PoolID, epoch *koios.EpochNo) { - res, err := client.GetPoolHistory(context.Background(), poolID, epoch, nil) - if !assert.NoError(t, err) { - return - } - for _, d := range res.Data { - assertGreater(t, d.EpochNo, 0, "block_hash") - assertIsPositive(t, d.ActiveStake, "active_stake") - assertGreater(t, d.ActiveStakePCT, 0, "active_stake_pct") - // assertGreater(t, d.SaturationPCT, 0, "saturation_pct") - assertGreater(t, d.BlockCNT, 0, "block_cnt") - assertGreater(t, d.DelegatorCNT, 0, "delegator_cnt") - assertGreater(t, d.Margin, 0, "margin") - assertIsPositive(t, d.PoolFees, "pool_fees") - assertIsPositive(t, d.FixedCost, "fixed_cost") - // assertIsPositive(t, d.DelegRewards, "deleg_rewards") - // assertGreater(t, d.EpochROS, 0, "epoch_ros") - } -} +// func poolHistoryTest(t TestingT, client *koios.Client, poolID koios.PoolID, epoch *koios.EpochNo) { +// res, err := client.GetPoolHistory(context.Background(), poolID, epoch, nil) +// if !assert.NoError(t, err) { +// return +// } +// for _, d := range res.Data { +// assertGreater(t, d.EpochNo, 0, "block_hash") +// assertIsPositive(t, d.ActiveStake, "active_stake") +// assertGreater(t, d.ActiveStakePCT, 0, "active_stake_pct") +// // assertGreater(t, d.SaturationPCT, 0, "saturation_pct") +// assertGreater(t, d.BlockCNT, 0, "block_cnt") +// assertGreater(t, d.DelegatorCNT, 0, "delegator_cnt") +// assertGreater(t, d.Margin, 0, "margin") +// assertIsPositive(t, d.PoolFees, "pool_fees") +// assertIsPositive(t, d.FixedCost, "fixed_cost") +// // assertIsPositive(t, d.DelegRewards, "deleg_rewards") +// // assertGreater(t, d.EpochROS, 0, "epoch_ros") +// } +// } -func TestPoolUpdates(t *testing.T) { - client, err := getLiveClient() - if testIsLocal(t, err) { - return - } - poolID := networkPoolID() - poolUpdatesTest(t, client, &poolID) -} +// func TestPoolUpdates(t *testing.T) { +// client, err := getLiveClient() +// if testIsLocal(t, err) { +// return +// } +// poolID := networkPoolID() +// poolUpdatesTest(t, client, &poolID) +// } -func poolUpdatesTest(t TestingT, client *koios.Client, poolID *koios.PoolID) { - res, err := client.GetPoolUpdates(context.Background(), poolID, nil) - if !assert.NoError(t, err) { - return - } - for _, update := range res.Data { - assertNotEmpty(t, update.TxHash, "tx_hash") - assertTimeNotZero(t, update.BlockTime, "block_time") - assertNotEmpty(t, update.PoolID, "pool_id_bech32") - assertNotEmpty(t, update.PoolIDHex, "pool_id_hex") - assertGreater(t, update.ActiveEpoch, 0, "active_epoch_no") - assertNotEmpty(t, update.VrfKeyHash, "vrf_key_hash") - assertGreater(t, update.Margin, 0, "margin") - assertIsPositive(t, update.FixedCost, "fixed_cost") - assertIsPositive(t, update.Pledge, "pledge") - assertNotEmpty(t, update.RewardAddr, "reward_addr") - for _, owner := range update.Owners { - assertNotEmpty(t, owner, "owners") - } - for _, relay := range update.Relays { - assertNotEmpty(t, relay.DNS, "relays.dns") - } - assertNotEmpty(t, update.MetaURL, "meta_url") - assertNotEmpty(t, update.MetaHash, "meta_hash") - assertNotEmpty(t, update.PoolStatus, "pool_status") - // assertGreater(t, update.RetiringEpoch, 0, "retiring_epoch") - } -} +// func poolUpdatesTest(t TestingT, client *koios.Client, poolID *koios.PoolID) { +// res, err := client.GetPoolUpdates(context.Background(), poolID, nil) +// if !assert.NoError(t, err) { +// return +// } +// for _, update := range res.Data { +// assertNotEmpty(t, update.TxHash, "tx_hash") +// assertTimeNotZero(t, update.BlockTime, "block_time") +// assertNotEmpty(t, update.PoolID, "pool_id_bech32") +// assertNotEmpty(t, update.PoolIDHex, "pool_id_hex") +// assertGreater(t, update.ActiveEpoch, 0, "active_epoch_no") +// assertNotEmpty(t, update.VrfKeyHash, "vrf_key_hash") +// assertGreater(t, update.Margin, 0, "margin") +// assertIsPositive(t, update.FixedCost, "fixed_cost") +// assertIsPositive(t, update.Pledge, "pledge") +// assertNotEmpty(t, update.RewardAddr, "reward_addr") +// for _, owner := range update.Owners { +// assertNotEmpty(t, owner, "owners") +// } +// for _, relay := range update.Relays { +// assertNotEmpty(t, relay.DNS, "relays.dns") +// } +// assertNotEmpty(t, update.MetaURL, "meta_url") +// assertNotEmpty(t, update.MetaHash, "meta_hash") +// assertNotEmpty(t, update.PoolStatus, "pool_status") +// // assertGreater(t, update.RetiringEpoch, 0, "retiring_epoch") +// } +// } -func TestPoolRelays(t *testing.T) { - client, err := getLiveClient() - if testIsLocal(t, err) { - return - } - poolRelaysTest(t, client) -} +// func TestPoolRelays(t *testing.T) { +// client, err := getLiveClient() +// if testIsLocal(t, err) { +// return +// } +// poolRelaysTest(t, client) +// } -func poolRelaysTest(t TestingT, client *koios.Client) { - opts := client.NewRequestOptions() - opts.SetPageSize(10) - res, err := client.GetPoolRelays(context.Background(), opts) - if !assert.NoError(t, err) { - return - } - assertEqual(t, 10, len(res.Data), "ppol relays returned") - for _, pool := range res.Data { - assertNotEmpty(t, pool.PoolID, "pool_id_bech32") - for i, relay := range pool.Relays { - if len(relay.Ipv4) == 0 { - assertNotEmpty(t, relay.DNS, fmt.Sprintf("pool[%s].relays[%d]", pool.PoolID, i)) - } - } - } -} +// func poolRelaysTest(t TestingT, client *koios.Client) { +// opts := client.NewRequestOptions() +// opts.SetPageSize(10) +// res, err := client.GetPoolRelays(context.Background(), opts) +// if !assert.NoError(t, err) { +// return +// } +// assertEqual(t, 10, len(res.Data), "ppol relays returned") +// for _, pool := range res.Data { +// assertNotEmpty(t, pool.PoolID, "pool_id_bech32") +// for i, relay := range pool.Relays { +// if len(relay.Ipv4) == 0 { +// assertNotEmpty(t, relay.DNS, fmt.Sprintf("pool[%s].relays[%d]", pool.PoolID, i)) +// } +// } +// } +// } -func TestPoolMetadata(t *testing.T) { - client, err := getLiveClient() - if testIsLocal(t, err) { - return - } - poolID := networkPoolID() - poolMetadataTest(t, client, poolID) -} +// func TestPoolMetadata(t *testing.T) { +// client, err := getLiveClient() +// if testIsLocal(t, err) { +// return +// } +// poolID := networkPoolID() +// poolMetadataTest(t, client, poolID) +// } -func poolMetadataTest(t TestingT, client *koios.Client, poolID koios.PoolID) { - res, err := client.GetPoolMetadata(context.Background(), []koios.PoolID{poolID}, nil) - if !assert.NoError(t, err) { - return - } - for _, meta := range res.Data { - assertNotEmpty(t, meta.PoolID, "pool_id_bech32") - assertNotEmpty(t, meta.MetaURL, "meta_url") - assertNotEmpty(t, meta.MetaHash, "meta_hash") - if meta.MetaJSON != nil { - assertNotEmpty(t, meta.MetaJSON.Name, "meta_json.name") - assertNotEmpty(t, meta.MetaJSON.Ticker, "meta_json.ticker") - assertNotEmpty(t, meta.MetaJSON.Homepage, "meta_json.homepage") - assertNotEmpty(t, meta.MetaJSON.Description, "meta_json.description") - } - } -} +// func poolMetadataTest(t TestingT, client *koios.Client, poolID koios.PoolID) { +// res, err := client.GetPoolMetadata(context.Background(), []koios.PoolID{poolID}, nil) +// if !assert.NoError(t, err) { +// return +// } +// for _, meta := range res.Data { +// assertNotEmpty(t, meta.PoolID, "pool_id_bech32") +// assertNotEmpty(t, meta.MetaURL, "meta_url") +// assertNotEmpty(t, meta.MetaHash, "meta_hash") +// if meta.MetaJSON != nil { +// assertNotEmpty(t, meta.MetaJSON.Name, "meta_json.name") +// assertNotEmpty(t, meta.MetaJSON.Ticker, "meta_json.ticker") +// assertNotEmpty(t, meta.MetaJSON.Homepage, "meta_json.homepage") +// assertNotEmpty(t, meta.MetaJSON.Description, "meta_json.description") +// } +// } +// } diff --git a/script_test.go b/script_test.go index 9bb2be3..f945cf9 100644 --- a/script_test.go +++ b/script_test.go @@ -1,120 +1,100 @@ -// Copyright 2022 The Cardano Community Authors // SPDX-License-Identifier: Apache-2.0 // -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at: -// -// http://www.apache.org/licenses/LICENSE-2.0 -// or LICENSE file in repository root. -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. +// Copyright © 2022 The Cardano Community Authors package koios_test -import ( - "context" - "testing" - - "github.com/cardano-community/koios-go-client/v4" - "github.com/stretchr/testify/assert" -) - -func TestNativeScriptList(t *testing.T) { - client, err := getLiveClient() - if testIsLocal(t, err) { - return - } - nativeScriptListTest(t, client) -} - -func nativeScriptListTest(t TestingT, client *koios.Client) { - opts := client.NewRequestOptions() - opts.SetPageSize(10) - - res, err := client.GetNativeScripts(context.Background(), opts) - if !assert.NoError(t, err) { - return - } - assertEqual(t, 10, len(res.Data), "native script returned") - - for _, script := range res.Data { - assertNotEmpty(t, script.ScriptHash, "script_hash") - assertNotEmpty(t, script.Type, "type") - assertNotEmpty(t, script.CreationTxHash, "creation_tx_hash") - } -} - -func TestPlutusScriptList(t *testing.T) { - client, err := getLiveClient() - if testIsLocal(t, err) { - return - } - plutusScriptListTest(t, client) -} - -func plutusScriptListTest(t TestingT, client *koios.Client) { - opts := client.NewRequestOptions() - opts.SetPageSize(10) - - res, err := client.GetPlutusScripts(context.Background(), opts) - if !assert.NoError(t, err) { - return - } - assertEqual(t, 10, len(res.Data), "plutus script list returned") - - for _, script := range res.Data { - assertNotEmpty(t, script.ScriptHash, "script_hash") - assertNotEmpty(t, script.CreationTxHash, "creation_tx_hash") - } -} - -func TestScriptRedeemers(t *testing.T) { - client, err := getLiveClient() - if testIsLocal(t, err) { - return - } - scripthash := networkScriptHash() - scriptRedeemersTest(t, client, scripthash) -} - -func scriptRedeemersTest(t TestingT, client *koios.Client, scripthash koios.ScriptHash) { - res, err := client.GetScriptRedeemers(context.Background(), scripthash, nil) - if !assert.NoError(t, err) { - return - } - - assertNotEmpty(t, res.Data.ScriptHash, "script_hash") - for _, redeemer := range res.Data.Redeemers { - assertNotEmpty(t, redeemer.TxHash, "tx_hash") - assertNotEmpty(t, redeemer.Purpose, "purpose") - assertNotEmpty(t, redeemer.DatumHash, "datum_hash") - // assertGreater(t, redeemer.TxIndex,0, "tx_index") - assertGreater(t, redeemer.UnitMem, 0, "unit_mem") - assertGreater(t, redeemer.UnitSteps, 0, "unit_steps") - assertIsPositive(t, redeemer.Fee, "fee") - } -} - -func TestDatumInfo(t *testing.T) { - client, err := getLiveClient() - if testIsLocal(t, err) { - return - } - datumhash := networkDatumHash() - datumInfoTest(t, client, datumhash) -} - -func datumInfoTest(t TestingT, client *koios.Client, datumhash koios.DatumHash) { - res, err := client.GetDatumInfo(context.Background(), datumhash, nil) - if !assert.NoError(t, err) { - return - } - - assertNotEmpty(t, res.Data.Hash, "hash") - assertNotEmpty(t, res.Data.Bytes, "bytes") -} +// func TestNativeScriptList(t *testing.T) { +// client, err := getLiveClient() +// if testIsLocal(t, err) { +// return +// } +// nativeScriptListTest(t, client) +// } + +// func nativeScriptListTest(t TestingT, client *koios.Client) { +// opts := client.NewRequestOptions() +// opts.SetPageSize(10) + +// res, err := client.GetNativeScripts(context.Background(), opts) +// if !assert.NoError(t, err) { +// return +// } +// assertEqual(t, 10, len(res.Data), "native script returned") + +// for _, script := range res.Data { +// assertNotEmpty(t, script.ScriptHash, "script_hash") +// assertNotEmpty(t, script.Type, "type") +// assertNotEmpty(t, script.CreationTxHash, "creation_tx_hash") +// } +// } + +// func TestPlutusScriptList(t *testing.T) { +// client, err := getLiveClient() +// if testIsLocal(t, err) { +// return +// } +// plutusScriptListTest(t, client) +// } + +// func plutusScriptListTest(t TestingT, client *koios.Client) { +// opts := client.NewRequestOptions() +// opts.SetPageSize(10) + +// res, err := client.GetPlutusScripts(context.Background(), opts) +// if !assert.NoError(t, err) { +// return +// } +// assertEqual(t, 10, len(res.Data), "plutus script list returned") + +// for _, script := range res.Data { +// assertNotEmpty(t, script.ScriptHash, "script_hash") +// assertNotEmpty(t, script.CreationTxHash, "creation_tx_hash") +// } +// } + +// func TestScriptRedeemers(t *testing.T) { +// client, err := getLiveClient() +// if testIsLocal(t, err) { +// return +// } +// scripthash := networkScriptHash() +// scriptRedeemersTest(t, client, scripthash) +// } + +// func scriptRedeemersTest(t TestingT, client *koios.Client, scripthash koios.ScriptHash) { +// res, err := client.GetScriptRedeemers(context.Background(), scripthash, nil) +// if !assert.NoError(t, err) { +// return +// } + +// assertNotEmpty(t, res.Data.ScriptHash, "script_hash") +// for _, redeemer := range res.Data.Redeemers { +// assertNotEmpty(t, redeemer.TxHash, "tx_hash") +// assertNotEmpty(t, redeemer.Purpose, "purpose") +// assertNotEmpty(t, redeemer.DatumHash, "datum_hash") +// // assertGreater(t, redeemer.TxIndex,0, "tx_index") +// assertGreater(t, redeemer.UnitMem, 0, "unit_mem") +// assertGreater(t, redeemer.UnitSteps, 0, "unit_steps") +// assertIsPositive(t, redeemer.Fee, "fee") +// } +// } + +// func TestDatumInfo(t *testing.T) { +// client, err := getLiveClient() +// if testIsLocal(t, err) { +// return +// } +// datumhash := networkDatumHash() +// datumInfoTest(t, client, datumhash) +// } + +// func datumInfoTest(t TestingT, client *koios.Client, datumhash koios.DatumHash) { +// res, err := client.GetDatumInfo(context.Background(), datumhash, nil) +// if !assert.NoError(t, err) { +// return +// } + +// assertNotEmpty(t, res.Data.Hash, "hash") +// assertNotEmpty(t, res.Data.Bytes, "bytes") +// } diff --git a/transaction_test.go b/transaction_test.go index c7a36f2..2675b48 100644 --- a/transaction_test.go +++ b/transaction_test.go @@ -1,195 +1,174 @@ -// Copyright 2022 The Cardano Community Authors // SPDX-License-Identifier: Apache-2.0 // -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at: -// -// http://www.apache.org/licenses/LICENSE-2.0 -// or LICENSE file in repository root. -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. +// Copyright © 2022 The Cardano Community Authors package koios_test -import ( - "context" - "fmt" - "testing" - - "github.com/cardano-community/koios-go-client/v4" - "github.com/stretchr/testify/assert" -) - -func TestTxInfo(t *testing.T) { - client, err := getLiveClient() - if testIsLocal(t, err) { - return - } - txInfoTest(t, networkTxHashes(), client) -} - -func txInfoTest(t TestingT, hashes []koios.TxHash, client *koios.Client) { - res, err := client.GetTxsInfo(context.Background(), hashes, nil) - if !assert.NoError(t, err) { - return - } - - for _, tx := range res.Data { - assertNotEmpty(t, tx.TxHash, fmt.Sprintf("tx[%s].tx_hash", tx.TxHash)) - assertNotEmpty(t, tx.BlockHash, fmt.Sprintf("tx[%s].block_hash", tx.TxHash)) - assertGreater(t, tx.BlockHeight, 0, fmt.Sprintf("tx[%s].block_height", tx.TxHash)) - assertGreater(t, tx.EpochNo, koios.EpochNo(0), fmt.Sprintf("tx[%s].epoch_no", tx.TxHash)) - assertGreater(t, tx.EpochSlot, koios.Slot(0), fmt.Sprintf("tx[%s].epoch_slot", tx.TxHash)) - assertGreater(t, tx.AbsoluteSlot, koios.Slot(0), fmt.Sprintf("tx[%s].absolute_slot", tx.TxHash)) - assertTimeNotZero(t, tx.TxTimestamp, fmt.Sprintf("tx[%s].tx_timestamp", tx.TxHash)) - // assertGreater(t, tx.TxBlockIndex, 0, fmt.Sprintf("tx[%s].tx_block_index", tx.TxHash)) - assertGreater(t, tx.TxSize, 0, fmt.Sprintf("tx[%s].tx_size", tx.TxHash)) - assertIsPositive(t, tx.TotalOutput, fmt.Sprintf("tx[%s].total_output", tx.TxHash)) - assertIsPositive(t, tx.Fee, fmt.Sprintf("tx[%s].fee", tx.TxHash)) - - // assertTimeNotZero(t, tx.InvalidBefore, "invalid_before") - // assertTimeNotZero(t, tx.InvalidAfter, fmt.Sprintf("tx[%s].invalid_after", tx.TxHash)) - - if !tx.Deposit.IsZero() { - assertIsPositive(t, tx.Deposit, fmt.Sprintf("tx[%s].deposit", tx.TxHash)) - } - // DATA - if len(tx.CollateralInputs) > 0 { - for _, utxo := range tx.CollateralInputs { - assertUTxO(t, utxo, fmt.Sprintf("tx[%s].tx.collateral_inputs", tx.TxHash)) - } - } - - if tx.CollateralOutput != nil { - // assertNotEmpty(t, , "collateral_inputs") - assertUTxO(t, *tx.CollateralOutput, fmt.Sprintf("tx[%s].tx.collateral_output", tx.TxHash)) - } - - if len(tx.ReferenceInputs) > 0 { - for i, utxo := range tx.ReferenceInputs { - assertUTxO(t, utxo, fmt.Sprintf("tx[%s].reference_inputs[%d]", tx.TxHash, i)) - } - } - - if assertGreater(t, len(tx.Inputs), 0, "inputs") { - for i, utxo := range tx.Inputs { - assertUTxO(t, utxo, fmt.Sprintf("tx[%s].inputs[%d]", tx.TxHash, i)) - } - } - if assertGreater(t, len(tx.Outputs), 0, "outputs") { - for i, utxo := range tx.Outputs { - assertUTxO(t, utxo, fmt.Sprintf("tx[%s].outputs[%d]", tx.TxHash, i)) - } - } - - if len(tx.Withdrawals) > 0 { - for i, withdrawal := range tx.Withdrawals { - assertNotEmpty(t, withdrawal.StakeAddress, fmt.Sprintf("tx[%s].withdrawals[%d].stake_addr", tx.TxHash, i)) - assertIsPositive(t, withdrawal.Amount, fmt.Sprintf("tx[%s].withdrawals[%d].amount", tx.TxHash, i)) - } - } - - if len(tx.AssetsMinted) > 0 { - for i, asset := range tx.AssetsMinted { - assertAsset(t, asset, fmt.Sprintf("tx[%s].assets_minted[%d]", tx.TxHash, i)) - } - } - - if tx.Metadata != nil { - assertTxMetadata(t, tx.Metadata, fmt.Sprintf("tx[%s].metadata", tx.TxHash)) - } - - if len(tx.Certificates) > 0 { - assertCertificates(t, tx.Certificates, fmt.Sprintf("tx[%s].certificates", tx.TxHash)) - } - if len(tx.NativeScripts) > 0 { - assertNativeScripts(t, tx.NativeScripts, fmt.Sprintf("tx[%s].native_scripts", tx.TxHash)) - } - if len(tx.PlutusContracts) > 0 { - assertPlutusContracts(t, tx.PlutusContracts, fmt.Sprintf("tx[%s].plutus_contracts", tx.TxHash)) - } - } -} - -func TestTxUTxO(t *testing.T) { - client, err := getLiveClient() - if testIsLocal(t, err) { - return - } - txUTxOsTest(t, networkTxHashes(), client) -} - -func txUTxOsTest(t TestingT, hashes []koios.TxHash, client *koios.Client) { - res, err := client.GetTxsUTxOs(context.Background(), hashes, nil) - if !assert.NoError(t, err) { - return - } - for _, eutxo := range res.Data { - assertEUTxO(t, eutxo, fmt.Sprintf("tx[%s]", eutxo.TxHash)) - } -} - -func TestTxMetadata(t *testing.T) { - client, err := getLiveClient() - if testIsLocal(t, err) { - return - } - txMetadataTest(t, networkTxHashes(), client) -} - -func txMetadataTest(t TestingT, hashes []koios.TxHash, client *koios.Client) { - res, err := client.GetTxsMetadata(context.Background(), hashes, nil) - if !assert.NoError(t, err) { - return - } - for _, listitem := range res.Data { - assertTxMetadata(t, listitem.Metadata, fmt.Sprintf("tx[%s].metadata", listitem.TxHash)) - } -} - -func TestTxMetaLabels(t *testing.T) { - client, err := getLiveClient() - if testIsLocal(t, err) { - return - } - txMetaLabelsTest(t, client) -} - -func txMetaLabelsTest(t TestingT, client *koios.Client) { - opts := client.NewRequestOptions() - opts.SetPageSize(2) // testnets Range error if number is too big - - res, err := client.GetTxMetaLabels(context.Background(), opts) - if !assert.NoError(t, err) { - return - } - - assertGreater(t, len(res.Data), 1, "GetTxMetaLabels") - for _, label := range res.Data { - assertNotEmpty(t, label.Key, "empty label") - } -} - -func TestTxStatus(t *testing.T) { - client, err := getLiveClient() - if testIsLocal(t, err) { - return - } - txStatusTest(t, networkTxHashes(), client) -} - -func txStatusTest(t TestingT, hashes []koios.TxHash, client *koios.Client) { - res, err := client.GetTxsStatuses(context.Background(), hashes, nil) - if !assert.NoError(t, err) { - return - } - for i, status := range res.Data { - assertNotEmpty(t, status.TxHash, fmt.Sprintf("status[%d].status", i)) - assertGreater(t, status.Confirmations, 0, fmt.Sprintf("status[%d].confirmations", i)) - } -} +// func TestTxInfo(t *testing.T) { +// client, err := getLiveClient() +// if testIsLocal(t, err) { +// return +// } +// txInfoTest(t, networkTxHashes(), client) +// } + +// func txInfoTest(t TestingT, hashes []koios.TxHash, client *koios.Client) { +// res, err := client.GetTxsInfo(context.Background(), hashes, nil) +// if !assert.NoError(t, err) { +// return +// } + +// for _, tx := range res.Data { +// assertNotEmpty(t, tx.TxHash, fmt.Sprintf("tx[%s].tx_hash", tx.TxHash)) +// assertNotEmpty(t, tx.BlockHash, fmt.Sprintf("tx[%s].block_hash", tx.TxHash)) +// assertGreater(t, tx.BlockHeight, 0, fmt.Sprintf("tx[%s].block_height", tx.TxHash)) +// assertGreater(t, tx.EpochNo, koios.EpochNo(0), fmt.Sprintf("tx[%s].epoch_no", tx.TxHash)) +// assertGreater(t, tx.EpochSlot, koios.Slot(0), fmt.Sprintf("tx[%s].epoch_slot", tx.TxHash)) +// assertGreater(t, tx.AbsoluteSlot, koios.Slot(0), fmt.Sprintf("tx[%s].absolute_slot", tx.TxHash)) +// assertTimeNotZero(t, tx.TxTimestamp, fmt.Sprintf("tx[%s].tx_timestamp", tx.TxHash)) +// // assertGreater(t, tx.TxBlockIndex, 0, fmt.Sprintf("tx[%s].tx_block_index", tx.TxHash)) +// assertGreater(t, tx.TxSize, 0, fmt.Sprintf("tx[%s].tx_size", tx.TxHash)) +// assertIsPositive(t, tx.TotalOutput, fmt.Sprintf("tx[%s].total_output", tx.TxHash)) +// assertIsPositive(t, tx.Fee, fmt.Sprintf("tx[%s].fee", tx.TxHash)) + +// // assertTimeNotZero(t, tx.InvalidBefore, "invalid_before") +// // assertTimeNotZero(t, tx.InvalidAfter, fmt.Sprintf("tx[%s].invalid_after", tx.TxHash)) + +// if !tx.Deposit.IsZero() { +// assertIsPositive(t, tx.Deposit, fmt.Sprintf("tx[%s].deposit", tx.TxHash)) +// } +// // DATA +// if len(tx.CollateralInputs) > 0 { +// for _, utxo := range tx.CollateralInputs { +// assertUTxO(t, utxo, fmt.Sprintf("tx[%s].tx.collateral_inputs", tx.TxHash)) +// } +// } + +// if tx.CollateralOutput != nil { +// // assertNotEmpty(t, , "collateral_inputs") +// assertUTxO(t, *tx.CollateralOutput, fmt.Sprintf("tx[%s].tx.collateral_output", tx.TxHash)) +// } + +// if len(tx.ReferenceInputs) > 0 { +// for i, utxo := range tx.ReferenceInputs { +// assertUTxO(t, utxo, fmt.Sprintf("tx[%s].reference_inputs[%d]", tx.TxHash, i)) +// } +// } + +// if assertGreater(t, len(tx.Inputs), 0, "inputs") { +// for i, utxo := range tx.Inputs { +// assertUTxO(t, utxo, fmt.Sprintf("tx[%s].inputs[%d]", tx.TxHash, i)) +// } +// } +// if assertGreater(t, len(tx.Outputs), 0, "outputs") { +// for i, utxo := range tx.Outputs { +// assertUTxO(t, utxo, fmt.Sprintf("tx[%s].outputs[%d]", tx.TxHash, i)) +// } +// } + +// if len(tx.Withdrawals) > 0 { +// for i, withdrawal := range tx.Withdrawals { +// assertNotEmpty(t, withdrawal.StakeAddress, fmt.Sprintf("tx[%s].withdrawals[%d].stake_addr", tx.TxHash, i)) +// assertIsPositive(t, withdrawal.Amount, fmt.Sprintf("tx[%s].withdrawals[%d].amount", tx.TxHash, i)) +// } +// } + +// if len(tx.AssetsMinted) > 0 { +// for i, asset := range tx.AssetsMinted { +// assertAsset(t, asset, fmt.Sprintf("tx[%s].assets_minted[%d]", tx.TxHash, i)) +// } +// } + +// if tx.Metadata != nil { +// assertTxMetadata(t, tx.Metadata, fmt.Sprintf("tx[%s].metadata", tx.TxHash)) +// } + +// if len(tx.Certificates) > 0 { +// assertCertificates(t, tx.Certificates, fmt.Sprintf("tx[%s].certificates", tx.TxHash)) +// } +// if len(tx.NativeScripts) > 0 { +// assertNativeScripts(t, tx.NativeScripts, fmt.Sprintf("tx[%s].native_scripts", tx.TxHash)) +// } +// if len(tx.PlutusContracts) > 0 { +// assertPlutusContracts(t, tx.PlutusContracts, fmt.Sprintf("tx[%s].plutus_contracts", tx.TxHash)) +// } +// } +// } + +// func TestTxUTxO(t *testing.T) { +// client, err := getLiveClient() +// if testIsLocal(t, err) { +// return +// } +// txUTxOsTest(t, networkTxHashes(), client) +// } + +// func txUTxOsTest(t TestingT, hashes []koios.TxHash, client *koios.Client) { +// res, err := client.GetTxsUTxOs(context.Background(), hashes, nil) +// if !assert.NoError(t, err) { +// return +// } +// for _, eutxo := range res.Data { +// assertEUTxO(t, eutxo, fmt.Sprintf("tx[%s]", eutxo.TxHash)) +// } +// } + +// func TestTxMetadata(t *testing.T) { +// client, err := getLiveClient() +// if testIsLocal(t, err) { +// return +// } +// txMetadataTest(t, networkTxHashes(), client) +// } + +// func txMetadataTest(t TestingT, hashes []koios.TxHash, client *koios.Client) { +// res, err := client.GetTxsMetadata(context.Background(), hashes, nil) +// if !assert.NoError(t, err) { +// return +// } +// for _, listitem := range res.Data { +// assertTxMetadata(t, listitem.Metadata, fmt.Sprintf("tx[%s].metadata", listitem.TxHash)) +// } +// } + +// func TestTxMetaLabels(t *testing.T) { +// client, err := getLiveClient() +// if testIsLocal(t, err) { +// return +// } +// txMetaLabelsTest(t, client) +// } + +// func txMetaLabelsTest(t TestingT, client *koios.Client) { +// opts := client.NewRequestOptions() +// opts.SetPageSize(2) // testnets Range error if number is too big + +// res, err := client.GetTxMetaLabels(context.Background(), opts) +// if !assert.NoError(t, err) { +// return +// } + +// assertGreater(t, len(res.Data), 1, "GetTxMetaLabels") +// for _, label := range res.Data { +// assertNotEmpty(t, label.Key, "empty label") +// } +// } + +// func TestTxStatus(t *testing.T) { +// client, err := getLiveClient() +// if testIsLocal(t, err) { +// return +// } +// txStatusTest(t, networkTxHashes(), client) +// } + +// func txStatusTest(t TestingT, hashes []koios.TxHash, client *koios.Client) { +// res, err := client.GetTxsStatuses(context.Background(), hashes, nil) +// if !assert.NoError(t, err) { +// return +// } +// for i, status := range res.Data { +// assertNotEmpty(t, status.TxHash, fmt.Sprintf("status[%d].status", i)) +// assertGreater(t, status.Confirmations, 0, fmt.Sprintf("status[%d].confirmations", i)) +// } +// } From c9f8a7c6b87064cc97792f3030cb8c45cc566dde Mon Sep 17 00:00:00 2001 From: Marko Kungla Date: Tue, 27 Feb 2024 19:40:33 +0200 Subject: [PATCH 08/65] chore: update file headers Signed-off-by: Marko Kungla --- account.go | 14 +------------- address.go | 14 +------------- asset.go | 14 +------------- block.go | 14 +------------- client.go | 14 +------------- epoch.go | 14 +------------- go.mod | 8 +------- go.sum | 10 ---------- koios.go | 3 ++- network.go | 14 +------------- options.go | 14 +------------- pool.go | 14 +------------- request.go | 14 +------------- response.go | 14 +------------- script.go | 14 +------------- transaction.go | 14 +------------- 16 files changed, 16 insertions(+), 187 deletions(-) diff --git a/account.go b/account.go index f0e5783..4b6a2eb 100644 --- a/account.go +++ b/account.go @@ -1,18 +1,6 @@ -// Copyright 2022 The Cardano Community Authors // SPDX-License-Identifier: Apache-2.0 // -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at: -// -// http://www.apache.org/licenses/LICENSE-2.0 -// or LICENSE file in repository root. -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. +// Copyright © 2022 The Cardano Community Authors package koios diff --git a/address.go b/address.go index fed99ab..d6844b5 100644 --- a/address.go +++ b/address.go @@ -1,18 +1,6 @@ -// Copyright 2022 The Cardano Community Authors // SPDX-License-Identifier: Apache-2.0 // -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at: -// -// http://www.apache.org/licenses/LICENSE-2.0 -// or LICENSE file in repository root. -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. +// Copyright © 2022 The Cardano Community Authors package koios diff --git a/asset.go b/asset.go index eac27a6..3ec8980 100644 --- a/asset.go +++ b/asset.go @@ -1,18 +1,6 @@ -// Copyright 2022 The Cardano Community Authors // SPDX-License-Identifier: Apache-2.0 // -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at: -// -// http://www.apache.org/licenses/LICENSE-2.0 -// or LICENSE file in repository root. -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. +// Copyright © 2022 The Cardano Community Authors package koios diff --git a/block.go b/block.go index 9f611c1..aa76b88 100644 --- a/block.go +++ b/block.go @@ -1,18 +1,6 @@ -// Copyright 2022 The Cardano Community Authors // SPDX-License-Identifier: Apache-2.0 // -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at: -// -// http://www.apache.org/licenses/LICENSE-2.0 -// or LICENSE file in repository root. -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. +// Copyright © 2022 The Cardano Community Authors package koios diff --git a/client.go b/client.go index 0871121..f371f03 100644 --- a/client.go +++ b/client.go @@ -1,18 +1,6 @@ -// Copyright 2022 The Cardano Community Authors // SPDX-License-Identifier: Apache-2.0 // -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at: -// -// http://www.apache.org/licenses/LICENSE-2.0 -// or LICENSE file in repository root. -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. +// Copyright © 2022 The Cardano Community Authors package koios diff --git a/epoch.go b/epoch.go index 2a1dd5d..a7633b2 100644 --- a/epoch.go +++ b/epoch.go @@ -1,18 +1,6 @@ -// Copyright 2022 The Cardano Community Authors // SPDX-License-Identifier: Apache-2.0 // -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at: -// -// http://www.apache.org/licenses/LICENSE-2.0 -// or LICENSE file in repository root. -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. +// Copyright © 2022 The Cardano Community Authors package koios diff --git a/go.mod b/go.mod index 91543f0..68a4262 100644 --- a/go.mod +++ b/go.mod @@ -5,14 +5,8 @@ go 1.22 require ( github.com/happy-sdk/happy/pkg/version v0.1.2 github.com/shopspring/decimal v1.3.1 - github.com/stretchr/testify v1.8.4 golang.org/x/text v0.14.0 golang.org/x/time v0.5.0 ) -require ( - github.com/davecgh/go-spew v1.1.1 // indirect - github.com/pmezard/go-difflib v1.0.0 // indirect - golang.org/x/mod v0.15.0 // indirect - gopkg.in/yaml.v3 v3.0.1 // indirect -) +require golang.org/x/mod v0.15.0 // indirect diff --git a/go.sum b/go.sum index 3958049..a1491ac 100644 --- a/go.sum +++ b/go.sum @@ -1,20 +1,10 @@ -github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= -github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/happy-sdk/happy/pkg/version v0.1.2 h1:8DJ0afkEVW2fdm1uEScTS4wPgGe0Tmls3QPuX7jrbhY= github.com/happy-sdk/happy/pkg/version v0.1.2/go.mod h1:mFhI4DRvXZ8Ls8D5/aXIqcMnjCUBNtI3Ye9ilYL2Bz0= -github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= -github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= github.com/shopspring/decimal v1.3.1 h1:2Usl1nmF/WZucqkFZhnfFYxxxu8LG21F6nPQBE5gKV8= github.com/shopspring/decimal v1.3.1/go.mod h1:DKyhrW/HYNuLGql+MJL6WCR6knT2jwCFRcu2hWCYk4o= -github.com/stretchr/testify v1.8.4 h1:CcVxjf3Q8PM0mHUKJCdn+eZZtm5yQwehR5yeSVQQcUk= -github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo= golang.org/x/mod v0.15.0 h1:SernR4v+D55NyBH2QiEQrlBAnj1ECL6AGrA5+dPaMY8= golang.org/x/mod v0.15.0/go.mod h1:hTbmBsO62+eylJbnUtE2MGJUyE7QWk4xUqPFrRgJ+7c= golang.org/x/text v0.14.0 h1:ScX5w1eTa3QqT8oi6+ziP7dTV1S2+ALU0bI+0zXKWiQ= golang.org/x/text v0.14.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU= golang.org/x/time v0.5.0 h1:o7cqy6amK/52YcAKIPlM3a+Fpj35zvRj2TP+e1xFSfk= golang.org/x/time v0.5.0/go.mod h1:3BpzKBy/shNhVucY/MWOyx10tF3SFh9QdLuxbVysPQM= -gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM= -gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= -gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= -gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/koios.go b/koios.go index 63bbf61..fa4b76e 100644 --- a/koios.go +++ b/koios.go @@ -1,5 +1,6 @@ -// Copyright 2022 The Cardano Community Authors // SPDX-License-Identifier: Apache-2.0 +// +// Copyright © 2022 The Cardano Community Authors // Package koios provides api client library to interact with Koios API // endpoints and Cardano Blockchain. Sub package ./cmd/koios-rest diff --git a/network.go b/network.go index bc8be84..eeb8d48 100644 --- a/network.go +++ b/network.go @@ -1,18 +1,6 @@ -// Copyright 2022 The Cardano Community Authors // SPDX-License-Identifier: Apache-2.0 // -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at: -// -// http://www.apache.org/licenses/LICENSE-2.0 -// or LICENSE file in repository root. -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. +// Copyright © 2022 The Cardano Community Authors package koios diff --git a/options.go b/options.go index 453843d..22bb3c6 100644 --- a/options.go +++ b/options.go @@ -1,18 +1,6 @@ -// Copyright 2022 The Cardano Community Authors // SPDX-License-Identifier: Apache-2.0 // -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at: -// -// http://www.apache.org/licenses/LICENSE-2.0 -// or LICENSE file in repository root. -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. +// Copyright © 2022 The Cardano Community Authors package koios diff --git a/pool.go b/pool.go index 00a966c..0904ff4 100644 --- a/pool.go +++ b/pool.go @@ -1,18 +1,6 @@ -// Copyright 2022 The Cardano Community Authors // SPDX-License-Identifier: Apache-2.0 // -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at: -// -// http://www.apache.org/licenses/LICENSE-2.0 -// or LICENSE file in repository root. -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. +// Copyright © 2022 The Cardano Community Authors package koios diff --git a/request.go b/request.go index 99712bd..f3c1c2b 100644 --- a/request.go +++ b/request.go @@ -1,18 +1,6 @@ -// Copyright 2022 The Cardano Community Authors // SPDX-License-Identifier: Apache-2.0 // -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at: -// -// http://www.apache.org/licenses/LICENSE-2.0 -// or LICENSE file in repository root. -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. +// Copyright © 2022 The Cardano Community Authors package koios diff --git a/response.go b/response.go index 17f5388..b695af2 100644 --- a/response.go +++ b/response.go @@ -1,18 +1,6 @@ -// Copyright 2022 The Cardano Community Authors // SPDX-License-Identifier: Apache-2.0 // -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at: -// -// http://www.apache.org/licenses/LICENSE-2.0 -// or LICENSE file in repository root. -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. +// Copyright © 2022 The Cardano Community Authors package koios diff --git a/script.go b/script.go index 3a5c0f9..255d4be 100644 --- a/script.go +++ b/script.go @@ -1,18 +1,6 @@ -// Copyright 2022 The Cardano Community Authors // SPDX-License-Identifier: Apache-2.0 // -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at: -// -// http://www.apache.org/licenses/LICENSE-2.0 -// or LICENSE file in repository root. -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. +// Copyright © 2022 The Cardano Community Authors package koios diff --git a/transaction.go b/transaction.go index e51eff7..7e66ad7 100644 --- a/transaction.go +++ b/transaction.go @@ -1,18 +1,6 @@ -// Copyright 2022 The Cardano Community Authors // SPDX-License-Identifier: Apache-2.0 // -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at: -// -// http://www.apache.org/licenses/LICENSE-2.0 -// or LICENSE file in repository root. -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. +// Copyright © 2022 The Cardano Community Authors package koios From 8a85363224c2291fe9d6c55eb2bcb7b009b62af9 Mon Sep 17 00:00:00 2001 From: Marko Kungla Date: Fri, 8 Mar 2024 15:49:01 +0200 Subject: [PATCH 09/65] feat: update v1 address_Assets schema Signed-off-by: Marko Kungla --- .github/workflows/ci.yml | 2 +- address.go | 4 ++-- asset.go | 8 +++++--- 3 files changed, 8 insertions(+), 6 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 3e72b90..8520339 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -39,7 +39,7 @@ jobs: - uses: github/codeql-action/init@v3 with: languages: go - - uses: github/codeql-action/autobuild@v3 + # - uses: github/codeql-action/autobuild@v3 - uses: github/codeql-action/analyze@v3 ############################################################################### diff --git a/address.go b/address.go index d6844b5..192776d 100644 --- a/address.go +++ b/address.go @@ -40,8 +40,8 @@ type ( } AddressAssets struct { - Address Address `json:"address"` - AssetList []Asset `json:"asset_list"` + Asset + Address Address `json:"address"` } // AddressInfoResponse represents response from `/address_info` endpoint. diff --git a/asset.go b/asset.go index 3ec8980..a724fa1 100644 --- a/asset.go +++ b/asset.go @@ -28,9 +28,9 @@ type ( // Asset represents Cardano Asset. Asset struct { // Asset Name (hex). - AssetName AssetName `json:"asset_name,omitempty"` + AssetName AssetName `json:"asset_name"` - Fingerprint AssetFingerprint `json:"fingerprint,omitempty"` + Fingerprint AssetFingerprint `json:"fingerprint"` // Asset Policy ID (hex). PolicyID PolicyID `json:"policy_id"` @@ -39,7 +39,9 @@ type ( // Input: asset balance on the selected input transaction. // Output: sum of assets for output UTxO. // Mint: sum of minted assets (negative on burn). - Quantity decimal.Decimal `json:"quantity,omitempty"` + Quantity decimal.Decimal `json:"quantity"` + + Decimals uint8 `json:"decimals"` } // TokenRegistryMetadata metadata registered on the Cardano Token Registry. From dbba179a502b6cfca092b623bb7dcc61d580c94f Mon Sep 17 00:00:00 2001 From: Marko Kungla Date: Sat, 9 Mar 2024 11:25:50 +0200 Subject: [PATCH 10/65] feat: add GetCredentialUTxOs and GetAddressUTxOs Signed-off-by: Marko Kungla --- .github/workflows/ci.yml | 1 - address.go | 72 ++++++++++++++++++++++++++++++++++++++-- koios.go | 2 ++ response.go | 3 ++ script.go | 7 ++++ transaction.go | 26 ++++++++------- 6 files changed, 96 insertions(+), 15 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 8520339..1b7ad91 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -39,7 +39,6 @@ jobs: - uses: github/codeql-action/init@v3 with: languages: go - # - uses: github/codeql-action/autobuild@v3 - uses: github/codeql-action/analyze@v3 ############################################################################### diff --git a/address.go b/address.go index 192776d..09e30ce 100644 --- a/address.go +++ b/address.go @@ -82,6 +82,11 @@ type ( AssetNameASCII string `json:"asset_name_ascii"` Balance decimal.Decimal `json:"balance"` } + + UTxOsResponse struct { + Response + Data []UTxO `json:"data"` + } ) // Valid validates address and returns false and error @@ -128,8 +133,7 @@ func (c *Client) GetAddressesInfo( ) (res *AddressesInfoResponse, err error) { res = &AddressesInfoResponse{} if len(addr) == 0 { - err = ErrNoAddress - res.applyError(nil, err) + res.applyError(nil, ErrNoAddressesProvided) return } rsp, err := c.request(ctx, &res.Response, "POST", "/address_info", addressesPL(addr), opts) @@ -267,6 +271,70 @@ func (c *Client) GetCredentialTxs( return res, ReadAndUnmarshalResponse(rsp, &res.Response, &res.Data) } +func (c *Client) GetAddressUTxOs( + ctx context.Context, + addrs []Address, + extended bool, + opts *RequestOptions, +) (*UTxOsResponse, error) { + res := &UTxOsResponse{} + if len(addrs) == 0 { + err := ErrNoAddress + res.applyError(nil, err) + return res, err + } + + var payload = struct { + Adresses []Address `json:"_addresses"` + Extended bool `json:"_extended,omitempty"` + }{ + Adresses: addrs, + Extended: extended, + } + + rpipe, w := io.Pipe() + go func() { + _ = json.NewEncoder(w).Encode(payload) + defer w.Close() + }() + + rsp, err := c.request(ctx, &res.Response, "POST", "/address_utxos", rpipe, opts) + res.applyError(nil, err) + err = ReadAndUnmarshalResponse(rsp, &res.Response, &res.Data) + return res, err +} + +func (c *Client) GetCredentialUTxOs( + ctx context.Context, + creds []PaymentCredential, + extended bool, + opts *RequestOptions, +) (*UTxOsResponse, error) { + res := &UTxOsResponse{} + if len(creds) == 0 || len(creds[0]) == 0 { + err := ErrNoCredentialsProvided + res.applyError(nil, err) + return res, err + } + var payload = struct { + Creds []PaymentCredential `json:"_payment_credentials"` + Extended bool `json:"_extended,omitempty"` + }{ + Creds: creds, + Extended: extended, + } + rpipe, w := io.Pipe() + go func() { + _ = json.NewEncoder(w).Encode(payload) + defer w.Close() + }() + + rsp, err := c.request(ctx, &res.Response, "POST", "/credential_utxos", rpipe, opts) + res.applyError(nil, err) + err = ReadAndUnmarshalResponse(rsp, &res.Response, &res.Data) + return res, err +} + func addressesPL(addrs []Address) io.Reader { var payload = struct { Adresses []Address `json:"_addresses"` diff --git a/koios.go b/koios.go index fa4b76e..3533c51 100644 --- a/koios.go +++ b/koios.go @@ -62,6 +62,8 @@ var ( ErrNoTxHash = errors.New("missing transaxtion hash(es)") ErrNoDatumHash = errors.New("missing datum hash(es)") ErrNoAddress = errors.New("missing address") + ErrNoAddressesProvided = errors.New("atleast one address required") + ErrNoCredentialsProvided = errors.New("atleast one payment credential required") ErrNoPoolID = errors.New("missing pool id") ErrResponse = errors.New("response error") ErrSchema = errors.New("scheme must be http or https") diff --git a/response.go b/response.go index b695af2..c19f51f 100644 --- a/response.go +++ b/response.go @@ -89,6 +89,9 @@ func ReadResponseBody(rsp *http.Response) (body []byte, err error) { // ReadAndUnmarshalResponse is helper to unmarchal json responses. func ReadAndUnmarshalResponse(rsp *http.Response, res *Response, dest any) error { + if rsp == nil { + return fmt.Errorf("%w: got no response", ErrResponse) + } body, err := ReadResponseBody(rsp) if !strings.Contains(rsp.Header.Get("Content-Type"), "json") { return fmt.Errorf("%w: %s", ErrResponseIsNotJSON, string(body)) diff --git a/script.go b/script.go index 255d4be..632cc83 100644 --- a/script.go +++ b/script.go @@ -134,6 +134,13 @@ func (v DatumHash) String() string { return string(v) } +func (v *DatumHash) MarshalJSON() ([]byte, error) { + if len(v.String()) == 0 { + return []byte("null"), nil + } + return []byte(fmt.Sprintf(`"%s"`, v.String())), nil +} + // GetNativeScriptList returns list of all existing native script hashes // along with their creation transaction hashes. func (c *Client) GetNativeScripts( diff --git a/transaction.go b/transaction.go index 7e66ad7..975cdad 100644 --- a/transaction.go +++ b/transaction.go @@ -44,27 +44,29 @@ type ( UTxO struct { // Hash of this transaction. TxHash TxHash `json:"tx_hash"` - // Index of output UTxO. TxIndex int `json:"tx_index"` - - // where funds were sent or change to be returned. - PaymentAddr *PaymentAddr `json:"payment_addr,omitempty"` - + // Address A Cardano payment/base address (bech32 encoded) + Address *Address `json:"address,omitempty"` + // Total sum of ADA on the UTxO + Value decimal.Decimal `json:"value"` // StakeAddress for transaction's output UTxO. StakeAddress *Address `json:"stake_addr,omitempty"` + // where funds were sent or change to be returned. + PaymentAddr *PaymentAddr `json:"payment_addr,omitempty"` - // BlockHeight int `json:"block_height"` - // BlockTime Timestamp `json:"block_time"` + EpochNo EpochNo `json:"epoch_no"` + BlockHeight uint64 `json:"block_height"` + BlockTime Timestamp `json:"block_time"` - // Total sum on the output address. - Value decimal.Decimal `json:"value"` + DatumHash DatumHash `json:"datum_hash"` + InlineDatum any `json:"inline_datum"` + ReferenceScript any `json:"reference_script"` - DatumHash DatumHash `json:"datum_hash,omitempty"` - InlineDatum any `json:"inline_datum,omitempty"` - ReferenceScript any `json:"reference_script,omitempty"` // An array of assets to be included in output UTxO. AssetList []Asset `json:"asset_list,omitempty"` + + IsSpent bool `json:"is_spent,omitempty"` } // TxsWithdrawal withdrawal record in transaction. From 8725e4128b0a29e1e89c098b41814ae7c2f12273 Mon Sep 17 00:00:00 2001 From: Marko Kungla Date: Sun, 10 Mar 2024 10:47:19 +0200 Subject: [PATCH 11/65] feat: add GetPolicyAssetList Signed-off-by: Marko Kungla --- asset.go | 60 ++++++++++++++++++++++++++++++++++++++++++++++++++------ 1 file changed, 54 insertions(+), 6 deletions(-) diff --git a/asset.go b/asset.go index a724fa1..13f26cc 100644 --- a/asset.go +++ b/asset.go @@ -44,6 +44,27 @@ type ( Decimals uint8 `json:"decimals"` } + AssetListItem struct { + // Asset Name (hex). + AssetName AssetName `json:"asset_name"` + + Fingerprint AssetFingerprint `json:"fingerprint"` + + // Asset Policy ID (hex). + PolicyID PolicyID `json:"policy_id"` + } + + PolicyAssetListItem struct { + // Asset Name (hex). + AssetName AssetName `json:"asset_name"` + + Fingerprint AssetFingerprint `json:"fingerprint"` + // TotalSupply of Asset + TotalSupply decimal.Decimal `json:"total_supply"` + + Decimals uint8 `json:"decimals"` + } + // TokenRegistryMetadata metadata registered on the Cardano Token Registry. TokenRegistryMetadata struct { Decimals int `json:"decimals"` @@ -77,7 +98,7 @@ type ( AssetName AssetName `json:"asset_name"` // Asset Name (ASCII) - AssetNameASCII string `json:"asset_name_ascii"` + AssetNameASCII string `json:"asset_name_ascii,omitempty"` // The CIP14 fingerprint of the asset Fingerprint AssetFingerprint `json:"fingerprint"` @@ -96,22 +117,22 @@ type ( TotalSupply decimal.Decimal `json:"total_supply"` // CreationTime of Asset - CreationTime Timestamp `json:"creation_time"` + CreationTime Timestamp `json:"creation_time,omitempty"` // MintCnt count of mint transactions - MintCnt int `json:"mint_cnt"` + MintCnt int `json:"mint_cnt,omitempty"` // BurnCnt count of burn transactions - BurnCnt int `json:"burn_cnt"` + BurnCnt int `json:"burn_cnt,omitempty"` // MintingTxHash mint tx - MintingTxHash TxHash `json:"minting_tx_hash"` + MintingTxHash TxHash `json:"minting_tx_hash,omitempty"` } // AssetListResponse represents response from `/asset_list` endpoint. AssetListResponse struct { Response - Data []Asset `json:"data"` + Data []AssetListItem `json:"data"` } // AssetHolder payment addresses holding the given token (including balance). @@ -169,6 +190,12 @@ type ( Response Data *AssetHistory `json:"data"` } + + // AssetPolicyAssetListResponse represents response from `/policy_asset_list` endpoint. + AssetPolicyAssetListResponse struct { + Response + Data []PolicyAssetListItem `json:"data"` + } ) // String returns AssetName as string. @@ -363,3 +390,24 @@ func (c *Client) GetAssetHistory( } return } + +func (c *Client) GetPolicyAssetList( + ctx context.Context, + policy PolicyID, + opts *RequestOptions, +) (res *AssetPolicyAssetListResponse, err error) { + res = &AssetPolicyAssetListResponse{} + + if opts == nil { + opts = c.NewRequestOptions() + } + opts.QuerySet("_asset_policy", policy.String()) + + rsp, err := c.request(ctx, &res.Response, "GET", "/policy_asset_list", nil, opts) + if err != nil { + return + } + + err = ReadAndUnmarshalResponse(rsp, &res.Response, &res.Data) + return +} From d41fcda2094cd91d2b708064a54a2a3a3abca0a1 Mon Sep 17 00:00:00 2001 From: Marko Kungla Date: Fri, 29 Mar 2024 16:41:37 +0200 Subject: [PATCH 12/65] feat: add GetAssetTokenRegistry for asset_token_registry endpoint Signed-off-by: Marko Kungla --- asset.go | 36 ++++++++++++++++++++++++++++-------- 1 file changed, 28 insertions(+), 8 deletions(-) diff --git a/asset.go b/asset.go index 13f26cc..0781afe 100644 --- a/asset.go +++ b/asset.go @@ -67,14 +67,14 @@ type ( // TokenRegistryMetadata metadata registered on the Cardano Token Registry. TokenRegistryMetadata struct { - Decimals int `json:"decimals"` - Description string `json:"description"` - - // A PNG image file as a byte string - Logo string `json:"logo"` - Name string `json:"name"` - Ticker string `json:"ticker"` - URL string `json:"url"` + PolicyID PolicyID `json:"policy_id"` + AssetName AssetName `json:"asset_name"` + AccetNameASCII string `json:"asset_name_ascii"` + Ticker string `json:"ticker"` + Description string `json:"description"` + URL string `json:"url"` + Decimals int `json:"decimals"` + Logo string `json:"logo"` } // AssetSummary aggregated asset summary. @@ -196,6 +196,12 @@ type ( Response Data []PolicyAssetListItem `json:"data"` } + + // AssetTokenRegistryResponse represents response from `/asset_token_registry` endpoint. + AssetTokenRegistryResponse struct { + Response + Data []TokenRegistryMetadata `json:"data"` + } ) // String returns AssetName as string. @@ -411,3 +417,17 @@ func (c *Client) GetPolicyAssetList( err = ReadAndUnmarshalResponse(rsp, &res.Response, &res.Data) return } + +func (c *Client) GetAssetTokenRegistry( + ctx context.Context, + opts *RequestOptions, +) (res *AssetTokenRegistryResponse, err error) { + res = &AssetTokenRegistryResponse{} + + rsp, err := c.request(ctx, &res.Response, "GET", "/asset_token_registry", nil, opts) + if err != nil { + return + } + err = ReadAndUnmarshalResponse(rsp, &res.Response, &res.Data) + return +} From 79519bdad6858db1f247a8db33db7b58af15dfe5 Mon Sep 17 00:00:00 2001 From: Marko Kungla Date: Fri, 29 Mar 2024 17:08:15 +0200 Subject: [PATCH 13/65] fix: update GetAssetInfo to return list pased on provided args BREAKING CHANGE: requires argument of assets with asset policy id and asset name set Signed-off-by: Marko Kungla --- asset.go | 70 +++++++++++++++++++++++++++++++------------------------- koios.go | 1 + 2 files changed, 40 insertions(+), 31 deletions(-) diff --git a/asset.go b/asset.go index 0781afe..c33dbb3 100644 --- a/asset.go +++ b/asset.go @@ -8,6 +8,7 @@ import ( "context" "encoding/json" "fmt" + "io" "github.com/shopspring/decimal" ) @@ -94,14 +95,24 @@ type ( // AssetInfo info about the asset. AssetInfo struct { + // Asset Policy ID (hex). + PolicyID PolicyID `json:"policy_id,omitempty"` // Asset Name (hex). AssetName AssetName `json:"asset_name"` - // Asset Name (ASCII) AssetNameASCII string `json:"asset_name_ascii,omitempty"` - // The CIP14 fingerprint of the asset Fingerprint AssetFingerprint `json:"fingerprint"` + // MintingTxHash mint tx + MintingTxHash TxHash `json:"minting_tx_hash,omitempty"` + // TotalSupply of Asset + TotalSupply decimal.Decimal `json:"total_supply"` + // MintCnt count of mint transactions + MintCnt int `json:"mint_cnt,omitempty"` + // BurnCnt count of burn transactions + BurnCnt int `json:"burn_cnt,omitempty"` + // CreationTime of Asset + CreationTime Timestamp `json:"creation_time,omitempty"` // MintingTxMetadata minting Tx JSON payload if it can be decoded as JSON // MintingTxMetadata *TxInfoMetadata `json:"minting_tx_metadata"` @@ -110,23 +121,7 @@ type ( // Asset metadata registered on the Cardano Token Registry TokenRegistryMetadata *TokenRegistryMetadata `json:"token_registry_metadata,omitempty"` - // Asset Policy ID (hex). - PolicyID PolicyID `json:"policy_id,omitempty"` - - // TotalSupply of Asset - TotalSupply decimal.Decimal `json:"total_supply"` - - // CreationTime of Asset - CreationTime Timestamp `json:"creation_time,omitempty"` - - // MintCnt count of mint transactions - MintCnt int `json:"mint_cnt,omitempty"` - - // BurnCnt count of burn transactions - BurnCnt int `json:"burn_cnt,omitempty"` - - // MintingTxHash mint tx - MintingTxHash TxHash `json:"minting_tx_hash,omitempty"` + CIP68Metadata *json.RawMessage `json:"cip68_metadata,omitempty"` } // AssetListResponse represents response from `/asset_list` endpoint. @@ -149,7 +144,7 @@ type ( // AssetInfoResponse represents response from `/asset_info` endpoint. AssetInfoResponse struct { - Data *AssetInfo `json:"data"` + Data []AssetInfo `json:"data"` Response } @@ -256,8 +251,7 @@ func (c *Client) GetAssetAddresses( // first minting & token registry metadata. func (c *Client) GetAssetInfo( ctx context.Context, - policy PolicyID, - name AssetName, + assets []Asset, opts *RequestOptions, ) (res *AssetInfoResponse, err error) { res = &AssetInfoResponse{} @@ -265,19 +259,33 @@ func (c *Client) GetAssetInfo( if opts == nil { opts = c.NewRequestOptions() } - opts.QuerySet("_asset_policy", policy.String()) - opts.QuerySet("_asset_name", name.String()) - rsp, err := c.request(ctx, &res.Response, "GET", "/asset_info", nil, opts) - if err != nil { - return + if len(assets) == 0 { + return nil, fmt.Errorf("%w: atleast one asset must be provided", ErrAsset) } - info := []AssetInfo{} - err = ReadAndUnmarshalResponse(rsp, &res.Response, &info) - if len(info) == 1 { - res.Data = &info[0] + var payload = struct { + Assets [][]string `json:"_asset_list"` + }{} + + for _, asset := range assets { + if asset.PolicyID == "" || asset.AssetName == "" { + return nil, fmt.Errorf("%w: policy_id and asset_name must be provided", ErrAsset) + } + payload.Assets = append(payload.Assets, []string{asset.PolicyID.String(), asset.AssetName.String()}) } + + rpipe, w := io.Pipe() + go func() { + _ = json.NewEncoder(w).Encode(payload) + defer w.Close() + }() + + rsp, err := c.request(ctx, &res.Response, "POST", "/asset_info", rpipe, opts) + if err != nil { + return + } + err = ReadAndUnmarshalResponse(rsp, &res.Response, &res.Data) return } diff --git a/koios.go b/koios.go index 3533c51..858f709 100644 --- a/koios.go +++ b/koios.go @@ -71,6 +71,7 @@ var ( ErrUnexpectedResponseField = errors.New("unexpected response field") ErrUTxOInputAlreadyUsed = errors.New("UTxO already used") ErrNoData = errors.New("no data") + ErrAsset = errors.New("asset error") // ZeroLovelace is alias decimal.Zero. ZeroLovelace = decimal.Zero.Copy() //nolint: gochecknoglobals From 4baa1eb7650c69862fcfe3dbd82e1e9549e37132 Mon Sep 17 00:00:00 2001 From: Marko Kungla Date: Fri, 29 Mar 2024 17:48:24 +0200 Subject: [PATCH 14/65] feat: add GetAssetUTxOs to call asset_utxos endpoint Signed-off-by: Marko Kungla --- asset.go | 41 +++++++++++++++++++++++++++++++++++++++++ koios.go | 30 ------------------------------ response.go | 32 ++++++++++++++++++++++++++++++++ 3 files changed, 73 insertions(+), 30 deletions(-) diff --git a/asset.go b/asset.go index c33dbb3..6107d4a 100644 --- a/asset.go +++ b/asset.go @@ -197,6 +197,11 @@ type ( Response Data []TokenRegistryMetadata `json:"data"` } + + AssetUTxOsResponse struct { + Response + Data []UTxO `json:"data"` + } ) // String returns AssetName as string. @@ -439,3 +444,39 @@ func (c *Client) GetAssetTokenRegistry( err = ReadAndUnmarshalResponse(rsp, &res.Response, &res.Data) return } + +func (c *Client) GetAssetUTxOs( + ctx context.Context, + assets []Asset, + opts *RequestOptions, +) (res *AssetUTxOsResponse, err error) { + res = &AssetUTxOsResponse{} + + if opts == nil { + opts = c.NewRequestOptions() + } + + var payload = struct { + Assets [][]string `json:"_asset_list"` + }{} + + for _, asset := range assets { + if asset.PolicyID == "" || asset.AssetName == "" { + return nil, fmt.Errorf("%w: policy_id and asset_name must be provided", ErrAsset) + } + payload.Assets = append(payload.Assets, []string{asset.PolicyID.String(), asset.AssetName.String()}) + } + + rpipe, w := io.Pipe() + go func() { + _ = json.NewEncoder(w).Encode(payload) + defer w.Close() + }() + + rsp, err := c.request(ctx, &res.Response, "POST", "/asset_utxos", rpipe, opts) + if err != nil { + return + } + err = ReadAndUnmarshalResponse(rsp, &res.Response, &res.Data) + return +} diff --git a/koios.go b/koios.go index 858f709..c89607a 100644 --- a/koios.go +++ b/koios.go @@ -130,36 +130,6 @@ type ( Type string `json:"type"` } - // Response wraps API responses. - Response struct { - // RequestURL is full request url. - RequestURL string `json:"request_url"` - - // RequestMethod is HTTP method used for request. - RequestMethod string `json:"request_method"` - - // StatusCode of the HTTP response. - StatusCode int `json:"status_code"` - - // Status of the HTTP response header if present. - Status string `json:"status"` - - // Date response header. - Date string `json:"date,omitempty"` - - // ContentLocation response header if present. - ContentLocation string `json:"content_location,omitempty"` - - // ContentRange response header if present. - ContentRange string `json:"content_range,omitempty"` - - // Error response body if present. - Error *ResponseError `json:"error,omitempty"` - - // Stats of the request if stats are enabled. - Stats *RequestStats `json:"stats,omitempty"` - } - // RequestStats represent collected request stats if collecting // request stats is enabled. RequestStats struct { diff --git a/response.go b/response.go index c19f51f..57e7900 100644 --- a/response.go +++ b/response.go @@ -17,6 +17,38 @@ import ( ) type ( + // Response wraps API responses. + Response struct { + // RequestURL is full request url. + RequestURL string `json:"request_url"` + + // RequestMethod is HTTP method used for request. + RequestMethod string `json:"request_method"` + + RequestHeaders http.Header `json:"request_headers"` + + // StatusCode of the HTTP response. + StatusCode int `json:"status_code"` + + // Status of the HTTP response header if present. + Status string `json:"status"` + + // Date response header. + Date string `json:"date,omitempty"` + + // ContentLocation response header if present. + ContentLocation string `json:"content_location,omitempty"` + + // ContentRange response header if present. + ContentRange string `json:"content_range,omitempty"` + + // Error response body if present. + Error *ResponseError `json:"error,omitempty"` + + // Stats of the request if stats are enabled. + Stats *RequestStats `json:"stats,omitempty"` + } + ErrorCode string // ResponseError represents api error messages. From 5afcb85cec9d63c6dd89954f34040a002904f9fe Mon Sep 17 00:00:00 2001 From: Marko Kungla Date: Fri, 29 Mar 2024 18:03:31 +0200 Subject: [PATCH 15/65] fix: update GetAssetHistory method to match new api Signed-off-by: Marko Kungla --- asset.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/asset.go b/asset.go index 6107d4a..9f0a776 100644 --- a/asset.go +++ b/asset.go @@ -176,7 +176,7 @@ type ( // AssetHistory holds given asset mint/burn tx's. AssetHistory struct { - Asset + AssetListItem MintingTXs []AssetMintTX `json:"minting_txs"` } From 0ba07346297bb5ab542cd20f0b8487d6ba6fd359 Mon Sep 17 00:00:00 2001 From: Marko Kungla Date: Fri, 29 Mar 2024 18:24:12 +0200 Subject: [PATCH 16/65] feat: implement GetAssetNftAddress for asset_nft_address endpoint Signed-off-by: Marko Kungla --- asset.go | 32 ++++++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) diff --git a/asset.go b/asset.go index 9f0a776..0ad47d3 100644 --- a/asset.go +++ b/asset.go @@ -141,6 +141,10 @@ type ( Response Data []AssetHolder `json:"data"` } + AssetNFTAddressResponse struct { + Response + Data *Address `json:"data"` + } // AssetInfoResponse represents response from `/asset_info` endpoint. AssetInfoResponse struct { @@ -480,3 +484,31 @@ func (c *Client) GetAssetUTxOs( err = ReadAndUnmarshalResponse(rsp, &res.Response, &res.Data) return } + +func (c *Client) GetAssetNftAddress( + ctx context.Context, + policy PolicyID, + name AssetName, + opts *RequestOptions, +) (res *AssetNFTAddressResponse, err error) { + res = &AssetNFTAddressResponse{} + + if opts == nil { + opts = c.NewRequestOptions() + } + opts.QuerySet("_asset_policy", policy.String()) + opts.QuerySet("_asset_name", name.String()) + + rsp, err := c.request(ctx, &res.Response, "GET", "/asset_nft_address", nil, opts) + if err != nil { + return + } + + var holders []AssetHolder + + err = ReadAndUnmarshalResponse(rsp, &res.Response, &holders) + if len(holders) > 0 { + res.Data = &holders[0].PaymentAddress + } + return +} From cb293350427923837b2525244e6a529c96e055d5 Mon Sep 17 00:00:00 2001 From: Marko Kungla Date: Fri, 29 Mar 2024 18:32:55 +0200 Subject: [PATCH 17/65] feat: implement GetAssetPolicyAddresses for policy_asset_addresses endpoint Signed-off-by: Marko Kungla --- asset.go | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/asset.go b/asset.go index 0ad47d3..9b39647 100644 --- a/asset.go +++ b/asset.go @@ -132,6 +132,7 @@ type ( // AssetHolder payment addresses holding the given token (including balance). AssetHolder struct { + AssetName AssetName `json:"asset_name,omitempty"` PaymentAddress Address `json:"payment_address"` Quantity decimal.Decimal `json:"quantity"` } @@ -512,3 +513,24 @@ func (c *Client) GetAssetNftAddress( } return } + +func (c *Client) GetAssetPolicyAddresses( + ctx context.Context, + policy PolicyID, + opts *RequestOptions, +) (res *AssetAddressListResponse, err error) { + res = &AssetAddressListResponse{} + + if opts == nil { + opts = c.NewRequestOptions() + } + opts.QuerySet("_asset_policy", policy.String()) + + rsp, err := c.request(ctx, &res.Response, "GET", "/policy_asset_addresses", nil, opts) + if err != nil { + return + } + err = ReadAndUnmarshalResponse(rsp, &res.Response, &res.Data) + + return +} From d1753e4d1ed6cf7a23d40f10705a7eea8f9902c2 Mon Sep 17 00:00:00 2001 From: Marko Kungla Date: Fri, 29 Mar 2024 18:41:27 +0200 Subject: [PATCH 18/65] fix: update GetPolicyAssetInfo response Signed-off-by: Marko Kungla --- asset.go | 9 +++------ 1 file changed, 3 insertions(+), 6 deletions(-) diff --git a/asset.go b/asset.go index 9b39647..a434a9b 100644 --- a/asset.go +++ b/asset.go @@ -113,15 +113,12 @@ type ( BurnCnt int `json:"burn_cnt,omitempty"` // CreationTime of Asset CreationTime Timestamp `json:"creation_time,omitempty"` - // MintingTxMetadata minting Tx JSON payload if it can be decoded as JSON // MintingTxMetadata *TxInfoMetadata `json:"minting_tx_metadata"` MintingTxMetadata *json.RawMessage `json:"minting_tx_metadata,omitempty"` - // Asset metadata registered on the Cardano Token Registry TokenRegistryMetadata *TokenRegistryMetadata `json:"token_registry_metadata,omitempty"` - - CIP68Metadata *json.RawMessage `json:"cip68_metadata,omitempty"` + CIP68Metadata *json.RawMessage `json:"cip68_metadata,omitempty"` } // AssetListResponse represents response from `/asset_list` endpoint. @@ -361,7 +358,7 @@ func (c *Client) GetAssetTxs( } // GetAssetPolicyInfo returns information for all assets under the same policy. -func (c *Client) GetAssetPolicyInfo( +func (c *Client) GetPolicyAssetInfo( ctx context.Context, policy PolicyID, opts *RequestOptions, @@ -514,7 +511,7 @@ func (c *Client) GetAssetNftAddress( return } -func (c *Client) GetAssetPolicyAddresses( +func (c *Client) GetPolicyAssetAddresses( ctx context.Context, policy PolicyID, opts *RequestOptions, From d7259c0737f65d256399af4dbb97bbe3645ead0d Mon Sep 17 00:00:00 2001 From: Marko Kungla Date: Fri, 29 Mar 2024 18:57:29 +0200 Subject: [PATCH 19/65] fix: update asset summary request Signed-off-by: Marko Kungla --- asset.go | 13 +++++++++---- 1 file changed, 9 insertions(+), 4 deletions(-) diff --git a/asset.go b/asset.go index a434a9b..ef1dc92 100644 --- a/asset.go +++ b/asset.go @@ -40,9 +40,9 @@ type ( // Input: asset balance on the selected input transaction. // Output: sum of assets for output UTxO. // Mint: sum of minted assets (negative on burn). - Quantity decimal.Decimal `json:"quantity"` + Quantity decimal.Decimal `json:"quantity,omitempty"` - Decimals uint8 `json:"decimals"` + Decimals uint8 `json:"decimals,omitempty"` } AssetListItem struct { @@ -153,7 +153,7 @@ type ( // AssetSummaryResponse represents response from `/asset_summary` endpoint. AssetSummaryResponse struct { Response - Data []AssetSummary `json:"data"` + Data *AssetSummary `json:"data"` } // AssetTxsResponse represents response from `/asset_txs` endpoint. @@ -318,7 +318,12 @@ func (c *Client) GetAssetSummary( return } - err = ReadAndUnmarshalResponse(rsp, &res.Response, &res.Data) + var assetSummary []AssetSummary + err = ReadAndUnmarshalResponse(rsp, &res.Response, &assetSummary) + if len(assetSummary) == 1 { + data := assetSummary[0] + res.Data = &data + } return } From 77947b7beb73dfee2f9fa0e255e65a0a809afcdb Mon Sep 17 00:00:00 2001 From: Marko Kungla Date: Fri, 29 Mar 2024 19:36:12 +0200 Subject: [PATCH 20/65] feat: implement http client timeout option Signed-off-by: Marko Kungla --- client.go | 10 ++++++---- koios.go | 18 ++++++++++-------- options.go | 27 ++++++++++++++++++++++----- 3 files changed, 38 insertions(+), 17 deletions(-) diff --git a/client.go b/client.go index f371f03..62d3690 100644 --- a/client.go +++ b/client.go @@ -26,6 +26,7 @@ type ( url *url.URL client *http.Client commonHeaders http.Header + locked bool } ) @@ -39,16 +40,17 @@ func (c *Client) WithOptions(opts ...Option) (*Client, error) { u, uerr := url.Parse(c.url.String()) nc.url = u + if nc.client == nil { + nc.client = c.client + } + // Apply provided options for _, opt := range opts { if err := opt.apply(nc); err != nil { return nil, err } } - - if nc.client == nil { - nc.client = c.client - } + nc.locked = true return nc, uerr } diff --git a/koios.go b/koios.go index c89607a..e795ed2 100644 --- a/koios.go +++ b/koios.go @@ -72,6 +72,8 @@ var ( ErrUTxOInputAlreadyUsed = errors.New("UTxO already used") ErrNoData = errors.New("no data") ErrAsset = errors.New("asset error") + ErrHTTPClientNotSet = errors.New("http.Client not set") + ErrClientLocked = errors.New("client is locked") // ZeroLovelace is alias decimal.Zero. ZeroLovelace = decimal.Zero.Copy() //nolint: gochecknoglobals @@ -193,6 +195,13 @@ func New(opts ...Option) (*Client, error) { ), ) + // If HttpClient option was not provided + // use default http.Client + if c.client == nil { + // there is really no point to check that error + _ = HTTPClient(nil).apply(c) + } + // Apply provided options for _, opt := range opts { if err := opt.apply(c); err != nil { @@ -209,14 +218,7 @@ func New(opts ...Option) (*Client, error) { // Sets default origin if option was not provided. _ = Origin(DefaultOrigin).apply(c) } - - // If HttpClient option was not provided - // use default http.Client - if c.client == nil { - // there is really no point to check that error - _ = HTTPClient(nil).apply(c) - } - + c.locked = true return c, nil } diff --git a/options.go b/options.go index 22bb3c6..7d17a50 100644 --- a/options.go +++ b/options.go @@ -79,14 +79,19 @@ func Scheme(scheme string) Option { func HTTPClient(client *http.Client) Option { return Option{ apply: func(c *Client) error { - if c.client != nil { - return ErrHTTPClientChange + if c.locked { + return ErrClientLocked } + timeout := time.Second * 60 if client == nil { - client = &http.Client{ - Timeout: time.Second * 60, - } + client = &http.Client{} } + + if client.Timeout == 0 && c.client != nil && c.client.Timeout > 0 { + timeout = c.client.Timeout + } + client.Timeout = timeout + if client.Timeout == 0 { return ErrHTTPClientTimeoutSetting } @@ -159,3 +164,15 @@ func EnableRequestsStats(enable bool) Option { }, } } + +func Timeout(timeout time.Duration) Option { + return Option{ + apply: func(c *Client) error { + if c.client == nil { + return ErrHTTPClientNotSet + } + c.client.Timeout = timeout + return nil + }, + } +} From 2f7bd4ced028ed0113da60d4c3768f9f686a8435 Mon Sep 17 00:00:00 2001 From: Marko Kungla Date: Fri, 29 Mar 2024 19:42:17 +0200 Subject: [PATCH 21/65] fix: deprecate asset_policy_info and asset_address_list Signed-off-by: Marko Kungla --- asset.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/asset.go b/asset.go index ef1dc92..ae11998 100644 --- a/asset.go +++ b/asset.go @@ -375,7 +375,7 @@ func (c *Client) GetPolicyAssetInfo( } opts.QuerySet("_asset_policy", policy.String()) - rsp, err := c.request(ctx, &res.Response, "GET", "/asset_policy_info", nil, opts) + rsp, err := c.request(ctx, &res.Response, "GET", "/policy_asset_info", nil, opts) if err != nil { return } From 9c640e5b430756f564f13318fb587ef4d639bacd Mon Sep 17 00:00:00 2001 From: Marko Kungla Date: Fri, 29 Mar 2024 20:38:29 +0200 Subject: [PATCH 22/65] fix: deprecate /asset_address_list Signed-off-by: Marko Kungla --- asset.go | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/asset.go b/asset.go index ae11998..3bc294c 100644 --- a/asset.go +++ b/asset.go @@ -134,7 +134,7 @@ type ( Quantity decimal.Decimal `json:"quantity"` } - // AssetAddressListResponse represents response from `/asset_address_list` endpoint. + // AssetAddressListResponse represents response from `/policy_asset_addresses` endpoint. AssetAddressListResponse struct { Response Data []AssetHolder `json:"data"` @@ -245,7 +245,7 @@ func (c *Client) GetAssetAddresses( opts.QuerySet("_asset_policy", policy.String()) opts.QuerySet("_asset_name", assetName.String()) - rsp, err := c.request(ctx, &res.Response, "GET", "/asset_address_list", nil, opts) + rsp, err := c.request(ctx, &res.Response, "GET", "/asset_addresses", nil, opts) if err != nil { return } From 3ace9988cb30f8b85a3ebcef7470e0cd24ccd50b Mon Sep 17 00:00:00 2001 From: Marko Kungla Date: Fri, 29 Mar 2024 20:51:28 +0200 Subject: [PATCH 23/65] fix: update GetAssetTxs Signed-off-by: Marko Kungla --- asset.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/asset.go b/asset.go index 3bc294c..733805e 100644 --- a/asset.go +++ b/asset.go @@ -333,7 +333,7 @@ func (c *Client) GetAssetTxs( ctx context.Context, policy PolicyID, name AssetName, - afterBlockHeight int, + afterBlockHeight uint, history bool, opts *RequestOptions, ) (res *AssetTxsResponse, err error) { From 2689d90aa2c6fd236c31c7b621281afddc56e163 Mon Sep 17 00:00:00 2001 From: Marko Kungla Date: Fri, 29 Mar 2024 21:06:10 +0200 Subject: [PATCH 24/65] fix: update GetBlocks Signed-off-by: Marko Kungla --- block.go | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/block.go b/block.go index aa76b88..b428cdb 100644 --- a/block.go +++ b/block.go @@ -61,7 +61,7 @@ type ( // ProtoMajor is protocol major version ProtoMajor int `json:"proto_major,omitempty"` // ProtoMinor is protocol minor version - ProtoMinor int `json:"proto_minor,omitempty"` + ProtoMinor int `json:"proto_minor"` // TotalOutput output of the block (in lovelace) TotalOutput decimal.Decimal `json:"total_output,omitempty"` @@ -70,7 +70,7 @@ type ( TotalFees decimal.Decimal `json:"total_fees,omitempty"` // Confirmations is number of confirmations for the block - Confirmations int `json:"num_confirmations"` + Confirmations int `json:"num_confirmations,omitempty"` } // BlocksResponse represents response from `/blocks` endpoint. From 204dd4f886e4c60d04bf4439532854412f57267e Mon Sep 17 00:00:00 2001 From: Marko Kungla Date: Fri, 29 Mar 2024 21:21:24 +0200 Subject: [PATCH 25/65] fix: update GetBlocksTxs response Signed-off-by: Marko Kungla --- block.go | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/block.go b/block.go index b428cdb..043e813 100644 --- a/block.go +++ b/block.go @@ -91,8 +91,11 @@ type ( // BlockTxsHashesResponse represents response from `/block_txs` endpoint. BlockTxs struct { - BlockHash BlockHash `json:"block_hash"` - TxHashes []TxHash `json:"tx_hashes"` + BlockHash BlockHash `json:"block_hash"` + TxHashes TxHash `json:"tx_hash"` + EpochNo EpochNo `json:"epoch_no"` + BlockHeight uint `json:"block_height"` + BlockTime Timestamp `json:"block_time"` } BlocksTxsResponse struct { From 22ef09111ed0f4e946774ae2ebcf3fa83f5a3490 Mon Sep 17 00:00:00 2001 From: Marko Kungla Date: Fri, 29 Mar 2024 22:15:25 +0200 Subject: [PATCH 26/65] fix: update GetEpochInfo Signed-off-by: Marko Kungla --- epoch.go | 13 ++++++++++--- response.go | 2 -- 2 files changed, 10 insertions(+), 5 deletions(-) diff --git a/epoch.go b/epoch.go index a7633b2..78c9f3f 100644 --- a/epoch.go +++ b/epoch.go @@ -15,7 +15,7 @@ import ( type ( // EpochNo defines type for _epoch_no. - EpochNo int + EpochNo uint // EpochInfo defines model for epoch_info. EpochInfo struct { @@ -190,16 +190,23 @@ type ( // GetEpochInfo returns the epoch information, all epochs if no epoch specified. func (c *Client) GetEpochInfo( ctx context.Context, - epoch *EpochNo, + epoch EpochNo, + includeNextEpoch bool, opts *RequestOptions, ) (res *EpochInfoResponse, err error) { res = &EpochInfoResponse{} if opts == nil { opts = c.NewRequestOptions() } - if epoch != nil { + if !opts.query.Has("order") { + opts.query.Set("order", "epoch_no.desc") + } + if epoch > 0 { opts.QuerySet("_epoch_no", epoch.String()) } + if includeNextEpoch { + opts.QuerySet("_include_next_epoch", "true") + } rsp, err := c.request(ctx, &res.Response, "GET", "/epoch_info", nil, opts) if err != nil { diff --git a/response.go b/response.go index 57e7900..d4c8295 100644 --- a/response.go +++ b/response.go @@ -25,8 +25,6 @@ type ( // RequestMethod is HTTP method used for request. RequestMethod string `json:"request_method"` - RequestHeaders http.Header `json:"request_headers"` - // StatusCode of the HTTP response. StatusCode int `json:"status_code"` From bc047c6a036c5ac0e8ac195f8f6a98d129fb0eb2 Mon Sep 17 00:00:00 2001 From: Marko Kungla Date: Sat, 30 Mar 2024 11:21:47 +0200 Subject: [PATCH 27/65] fix: update EpochParams CostModels Signed-off-by: Marko Kungla --- epoch.go | 139 +++++++++++++++++++++---------------------------------- 1 file changed, 54 insertions(+), 85 deletions(-) diff --git a/epoch.go b/epoch.go index 78c9f3f..7626da2 100644 --- a/epoch.go +++ b/epoch.go @@ -65,104 +65,73 @@ type ( // EpochParams defines model for epoch_params. EpochParams struct { - // The hash of the first block where these parameters are valid - BlockHash BlockHash `json:"block_hash"` - - // The cost per UTxO word - CoinsPerUtxoSize decimal.Decimal `json:"coins_per_utxo_size"` - - // The percentage of the tx fee which must be provided as collateral - // when including non-native scripts - CollateralPercent int `json:"collateral_percent"` - - // The per language cost models - CostModels string `json:"cost_models"` - - // The decentralisation parameter (1 fully centralised, 0 fully decentralised) - Decentralisation float64 `json:"decentralisation"` - - // The hash of 32-byte string of extra random-ness added into - // the protocol's entropy pool - ExtraEntropy string `json:"extra_entropy"` - // Epoch number EpochNo EpochNo `json:"epoch_no"` - - // The pledge influence on pool rewards - Influence float64 `json:"influence"` - - // The amount (in lovelace) required for a deposit to register a stake address - KeyDeposit decimal.Decimal `json:"key_deposit"` - - // The maximum block header size (in bytes) - MaxBhSize int `json:"max_bh_size"` - - // The maximum number of execution memory allowed to be used in a single block - MaxBlockExMem float32 `json:"max_block_ex_mem"` - - // The maximum number of execution steps allowed to be used in a single block - MaxBlockExSteps float32 `json:"max_block_ex_steps"` - + // The 'a' parameter to calculate the minimum transaction fee + MinFeeA decimal.Decimal `json:"min_fee_a"` + // The 'b' parameter to calculate the minimum transaction fee + MinFeeB decimal.Decimal `json:"min_fee_b"` // The maximum block size (in bytes) MaxBlockSize int `json:"max_block_size"` - - // The maximum number of collateral inputs allowed in a transaction - MaxCollateralInputs int `json:"max_collateral_inputs"` - + // The maximum transaction size (in bytes) + MaxTxSize int `json:"max_tx_size"` + // The maximum block header size (in bytes) + MaxBhSize int `json:"max_bh_size"` + // The amount (in lovelace) required for a deposit to register a stake address + KeyDeposit decimal.Decimal `json:"key_deposit"` + // The amount (in lovelace) required for a deposit to register a stake pool + PoolDeposit decimal.Decimal `json:"pool_deposit"` // The maximum number of epochs in the future that a pool retirement // is allowed to be scheduled for MaxEpoch int `json:"max_epoch"` - - // The maximum number of execution memory allowed to be used in a single transaction - MaxTxExMem float32 `json:"max_tx_ex_mem"` - - // The maximum number of execution steps allowed to be used in a single transaction - MaxTxExSteps float32 `json:"max_tx_ex_steps"` - - // The maximum transaction size (in bytes) - MaxTxSize int `json:"max_tx_size"` - - // The maximum Val size - MaxValSize float64 `json:"max_val_size"` - - // The 'a' parameter to calculate the minimum transaction fee - MinFeeA decimal.Decimal `json:"min_fee_a"` - - // The 'b' parameter to calculate the minimum transaction fee - MinFeeB decimal.Decimal `json:"min_fee_b"` - - // The minimum pool cost - MinPoolCost decimal.Decimal `json:"min_pool_cost"` - - // The minimum value of a UTxO entry - MinUtxoValue decimal.Decimal `json:"min_utxo_value"` - + // The optimal number of stake pools + OptimalPoolCount int `json:"optimal_pool_count"` + // The pledge influence on pool rewards + Influence float64 `json:"influence"` // The monetary expansion rate MonetaryExpandRate float64 `json:"monetary_expand_rate"` - + // The treasury growth rate + TreasuryGrowthRate float64 `json:"treasury_growth_rate"` + // The decentralisation parameter (1 fully centralised, 0 fully decentralised) + Decentralisation float64 `json:"decentralisation"` + // The hash of 32-byte string of extra random-ness added into + // the protocol's entropy pool + ExtraEntropy string `json:"extra_entropy"` + // The protocol major version + ProtocolMajor int `json:"protocol_major"` + // The protocol minor version + ProtocolMinor int `json:"protocol_minor"` + // The minimum value of a UTxO entry + MinUtxoValue decimal.Decimal `json:"min_utxo_value"` + // The minimum pool cost + MinPoolCost decimal.Decimal `json:"min_pool_cost"` // The nonce value for this epoch Nonce string `json:"nonce"` - - // The optimal number of stake pools - OptimalPoolCount int `json:"optimal_pool_count"` - - // The amount (in lovelace) required for a deposit to register a stake pool - PoolDeposit decimal.Decimal `json:"pool_deposit"` - + // The hash of the first block where these parameters are valid + BlockHash BlockHash `json:"block_hash"` + // The per language cost models + CostModels map[string][]int `json:"cost_models"` // The per word cost of script memory usage PriceMem decimal.Decimal `json:"price_mem"` - // The cost of script execution step usage PriceStep decimal.Decimal `json:"price_step"` - - // The protocol major version - ProtocolMajor int `json:"protocol_major"` - - // The protocol minor version - ProtocolMinor int `json:"protocol_minor"` - - // The treasury growth rate - TreasuryGrowthRate float64 `json:"treasury_growth_rate"` + // The maximum number of execution memory allowed to be used in a single transaction + MaxTxExMem float32 `json:"max_tx_ex_mem"` + // The maximum number of execution steps allowed to be used in a single transaction + MaxTxExSteps float32 `json:"max_tx_ex_steps"` + // The maximum number of execution memory allowed to be used in a single block + MaxBlockExMem float32 `json:"max_block_ex_mem"` + // The maximum number of execution steps allowed to be used in a single block + MaxBlockExSteps float32 `json:"max_block_ex_steps"` + // The maximum Val size + MaxValSize float64 `json:"max_val_size"` + // The percentage of the tx fee which must be provided as collateral + // when including non-native scripts + CollateralPercent int `json:"collateral_percent"` + // The maximum number of collateral inputs allowed in a transaction + MaxCollateralInputs int `json:"max_collateral_inputs"` + // The cost per UTxO word + CoinsPerUtxoSize decimal.Decimal `json:"coins_per_utxo_size"` } // EpochParamsResponse response of /epoch_params. @@ -220,14 +189,14 @@ func (c *Client) GetEpochInfo( // and information about all epochs if no epoch specified. func (c *Client) GetEpochParams( ctx context.Context, - epoch *EpochNo, + epoch EpochNo, opts *RequestOptions, ) (res *EpochParamsResponse, err error) { res = &EpochParamsResponse{} if opts == nil { opts = c.NewRequestOptions() } - if epoch != nil { + if epoch > 0 { opts.QuerySet("_epoch_no", epoch.String()) } From fd7f11ac96c52320df3b32bfe0deece97c92d7b1 Mon Sep 17 00:00:00 2001 From: Marko Kungla Date: Sat, 30 Mar 2024 11:27:53 +0200 Subject: [PATCH 28/65] fix: update GetEpochBlockProtocols remove pointer to EpochNo Signed-off-by: Marko Kungla --- epoch.go | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/epoch.go b/epoch.go index 7626da2..2b8284e 100644 --- a/epoch.go +++ b/epoch.go @@ -216,14 +216,14 @@ func (c *Client) GetEpochParams( // GetEpochBlockProtocols returns the information about block protocol distribution in epoch. func (c *Client) GetEpochBlockProtocols( ctx context.Context, - epoch *EpochNo, + epoch EpochNo, opts *RequestOptions, ) (res *EpochBlockProtocolsResponse, err error) { res = &EpochBlockProtocolsResponse{} if opts == nil { opts = c.NewRequestOptions() } - if epoch != nil { + if epoch > 0 { opts.QuerySet("_epoch_no", epoch.String()) } From 163cae16ec0e0efc068000b71c0aa59383625ff3 Mon Sep 17 00:00:00 2001 From: Marko Kungla Date: Sat, 30 Mar 2024 11:47:20 +0200 Subject: [PATCH 29/65] fix: enhance PoolListItem and GetPoolList Signed-off-by: Marko Kungla --- pool.go | 28 +++++++++++++++++++++++++--- 1 file changed, 25 insertions(+), 3 deletions(-) diff --git a/pool.go b/pool.go index 0904ff4..ba95994 100644 --- a/pool.go +++ b/pool.go @@ -19,10 +19,32 @@ type ( // PoolListItem defines model for pool list item. PoolListItem struct { // PoolID Bech32 representation of pool ID. - PoolID PoolID `json:"pool_id_bech32"` - + PoolIDBech32 PoolID `json:"pool_id_bech32"` + PoolIDHEX PoolID `json:"pool_id_hex"` + // ActiveEpochNo Block number on chain where transaction was included. + ActiveEpochNo EpochNo `json:"active_epoch_no"` + // Margin (decimal format) + Margin float32 `json:"margin"` + // FixedCost Pool fixed cost per epoch + FixedCost decimal.Decimal `json:"fixed_cost"` + // Pledge pledge in lovelace. + Pledge decimal.Decimal `json:"pledge"` + // Pool reward address. + RewardAddr Address `json:"reward_addr"` + // Owners of the pool + Owners []Address `json:"owners"` + // Relays of the pool + Relays []Relay `json:"relays"` // Ticker of Pool. Ticker string `json:"ticker,omitempty"` + // MetaUrl Pool metadata URL + MetaURL string `json:"meta_url"` + // MetaHash Pool metadata hash + MetaHash string `json:"meta_hash"` + // Pool status (registered | retiring | retired). + PoolStatus string `json:"pool_status"` + // Announced retiring epoch (nullable). + RetiringEpoch *EpochNo `json:"retiring_epoch.omitempty"` } // PoolMetaJSON pool meadata json. @@ -355,7 +377,7 @@ type ( ) // GetPoolList returns the list of all currently registered/retiring (not retired) pools. -func (c *Client) GetPools( +func (c *Client) GetPoolList( ctx context.Context, opts *RequestOptions, ) (res *PoolListResponse, err error) { From 6c819bc343c500eda8fba430ec273870019e48ef Mon Sep 17 00:00:00 2001 From: Marko Kungla Date: Sat, 30 Mar 2024 11:57:32 +0200 Subject: [PATCH 30/65] fix: update PoolInfo sigma decimal Signed-off-by: Marko Kungla --- pool.go | 94 ++++++++++++++++++++++----------------------------------- 1 file changed, 36 insertions(+), 58 deletions(-) diff --git a/pool.go b/pool.go index ba95994..78e9731 100644 --- a/pool.go +++ b/pool.go @@ -96,76 +96,54 @@ type ( // PoolInfo defines model for pool_info. PoolInfo struct { + // ID (bech32 format) + PoolIDBech32 PoolID `json:"pool_id_bech32"` + // IDHex Pool ID (Hex format) + PoolIDHex string `json:"pool_id_hex"` // ActiveEpochNo Block number on chain where transaction was included. ActiveEpoch EpochNo `json:"active_epoch_no"` - - // ActiveStake Pool active stake. - ActiveStake decimal.Decimal `json:"active_stake"` - - // Total pool blocks on chain - BlockCount uint64 `json:"block_count"` - - // FixedCost Pool fixed cost per epoch - FixedCost decimal.Decimal `json:"fixed_cost"` - - // LiveDelegators Pool live delegator count - LiveDelegators uint64 `json:"live_delegators"` - - // LiveSaturation Pool live saturation (decimal format) - LiveSaturation float32 `json:"live_saturation"` - - // LiveStake Pool live stake - LiveStake decimal.Decimal `json:"live_stake"` - - // LivePledge Pool live pledge - LivePledge decimal.Decimal `json:"live_pledge"` - + // Pool VRF key hash + VrfKeyHash string `json:"vrf_key_hash"` // Margin (decimal format) Margin float32 `json:"margin"` - + // FixedCost Pool fixed cost per epoch + FixedCost decimal.Decimal `json:"fixed_cost"` + // Pledge pledge in lovelace + Pledge decimal.Decimal `json:"pledge"` + // Pool reward address + RewardAddr Address `json:"reward_addr"` + // Owners of the pool + Owners []Address `json:"owners"` + // Relays of the pool + Relays []Relay `json:"relays"` + // MetaUrl Pool metadata URL + MetaURL string `json:"meta_url"` // MetaHash Pool metadata hash MetaHash string `json:"meta_hash"` - // MetaJson pool meta json MetaJSON PoolMetaJSON `json:"meta_json"` - - // MetaUrl Pool metadata URL - MetaURL string `json:"meta_url"` - - // OpCert Pool latest operational certificate hash - OpCert string `json:"op_cert"` - - // OpCertCounter Pool latest operational certificate counter value - OpCertCounter int `json:"op_cert_counter"` - - // Owners of the pool - Owners []Address `json:"owners"` - - // Pledge pledge in lovelace - Pledge decimal.Decimal `json:"pledge"` - - // ID (bech32 format) - PoolID PoolID `json:"pool_id_bech32"` - - // IDHex Pool ID (Hex format) - PoolIdHex string `json:"pool_id_hex"` - // Pool status (registered | retiring | retired) PoolStatus string `json:"pool_status"` - // Announced retiring epoch (nullable) RetiringEpoch *EpochNo `json:"retiring_epoch"` - - // Pool reward address - RewardAddr Address `json:"reward_addr"` - - // Pool VRF key hash - VrfKeyHash string `json:"vrf_key_hash"` - - // Relays of the pool - Relays []Relay `json:"relays"` - - Sigma float64 `json:"sigma"` + // OpCert Pool latest operational certificate hash + OpCert string `json:"op_cert"` + // OpCertCounter Pool latest operational certificate counter value + OpCertCounter int `json:"op_cert_counter"` + // ActiveStake Pool active stake. + ActiveStake decimal.Decimal `json:"active_stake"` + // Pool relative active stake share + Sigma decimal.Decimal `json:"sigma"` + // Total pool blocks on chain + BlockCount uint64 `json:"block_count"` + // LivePledge Pool live pledge + LivePledge decimal.Decimal `json:"live_pledge"` + // LiveStake Pool live stake + LiveStake decimal.Decimal `json:"live_stake"` + // LiveDelegators Pool live delegator count + LiveDelegators uint64 `json:"live_delegators"` + // LiveSaturation Pool live saturation (decimal format) + LiveSaturation float32 `json:"live_saturation"` } // PoolUpdateInfo response item from `/pool_updates`. From 601c04604a00f0bc3bc1881744c93a3f237e6038 Mon Sep 17 00:00:00 2001 From: Marko Kungla Date: Sat, 30 Mar 2024 12:03:08 +0200 Subject: [PATCH 31/65] fix: rename GetPoolSnapshot to GetPoolStakeSnapshot Signed-off-by: Marko Kungla --- pool.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pool.go b/pool.go index 78e9731..c1cc142 100644 --- a/pool.go +++ b/pool.go @@ -404,7 +404,7 @@ func (c *Client) GetPoolInfos( return } -func (c *Client) GetPoolSnapshot( +func (c *Client) GetPoolStakeSnapshot( ctx context.Context, pid PoolID, opts *RequestOptions, From 37778d1386ddd265bfc902ccbf53fd47e9c7e85b Mon Sep 17 00:00:00 2001 From: Marko Kungla Date: Sat, 30 Mar 2024 12:13:31 +0200 Subject: [PATCH 32/65] fix: update GetPoolDelegatorsHistory Signed-off-by: Marko Kungla --- pool.go | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/pool.go b/pool.go index c1cc142..7644c7d 100644 --- a/pool.go +++ b/pool.go @@ -448,7 +448,7 @@ func (c *Client) GetPoolDelegators( func (c *Client) GetPoolDelegatorsHistory( ctx context.Context, pid PoolID, - epoch *EpochNo, + epoch EpochNo, opts *RequestOptions, ) (res *PoolDelegatorsHistoryResponse, err error) { res = &PoolDelegatorsHistoryResponse{} @@ -457,7 +457,7 @@ func (c *Client) GetPoolDelegatorsHistory( opts = c.NewRequestOptions() } opts.QuerySet("_pool_bech32", pid.String()) - if epoch != nil { + if epoch > 0 { opts.QuerySet("_epoch_no", epoch.String()) } From 6b108dc57f511afc377bf523a0ccd2566b0dabdc Mon Sep 17 00:00:00 2001 From: Marko Kungla Date: Sat, 30 Mar 2024 12:17:06 +0200 Subject: [PATCH 33/65] fix: update GetPoolBlocks Signed-off-by: Marko Kungla --- pool.go | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/pool.go b/pool.go index 7644c7d..5271d25 100644 --- a/pool.go +++ b/pool.go @@ -475,7 +475,7 @@ func (c *Client) GetPoolDelegatorsHistory( func (c *Client) GetPoolBlocks( ctx context.Context, pid PoolID, - epoch *EpochNo, + epoch EpochNo, opts *RequestOptions, ) (res *PoolBlocksResponse, err error) { res = &PoolBlocksResponse{} @@ -484,7 +484,7 @@ func (c *Client) GetPoolBlocks( opts = c.NewRequestOptions() } opts.QuerySet("_pool_bech32", pid.String()) - if epoch != nil { + if epoch > 0 { opts.QuerySet("_epoch_no", epoch.String()) } rsp, err := c.request(ctx, &res.Response, "GET", "/pool_blocks", nil, opts) From 817a2459687a3f9f8c16d8c722cddf52d5b1ffad Mon Sep 17 00:00:00 2001 From: Marko Kungla Date: Sat, 30 Mar 2024 12:25:30 +0200 Subject: [PATCH 34/65] feat: add MemberRewards to PoolHistory response Signed-off-by: Marko Kungla --- pool.go | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/pool.go b/pool.go index 5271d25..d21c736 100644 --- a/pool.go +++ b/pool.go @@ -277,6 +277,7 @@ type ( FixedCost decimal.Decimal `json:"fixed_cost"` PoolFees decimal.Decimal `json:"pool_fees"` DelegRewards decimal.Decimal `json:"deleg_rewards"` + MemberRewards decimal.Decimal `json:"member_rewards"` EpochROS decimal.Decimal `json:"epoch_ros"` } @@ -558,7 +559,7 @@ func (c *Client) GetPoolMetadata( func (c *Client) GetPoolHistory( ctx context.Context, pid PoolID, - epoch *EpochNo, + epoch EpochNo, opts *RequestOptions, ) (res *PoolHistoryResponse, err error) { res = &PoolHistoryResponse{} @@ -567,7 +568,7 @@ func (c *Client) GetPoolHistory( opts = c.NewRequestOptions() } opts.QuerySet("_pool_bech32", pid.String()) - if epoch != nil { + if epoch > 0 { opts.QuerySet("_epoch_no", epoch.String()) } rsp, err := c.request(ctx, &res.Response, "GET", "/pool_history", nil, opts) From b0cb594d165dab7f8b411ec45d06ae421a72c88d Mon Sep 17 00:00:00 2001 From: Marko Kungla Date: Sat, 30 Mar 2024 12:31:18 +0200 Subject: [PATCH 35/65] fix: update GetPoolUpdates Signed-off-by: Marko Kungla --- koios.go | 4 ++++ pool.go | 4 ++-- 2 files changed, 6 insertions(+), 2 deletions(-) diff --git a/koios.go b/koios.go index e795ed2..b335df1 100644 --- a/koios.go +++ b/koios.go @@ -259,6 +259,10 @@ func (v PoolID) String() string { return string(v) } +func (v PoolID) Valid() bool { + return len(v) == 56 +} + // String returns PolicyID as string. func (v PolicyID) String() string { return string(v) diff --git a/pool.go b/pool.go index d21c736..dcb9985 100644 --- a/pool.go +++ b/pool.go @@ -500,7 +500,7 @@ func (c *Client) GetPoolBlocks( // only updates for specific pool if specified. func (c *Client) GetPoolUpdates( ctx context.Context, - pid *PoolID, + pid PoolID, opts *RequestOptions, ) (res *PoolUpdatesResponse, err error) { res = &PoolUpdatesResponse{} @@ -508,7 +508,7 @@ func (c *Client) GetPoolUpdates( if opts == nil { opts = c.NewRequestOptions() } - if pid != nil { + if pid.Valid() { opts.QuerySet("_pool_bech32", pid.String()) } From 59b0c9c49cc39fcbadc041467077dceaecaaa854 Mon Sep 17 00:00:00 2001 From: Marko Kungla Date: Sat, 30 Mar 2024 12:40:59 +0200 Subject: [PATCH 36/65] feat: implement GetPoolRegistrations Signed-off-by: Marko Kungla --- pool.go | 37 +++++++++++++++++++++++++++++++++++++ 1 file changed, 37 insertions(+) diff --git a/pool.go b/pool.go index dcb9985..fbf4eb8 100644 --- a/pool.go +++ b/pool.go @@ -47,6 +47,16 @@ type ( RetiringEpoch *EpochNo `json:"retiring_epoch.omitempty"` } + PoolRegistration struct { + PoolIDBech32 PoolID `json:"pool_id_bech32"` + TxHash TxHash `json:"tx_hash"` + BlockHash BlockHash `json:"block_hash"` + BlockHeight uint64 `json:"block_height"` + EpochNo EpochNo `json:"epoch_no"` + EpochSlot Slot `json:"epoch_slot"` + ActiveEpochNo EpochNo `json:"active_epoch_no"` + } + // PoolMetaJSON pool meadata json. PoolMetaJSON struct { // Pool description @@ -353,6 +363,11 @@ type ( Response Data []PoolHistory `json:"data"` } + + PoolRegistrationsResponse struct { + Response + Data []PoolRegistration `json:"data"` + } ) // GetPoolList returns the list of all currently registered/retiring (not retired) pools. @@ -590,3 +605,25 @@ func poolIdsPL(pids []PoolID) io.Reader { }() return rpipe } + +func (c *Client) GetPoolRegistrations( + ctx context.Context, + epoch EpochNo, + opts *RequestOptions, +) (res *PoolRegistrationsResponse, err error) { + res = &PoolRegistrationsResponse{} + if opts == nil { + opts = c.NewRequestOptions() + } + + if epoch > 0 { + opts.QuerySet("_epoch_no", epoch.String()) + } + + rsp, err := c.request(ctx, &res.Response, "GET", "/pool_registrations", nil, opts) + if err != nil { + return + } + err = ReadAndUnmarshalResponse(rsp, &res.Response, &res.Data) + return +} From 84e341b2cc4a09504384a2bd8881fd079d662048 Mon Sep 17 00:00:00 2001 From: Marko Kungla Date: Sat, 30 Mar 2024 12:46:26 +0200 Subject: [PATCH 37/65] feat: implement GetPoolRetirements Signed-off-by: Marko Kungla --- pool.go | 31 +++++++++++++++++++++++++++++-- 1 file changed, 29 insertions(+), 2 deletions(-) diff --git a/pool.go b/pool.go index fbf4eb8..6759099 100644 --- a/pool.go +++ b/pool.go @@ -47,7 +47,7 @@ type ( RetiringEpoch *EpochNo `json:"retiring_epoch.omitempty"` } - PoolRegistration struct { + PoolRegistrationOrRetirement struct { PoolIDBech32 PoolID `json:"pool_id_bech32"` TxHash TxHash `json:"tx_hash"` BlockHash BlockHash `json:"block_hash"` @@ -366,7 +366,12 @@ type ( PoolRegistrationsResponse struct { Response - Data []PoolRegistration `json:"data"` + Data []PoolRegistrationOrRetirement `json:"data"` + } + + PoolRetirementsResponse struct { + Response + Data []PoolRegistrationOrRetirement `json:"data"` } ) @@ -627,3 +632,25 @@ func (c *Client) GetPoolRegistrations( err = ReadAndUnmarshalResponse(rsp, &res.Response, &res.Data) return } + +func (c *Client) GetPoolRetirements( + ctx context.Context, + epoch EpochNo, + opts *RequestOptions, +) (res *PoolRetirementsResponse, err error) { + res = &PoolRetirementsResponse{} + if opts == nil { + opts = c.NewRequestOptions() + } + + if epoch > 0 { + opts.QuerySet("_epoch_no", epoch.String()) + } + + rsp, err := c.request(ctx, &res.Response, "GET", "/pool_retirements", nil, opts) + if err != nil { + return + } + err = ReadAndUnmarshalResponse(rsp, &res.Response, &res.Data) + return +} From 73d55126fbff1d6493f6306cac90101289cf7893 Mon Sep 17 00:00:00 2001 From: Marko Kungla Date: Sat, 30 Mar 2024 12:50:19 +0200 Subject: [PATCH 38/65] fix: update PoolRelays Signed-off-by: Marko Kungla --- pool.go | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/pool.go b/pool.go index 6759099..58947ce 100644 --- a/pool.go +++ b/pool.go @@ -247,9 +247,9 @@ type ( // PoolRelays list item. PoolRelays struct { - PoolID PoolID `json:"pool_id_bech32"` - // Relays of the pool. - Relays []Relay `json:"relays"` + PoolIDBech32 PoolID `json:"pool_id_bech32"` + Relays []Relay `json:"relays"` + PoolStatus string `json:"pool_status"` } // PoolBlockInfo block info. From 49401309e974ec56fc5e95ac72299c4901663fd5 Mon Sep 17 00:00:00 2001 From: Marko Kungla Date: Sat, 30 Mar 2024 12:54:45 +0200 Subject: [PATCH 39/65] sfix: update GetPoolMetadata --- pool.go | 2 ++ 1 file changed, 2 insertions(+) diff --git a/pool.go b/pool.go index 58947ce..0bc30b3 100644 --- a/pool.go +++ b/pool.go @@ -84,6 +84,8 @@ type ( // MetaJson pool meta json MetaJSON *PoolMetaJSON `json:"meta_json,omitempty"` + + PoolStatus string `json:"pool_status"` } // Relay defines model for pool relay. From 38224d484bffc1f7590fd8e93c3557fa4ff9320b Mon Sep 17 00:00:00 2001 From: Marko Kungla Date: Sat, 30 Mar 2024 13:05:52 +0200 Subject: [PATCH 40/65] sfeat: implement GetScriptInfo --- koios.go | 1 + script.go | 49 +++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 50 insertions(+) diff --git a/koios.go b/koios.go index b335df1..692eba7 100644 --- a/koios.go +++ b/koios.go @@ -74,6 +74,7 @@ var ( ErrAsset = errors.New("asset error") ErrHTTPClientNotSet = errors.New("http.Client not set") ErrClientLocked = errors.New("client is locked") + ErrNoScriptHash = errors.New("missing script hash(es)") // ZeroLovelace is alias decimal.Zero. ZeroLovelace = decimal.Zero.Copy() //nolint: gochecknoglobals diff --git a/script.go b/script.go index 632cc83..d5f99fa 100644 --- a/script.go +++ b/script.go @@ -28,6 +28,19 @@ type ( Redeemers []ScriptRedeemer `json:"redeemers"` } + ScriptInfo struct { + // The Hash of the Plutus Data + ScriptHash string `json:"script_hash"` + // CreationTxHash is the hash of the transaction that created the script + CreationTxHash TxHash `json:"creation_tx_hash"` + // type + Type string `json:"type"` + // + Value *json.RawMessage `json:"value"` + Bytes string `json:"bytes"` + Size uint `json:"size"` + } + // ScriptRedeemer model. ScriptRedeemer struct { // The Hash of the Plutus Data @@ -122,6 +135,11 @@ type ( Response Data *DatumInfo `json:"data"` } + + ScriptInfosResponse struct { + Response + Data []ScriptInfo `json:"data"` + } ) // String returns ScriptHash as string. @@ -234,6 +252,25 @@ func (c *Client) GetDatumInfos( return res, ReadAndUnmarshalResponse(rsp, &res.Response, &res.Data) } +func (c *Client) GetScriptInfo( + ctx context.Context, + hashes []ScriptHash, + opts *RequestOptions, +) (*ScriptInfosResponse, error) { + res := &ScriptInfosResponse{} + if len(hashes) == 0 { + err := ErrNoScriptHash + res.applyError(nil, err) + return res, err + } + + rsp, err := c.request(ctx, &res.Response, "POST", "/script_info", scriptHashesPL(hashes), opts) + if err != nil { + return res, err + } + return res, ReadAndUnmarshalResponse(rsp, &res.Response, &res.Data) +} + func datumHashesPL(hashes []DatumHash) io.Reader { var payload = struct { DatumHashes []DatumHash `json:"_datum_hashes"` @@ -245,3 +282,15 @@ func datumHashesPL(hashes []DatumHash) io.Reader { }() return rpipe } + +func scriptHashesPL(hashes []ScriptHash) io.Reader { + var payload = struct { + DatumHashes []ScriptHash `json:"_script_hashes"` + }{hashes} + rpipe, w := io.Pipe() + go func() { + _ = json.NewEncoder(w).Encode(payload) + defer w.Close() + }() + return rpipe +} From daebb235774110c69defbb93a831a6da4f39217a Mon Sep 17 00:00:00 2001 From: Marko Kungla Date: Sat, 30 Mar 2024 13:10:57 +0200 Subject: [PATCH 41/65] sfix: update NativeScript --- script.go | 7 ++----- 1 file changed, 2 insertions(+), 5 deletions(-) diff --git a/script.go b/script.go index d5f99fa..f8c291d 100644 --- a/script.go +++ b/script.go @@ -81,7 +81,7 @@ type ( Address Address `json:"address"` ScriptHash ScriptHash `json:"script_hash"` ByteCode string `json:"bytecode"` - Size int `json:"size"` + Size uint `json:"size"` ValidContract bool `json:"valid_contract"` } @@ -93,10 +93,7 @@ type ( // Hash of a script ScriptHash string `json:"script_hash"` Type string `json:"type"` - Script struct { - Type string `json:"type"` - Scripts []json.RawMessage `json:"scripts"` - } `json:"script"` + Size uint `json:"size"` } // NativeScriptListResponse represents response from `/native_script_list` endpoint. From 2511488a5debef43a0081b9648cd31e26d0cf611 Mon Sep 17 00:00:00 2001 From: Marko Kungla Date: Sat, 30 Mar 2024 13:22:00 +0200 Subject: [PATCH 42/65] sfix: update PlutusScriptListItem --- script.go | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/script.go b/script.go index f8c291d..ed246ee 100644 --- a/script.go +++ b/script.go @@ -109,6 +109,12 @@ type ( // Hash of a script ScriptHash string `json:"script_hash"` + + // Type of the script + Type string `json:"type"` + + // Size of the script + Size uint `json:"size"` } // PlutusScriptListResponse represents response from `/plutus_script_list` endpoint. From 54d4bad824af9e4f194ce998d837ddc90343615f Mon Sep 17 00:00:00 2001 From: Marko Kungla Date: Sat, 30 Mar 2024 13:28:18 +0200 Subject: [PATCH 43/65] sfix: update ScriptRedeemer --- script.go | 28 +++++++++++----------------- 1 file changed, 11 insertions(+), 17 deletions(-) diff --git a/script.go b/script.go index ed246ee..5c2253e 100644 --- a/script.go +++ b/script.go @@ -43,31 +43,25 @@ type ( // ScriptRedeemer model. ScriptRedeemer struct { - // The Hash of the Plutus Data - DatumHash string `json:"datum_hash"` - - // The actual data in json format - DatumValue map[string]any `json:"datum_value"` - - // The budget in fees to run a script - the fees depend on the - // ExUnits and the current prices. - Fee decimal.Decimal `json:"fee,omitempty"` - - // What kind pf validation this redeemer is used for, - // it can be one of 'spend', 'mint', 'cert', 'reward'. - Purpose string `json:"purpose"` - // TxHash of Transaction containing the redeemer. TxHash TxHash `json:"tx_hash"` - // TxIndex The index of the redeemer pointer in the transaction. TxIndex uint32 `json:"tx_index"` - // The budget in Memory to run a script. UnitMem int `json:"unit_mem"` - // The budget in Cpu steps to run a script. UnitSteps int `json:"unit_steps"` + // The budget in fees to run a script - the fees depend on the + // ExUnits and the current prices. + Fee decimal.Decimal `json:"fee,omitempty"` + // What kind pf validation this redeemer is used for, + // it can be one of 'spend', 'mint', 'cert', 'reward'. + Purpose string `json:"purpose"` + + // The Hash of the Plutus Data + DatumHash string `json:"datum_hash"` + // The actual data in json format + DatumValue map[string]any `json:"datum_value"` } // DatumInfo datum information for given datum hash From e955378880330edb711cf1b5f94ae51e27314a8c Mon Sep 17 00:00:00 2001 From: Marko Kungla Date: Sat, 30 Mar 2024 13:55:47 +0200 Subject: [PATCH 44/65] feat: imlplement GetScriptUtxos --- script.go | 32 ++++++++++++++++++++++++++++++++ transaction.go | 20 ++++++++------------ 2 files changed, 40 insertions(+), 12 deletions(-) diff --git a/script.go b/script.go index 5c2253e..d3739d7 100644 --- a/script.go +++ b/script.go @@ -137,6 +137,11 @@ type ( Response Data []ScriptInfo `json:"data"` } + + ScriptUTxOsResponse struct { + Response + Data []UTxO `json:"data"` + } ) // String returns ScriptHash as string. @@ -268,6 +273,33 @@ func (c *Client) GetScriptInfo( return res, ReadAndUnmarshalResponse(rsp, &res.Response, &res.Data) } +func (c *Client) GetScriptUtxos( + ctx context.Context, + hash ScriptHash, + Extended bool, + opts *RequestOptions, +) (*ScriptUTxOsResponse, error) { + res := &ScriptUTxOsResponse{} + if len(hash) == 0 { + err := ErrNoScriptHash + res.applyError(nil, err) + return res, err + } + + if opts == nil { + opts = c.NewRequestOptions() + } + + opts.QuerySet("_extended", fmt.Sprintf("%t", Extended)) + opts.QuerySet("_script_hash", hash.String()) + + rsp, err := c.request(ctx, &res.Response, "GET", "/script_utxos", nil, opts) + if err != nil { + return res, err + } + return res, ReadAndUnmarshalResponse(rsp, &res.Response, &res.Data) +} + func datumHashesPL(hashes []DatumHash) io.Reader { var payload = struct { DatumHashes []DatumHash `json:"_datum_hashes"` diff --git a/transaction.go b/transaction.go index 975cdad..09e08a1 100644 --- a/transaction.go +++ b/transaction.go @@ -53,20 +53,16 @@ type ( // StakeAddress for transaction's output UTxO. StakeAddress *Address `json:"stake_addr,omitempty"` // where funds were sent or change to be returned. - PaymentAddr *PaymentAddr `json:"payment_addr,omitempty"` - - EpochNo EpochNo `json:"epoch_no"` - BlockHeight uint64 `json:"block_height"` - BlockTime Timestamp `json:"block_time"` - - DatumHash DatumHash `json:"datum_hash"` - InlineDatum any `json:"inline_datum"` - ReferenceScript any `json:"reference_script"` - + PaymentCred *PaymentCredential `json:"payment_cred,omitempty"` + EpochNo EpochNo `json:"epoch_no"` + BlockHeight uint64 `json:"block_height"` + BlockTime Timestamp `json:"block_time"` + DatumHash DatumHash `json:"datum_hash"` + InlineDatum any `json:"inline_datum"` + ReferenceScript any `json:"reference_script"` // An array of assets to be included in output UTxO. AssetList []Asset `json:"asset_list,omitempty"` - - IsSpent bool `json:"is_spent,omitempty"` + IsSpent bool `json:"is_spent,omitempty"` } // TxsWithdrawal withdrawal record in transaction. From ddf8c4313e4cccaa2746fce3588169f52be1eb7c Mon Sep 17 00:00:00 2001 From: Marko Kungla Date: Sat, 30 Mar 2024 14:02:29 +0200 Subject: [PATCH 45/65] sfix: add missing DatumInfo fields --- script.go | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/script.go b/script.go index d3739d7..bc6ed96 100644 --- a/script.go +++ b/script.go @@ -66,9 +66,10 @@ type ( // DatumInfo datum information for given datum hash DatumInfo struct { - Hash DatumHash `json:"hash"` - Bytes string `json:"bytes"` - Value *json.RawMessage `json:"value"` + DatumHash DatumHash `json:"datum_hash"` + CreationTxHash TxHash `json:"creation_tx_hash"` + Bytes string `json:"bytes"` + Value *json.RawMessage `json:"value"` } PlutusContract struct { From ab87d6b94fd5272d924ad0914d3296dce76f8181 Mon Sep 17 00:00:00 2001 From: Marko Kungla Date: Sat, 30 Mar 2024 14:13:01 +0200 Subject: [PATCH 46/65] chore: rename account -> stake_account Signed-off-by: Marko Kungla --- account.go => stake_account.go | 0 account_test.go => stake_account_test.go | 0 2 files changed, 0 insertions(+), 0 deletions(-) rename account.go => stake_account.go (100%) rename account_test.go => stake_account_test.go (100%) diff --git a/account.go b/stake_account.go similarity index 100% rename from account.go rename to stake_account.go diff --git a/account_test.go b/stake_account_test.go similarity index 100% rename from account_test.go rename to stake_account_test.go From 3b8636bb750a70dd6ee1dda793b8000d4308eb6d Mon Sep 17 00:00:00 2001 From: Marko Kungla Date: Sat, 30 Mar 2024 14:17:24 +0200 Subject: [PATCH 47/65] sfix: update GetAccountList --- stake_account.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/stake_account.go b/stake_account.go index 4b6a2eb..6776c1b 100644 --- a/stake_account.go +++ b/stake_account.go @@ -148,7 +148,7 @@ type ( ) // GetAccountList returns a list of all accounts. -func (c *Client) GetAccounts( +func (c *Client) GetAccountList( ctx context.Context, opts *RequestOptions, ) (res *AccountListResponse, err error) { From 923bfd1d6ea9497806ffcb239400181e92f0cbce Mon Sep 17 00:00:00 2001 From: Marko Kungla Date: Sat, 30 Mar 2024 14:23:47 +0200 Subject: [PATCH 48/65] sfeat: update GetAccountInfo and GetAccountInfoCached --- stake_account.go | 30 ++++++++++++++---------------- 1 file changed, 14 insertions(+), 16 deletions(-) diff --git a/stake_account.go b/stake_account.go index 6776c1b..f827e3a 100644 --- a/stake_account.go +++ b/stake_account.go @@ -175,27 +175,28 @@ func (c *Client) GetAccountList( // GetAccountInfo returns the account info of any (payment or staking) address. func (c *Client) GetAccountInfo( ctx context.Context, - acc Address, - cached bool, + accs []Address, opts *RequestOptions, -) (res *AccountInfoResponse, err error) { - res = &AccountInfoResponse{} - res2, err := c.GetAccountsInfo(ctx, []Address{acc}, cached, opts) - if err != nil { +) (res *AccountsInfoResponse, err error) { + res = &AccountsInfoResponse{} + if len(accs) == 0 { + err = ErrNoAddress + res.applyError(nil, err) return } - if len(res2.Data) == 1 { - res.Data = &res2.Data[0] - } else { - return nil, fmt.Errorf("%w: no account info found for address %s", ErrNoData, acc) + endpoint := "/account_info" + + rsp, err := c.request(ctx, &res.Response, "POST", endpoint, stakeAddressesPL(accs, nil), opts) + if err != nil { + return } + err = ReadAndUnmarshalResponse(rsp, &res.Response, &res.Data) return } -func (c *Client) GetAccountsInfo( +func (c *Client) GetAccountInfoCached( ctx context.Context, accs []Address, - cached bool, opts *RequestOptions, ) (res *AccountsInfoResponse, err error) { res = &AccountsInfoResponse{} @@ -204,10 +205,7 @@ func (c *Client) GetAccountsInfo( res.applyError(nil, err) return } - endpoint := "/account_info" - if cached { - endpoint = "/account_info_cached" - } + endpoint := "/account_info_cached" rsp, err := c.request(ctx, &res.Response, "POST", endpoint, stakeAddressesPL(accs, nil), opts) if err != nil { From 2fc79c67e3777d8930950826e955f56b8a725b92 Mon Sep 17 00:00:00 2001 From: Marko Kungla Date: Sat, 30 Mar 2024 14:37:59 +0200 Subject: [PATCH 49/65] sfeat: implement GetAccountUtxos --- stake_account.go | 40 +++++++++++++++++++++++++++++++--------- 1 file changed, 31 insertions(+), 9 deletions(-) diff --git a/stake_account.go b/stake_account.go index f827e3a..e4ea46b 100644 --- a/stake_account.go +++ b/stake_account.go @@ -186,7 +186,7 @@ func (c *Client) GetAccountInfo( } endpoint := "/account_info" - rsp, err := c.request(ctx, &res.Response, "POST", endpoint, stakeAddressesPL(accs, nil), opts) + rsp, err := c.request(ctx, &res.Response, "POST", endpoint, stakeAddressesPL(accs, nil, nil), opts) if err != nil { return } @@ -207,7 +207,7 @@ func (c *Client) GetAccountInfoCached( } endpoint := "/account_info_cached" - rsp, err := c.request(ctx, &res.Response, "POST", endpoint, stakeAddressesPL(accs, nil), opts) + rsp, err := c.request(ctx, &res.Response, "POST", endpoint, stakeAddressesPL(accs, nil, nil), opts) if err != nil { return } @@ -249,7 +249,7 @@ func (c *Client) GetAccountsRewards( res.applyError(nil, err) return } - rsp, err := c.request(ctx, &res.Response, "POST", "/account_rewards", stakeAddressesPL(accs, epoch), opts) + rsp, err := c.request(ctx, &res.Response, "POST", "/account_rewards", stakeAddressesPL(accs, epoch, nil), opts) if err != nil { return } @@ -291,7 +291,7 @@ func (c *Client) GetAccountsUpdates( res.applyError(nil, err) return } - rsp, err := c.request(ctx, &res.Response, "POST", "/account_updates", stakeAddressesPL(accs, nil), opts) + rsp, err := c.request(ctx, &res.Response, "POST", "/account_updates", stakeAddressesPL(accs, nil, nil), opts) if err != nil { return } @@ -331,7 +331,7 @@ func (c *Client) GetAccountsAddresses( res.applyError(nil, err) return } - rsp, err := c.request(ctx, &res.Response, "POST", "/account_addresses", stakeAddressesPL(accs, nil), opts) + rsp, err := c.request(ctx, &res.Response, "POST", "/account_addresses", stakeAddressesPL(accs, nil, nil), opts) if err != nil { return } @@ -370,7 +370,7 @@ func (c *Client) GetAccountsAssets( res.applyError(nil, err) return } - rsp, err := c.request(ctx, &res.Response, "POST", "/account_assets", stakeAddressesPL(accs, nil), opts) + rsp, err := c.request(ctx, &res.Response, "POST", "/account_assets", stakeAddressesPL(accs, nil, nil), opts) if err != nil { return } @@ -410,7 +410,7 @@ func (c *Client) GetAccountsHistory( res.applyError(nil, err) return } - rsp, err := c.request(ctx, &res.Response, "POST", "/account_history", stakeAddressesPL(accs, nil), opts) + rsp, err := c.request(ctx, &res.Response, "POST", "/account_history", stakeAddressesPL(accs, nil, nil), opts) if err != nil { return } @@ -418,11 +418,33 @@ func (c *Client) GetAccountsHistory( return } -func stakeAddressesPL(addrs []Address, epoch *EpochNo) io.Reader { +func (c *Client) GetAccountUtxos( + ctx context.Context, + accs []Address, + extended bool, + opts *RequestOptions, +) (res *UTxOsResponse, err error) { + res = &UTxOsResponse{} + if len(accs) == 0 { + err = ErrNoAddress + res.applyError(nil, err) + return + } + + rsp, err := c.request(ctx, &res.Response, "POST", "/account_utxos", stakeAddressesPL(accs, nil, &extended), opts) + if err != nil { + return + } + err = ReadAndUnmarshalResponse(rsp, &res.Response, &res.Data) + return +} + +func stakeAddressesPL(addrs []Address, epoch *EpochNo, extended *bool) io.Reader { var payload = struct { Adresses []Address `json:"_stake_addresses"` Epoch *EpochNo `json:"_epoch_no,omitempty"` - }{addrs, epoch} + Extended *bool `json:"_extended,omitempty"` + }{addrs, epoch, extended} rpipe, w := io.Pipe() go func() { _ = json.NewEncoder(w).Encode(payload) From 32c98cf848fe24af329aac557d31b477fbf633e9 Mon Sep 17 00:00:00 2001 From: Marko Kungla Date: Sat, 30 Mar 2024 14:52:23 +0200 Subject: [PATCH 50/65] sfeat: implement GetAccountTxs --- stake_account.go | 26 ++++++++++++++++++++++++++ transaction.go | 7 +++++++ 2 files changed, 33 insertions(+) diff --git a/stake_account.go b/stake_account.go index e4ea46b..f2a7699 100644 --- a/stake_account.go +++ b/stake_account.go @@ -145,6 +145,11 @@ type ( Response Data []AccountHistory `json:"data"` } + + AccountTXsResponse struct { + Response + Data []TxListItem `json:"data"` + } ) // GetAccountList returns a list of all accounts. @@ -439,6 +444,27 @@ func (c *Client) GetAccountUtxos( return } +func (c *Client) GetAccountTxs( + ctx context.Context, + acc Address, + afterBlockHeight uint64, + opts *RequestOptions, +) (res *AccountTXsResponse, err error) { + res = &AccountTXsResponse{} + + opts.QueryAdd("_stake_address", acc.String()) + if afterBlockHeight > 0 { + opts.QueryAdd("after_block_height", fmt.Sprint(afterBlockHeight)) + } + + rsp, err := c.request(ctx, &res.Response, "GET", "/account_txs", nil, opts) + if err != nil { + return + } + err = ReadAndUnmarshalResponse(rsp, &res.Response, &res.Data) + return +} + func stakeAddressesPL(addrs []Address, epoch *EpochNo, extended *bool) io.Reader { var payload = struct { Adresses []Address `json:"_stake_addresses"` diff --git a/transaction.go b/transaction.go index 09e08a1..e04966d 100644 --- a/transaction.go +++ b/transaction.go @@ -73,6 +73,13 @@ type ( StakeAddress Address `json:"stake_addr,omitempty"` } + TxListItem struct { + TxHash TxHash `json:"tx_hash"` + BlockHeight uint64 `json:"block_height"` + BlockTime Timestamp `json:"block_time"` + EpochNo EpochNo `json:"epoch_no"` + } + // TxInfo transaction info. TxInfo struct { // BlockHash is hash of the block in which transaction was included. From f2a0a5334ca2ac556ba18a4dc6eb9f1e8a0ed773 Mon Sep 17 00:00:00 2001 From: Marko Kungla Date: Sat, 30 Mar 2024 14:58:32 +0200 Subject: [PATCH 51/65] sfix: update GetAccountRewards --- stake_account.go | 28 ++++++---------------------- 1 file changed, 6 insertions(+), 22 deletions(-) diff --git a/stake_account.go b/stake_account.go index f2a7699..8232cdb 100644 --- a/stake_account.go +++ b/stake_account.go @@ -223,29 +223,9 @@ func (c *Client) GetAccountInfoCached( // GetAccountRewards retruns the full rewards history (including MIR) // for a stake address, or certain epoch if specified. func (c *Client) GetAccountRewards( - ctx context.Context, - acc Address, - epoch *EpochNo, - opts *RequestOptions, -) (res *AccountRewardsResponse, err error) { - res = &AccountRewardsResponse{} - - res2, err := c.GetAccountsRewards(ctx, []Address{acc}, epoch, opts) - if err != nil { - return - } - if len(res2.Data) == 1 { - res.Data = &res2.Data[0] - } else { - return nil, fmt.Errorf("%w: no rewards found for account %s", ErrNoData, acc) - } - return -} - -func (c *Client) GetAccountsRewards( ctx context.Context, accs []Address, - epoch *EpochNo, + epoch EpochNo, opts *RequestOptions, ) (res *AccountsRewardsResponse, err error) { res = &AccountsRewardsResponse{} @@ -254,7 +234,11 @@ func (c *Client) GetAccountsRewards( res.applyError(nil, err) return } - rsp, err := c.request(ctx, &res.Response, "POST", "/account_rewards", stakeAddressesPL(accs, epoch, nil), opts) + var epochNo *EpochNo + if epoch > 0 { + epochNo = &epoch + } + rsp, err := c.request(ctx, &res.Response, "POST", "/account_rewards", stakeAddressesPL(accs, epochNo, nil), opts) if err != nil { return } From 74064fda49ef991d1a511e6f68b75f554dcd47b2 Mon Sep 17 00:00:00 2001 From: Marko Kungla Date: Sat, 30 Mar 2024 15:07:31 +0200 Subject: [PATCH 52/65] sfix: update GetAccountUpdates --- stake_account.go | 21 --------------------- 1 file changed, 21 deletions(-) diff --git a/stake_account.go b/stake_account.go index 8232cdb..896369e 100644 --- a/stake_account.go +++ b/stake_account.go @@ -248,28 +248,7 @@ func (c *Client) GetAccountRewards( // GetAccountUpdates (History) retruns the account updates // (registration, deregistration, delegation and withdrawals). - func (c *Client) GetAccountUpdates( - ctx context.Context, - acc Address, - epoch *EpochNo, - opts *RequestOptions, -) (res *AccountUpdatesResponse, err error) { - res = &AccountUpdatesResponse{} - - res2, err := c.GetAccountsUpdates(ctx, []Address{acc}, opts) - if err != nil { - return - } - if len(res2.Data) == 1 { - res.Data = &res2.Data[0] - } else { - return nil, fmt.Errorf("%w: no updates found for account %s", ErrNoData, acc) - } - return -} - -func (c *Client) GetAccountsUpdates( ctx context.Context, accs []Address, opts *RequestOptions, From 6db99c79f55c9f24d7ecf0d1d2c024c552b64c64 Mon Sep 17 00:00:00 2001 From: Marko Kungla Date: Sat, 30 Mar 2024 15:22:52 +0200 Subject: [PATCH 53/65] fix: update GetAccountAddresses Signed-off-by: Marko Kungla --- stake_account.go | 46 +++++++++++++++++++++++++--------------------- 1 file changed, 25 insertions(+), 21 deletions(-) diff --git a/stake_account.go b/stake_account.go index 896369e..2672c25 100644 --- a/stake_account.go +++ b/stake_account.go @@ -269,28 +269,9 @@ func (c *Client) GetAccountUpdates( // GetAccountAddresses retruns all addresses associated with an account. func (c *Client) GetAccountAddresses( - ctx context.Context, - acc Address, - epoch *EpochNo, - opts *RequestOptions, -) (res *AccountAddressesResponse, err error) { - res = &AccountAddressesResponse{} - - res2, err := c.GetAccountsAddresses(ctx, []Address{acc}, opts) - if err != nil { - return - } - if len(res2.Data) == 1 { - res.Data = &res2.Data[0] - } else { - return nil, fmt.Errorf("%w: no updates found for account %s", ErrNoData, acc) - } - return -} - -func (c *Client) GetAccountsAddresses( ctx context.Context, accs []Address, + firstOnly, empty bool, opts *RequestOptions, ) (res *AccountsAddressesResponse, err error) { res = &AccountsAddressesResponse{} @@ -299,7 +280,7 @@ func (c *Client) GetAccountsAddresses( res.applyError(nil, err) return } - rsp, err := c.request(ctx, &res.Response, "POST", "/account_addresses", stakeAddressesPL(accs, nil, nil), opts) + rsp, err := c.request(ctx, &res.Response, "POST", "/account_addresses", stakeAddresses2PL(accs, firstOnly, empty), opts) if err != nil { return } @@ -441,3 +422,26 @@ func stakeAddressesPL(addrs []Address, epoch *EpochNo, extended *bool) io.Reader }() return rpipe } + +func stakeAddresses2PL(addrs []Address, firstOnly, empty bool) io.Reader { + var ( + firstOnlyVal, emptyVal *bool + ) + if firstOnly { + firstOnlyVal = &firstOnly + } + if empty { + emptyVal = &empty + } + var payload = struct { + Adresses []Address `json:"_stake_addresses"` + FirstOnly *bool `json:"_first_only,omitempty"` + Empty *bool `json:"_empty,omitempty"` + }{addrs, firstOnlyVal, emptyVal} + rpipe, w := io.Pipe() + go func() { + _ = json.NewEncoder(w).Encode(payload) + defer w.Close() + }() + return rpipe +} From 236d1e5581cb06c076abd5aab588bc03a138791c Mon Sep 17 00:00:00 2001 From: Marko Kungla Date: Sat, 30 Mar 2024 15:31:26 +0200 Subject: [PATCH 54/65] fix: update AccountAssets Signed-off-by: Marko Kungla --- stake_account.go | 21 +-------------------- 1 file changed, 1 insertion(+), 20 deletions(-) diff --git a/stake_account.go b/stake_account.go index 2672c25..22bacc8 100644 --- a/stake_account.go +++ b/stake_account.go @@ -133,7 +133,7 @@ type ( AccountAssets struct { StakeAddress Address `json:"stake_address"` - Assets []Asset `json:"asset_list"` + Asset } // AccountHistoryResponse represents response from `/account_history` endpoint. @@ -290,25 +290,6 @@ func (c *Client) GetAccountAddresses( // GetAccountAssets retruns all the native asset balance of an account. func (c *Client) GetAccountAssets( - ctx context.Context, - acc Address, - opts *RequestOptions, -) (res *AccountAssetsResponse, err error) { - res = &AccountAssetsResponse{} - - res2, err := c.GetAccountsAssets(ctx, []Address{acc}, opts) - if err != nil { - return - } - if len(res2.Data) == 1 { - res.Data = &res2.Data[0] - } else { - return nil, fmt.Errorf("%w: no assets found for account %s", ErrNoData, acc) - } - return -} - -func (c *Client) GetAccountsAssets( ctx context.Context, accs []Address, opts *RequestOptions, From 353ba4b80d6b4b1aadb39831cfa7e7e1c09f42ac Mon Sep 17 00:00:00 2001 From: Marko Kungla Date: Sat, 30 Mar 2024 15:36:26 +0200 Subject: [PATCH 55/65] fix: update GetAccountHistory Signed-off-by: Marko Kungla --- stake_account.go | 23 ++--------------------- 1 file changed, 2 insertions(+), 21 deletions(-) diff --git a/stake_account.go b/stake_account.go index 22bacc8..419a648 100644 --- a/stake_account.go +++ b/stake_account.go @@ -310,28 +310,9 @@ func (c *Client) GetAccountAssets( // GetAccountHistory retruns the staking history of an account. func (c *Client) GetAccountHistory( - ctx context.Context, - acc Address, - epoch *EpochNo, - opts *RequestOptions, -) (res *AccountHistoryResponse, err error) { - res = &AccountHistoryResponse{} - - res2, err := c.GetAccountsHistory(ctx, []Address{acc}, opts) - if err != nil { - return - } - if len(res2.Data) == 1 { - res.Data = &res2.Data[0] - } else { - return nil, fmt.Errorf("%w: no history found for account %s", ErrNoData, acc) - } - return -} - -func (c *Client) GetAccountsHistory( ctx context.Context, accs []Address, + epoch *EpochNo, opts *RequestOptions, ) (res *AccountsHistoryResponse, err error) { res = &AccountsHistoryResponse{} @@ -340,7 +321,7 @@ func (c *Client) GetAccountsHistory( res.applyError(nil, err) return } - rsp, err := c.request(ctx, &res.Response, "POST", "/account_history", stakeAddressesPL(accs, nil, nil), opts) + rsp, err := c.request(ctx, &res.Response, "POST", "/account_history", stakeAddressesPL(accs, epoch, nil), opts) if err != nil { return } From fa9118dd7aebeb19d8483fa8828835eb4f20186c Mon Sep 17 00:00:00 2001 From: Marko Kungla Date: Sat, 30 Mar 2024 15:53:15 +0200 Subject: [PATCH 56/65] feat: implement GetPolicyAssetMints Signed-off-by: Marko Kungla --- asset.go | 38 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 38 insertions(+) diff --git a/asset.go b/asset.go index 733805e..7a8e0f3 100644 --- a/asset.go +++ b/asset.go @@ -204,6 +204,23 @@ type ( Response Data []UTxO `json:"data"` } + + PolicyAssetMintsResponse struct { + Response + Data []PolicyAssetMint `json:"data"` + } + + PolicyAssetMint struct { + AssetName AssetName `json:"asset_name"` + AssetNameASCII string `json:"asset_name_ascii"` + Fingerprint AssetFingerprint `json:"fingerprint"` + MintingTxHash TxHash `json:"minting_tx_hash"` + TotalSupply decimal.Decimal `json:"total_supply"` + MintCNT uint `json:"mint_cnt"` + BurnCNT uint `json:"burn_cnt"` + CreationTime Timestamp `json:"creation_time"` + Decimals uint8 `json:"decimals"` + } ) // String returns AssetName as string. @@ -536,3 +553,24 @@ func (c *Client) GetPolicyAssetAddresses( return } + +func (c *Client) GetPolicyAssetMints( + ctx context.Context, + policy PolicyID, + opts *RequestOptions, +) (res *PolicyAssetMintsResponse, err error) { + res = &PolicyAssetMintsResponse{} + + if opts == nil { + opts = c.NewRequestOptions() + } + opts.QuerySet("_asset_policy", policy.String()) + + rsp, err := c.request(ctx, &res.Response, "GET", "/policy_asset_mints", nil, opts) + if err != nil { + return + } + + err = ReadAndUnmarshalResponse(rsp, &res.Response, &res.Data) + return +} From 98a40435e3261f143c950c619a66384337d6f7e2 Mon Sep 17 00:00:00 2001 From: Marko Kungla Date: Sat, 30 Mar 2024 16:05:53 +0200 Subject: [PATCH 57/65] feat: implement GetUTxOInfo Signed-off-by: Marko Kungla --- koios.go | 1 + transaction.go | 46 ++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 47 insertions(+) diff --git a/koios.go b/koios.go index 692eba7..980c8ee 100644 --- a/koios.go +++ b/koios.go @@ -75,6 +75,7 @@ var ( ErrHTTPClientNotSet = errors.New("http.Client not set") ErrClientLocked = errors.New("client is locked") ErrNoScriptHash = errors.New("missing script hash(es)") + ErrNoUTxORef = errors.New("missing UTxO reference(s)") // ZeroLovelace is alias decimal.Zero. ZeroLovelace = decimal.Zero.Copy() //nolint: gochecknoglobals diff --git a/transaction.go b/transaction.go index e04966d..cb38945 100644 --- a/transaction.go +++ b/transaction.go @@ -227,6 +227,13 @@ type ( Response Data *TxStatus `json:"data"` } + + UTxORef string + + UTxOInfoResponse struct { + Response + Data []UTxO `json:"data"` + } ) // GetTxInfo returns detailed information about transaction. @@ -425,6 +432,32 @@ func (c *Client) GetTxsStatuses( return res, ReadAndUnmarshalResponse(rsp, &res.Response, &res.Data) } +func (c *Client) GetUTxOInfo( + ctx context.Context, + refs []UTxORef, + extended bool, + opts *RequestOptions, +) (*UTxOInfoResponse, error) { + res := &UTxOInfoResponse{} + if len(refs) == 0 { + err := ErrNoUTxORef + res.applyError(nil, err) + return res, err + } + + if opts == nil { + opts = c.NewRequestOptions() + } + + rsp, err := c.request(ctx, &res.Response, "POST", "/utxo_info", utxoRefsPL(refs, extended), opts) + if err != nil { + res.applyError(nil, err) + return res, err + } + + return res, ReadAndUnmarshalResponse(rsp, &res.Response, &res.Data) +} + func txHashesPL(txs []TxHash) io.Reader { var payload = struct { TxHashes []TxHash `json:"_tx_hashes"` @@ -437,6 +470,19 @@ func txHashesPL(txs []TxHash) io.Reader { return rpipe } +func utxoRefsPL(refs []UTxORef, extended bool) io.Reader { + var payload = struct { + UtxORefs []UTxORef `json:"_utxo_refs"` + Extended bool `json:"_extended"` + }{refs, extended} + rpipe, w := io.Pipe() + go func() { + _ = json.NewEncoder(w).Encode(payload) + defer w.Close() + }() + return rpipe +} + type metaArrayItem struct { // Key is metadata (index). Key string `json:"key,omitempty"` From e636d4154bac0e88c41f61cefaa4a4df2ceec2a6 Mon Sep 17 00:00:00 2001 From: Marko Kungla Date: Sat, 30 Mar 2024 16:29:07 +0200 Subject: [PATCH 58/65] fix: update TxInfo Signed-off-by: Marko Kungla --- transaction.go | 43 +++---------------------------------------- 1 file changed, 3 insertions(+), 40 deletions(-) diff --git a/transaction.go b/transaction.go index cb38945..7dde9e1 100644 --- a/transaction.go +++ b/transaction.go @@ -84,66 +84,46 @@ type ( TxInfo struct { // BlockHash is hash of the block in which transaction was included. BlockHash BlockHash `json:"block_hash"` - // BlockHeight is block number on chain where transaction was included. BlockHeight int `json:"block_height"` - // Epoch number. EpochNo EpochNo `json:"epoch_no"` - // EpochSlot is slot number within epoch. EpochSlot Slot `json:"epoch_slot"` - // AbsoluteSlot is overall slot number (slots from genesis block of chain). AbsoluteSlot Slot `json:"absolute_slot"` - // TxTimestamp is timestamp when block containing transaction was created. TxTimestamp Timestamp `json:"tx_timestamp"` - // TxBlockIndex is index of transaction within block. TxBlockIndex int `json:"tx_block_index"` - // TxSize is transaction size in bytes. TxSize int `json:"tx_size"` - // TotalOutput is total sum of all transaction outputs (in lovelaces). TotalOutput decimal.Decimal `json:"total_output"` - // Fee is total transaction fee (in lovelaces). Fee decimal.Decimal `json:"fee" cbor:"2,keyasint"` - // Deposit is total deposits included in transaction (for example, // if it is registering a pool/key). Deposit decimal.Decimal `json:"deposit"` - // InvalidAfter is slot number after which transaction cannot be validated. InvalidAfter Timestamp `json:"invalid_after,omitempty" cbor:"3,keyasint,omitempty"` - // InvalidBefore is slot number before which transaction cannot be validated. // (if supplied, else 0) InvalidBefore Timestamp `json:"invalid_before,omitempty" cbor:"8,keyasint,omitempty"` - // CollateralInputs An array of collateral inputs needed when dealing with smart contracts. CollateralInputs []UTxO `json:"collateral_inputs,omitempty"` - // CollateralOutput CollateralOutput *UTxO `json:"collateral_output,omitempty"` - // CollateralInputs An array of collateral inputs needed when dealing with smart contracts. ReferenceInputs []UTxO `json:"reference_inputs,omitempty"` - + // Array of withdrawals with-in a transaction (if any) + Withdrawals []TxsWithdrawal `json:"withdrawals,omitempty"` // AssetsMinted An array of minted assets with-in a transaction (if any). AssetsMinted []Asset `json:"assets_minted,omitempty"` - // Metadata present with-in a transaction (if any) Metadata TxMetadata `json:"metadata,omitempty"` - - // Array of withdrawals with-in a transaction (if any) - Withdrawals []TxsWithdrawal `json:"withdrawals,omitempty"` - // Certificates present with-in a transaction (if any) - Certificates []Certificate `json:"certificates,omitempty"` - + Certificates []Certificate `json:"certificates,omitempty"` NativeScripts []NativeScript `json:"native_scripts,omitempty"` PlutusContracts []PlutusContract `json:"plutus_contracts,omitempty"` } @@ -238,23 +218,6 @@ type ( // GetTxInfo returns detailed information about transaction. func (c *Client) GetTxInfo( - ctx context.Context, - hash TxHash, - opts *RequestOptions, -) (res *TxInfoResponse, err error) { - res = &TxInfoResponse{} - rsp, err := c.GetTxsInfo(ctx, []TxHash{hash}, opts) - res.Response = rsp.Response - if len(rsp.Data) == 1 { - res.Data = rsp.Data[0] - } else { - err = fmt.Errorf("%w: %s", ErrNoData, hash) - } - return -} - -// GetTxsInfo returns detailed information about transaction(s). -func (c *Client) GetTxsInfo( ctx context.Context, txs []TxHash, opts *RequestOptions, From bf0c5dedb11607e0dd7ec74967476ce774f1d504 Mon Sep 17 00:00:00 2001 From: Marko Kungla Date: Sat, 30 Mar 2024 16:32:06 +0200 Subject: [PATCH 59/65] fix: remove deprecated GetTxUTxOs Signed-off-by: Marko Kungla --- transaction.go | 37 ------------------------------------- 1 file changed, 37 deletions(-) diff --git a/transaction.go b/transaction.go index 7dde9e1..bd1d403 100644 --- a/transaction.go +++ b/transaction.go @@ -236,43 +236,6 @@ func (c *Client) GetTxInfo( return res, ReadAndUnmarshalResponse(rsp, &res.Response, &res.Data) } -// GetTxUTxOs returns UTxO set (inputs/outputs) of transaction. -func (c *Client) GetTxUTxOs( - ctx context.Context, - hash TxHash, - opts *RequestOptions, -) (res *TxUTxOsResponse, err error) { - res = &TxUTxOsResponse{} - rsp, err := c.GetTxsUTxOs(ctx, []TxHash{hash}, opts) - res.Response = rsp.Response - if len(rsp.Data) == 1 { - res.Data = &rsp.Data[0] - } else { - err = fmt.Errorf("%w: %s", ErrNoData, hash) - } - return -} - -// GetTxsUTxOs returns UTxO set (inputs/outputs) of transactions. -func (c *Client) GetTxsUTxOs( - ctx context.Context, - txs []TxHash, - opts *RequestOptions, -) (*TxsUTxOsResponse, error) { - res := &TxsUTxOsResponse{} - if len(txs) == 0 || len(txs[0]) == 0 { - err := ErrNoTxHash - res.applyError(nil, err) - return res, err - } - - rsp, err := c.request(ctx, &res.Response, "POST", "/tx_utxos", txHashesPL(txs), opts) - if err != nil { - return res, err - } - return res, ReadAndUnmarshalResponse(rsp, &res.Response, &res.Data) -} - // GetTxMetadata returns metadata information (if any) for given transaction. func (c *Client) GetTxMetadata( ctx context.Context, From 0d6afd9e1770422bc42c165b2d0f792d604514d7 Mon Sep 17 00:00:00 2001 From: Marko Kungla Date: Sat, 30 Mar 2024 16:35:03 +0200 Subject: [PATCH 60/65] fix: update GetTxMetadata Signed-off-by: Marko Kungla --- transaction.go | 17 ----------------- 1 file changed, 17 deletions(-) diff --git a/transaction.go b/transaction.go index bd1d403..36cefd3 100644 --- a/transaction.go +++ b/transaction.go @@ -238,23 +238,6 @@ func (c *Client) GetTxInfo( // GetTxMetadata returns metadata information (if any) for given transaction. func (c *Client) GetTxMetadata( - ctx context.Context, - hash TxHash, - opts *RequestOptions, -) (res *TxMetadataResponse, err error) { - res = &TxMetadataResponse{} - rsp, err := c.GetTxsMetadata(ctx, []TxHash{hash}, opts) - res.Response = rsp.Response - if len(rsp.Data) == 1 { - res.Data = &rsp.Data[0] - } else { - err = fmt.Errorf("%w: %s", ErrNoData, hash) - } - return -} - -// GetTxsMetadata returns metadata for requested transaction(s). -func (c *Client) GetTxsMetadata( ctx context.Context, txs []TxHash, opts *RequestOptions, From f0b03191ade93bbb213b07223abbd67928cdd307 Mon Sep 17 00:00:00 2001 From: Marko Kungla Date: Sat, 30 Mar 2024 16:44:15 +0200 Subject: [PATCH 61/65] fix: update GetTxStatus Signed-off-by: Marko Kungla --- transaction.go | 19 +------------------ 1 file changed, 1 insertion(+), 18 deletions(-) diff --git a/transaction.go b/transaction.go index 36cefd3..fc0bd8d 100644 --- a/transaction.go +++ b/transaction.go @@ -304,25 +304,8 @@ func (c *Client) SubmitSignedTx( return res, err } -// GetTxStatus returns status of transaction. +// GetTxStatus returns status of transaction(s). func (c *Client) GetTxStatus( - ctx context.Context, - hash TxHash, - opts *RequestOptions, -) (res *TxStatusResponse, err error) { - res = &TxStatusResponse{} - rsp, err := c.GetTxsStatuses(ctx, []TxHash{hash}, opts) - res.Response = rsp.Response - if len(rsp.Data) == 1 { - res.Data = &rsp.Data[0] - } else { - err = fmt.Errorf("%w: %s", ErrNoData, hash) - } - return -} - -// GetTxsStatuses returns status of transaction(s). -func (c *Client) GetTxsStatuses( ctx context.Context, txs []TxHash, opts *RequestOptions, From e0b153441463466abe4efca3e581301b6f1ecfe7 Mon Sep 17 00:00:00 2001 From: Marko Kungla Date: Sat, 30 Mar 2024 18:41:41 +0200 Subject: [PATCH 62/65] feat: add koios subscription auth Signed-off-by: Marko Kungla --- client.go | 5 ++++- koios.go | 7 ++++++- options.go | 2 +- 3 files changed, 11 insertions(+), 3 deletions(-) diff --git a/client.go b/client.go index 62d3690..df99b72 100644 --- a/client.go +++ b/client.go @@ -27,6 +27,7 @@ type ( client *http.Client commonHeaders http.Header locked bool + auth *AuthInfo } ) @@ -195,7 +196,9 @@ func (c *Client) applyReqHeaders(req *http.Request, headers http.Header) { } func (c *Client) requestWithStats(req *http.Request, res *Response) (*http.Response, error) { - res.Stats = &RequestStats{} + res.Stats = &RequestStats{ + Auth: c.getAuth(), + } var dns, tlshs, connect time.Time req = req.WithContext( httptrace.WithClientTrace( diff --git a/koios.go b/koios.go index 980c8ee..e89a50b 100644 --- a/koios.go +++ b/koios.go @@ -48,7 +48,8 @@ const ( // DefaultOrigin is default origin header used by api client. DefaultOrigin = "https://github.com/cardano-community/koios-go-client/v4" // PageSize is default page size used by api client. - PageSize uint = 1000 + PageSize uint = 1000 + DefaultTimeout = 30 * time.Second ) // Predefined errors used by the library. @@ -76,6 +77,7 @@ var ( ErrClientLocked = errors.New("client is locked") ErrNoScriptHash = errors.New("missing script hash(es)") ErrNoUTxORef = errors.New("missing UTxO reference(s)") + ErrAuth = errors.New("auth error") // ZeroLovelace is alias decimal.Zero. ZeroLovelace = decimal.Zero.Copy() //nolint: gochecknoglobals @@ -158,6 +160,8 @@ type ( // ReqDurStr String representation of ReqDur. ReqDurStr string `json:"req_dur_str,omitempty"` + + Auth AuthInfo `json:"auth"` } ) @@ -178,6 +182,7 @@ type ( func New(opts ...Option) (*Client, error) { c := &Client{ commonHeaders: make(http.Header), + auth: &AuthInfo{}, } // set default base url _ = c.setBaseURL(DefaultScheme, MainnetHost, DefaultAPIVersion, DefaultPort) diff --git a/options.go b/options.go index 7d17a50..1eddb6c 100644 --- a/options.go +++ b/options.go @@ -82,7 +82,7 @@ func HTTPClient(client *http.Client) Option { if c.locked { return ErrClientLocked } - timeout := time.Second * 60 + timeout := DefaultTimeout if client == nil { client = &http.Client{} } From da1f99105bae2d4d520b9ab783d45fe880d024bb Mon Sep 17 00:00:00 2001 From: Marko Kungla Date: Sat, 30 Mar 2024 22:36:55 +0200 Subject: [PATCH 63/65] feat: add Koios auth Signed-off-by: Marko Kungla --- client.go | 3 +++ 1 file changed, 3 insertions(+) diff --git a/client.go b/client.go index df99b72..d9c12d4 100644 --- a/client.go +++ b/client.go @@ -147,6 +147,9 @@ func (c *Client) request( return nil, err } + if auth := c.getAuth(); auth.token != "" { + opts.HeaderAdd("Authorization", "Bearer "+auth.token) + } c.applyReqHeaders(req, opts.headers) var ( From c1a9f65269d42e79dbdb97897584495311caa410 Mon Sep 17 00:00:00 2001 From: Marko Kungla Date: Sun, 31 Mar 2024 00:27:52 +0200 Subject: [PATCH 64/65] feat: add Koios auth Signed-off-by: Marko Kungla --- auth.go | 232 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 232 insertions(+) create mode 100644 auth.go diff --git a/auth.go b/auth.go new file mode 100644 index 0000000..d7a0fad --- /dev/null +++ b/auth.go @@ -0,0 +1,232 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// Copyright © 2022 The Cardano Community Authors + +package koios + +import ( + "encoding/base64" + "encoding/json" + "fmt" + "math" + "strings" + "time" +) + +func GetTokenAuthInfo(jwt string) (AuthInfo, error) { + auth, err := decodeJWT(jwt) + if err != nil { + fmt.Printf("Error decoding JWT: %v\n", err) + return AuthInfo{}, fmt.Errorf("%w: error decoding JWT %v", ErrAuth, err) + } + return *auth, nil +} + +func (c *Client) SetAuth(jwt string) error { + auth, err := GetTokenAuthInfo(jwt) + if err != nil { + return err + } + c.auth = &auth + return nil +} + +func (c *Client) getAuth() AuthInfo { + if c.auth == nil { + return AuthInfo{} + } + auth := *c.auth + return auth +} + +type AuthInfo struct { + // AuthType is the type of authentication used. + Tier AuthTier `json:"tier"` + ProjID string `json:"projID"` + Addr string `json:"addr"` + Expires AuthExpires `json:"expires"` + + MaxRequests uint `json:"max_requests"` + MaxRPS uint `json:"max_rps"` + MaxQueryTimeout time.Duration `json:"query_timeout"` + CORSRestricted bool `json:"cors_restricted"` + token string +} + +func (a *AuthInfo) MarshalJSON() ([]byte, error) { + return json.Marshal(&struct { + Tier string `json:"tier"` + ProjID string `json:"projID,omitempty"` + Addr string `json:"addr,omitempty"` + Expires AuthExpires `json:"expires"` + + MaxRequests uint `json:"max_requests"` + MaxRPS uint `json:"max_rps"` + MaxQueryTimeout string `json:"query_timeout"` + CORSRestricted bool `json:"cors_restricted"` + }{ + Tier: a.Tier.String(), + MaxRequests: a.Tier.MaxRequest(), + MaxRPS: a.Tier.MaxRPS(), + MaxQueryTimeout: a.Tier.MaxQueryTimeout().String(), + CORSRestricted: a.Tier.CORSRestricted(), + Expires: a.Expires, + Addr: a.Addr, + ProjID: a.ProjID, + }) +} + +type AuthTier uint8 + +const ( + // AutTierPublic gives everyone Free access to our API services so everyone is ready to start building. + AutTierPublic = iota + // AutTierFree Once familiar with our platform, consider our Advanced solution for "production ready" deployment. + AutTierFree + // AuthTierPro Enhanced resource capabilities that enable you to develop your application with ease. + AuthTierPro + // AuthTierPremium Top-notch resource capabilities, allowing you to relax and not worry about resource consumption. + AuthTierPremium + // AuthTierCustom A tailor made infrastructure design around your requirements, for optimal resource management, giving you peace of mind. + AuthTierCustom +) + +func (at AuthTier) String() string { + switch at { + case AutTierPublic: + return "public" + case AutTierFree: + return "free" + case AuthTierPro: + return "pro" + case AuthTierPremium: + return "premium" + case AuthTierCustom: + return "custom" + default: + return "unknown" + } +} + +func (at AuthTier) MaxRequest() uint { + switch at { + case AutTierPublic: + return 5000 + case AutTierFree: + return 50000 + case AuthTierPro: + return 500000 + case AuthTierPremium: + return 1200000 + case AuthTierCustom: + return math.MaxUint + default: + return 0 + } +} + +func (at AuthTier) MaxRPS() uint { + switch at { + case AutTierPublic, AutTierFree: + return 10 + case AuthTierPro: + return 25 + case AuthTierPremium: + return 500 + case AuthTierCustom: + return math.MaxUint + default: + return 0 + } +} + +func (at AuthTier) MaxQueryTimeout() time.Duration { + switch at { + case AutTierPublic, AutTierFree: + return 30 * time.Second + case AuthTierPro: + return time.Minute + case AuthTierPremium: + return 2 * time.Minute + case AuthTierCustom: + return time.Duration(math.MaxInt64) + default: + return 0 + } +} + +func (at AuthTier) CORSRestricted() bool { + switch at { + case AutTierPublic: + return true + default: + return false + } +} + +func (at AuthTier) MarshalJSON() ([]byte, error) { + return []byte(`"` + at.String() + `"`), nil +} + +type AuthExpires time.Time + +func (ae AuthExpires) MarshalJSON() ([]byte, error) { + if time.Time(ae).IsZero() { + return []byte("\"No expiration date\""), nil + } + return json.Marshal(ae.String()) +} + +func (ae AuthExpires) Time() time.Time { + return time.Time(ae) +} + +func (ae AuthExpires) String() string { + return time.Time(ae).String() +} + +// decodeBase64URL decodes a Base64URL string. +func decodeBase64URL(s string) (string, error) { + b, err := base64.RawURLEncoding.DecodeString(s) + if err != nil { + return "", err + } + return string(b), nil +} + +// decodeJWT decodes the payload of a JWT. +func decodeJWT(token string) (*AuthInfo, error) { + parts := strings.Split(token, ".") + if len(parts) != 3 { + return nil, fmt.Errorf("invalid JWT format") + } + + decoded, err := decodeBase64URL(parts[1]) + if err != nil { + return nil, fmt.Errorf("failed to decode payload: %w", err) + } + + var payload struct { + Addr string `json:"addr"` + Tier AuthTier `json:"tier"` + ProjID string `json:"projID"` + Exp Timestamp `json:"exp"` + } + err = json.Unmarshal([]byte(decoded), &payload) + if err != nil { + return nil, fmt.Errorf("failed to unmarshal payload: %w", err) + } + + var auth AuthInfo + auth.Addr = payload.Addr + auth.Tier = payload.Tier + auth.ProjID = payload.ProjID + auth.Expires = AuthExpires(payload.Exp.Time) + auth.token = token + + auth.MaxRequests = payload.Tier.MaxRequest() + auth.MaxRPS = payload.Tier.MaxRPS() + auth.MaxQueryTimeout = payload.Tier.MaxQueryTimeout() + + return &auth, nil +} From 809415b26acb9338e45aec1dfa02c7ab0ca1110d Mon Sep 17 00:00:00 2001 From: Marko Kungla Date: Sun, 31 Mar 2024 13:32:43 +0300 Subject: [PATCH 65/65] feat: allow tracking requests_today for subscription Signed-off-by: Marko Kungla --- client.go | 7 ++++--- go.mod | 2 +- go.sum | 4 ++-- koios.go | 2 ++ request.go | 27 +++++++++++++++++---------- 5 files changed, 26 insertions(+), 16 deletions(-) diff --git a/client.go b/client.go index d9c12d4..6dfe00b 100644 --- a/client.go +++ b/client.go @@ -157,7 +157,7 @@ func (c *Client) request( rsp *http.Response ) if res != nil && c.reqStatsEnabled { - rsp, eqerr = c.requestWithStats(req, res) + rsp, eqerr = c.requestWithStats(req, res, opts.requestsToday) } else { rsp, eqerr = c.client.Do(req) } @@ -198,9 +198,10 @@ func (c *Client) applyReqHeaders(req *http.Request, headers http.Header) { } } -func (c *Client) requestWithStats(req *http.Request, res *Response) (*http.Response, error) { +func (c *Client) requestWithStats(req *http.Request, res *Response, requestsToday uint) (*http.Response, error) { res.Stats = &RequestStats{ - Auth: c.getAuth(), + Auth: c.getAuth(), + RequstesToday: requestsToday, } var dns, tlshs, connect time.Time req = req.WithContext( diff --git a/go.mod b/go.mod index 68a4262..c944cca 100644 --- a/go.mod +++ b/go.mod @@ -9,4 +9,4 @@ require ( golang.org/x/time v0.5.0 ) -require golang.org/x/mod v0.15.0 // indirect +require golang.org/x/mod v0.16.0 // indirect diff --git a/go.sum b/go.sum index a1491ac..24fce82 100644 --- a/go.sum +++ b/go.sum @@ -2,8 +2,8 @@ github.com/happy-sdk/happy/pkg/version v0.1.2 h1:8DJ0afkEVW2fdm1uEScTS4wPgGe0Tml github.com/happy-sdk/happy/pkg/version v0.1.2/go.mod h1:mFhI4DRvXZ8Ls8D5/aXIqcMnjCUBNtI3Ye9ilYL2Bz0= github.com/shopspring/decimal v1.3.1 h1:2Usl1nmF/WZucqkFZhnfFYxxxu8LG21F6nPQBE5gKV8= github.com/shopspring/decimal v1.3.1/go.mod h1:DKyhrW/HYNuLGql+MJL6WCR6knT2jwCFRcu2hWCYk4o= -golang.org/x/mod v0.15.0 h1:SernR4v+D55NyBH2QiEQrlBAnj1ECL6AGrA5+dPaMY8= -golang.org/x/mod v0.15.0/go.mod h1:hTbmBsO62+eylJbnUtE2MGJUyE7QWk4xUqPFrRgJ+7c= +golang.org/x/mod v0.16.0 h1:QX4fJ0Rr5cPQCF7O9lh9Se4pmwfwskqZfq5moyldzic= +golang.org/x/mod v0.16.0/go.mod h1:hTbmBsO62+eylJbnUtE2MGJUyE7QWk4xUqPFrRgJ+7c= golang.org/x/text v0.14.0 h1:ScX5w1eTa3QqT8oi6+ziP7dTV1S2+ALU0bI+0zXKWiQ= golang.org/x/text v0.14.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU= golang.org/x/time v0.5.0 h1:o7cqy6amK/52YcAKIPlM3a+Fpj35zvRj2TP+e1xFSfk= diff --git a/koios.go b/koios.go index e89a50b..3623d59 100644 --- a/koios.go +++ b/koios.go @@ -162,6 +162,8 @@ type ( ReqDurStr string `json:"req_dur_str,omitempty"` Auth AuthInfo `json:"auth"` + + RequstesToday uint `json:"requests_today,omitempty"` } ) diff --git a/request.go b/request.go index f3c1c2b..c1ac449 100644 --- a/request.go +++ b/request.go @@ -12,11 +12,12 @@ import ( // RequestOptions for the request. type RequestOptions struct { - page uint - pageSize uint - locked bool - query url.Values - headers http.Header + page uint + pageSize uint + locked bool + query url.Values + headers http.Header + requestsToday uint } // QuerySet sets the key to value in request query. @@ -64,11 +65,12 @@ func (ro *RequestOptions) HeaderApply(h http.Header) { // Clone the request options for using it with other request. func (ro *RequestOptions) Clone() *RequestOptions { opts := &RequestOptions{ - headers: ro.headers.Clone(), - page: ro.page, - pageSize: ro.pageSize, - query: ro.query, - locked: false, + headers: ro.headers.Clone(), + page: ro.page, + pageSize: ro.pageSize, + query: ro.query, + requestsToday: ro.requestsToday, + locked: false, } q := url.Values{} for k, v := range ro.query { @@ -87,6 +89,11 @@ func (ro *RequestOptions) SetCurrentPage(page uint) { ro.page = page } +// SetRequestsToday sets the number of requests made today. +func (ro *RequestOptions) SetRequestsToday(n uint) { + ro.requestsToday = n +} + // lock the request options. func (ro *RequestOptions) lock() error { if ro.locked {