-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathkoios.go
313 lines (264 loc) · 8.91 KB
/
koios.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
// 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
// provides cli application.
// Koios is best described as a Decentralized and Elastic RESTful query layer
// for exploring data on Cardano blockchain to consume within
// applications/wallets/explorers/etc.
package koios // imports as package "koios"
import (
"encoding/json"
"errors"
"fmt"
"net/http"
"runtime"
"strconv"
"strings"
"time"
"github.com/happy-sdk/happy/pkg/version"
"github.com/shopspring/decimal"
"golang.org/x/text/cases"
"golang.org/x/text/language"
)
const (
// 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
DefaultTimeout = 30 * time.Second
)
// Predefined errors used by the library.
var (
ErrURLValuesLenght = errors.New("if presenent then only single url.Values should be provided")
ErrHTTPClientTimeoutSetting = errors.New("http.Client.Timeout should never be 0 in production")
ErrHTTPClientChange = errors.New("http.Client can only be set as option to koios.New")
ErrOriginSet = errors.New("origin can only be set as option to koios.New")
ErrRateLimitRange = errors.New("rate limit must be between 1-255 requests per sec")
ErrResponseIsNotJSON = errors.New("got non json response")
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")
ErrReqOptsAlreadyUsed = errors.New("request options can only be used once")
ErrUnexpectedResponseField = errors.New("unexpected response field")
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")
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
// ZeroCoin is alias decimal.Zero.
ZeroCoin = decimal.Zero.Copy() //nolint: gochecknoglobals
)
type (
Slot uint
BlockNo uint
// PaymentCredential type def.
PaymentCredential string
// BlockHash defines type for _block_hash.
BlockHash string
// TxHash defines type for tx_hash.
TxHash string
// PoolID type def.
PoolID string
// PolicyID type def.
PolicyID string
// Timestamp extends time to work with unix timestamps and
// fix time format anomalies when Unmarshaling and Marshaling
// Koios API times.
Timestamp struct {
time.Time
}
// PaymentAddr info.
PaymentAddr struct {
// Bech32 is Cardano payment/base address (bech32 encoded)
// for transaction's or change to be returned.
Bech32 Address `json:"bech32"`
// Payment credential.
Cred PaymentCredential `json:"cred"`
}
// Certificate information.
Certificate struct {
// Index of the certificate
Index int `json:"index"`
// Info is A JSON object containing information from the certificate.
Info map[string]json.RawMessage `json:"info"`
// Type of certificate could be:
// delegation, stake_registration, stake_deregistraion, pool_update,
// pool_retire, param_proposal, reserve_MIR, treasury_MIR).
Type string `json:"type"`
}
// RequestStats represent collected request stats if collecting
// request stats is enabled.
RequestStats struct {
// ReqStartedAt time when request was started.
ReqStartedAt time.Time `json:"req_started_at,omitempty"`
// DNSLookupDur DNS lookup duration.
DNSLookupDur time.Duration `json:"req_dns_lookup_dur,omitempty"`
// TLSHSDur time it took to perform TLS handshake.
TLSHSDur time.Duration `json:"tls_hs_dur,omitempty"`
// ESTCXNDur time it took to establish connection.
ESTCXNDur time.Duration `json:"est_cxn_dur,omitempty"`
// TTFB time it took to get the first byte of the response
// after connextion was established.
TTFB time.Duration `json:"ttfb,omitempty"`
// ReqDur total time it took to peform the request.
ReqDur time.Duration `json:"req_dur,omitempty"`
// ReqDurStr String representation of ReqDur.
ReqDurStr string `json:"req_dur_str,omitempty"`
Auth AuthInfo `json:"auth"`
RequstesToday uint `json:"requests_today,omitempty"`
}
)
// New creates thread-safe API client you can freerly pass this
// client to multiple go routines.
//
// Call to New without options is same as call with default options.
// e.g.
// api, err := koios.New(
//
// koios.Host(koios.MainnetHost),
// koios.APIVersion(koios.DefaultAPIVersion),
// koios.Port(koios.DefaultPort),
// koios.Schema(koios.DefaultSchema),
// koios.HttpClient(koios.DefaultHttpClient),
//
// ).
func New(opts ...Option) (*Client, error) {
c := &Client{
commonHeaders: make(http.Header),
auth: &AuthInfo{},
}
// set default base url
_ = c.setBaseURL(DefaultScheme, MainnetHost, DefaultAPIVersion, DefaultPort)
// set default common headers
c.commonHeaders.Set("Accept", "application/json")
c.commonHeaders.Set("Accept-Encoding", "gzip, deflate")
c.commonHeaders.Set(
"User-Agent",
fmt.Sprintf(
"go-koios/%s (%s %s) %s/%s https://github.com/cardano-community/go-koios",
Version(),
cases.Title(language.English).String(runtime.GOOS),
runtime.GOARCH,
runtime.GOOS,
runtime.GOARCH,
),
)
// 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 {
return nil, err
}
}
if c.r == nil {
// set default rate limit for outgoing requests if not configured.
_ = RateLimit(DefaultRateLimit).apply(c)
}
if c.commonHeaders.Get("Origin") == "" {
// Sets default origin if option was not provided.
_ = Origin(DefaultOrigin).apply(c)
}
c.locked = true
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)
}
// String returns BlockHash as string.
func (v BlockHash) String() string {
return string(v)
}
// String returns TxHash as string.
func (v TxHash) String() string {
return strings.Trim(string(v), "\"")
}
// String returns EpochNo as string.
func (v EpochNo) String() string {
return fmt.Sprintf("%d", v)
}
// String returns PoolID as string.
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)
}
func (t *Timestamp) UnmarshalJSON(b []byte) error {
if string(b) == "null" {
return nil
}
q, err := strconv.ParseInt(string(b), 10, 64)
if err != nil {
return nil
}
t.Time = time.Unix(q, 0)
return nil
}
// 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
}