Repository navigation
Expand file tree
/
Copy pathcsfloat.go
More file actions
1258 lines (1096 loc) · 32.2 KB
/
Copy pathcsfloat.go
File metadata and controls
1258 lines (1096 loc) · 32.2 KB
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
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package csfloat
import (
json "encoding/json/v2"
"errors"
"net"
"net/http"
"net/url"
"strconv"
"strings"
"time"
)
// Fee is a constant fee. Technically the profile has a setting, but it seems
// its unachievable to reduce the fee, so this is fine for now.
const Fee float64 = 2
const (
ErrorCodeOverpricedRedquireKYC = 4
ErrorCodeAlreadySold = 4
// ErrorCodeInvalidPurchaseState is thrown along HTTP status code 422. It
// is unclear when exactly, but it seems similar to AlreadySold. It might
// be unlisted.
ErrorCodeInvalidPurchaseState = 6
ErrorCodePriceChanged = 15
// ErrorCodeSalesHistoryNotAvailable implies that the history for a certain
// item was disabled. This is done for cases for example.
ErrorCodeSalesHistoryNotAvailable = 200
)
type API struct {
httpClient *http.Client
apiKey string
ratelimits map[RatelimitBucketKey]*Ratelimits
}
func NewWithHTTPClient(apiKey string, client *http.Client) *API {
return &API{
httpClient: client,
apiKey: apiKey,
ratelimits: make(map[RatelimitBucketKey]*Ratelimits),
}
}
func New(apiKey string) *API {
dialer := &net.Dialer{
Timeout: 15 * time.Second,
KeepAlive: 90 * time.Second,
}
transport := &http.Transport{
DialContext: dialer.DialContext,
MaxIdleConns: 2,
IdleConnTimeout: 90 * time.Second,
TLSHandshakeTimeout: 3 * time.Second,
ResponseHeaderTimeout: 15 * time.Second,
ExpectContinueTimeout: 3 * time.Second,
}
client := &http.Client{
Transport: transport,
Timeout: 15 * time.Second,
}
return NewWithHTTPClient(apiKey, client)
}
type Stall struct {
Items []ActiveListing `json:"data"`
Count int `json:"total_count"`
// Cursor determines where the next page starts.
Cursor string `json:"cursor"`
TotalPrice uint `json:"total_price"`
}
type ListingType string
const (
BuyNow ListingType = "buy_now"
Auction ListingType = "auction"
)
type Rarity uint8
const (
Consumer Rarity = 1
Industrial Rarity = 2
MilSpec Rarity = 3
Restricted Rarity = 4
Classified Rarity = 5
Covert Rarity = 6
Contraband Rarity = 7
)
type WearName string
const (
BattleScarred WearName = "Battle-Scarred"
WellWorn WearName = "Well-Worn"
FieldTested WearName = "Field-Tested"
MinimalWear WearName = "Minimal Wear"
FactoryNew WearName = "Factory New"
)
type ItemReference struct {
BasePrice int `json:"base_price,omitzero"`
FloatFactor float64 `json:"float_factor,omitzero"`
KeyChainPrice int `json:"keychain_price,omitzero"`
// PredictedPrice = (BasePrice * FloatFactor) + KeyChainPrice
PredictedPrice int `json:"predicted_price,omitzero"`
Quantity uint `json:"quantity,omitzero"`
}
// Reference is used as a price reference for items without dynamic factors, such as stickers.
type Reference struct {
Price uint `json:"price,omitzero"`
Quantity uint `json:"quantity,omitzero"`
}
type ListingState string
const (
ListingStateListed ListingState = "listed"
ListingStateRefunded ListingState = "refunded"
// Note, these are NOT all possible listing states. There are others, but we don't know about them.
)
// Contract is a snapshot of the listing at the time of purchase (or after failing / cancelling)
type Contract struct {
ID string `json:"id"`
CreatedAt time.Time `json:"created_at"`
Price int `json:"price"`
Item Item `json:"item"`
Reference ItemReference `json:"reference,omitzero"`
Type ListingType `json:"type"`
State ListingState `json:"state"`
}
type Seller struct {
// Obsfuscated ID of the seller
ObfuscatedID string `json:"obfuscated_id,omitempty"`
// Steam ID of the seller
SteamID string `json:"steam_id,omitempty"`
}
type ActiveListing struct {
ID string `json:"id"`
CreatedAt time.Time `json:"created_at"`
Price int `json:"price"`
Item Item `json:"item"`
Reference ItemReference `json:"reference,omitzero"`
Type ListingType `json:"type"`
State ListingState `json:"state"`
Seller Seller `json:"seller"`
Description string `json:"description,omitempty"`
Private bool `json:"private,omitzero"`
MaxOfferDiscount uint `json:"max_offer_discount,omitzero"`
Watchers uint `json:"watchers,omitzero"`
}
func (al *ActiveListing) URL() string {
return "https://csfloat.com/item/" + al.ID
}
type InventoryItem struct {
Item
// ListingID is only filled for items that are already in the stall.
ListingID string `json:"listing_id,omitempty"`
Reference ItemReference `json:"reference,omitzero"`
}
type Sticker struct {
Index uint `json:"stickerId"`
Name string `json:"name"`
Reference Reference `json:"reference,omitzero"`
IconURL string `json:"icon_url"`
Wear float32 `json:"wear,omitzero"`
Rotation float32 `json:"rotation,omitzero"`
}
type Charm struct {
// CharmId is called stickerId, not a typo.
Index uint `json:"stickerId"`
Pattern uint `json:"pattern,omitzero"`
WrappedSticker uint `json:"wrapped_sticker,omitzero"`
Name string `json:"name"`
IconURL string `json:"icon_url"`
Reference Reference `json:"reference,omitzero"`
}
type ItemType string
const (
TypeCharm ItemType = "charm"
TypeContainer ItemType = "container"
TypeSticker ItemType = "sticker"
TypeSkin ItemType = "skin"
TypeAgent ItemType = "agent"
)
type Fade struct {
// Seed sems to be the same as the paintseed so far.
Seed uint `json:"seed"`
Percentage float64 `json:"percentage"`
Rank uint `json:"rank"`
Type string `json:"type"`
}
type BlueGem struct {
PlaysideBlue float64 `json:"playside_blue,omitzero"`
PlaysideGold float64 `json:"playside_gold,omitzero"`
PlaysidePurple float64 `json:"playside_purple,omitzero"`
BacksideBlue float64 `json:"backside_blue,omitzero"`
BacksideGold float64 `json:"backside_gold,omitzero"`
BacksidePurple float64 `json:"backside_purple,omitzero"`
}
type Item struct {
ID string `json:"asset_id"`
Rarity Rarity `json:"rarity"`
Type ItemType `json:"type"`
MarketHashName string `json:"market_hash_name"`
IconURL string `json:"icon_url"`
// SerializedInspect is the new format for inspect links, replacing InspectLink.
// InspectLink is still available on float, but not needed in the endpoints. It
// was previously used for getting concrete buy orders.
SerializedInspect string `json:"serialized_inspect,omitempty"`
Sig string `json:"gs_sig,omitempty"`
ScreenshotID string `json:"cs2_screenshot_id,omitempty"`
Float float64 `json:"float_value,omitzero"`
// These two are part of the name and can be retrieved via category.
// IsStattrak bool `json:"is_stattrak,omitempty"`
// IsSouvenir bool `json:"is_souvenir,omitempty"`
// DefIndex is the weapon type
DefIndex uint `json:"def_index,omitzero"`
StickerIndex uint `json:"sticker_index,omitzero"`
// PaintIndex is the skin type
PaintIndex uint `json:"paint_index,omitzero"`
// PaintSeed determines the skin pattern
PaintSeed uint `json:"paint_seed,omitzero"`
Stickers []Sticker `json:"stickers,omitempty"`
Charms []Charm `json:"keychains,omitempty"`
Fade *Fade `json:"fade,omitempty"`
BlueGem *BlueGem `json:"blue_gem,omitempty"`
Collection string `json:"collection,omitempty"`
CharmIndex uint `json:"keychain_index,omitzero"`
CharmPattern uint `json:"keychain_pattern,omitzero"`
CharmHighlightReel uint `json:"keychain_highlight_reel,omitzero"`
}
func (item *Item) ScreenshotURL(playside bool) string {
if item.ScreenshotID == "" {
return ""
}
if playside {
return "https://csfloat.pics/m/" + item.ScreenshotID + "/playside.png?v=3"
}
return "https://csfloat.pics/m/" + item.ScreenshotID + "/backside.png?v=3"
}
// Category will map to the query category matching this item. This is required
// for listing similar items.
func (item *Item) Category() Category {
if strings.HasPrefix(item.MarketHashName, "Souvenir") {
return Souvenir
}
if strings.HasPrefix(item.MarketHashName, "StatTrak") {
return StatTrak
}
return Normal
}
type Category uint
const (
Normal = 1
StatTrak = 2
// Souvenir means has souvenir stickers and can't be stattrak.
Souvenir = 3
// Highlight is a bit special, as it doesn't actually apply to weapons, but highlight charm souvenir crates.
Highlight = 4
)
type SortListingsBy string
const (
BestDeals = ""
Newest = "most_recent"
HighestDiscount = "highest_discount"
LowestPrice = "lowest_price"
HighestPrice = "highest_price"
)
type ListingsRequest struct {
MinPrice int
MaxPrice int
MinFloat float32
MaxFloat float32
//ExcludeRare true causes min_ref_qty to be set to 20, just like on the CSFloat page.
ExcludeRare bool
MinRefQuantity uint
Categories []Category
SortBy SortListingsBy
DefIndex uint
StickerIndex uint
PaintIndex uint
PaintSeed []uint
CharmIndex uint
CharmHighlightReel uint
Type ListingType
}
type ListingResponse struct {
GenericResponse
Item ActiveListing
}
func (response *ListingResponse) responseBody() any {
return &response.Item
}
// Listing returns an existing listing.
func (api *API) Listing(listingId string) (*ListingResponse, error) {
return handleRequest(
api,
RatelimitKeyGetListing,
api.httpClient,
http.MethodGet,
"https://csfloat.com/api/v1/listings/"+listingId,
api.apiKey,
nil,
nil,
&ListingResponse{},
)
}
type StallResponse struct {
GenericResponse
Stall
}
func (response *StallResponse) responseBody() any {
return &response.Stall
}
type StallRequest struct {
SteamID string
Cursor string
}
func (api *API) Stall(request StallRequest) (*StallResponse, error) {
urlValues := url.Values{
"limit": []string{"40"},
}
if request.Cursor != "" {
urlValues.Set("cursor", request.Cursor)
}
return handleRequest(
api,
RatelimitKeyGetStall,
api.httpClient,
http.MethodGet,
"https://csfloat.com/api/v1/users/"+request.SteamID+"/stall",
api.apiKey,
nil,
urlValues,
&StallResponse{},
)
}
type InventoryResponse struct {
GenericResponse
Data []InventoryItem
}
func (response *InventoryResponse) responseBody() any {
return &response.Data
}
// Inventory returns all visible (tradable) items from the Steam inventory.
// This includes items already listed in the stall, those will have a
// `listing_id` set.
func (api *API) Inventory() (*InventoryResponse, error) {
return handleRequest(
api,
RatelimitKeyGetInventory,
api.httpClient,
http.MethodGet,
"https://csfloat.com/api/v1/me/inventory",
api.apiKey,
nil,
url.Values{
"limit": []string{"40"},
},
&InventoryResponse{},
)
}
type MeUser struct {
SteamId string `json:"steam_id"`
Balance uint `json:"balance"`
PendingBalance uint `json:"pending_balance"`
}
type MeResponse struct {
GenericResponse
User MeUser `json:"user"`
}
func (response *MeResponse) responseBody() any {
return response
}
func (api *API) Me() (*MeResponse, error) {
return handleRequest(
api,
RatelimitKeyGetMe,
api.httpClient,
http.MethodGet,
"https://csfloat.com/api/v1/me",
api.apiKey,
nil,
nil,
&MeResponse{},
)
}
type PostNewOfferRequest struct {
GivenAssetIds []string `json:"given_asset_ids"`
// ReceivedAssetIds is normally empty, as you usually only send assets.
ReceivedAssetIds []string `json:"received_asset_ids"`
// OfferId, figure out where it comes from.
OfferId string `json:"offer_id"`
}
func (api *API) PostNewOffer(offer PostNewOfferRequest) (*GenericResponse, error) {
return handleRequest(
api,
RatelimitKeyPostNewOffer,
api.httpClient,
http.MethodPost,
"https://csfloat.com/api/v1/trades/steam-status/new-offer",
api.apiKey,
offer,
nil,
&GenericResponse{},
)
}
type AcceptTradesResponse struct {
GenericResponse
Data []Trade `json:"data"`
}
func (response *AcceptTradesResponse) responseBody() any {
return response
}
func (api *API) BulkAcceptTrade(tradeIds ...string) (*AcceptTradesResponse, error) {
return handleRequest(
api,
RatelimitKeyBulkAcceptTrade,
api.httpClient,
http.MethodPost,
"https://csfloat.com/api/v1/trades/bulk/accept",
api.apiKey,
map[string]any{
"trade_ids": tradeIds,
},
nil,
&AcceptTradesResponse{},
)
}
func (api *API) BulkCancel(tradeIds ...string) (*GenericResponse, error) {
return handleRequest(
api,
RatelimitKeyBulkCancel,
api.httpClient,
http.MethodPost,
"https://csfloat.com/api/v1/trades/bulk/cancel",
api.apiKey,
map[string]any{
"trade_ids": tradeIds,
},
nil,
&GenericResponse{},
)
}
type BulkListRequest struct {
Items []ListRequest `json:"items"`
}
type BulkListResponse struct {
GenericResponse
Data []ActiveListing `json:"data"`
}
func (response *BulkListResponse) responseBody() any {
return response
}
func (api *API) BulkList(items ...ListRequest) (*BulkListResponse, error) {
return handleRequest(
api,
RatelimitKeyBulkList,
api.httpClient,
http.MethodPost,
"https://csfloat.com/api/v1/listings/bulk-list",
api.apiKey,
BulkListRequest{Items: items},
nil,
&BulkListResponse{},
)
}
func (api *API) BulkUnlist(listingId ...string) (*GenericResponse, error) {
if len(listingId) == 0 {
return nil, errors.New("no listings supplied")
}
if len(listingId) == 1 {
return handleRequest(
api,
RatelimitKeyUnlist,
api.httpClient,
http.MethodDelete,
"https://csfloat.com/api/v1/listings/"+listingId[0],
api.apiKey,
nil,
nil,
&GenericResponse{},
)
}
return handleRequest(
api,
RatelimitKeyBulkUnlist,
api.httpClient,
http.MethodPatch,
"https://csfloat.com/api/v1/listings/bulk-delist",
api.apiKey,
map[string][]string{
"contract_ids": listingId,
},
nil,
&GenericResponse{},
)
}
type UnlistResponse struct {
GenericResponse
}
func (response *UnlistResponse) responseBody() any {
return nil
}
func (api *API) Unlist(listingId string) (*UnlistResponse, error) {
return handleRequest(
api,
RatelimitKeyUnlist,
api.httpClient,
http.MethodDelete,
"https://csfloat.com/api/v1/listings/"+listingId,
api.apiKey,
nil,
nil,
&UnlistResponse{},
)
}
type UpdateListingResponse struct {
ListingResponse
}
func (api *API) UpdatePrivate(listingId string, private bool) (*UpdateListingResponse, error) {
return api.updateListing(listingId, map[string]any{"private": private})
}
func (api *API) UpdateDescription(listingId string, description string) (*UpdateListingResponse, error) {
return api.updateListing(listingId, map[string]any{"description": description})
}
func (api *API) UpdateDiscount(listingId string, discount uint) (*UpdateListingResponse, error) {
return api.updateListing(listingId, map[string]any{"max_offer_discount": discount})
}
func (api *API) UpdatePrice(listingId string, price uint) (*UpdateListingResponse, error) {
return api.updateListing(listingId, map[string]any{"price": price})
}
type UpdateListingRequest struct {
Private bool `json:"private"`
Description string `json:"description"`
MaxOfferDiscount uint `json:"max_offer_discount"`
Price uint `json:"price"`
}
func (api *API) UpdateListing(id string, payload UpdateListingRequest) (*UpdateListingResponse, error) {
return api.updateListing(id, payload)
}
func (api *API) updateListing(listingId string, payload any) (*UpdateListingResponse, error) {
return handleRequest(
api,
RatelimitKeyUpdateListing,
api.httpClient,
http.MethodPatch,
"https://csfloat.com/api/v1/listings/"+listingId,
api.apiKey,
payload,
nil,
&UpdateListingResponse{},
)
}
type BuyNowRequest struct {
Price uint `json:"price,omitzero"`
}
type AuctionRequest struct {
DurationDays uint `json:"duration_days,omitzero"`
ReservePrice uint `json:"reserve_price,omitzero"`
}
type ListRequest struct {
*BuyNowRequest
*AuctionRequest
AssetId string `json:"asset_id"`
AuctionType ListingType `json:"type"`
Description string `json:"description,omitempty"`
Private bool `json:"private,omitzero"`
}
type Error struct {
HttpStatus uint `json:"-"`
Code uint `json:"code"`
Message string `json:"message"`
}
type TradeState string
const (
// Queued means it was just bought, step 1.
Queued TradeState = "queued"
// Pending is the stage after queued, meaning the sale was accepted, but
// has not been verified yet. You can also be in this state if the item
// is still in trade protection, but would otherwise be verified. In this
// state it is relevant to check for all the different timestamp fields on
// the trade object. The verification mode will also already be escrow at
// this point in time.
Pending TradeState = "pending"
// Verified means both sides have received the goods.
Verified TradeState = "verified"
// Cancelled means the buyer decided not to buy afterall.
Cancelled TradeState = "cancelled"
// Failed means the buyer failed to accept.
Failed TradeState = "failed"
)
type VerificationMode string
const (
// Inventory is the mode right after purchase, before anyone has
// accepted anything until the seller accepted the sale.
Inventory VerificationMode = "inventory"
// Escrow means both sides have accepted everything, but the balance isn't
// usable yet.
Escrow VerificationMode = "escrow"
)
type SteamOfferState int
const (
NotSent SteamOfferState = 0
SentAwaitingMobileAuthenticator SteamOfferState = 9
Accepted SteamOfferState = 3
)
type SteamOffer struct {
State int `json:"state"`
SentAt time.Time `json:"sent_at,omitzero"`
UpdatedAt time.Time `json:"updated_at,omitzero"`
}
type Trade struct {
ID string `json:"id"`
// BuyerId is the steam ID, which can be your own ID if you are the buyer.
BuyerId string `json:"buyer_id"`
Contract Contract `json:"contract"`
// CreatedAt is the time at which the sale was made, either through a buy
// order or manually.
CreatedAt time.Time `json:"created_at"`
// AcceptedAt, is the time where the trade accepted the trade on CSFloat.
AcceptedAt time.Time `json:"accepted_at,omitzero"`
// TradeProtectionEndsAt seems to be correct again.
// An alternative is, to use the data from the SteamOffer field instead.
TradeProtectionEndsAt time.Time `json:"trade_protection_ends_at"`
// VerifySaleAt is the time after which the traede protection runs out.
VerifySaleAt time.Time `json:"verify_sale_at,omitzero"`
// VerifiedAt is the time at which escrow ended.
VerifiedAt time.Time `json:"verified_at,omitzero"`
SteamOffer SteamOffer `json:"steam_offer,omitzero"`
State TradeState `json:"state"`
VerificationMode VerificationMode `json:"verification_mode,omitempty"`
}
func (trade Trade) GetTradeProtectionEndsAt() time.Time {
return trade.TradeProtectionEndsAt
}
type TradesResponse struct {
GenericResponse
Trades []Trade `json:"trades"`
// Count is the total count of trades (all pages for the given query)
Count uint `json:"count"`
}
func (response *TradesResponse) responseBody() any {
return response
}
type TradesRequest struct {
// Page, default 0 (latest)
Page uint `json:"page"`
// Limit, default 100
Limit uint `json:"limit"`
// States, empty by default, not filtering
States []TradeState
}
func (api *API) Trades(payload TradesRequest) (*TradesResponse, error) {
if payload.Limit == 0 {
payload.Limit = 100
}
form := url.Values{}
if len(payload.States) > 0 {
var str strings.Builder
// longest state is cancelled with 9, so we'd fit cancelled + a comma
str.Grow(len(payload.States) * 10)
for index, state := range payload.States {
str.WriteString(string(state))
if index < len(payload.States)-1 {
str.WriteByte(',')
}
}
form.Set("state", str.String())
}
form.Set("page", strconv.FormatUint(uint64(payload.Page), 10))
form.Set("limit", strconv.FormatUint(uint64(payload.Limit), 10))
return handleRequest(
api,
RatelimitKeyGetTrades,
api.httpClient,
http.MethodGet,
"https://csfloat.com/api/v1/me/trades",
api.apiKey,
nil,
form,
&TradesResponse{},
)
}
type HistoryEntry struct {
Price uint `json:"price"`
Item Item `json:"item"`
Reference ItemReference `json:"reference,omitzero"`
SoldAt time.Time `json:"sold_at"`
}
type HistoryRequestPayload struct {
MarketHashName string
PaintIndex uint
}
type HistoryResponse struct {
GenericResponse
Data []HistoryEntry
}
func (response *HistoryResponse) responseBody() any {
return &response.Data
}
func (api *API) History(payload HistoryRequestPayload) (*HistoryResponse, error) {
form := url.Values{}
// Passing zero for a case / sticker will yield in an empty result.
// paint_index 0 for weapons is supposedly the default skin.
if payload.PaintIndex != 0 {
form.Set("paint_index", strconv.FormatUint(uint64(payload.PaintIndex), 10))
}
return handleRequest(
api,
RatelimitKeyGetHistory,
api.httpClient,
http.MethodGet,
"https://csfloat.com/api/v1/history/"+url.QueryEscape(payload.MarketHashName)+"/sales",
api.apiKey,
nil,
form,
&HistoryResponse{},
)
}
type BuyResponse struct {
GenericResponse
}
func (response *BuyResponse) responseBody() any {
return nil
}
type BuyRequestPayload struct {
ContractIds []string `json:"contract_ids"`
TotalPrice uint `json:"total_price"`
}
func (api *API) Buy(payload BuyRequestPayload) (*BuyResponse, error) {
return handleRequest(
api,
RatelimitKeyBuy,
api.httpClient,
http.MethodPost,
"https://csfloat.com/api/v1/listings/buy",
api.apiKey,
payload,
nil,
&BuyResponse{},
)
}
func (api *API) Unwatch(listingId string) (*GenericResponse, error) {
return handleRequest(
api,
RatelimitKeyUnwatch,
api.httpClient,
http.MethodDelete,
"https://csfloat.com/api/v1/listings/"+listingId+"/watchlist",
api.apiKey,
nil,
nil,
&GenericResponse{},
)
}
func (api *API) Watch(listingId string) (*GenericResponse, error) {
return handleRequest(
api,
RatelimitKeyWatch,
api.httpClient,
http.MethodPost,
"https://csfloat.com/api/v1/listings/"+listingId+"/watchlist",
api.apiKey,
nil,
nil,
&GenericResponse{},
)
}
// SimpleItemBuyOrdersResponse is the same as BuyOrders content-wise, BUT the structure is different.
type SimpleItemBuyOrdersResponse struct {
GenericResponse
Data []ItemBuyOrder `json:"data"`
}
func (response *SimpleItemBuyOrdersResponse) responseBody() any {
return response
}
type ItemBuyOrdersResponse struct {
GenericResponse
Data []ItemBuyOrder `json:"data"`
}
func (response *ItemBuyOrdersResponse) responseBody() any {
return &response.Data
}
type ItemBuyOrder struct {
ID string `json:"id"`
// MarketHashName is only used for simple buy orders.
MarketHashName string `json:"market_hash_name"`
// Expression is only used for advanced buy orders.
Expression string `json:"expression,omitempty"`
Quantity uint `json:"qty,omitzero"`
Price uint `json:"price"`
}
func (api *API) ItemBuyOrders(item *Item) (*ItemBuyOrdersResponse, error) {
formValues := url.Values{"limit": []string{"3"}}
formValues.Set("url", item.SerializedInspect)
formValues.Set("sig", item.Sig)
formValues.Set("market_hash_name", item.MarketHashName)
method := http.MethodGet
url := "https://csfloat.com/api/v1/buy-orders/item"
return handleRequest(
api,
RatelimitKeyGetItemBuyOrders,
api.httpClient,
method,
url,
api.apiKey,
nil,
formValues,
&ItemBuyOrdersResponse{},
)
}
func (api *API) SimpleItemBuyOrders(item *Item) (*SimpleItemBuyOrdersResponse, error) {
formValues := url.Values{"limit": []string{"3"}}
body := map[string]string{
"market_hash_name": item.MarketHashName,
}
// Well ... this is being abused for providing a body it seems.
method := http.MethodPost
url := "https://csfloat.com/api/v1/buy-orders/similar-orders"
return handleRequest(
api,
RatelimitKeyGetSimpleItemBuyOrders,
api.httpClient,
method,
url,
api.apiKey,
body,
formValues,
&SimpleItemBuyOrdersResponse{},
)
}
func (api *API) ListingBuyOrders(listingId string, limit int64) (*ItemBuyOrdersResponse, error) {
return handleRequest(
api,
RatelimitKeyGetListingBuyOrders,
api.httpClient,
http.MethodGet,
"https://csfloat.com/api/v1/listings/"+listingId+"/buy-orders",
api.apiKey,
nil,
url.Values{"limit": []string{strconv.FormatInt(limit, 10)}},
&ItemBuyOrdersResponse{},
)
}
type SimilarResponse struct {
GenericResponse
Data []*ActiveListing
}
func (response *SimilarResponse) responseBody() any {
return &response.Data
}
func (api *API) Similar(listingId string) (*SimilarResponse, error) {
return handleRequest(
api,
RatelimitKeyGetSimilar,
api.httpClient,
http.MethodGet,
"https://csfloat.com/api/v1/listings/"+listingId+"/similar",
api.apiKey,
nil,
nil,
&SimilarResponse{},
)
}
func errorFrom(response *http.Response) (Error, error) {
var csfloatError Error
csfloatError.HttpStatus = uint(response.StatusCode)
return csfloatError, json.UnmarshalRead(response.Body, &csfloatError)
}
type TransactionType string
const (
TransactionTypeDeposit TransactionType = "deposit"
TransactionTypeWithdrawal TransactionType = "withdrawal"
TransactionTypeContractSold TransactionType = "contract_sold"
TransactionTypeContractSaleRefund TransactionType = "contract_sale_refund"
TransactionTypeContractPurchased TransactionType = "contract_purchased"
TransactionTypeContractPurchaseRefund TransactionType = "contract_purchase_refund"
TransactionTypeTradeVerified TransactionType = "trade_verified"
TransactionTypeFine TransactionType = "fine"
TransactionTypeBidDeclined TransactionType = "bid_declined"
TransactionTypeBidPosted TransactionType = "bid_posted"
)