Skip to content

perps-studio/hip4-go

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

4 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

hip4-go

Go Reference Go Version License: BUSL-1.1

Go SDK for Hyperliquid HIP-4 prediction markets.

Surface-equivalent to:

Install

go get github.com/perps-studio/hip4-go/hip4

Requires Go 1.22 or newer.

Quick start

package main

import (
    "context"
    "fmt"
    "log"

    "github.com/perps-studio/hip4-go/hip4"
)

func main() {
    ctx := context.Background()

    adapter := hip4.NewBuilder().Testnet(true).Build()
    if err := adapter.Initialize(ctx); err != nil {
        log.Fatal(err)
    }
    defer adapter.Destroy()

    // Browse active events
    events, err := adapter.Events.FetchEvents(ctx, "", true, 10, 0, "")
    if err != nil {
        log.Fatal(err)
    }
    for _, e := range events {
        fmt.Printf("[%s] %s\n", e.ID, e.Title)
    }

    // Authenticate with an agent wallet
    if _, err := adapter.Auth.InitAuthFromPrivateKey(
        "0xYourMainWalletAddress", "0xYourAgentPrivateKey",
    ); err != nil {
        log.Fatal(err)
    }

    // Place a limit buy
    price := "0.5"
    result := adapter.Trading.PlaceOrder(ctx, hip4.PredictionOrderParams{
        MarketID: "123",
        Outcome:  "#1230",
        Side:     hip4.SideBuy,
        Type:     hip4.OrderTypeLimit,
        Price:    &price,
        Amount:   "20",
    })
    fmt.Printf("order: success=%v status=%v\n", result.Success, derefStr(result.Status))
}

func derefStr(s *string) string { if s != nil { return *s }; return "" }

Surface

The top-level *HIP4Adapter composes six sub-adapters and exposes the raw *HIP4Client for low-level access.

Auth

Method Notes
InitAuth(addr, HIP4Signer) Register an arbitrary signer.
InitAuthFromPrivateKey(addr, hex) Convenience for ECDSA.
ClearAuth() / State() / Signer() Lifecycle.
NextNonce() Strictly-increasing ms-based nonce.

Events

Method Returns
FetchEvents(ctx, category, active, limit, offset, query) []PredictionEvent
FetchEvent(ctx, eventID) *PredictionEvent
FetchCategories() []PredictionCategory
FetchMarkets(ctx, FetchMarketsParams) FetchMarketsResult (flat / MarketsByType / MarketsByQuestion)
EnsureSideNames(ctx) Populate the side-name resolver.
SubscribeOutcomeMetaUpdates(cb) WS stream of catalog changes.

MarketData

Method Notes
FetchOrderBook / FetchPrice / FetchTrades / FetchCandles REST.
SubscribeOrderBook / SubscribeTrades / SubscribePrice Per-market WS.
SubscribeAllMids / SubscribeActiveAssetCtx (spot) / SubscribePerpAssetCtx / SubscribeSpotAssetCtxs Cross-market WS.

Account

Method Notes
FetchPositions(ctx, addr) Names auto-resolved from Events.
FetchActivity(ctx, addr) Last 30 days of trades.
FetchBalance(ctx, addr) / FetchOpenOrders(ctx, addr) Spot side.
SubscribePositions(addr, cb) 10-second poll.

Trading

Method Notes
PlaceOrder / PlaceOrders (batch) / ModifyOrder Returns PredictionOrderResult (never throws).
CancelOrder([]PredictionCancelParams) Returns *HLCancelResponse.
SplitOutcome / MergeOutcome / MergeQuestion / NegateOutcome Share conversion (userOutcome family).
ScheduleCancel(*int64) HL dead-man's-switch; nil clears.

Builder-fee defaults live on TradingConfig; per-order overrides via PredictionOrderParams.BuilderAddress / .BuilderFee.

Wallet

Method Notes
SetSigner(HIP4Signer) / SetSignerFromPrivateKey(hex) Separate from the agent signer.
BuyUSDH / SellUSDH L1 agent signing against the USDH/USDC pair.
TransferToSpot / TransferToPerps / UsdClassTransfer Spot ↔ perp.
Withdraw / UsdSend / SpotSend EIP-712 user signing.
SendAsset Unified-account-compatible transfer primitive.
SendSpotTokenToEvm / SendToEvmWithData / SendUsdcToEvm HyperCore → HyperEVM.
SetReferrer(code) L1 agent signing.

Pure helpers

  • Pricing: ComputeTickSize, RoundToTick, FormatPrice, FormatPredictionPrice, StripZeros, GetMinShares, MinNotional.
  • Coin: OutcomeCoin, SideCoin, SideAssetID, ParseSideCoin, ParseOutcomeCoin, CoinOutcomeID, IsOutcomeCoin.
  • Discovery / classification: ParseDescription, ParsePriceBucketDescription, GetPriceBucketBounds, DiscoverPriceBinaryMarkets, TimeToExpiry, PeriodMinutes, FormatMarketLabel, BuildQuestionIndex, ClassifyOutcome, ClassifyAllOutcomes.
  • Signing: SignL1Action, SignUserSignedAction, SignAgent, SignApproveBuilderFee, ActionHash, FormatDecimal, ECDSASigner, HIP4Signer interface.
  • External-wallet approvals: AgentApprovalTypedData, BuilderFeeApprovalTypedData, SubmitAgentApproval, SubmitBuilderFeeApproval, NormalizeSignature, SplitHexSignature.
  • Core ↔ EVM: DeriveCoreEvmSystemAddress, EstimateCoreToEvmFee, MedianBaseFeeWei, HypeCoreEvmSystemAddress, CoreToEvmGasLimit, MaxCoreEvmTokenIndex.
  • HYPE spot: SelectHypeSpotMarkPx, FindHypeUsdcSpotPairCoin, HypeUSDCSpotPairMainnet/Testnet.
  • Orderbook: ComputeEstimatedCost, ComputePotentialReturn, ComputeTradeCost, TradeCostResult.
  • USD utils: IsUsdClassTransferRequired, ALL_DEXS.

Streams

Live merged historical-plus-WebSocket candle feeds, under github.com/perps-studio/hip4-go/hip4/streams:

  • PriceFeedCandle, IntervalToMs, CandleBoundaryMs, ProcessTick
  • CreatePriceFeed — outcome-side mid feed
  • CreatePerpPriceFeed — perp candle WS + activeAssetCtx mark + history

Examples

go run ./examples/fetch_markets
HYPERLIQUID_PRIVATE_KEY=0x... HYPERLIQUID_WALLET_ADDRESS=0x... go run ./examples/place_order

Versioning

Releases follow Semantic Versioning. See CHANGELOG.md for release notes.

Contributing

See CONTRIBUTING.md. For security reports, see SECURITY.md.

License

BUSL-1.1 — see LICENSE.

About

No description, website, or topics provided.

Resources

License

Contributing

Security policy

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors

Languages