Class: Hyperliquid::Exchange

Inherits:
Object
  • Object
show all
Defined in:
lib/hyperliquid/exchange.rb

Overview

Exchange API client for write operations (orders, cancels, etc.) Requires a private key for signing transactions

Constant Summary collapse

DEFAULT_SLIPPAGE =

Default slippage for market orders (5%)

0.05
SPOT_ASSET_THRESHOLD =

Spot assets have indices >= 10000

10_000

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(client:, signer:, info:, testnet: false, expires_after: nil) ⇒ Exchange

Initialize the exchange client

Parameters:

  • client (Hyperliquid::Client)

    HTTP client

  • signer (Hyperliquid::Signing::Signer)

    EIP-712 signer

  • info (Hyperliquid::Info)

    Info API client for metadata

  • testnet (Boolean) (defaults to: false)

    Whether targeting testnet (default: false)

  • expires_after (Integer, nil) (defaults to: nil)

    Optional global expiration timestamp



22
23
24
25
26
27
28
29
# File 'lib/hyperliquid/exchange.rb', line 22

def initialize(client:, signer:, info:, testnet: false, expires_after: nil)
  @client = client
  @signer = signer
  @info = info
  @testnet = testnet
  @expires_after = expires_after
  @asset_cache = nil
end

Instance Attribute Details

#expires_after=(value) ⇒ Object (writeonly)

Update the global expiration timestamp applied to subsequent L1 actions. expires_after is not supported on user-signed actions (e.g. usd_send, withdraw_from_bridge) and must be nil for those calls to succeed.

Parameters:

  • value (Integer, nil)

    Unix timestamp in milliseconds, or nil to clear



740
741
742
# File 'lib/hyperliquid/exchange.rb', line 740

def expires_after=(value)
  @expires_after = value
end

Instance Method Details

#activate_outcome_deployer(is_deactivate:) ⇒ Hash

Activate or deactivate the signer as an outcome deployer (activateOutcomeDeployer L1 action, HIP-4).

Parameters:

  • is_deactivate (Boolean)

    True to deactivate, false to activate

Returns:

  • (Hash)

    Exchange response



1367
1368
1369
1370
1371
1372
1373
1374
1375
# File 'lib/hyperliquid/exchange.rb', line 1367

def activate_outcome_deployer(is_deactivate:)
  nonce = timestamp_ms
  action = { type: 'activateOutcomeDeployer', isDeactivate: is_deactivate }
  signature = @signer.sign_l1_action(
    action, nonce,
    expires_after: @expires_after
  )
  post_action(action, signature, nonce, nil)
end

#addressString

Get the wallet address

Returns:

  • (String)

    Checksummed Ethereum address



33
34
35
# File 'lib/hyperliquid/exchange.rb', line 33

def address
  @signer.address
end

#agent_enable_dex_abstraction(vault_address: nil) ⇒ Hash

Enable HIP-3 DEX abstraction via agent (L1 action, enable only) This allows agents to enable DEX abstraction for the account they're trading on behalf of

Parameters:

  • vault_address (String, nil) (defaults to: nil)

    Vault address if trading on behalf of a vault

Returns:

  • (Hash)

    Agent enable DEX abstraction response



686
687
688
689
690
691
692
693
694
695
# File 'lib/hyperliquid/exchange.rb', line 686

def agent_enable_dex_abstraction(vault_address: nil)
  nonce = timestamp_ms
  action = { type: 'agentEnableDexAbstraction' }
  signature = @signer.sign_l1_action(
    action, nonce,
    vault_address: vault_address,
    expires_after: @expires_after
  )
  post_action(action, signature, nonce, vault_address)
end

#agent_send_asset(destination:, source_dex:, destination_dex:, token:, amount:, from_sub_account: '') ⇒ Hash

Move assets between DEX instances on behalf of an agent's principal (agentSendAsset L1 action). Unlike send_asset (which is user-signed), this is signed by an agent and the destination must equal the agent's principal address. source_dex/destination_dex accept "" (default USDC perp DEX) and "spot" (spot trading) per protocol convention.

Parameters:

  • destination (String)

    Destination wallet address (must match the agent's principal)

  • source_dex (String)

    Source DEX identifier

  • destination_dex (String)

    Destination DEX identifier

  • token (String)

    Token in "tokenName:tokenId" format

  • amount (String, Numeric)

    Amount to send

  • from_sub_account (String) (defaults to: '')

    Source sub-account address, or empty string for the principal

Returns:

  • (Hash)

    Exchange response



1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
# File 'lib/hyperliquid/exchange.rb', line 1075

def agent_send_asset(destination:, source_dex:, destination_dex:, token:, amount:,
                     from_sub_account: '')
  nonce = timestamp_ms
  action = {
    type: 'agentSendAsset',
    destination: destination,
    sourceDex: source_dex,
    destinationDex: destination_dex,
    token: token,
    amount: amount.to_s,
    fromSubAccount: ,
    nonce: nonce
  }
  signature = @signer.sign_l1_action(
    action, nonce,
    expires_after: @expires_after
  )
  post_action(action, signature, nonce, nil)
end

#agent_set_abstraction(abstraction:, vault_address: nil) ⇒ Hash

Set the agent abstraction mode (L1 action agentSetAbstraction).

Parameters:

  • abstraction (String)

    One of 'u' (unified), 'p' (portfolio margin), 'i' (isolated/disabled)

  • vault_address (String, nil) (defaults to: nil)

    Vault address if acting on behalf of a vault

Returns:

  • (Hash)

    Exchange response



701
702
703
704
705
706
707
708
709
710
# File 'lib/hyperliquid/exchange.rb', line 701

def agent_set_abstraction(abstraction:, vault_address: nil)
  nonce = timestamp_ms
  action = { type: 'agentSetAbstraction', abstraction: abstraction }
  signature = @signer.sign_l1_action(
    action, nonce,
    vault_address: vault_address,
    expires_after: @expires_after
  )
  post_action(action, signature, nonce, vault_address)
end

#approve_agent(agent_address:, agent_name: nil) ⇒ Hash

Authorize an agent wallet to trade on behalf of this account

Parameters:

  • agent_address (String)

    Agent's Ethereum address

  • agent_name (String, nil) (defaults to: nil)

    Optional agent name (omitted from action if nil)

Returns:

  • (Hash)

    Approve agent response



591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
# File 'lib/hyperliquid/exchange.rb', line 591

def approve_agent(agent_address:, agent_name: nil)
  nonce = timestamp_ms
  action = {
    type: 'approveAgent',
    signatureChainId: '0x66eee',
    hyperliquidChain: Signing::EIP712.hyperliquid_chain(testnet: @testnet),
    agentAddress: agent_address,
    nonce: nonce
  }
  # agentName is always included in the signed message (empty string if nil),
  # but only included in the posted action if a name was provided (matches Python SDK)
  action[:agentName] = agent_name if agent_name
  signature = @signer.sign_user_signed_action(
    { agentAddress: agent_address, agentName: agent_name || '', nonce: nonce },
    'HyperliquidTransaction:ApproveAgent',
    Signing::EIP712::APPROVE_AGENT_TYPES
  )
  post_action(action, signature, nonce, nil)
end

#approve_builder_fee(builder:, max_fee_rate:) ⇒ Hash

Approve a builder fee rate for a builder address Users must approve a builder before orders with that builder can be placed.

Parameters:

  • builder (String)

    Builder's Ethereum address

  • max_fee_rate (String)

    Maximum fee rate (e.g., "0.01%" for 1 basis point)

Returns:

  • (Hash)

    Approve builder fee response



616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
# File 'lib/hyperliquid/exchange.rb', line 616

def approve_builder_fee(builder:, max_fee_rate:)
  nonce = timestamp_ms
  action = {
    type: 'approveBuilderFee',
    signatureChainId: '0x66eee',
    hyperliquidChain: Signing::EIP712.hyperliquid_chain(testnet: @testnet),
    maxFeeRate: max_fee_rate,
    builder: builder,
    nonce: nonce
  }
  signature = @signer.sign_user_signed_action(
    { maxFeeRate: max_fee_rate, builder: builder, nonce: nonce },
    'HyperliquidTransaction:ApproveBuilderFee',
    Signing::EIP712::APPROVE_BUILDER_FEE_TYPES
  )
  post_action(action, signature, nonce, nil)
end

#authorize_aqav2_role(token:, role:) ⇒ Hash

Authorize an AQAv2 role (authorizeAqav2Role L1 action).

Parameters:

  • token (Integer)

    Token identifier

  • role (String)

    Role to authorize ("technical" or "treasury")

Returns:

  • (Hash)

    Exchange response



1418
1419
1420
1421
1422
1423
1424
1425
1426
# File 'lib/hyperliquid/exchange.rb', line 1418

def authorize_aqav2_role(token:, role:)
  nonce = timestamp_ms
  action = { type: 'authorizeAqav2Role', token: token.to_i, role: role }
  signature = @signer.sign_l1_action(
    action, nonce,
    expires_after: @expires_after
  )
  post_action(action, signature, nonce, nil)
end

#batch_modify(modifies:, vault_address: nil) ⇒ Hash

Modify multiple orders at once

Parameters:

  • modifies (Array<Hash>)

    Array of modify hashes with keys: :oid, :coin, :is_buy, :size, :limit_px, :order_type, :reduce_only, :cloid, :always_place

  • vault_address (String, nil) (defaults to: nil)

    Vault address for vault trading (optional)

Returns:

  • (Hash)

    Batch modify response



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
# File 'lib/hyperliquid/exchange.rb', line 265

def batch_modify(modifies:, vault_address: nil)
  nonce = timestamp_ms

  modify_wires = modifies.map do |m|
    order_wire = build_order_wire(
      coin: m[:coin],
      is_buy: m[:is_buy],
      size: m[:size],
      limit_px: m[:limit_px],
      order_type: m[:order_type] || { limit: { tif: 'Gtc' } },
      reduce_only: m[:reduce_only] || false,
      cloid: m[:cloid]
    )
    entry = { oid: normalize_oid(m[:oid]), order: order_wire }
    entry[:a] = true if m[:always_place]
    entry
  end

  action = {
    type: 'batchModify',
    modifies: modify_wires
  }

  signature = @signer.sign_l1_action(
    action, nonce,
    vault_address: vault_address,
    expires_after: @expires_after
  )
  post_action(action, signature, nonce, vault_address)
end

#borrow_lend(operation:, token:, amount: nil, vault_address: nil) ⇒ Hash

Borrow, lend, supply, or withdraw HIP-2 borrow/lend assets (borrowLend L1 action). Companion to the four HIP-2 info methods (borrow_lend_user_state etc.).

Parameters:

  • operation (String)

    One of 'supply', 'withdraw', 'repay', 'borrow'

  • token (Integer)

    HIP-2 token ID (e.g. 0 for USDC)

  • amount (String, Numeric, nil) (defaults to: nil)

    Amount to operate on; pass nil to use the full position

  • vault_address (String, nil) (defaults to: nil)

    Vault address if acting on behalf of a vault

Returns:

  • (Hash)

    Exchange response



978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
# File 'lib/hyperliquid/exchange.rb', line 978

def borrow_lend(operation:, token:, amount: nil, vault_address: nil)
  nonce = timestamp_ms
  action = {
    type: 'borrowLend',
    operation: operation,
    token: token,
    amount: amount&.to_s
  }
  signature = @signer.sign_l1_action(
    action, nonce,
    vault_address: vault_address,
    expires_after: @expires_after
  )
  post_action(action, signature, nonce, vault_address)
end

#bulk_cancel(cancels:, vault_address: nil) ⇒ Hash

Cancel multiple orders by order ID

Parameters:

  • cancels (Array<Hash>)

    Array of cancel hashes with :coin and :oid

  • vault_address (String, nil) (defaults to: nil)

    Vault address for vault trading (optional)

Returns:

  • (Hash)

    Bulk cancel response



198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
# File 'lib/hyperliquid/exchange.rb', line 198

def bulk_cancel(cancels:, vault_address: nil)
  nonce = timestamp_ms

  cancel_wires = cancels.map do |c|
    { a: asset_index(c[:coin]), o: c[:oid] }
  end
  action = { type: 'cancel', cancels: cancel_wires }

  signature = @signer.sign_l1_action(
    action, nonce,
    vault_address: vault_address,
    expires_after: @expires_after
  )
  post_action(action, signature, nonce, vault_address)
end

#bulk_cancel_by_cloid(cancels:, vault_address: nil) ⇒ Hash

Cancel multiple orders by client order ID

Parameters:

  • cancels (Array<Hash>)

    Array of cancel hashes with :coin and :cloid

  • vault_address (String, nil) (defaults to: nil)

    Vault address for vault trading (optional)

Returns:

  • (Hash)

    Bulk cancel by cloid response



218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
# File 'lib/hyperliquid/exchange.rb', line 218

def bulk_cancel_by_cloid(cancels:, vault_address: nil)
  nonce = timestamp_ms

  cancel_wires = cancels.map do |c|
    { asset: asset_index(c[:coin]), cloid: normalize_cloid(c[:cloid]) }
  end
  action = { type: 'cancelByCloid', cancels: cancel_wires }

  signature = @signer.sign_l1_action(
    action, nonce,
    vault_address: vault_address,
    expires_after: @expires_after
  )
  post_action(action, signature, nonce, vault_address)
end

#bulk_orders(orders:, grouping: 'na', vault_address: nil, builder: nil) ⇒ Hash

Place multiple orders in a batch

Parameters:

  • orders (Array<Hash>)

    Array of order hashes with keys: :coin, :is_buy, :size, :limit_px, :order_type, :reduce_only, :cloid

  • grouping (String) (defaults to: 'na')

    Order grouping ("na", "normalTpsl", "positionTpsl")

  • vault_address (String, nil) (defaults to: nil)

    Vault address for vault trading (optional)

  • builder (Hash, nil) (defaults to: nil)

    Builder fee config { b: "0xaddress", f: fee_in_tenths_of_bp } (optional)

Returns:

  • (Hash)

    Bulk order response



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
# File 'lib/hyperliquid/exchange.rb', line 84

def bulk_orders(orders:, grouping: 'na', vault_address: nil, builder: nil)
  nonce = timestamp_ms

  order_wires = orders.map do |o|
    build_order_wire(
      coin: o[:coin],
      is_buy: o[:is_buy],
      size: o[:size],
      limit_px: o[:limit_px],
      order_type: o[:order_type] || { limit: { tif: 'Gtc' } },
      reduce_only: o[:reduce_only] || false,
      cloid: o[:cloid]
    )
  end

  action = {
    type: 'order',
    orders: order_wires,
    grouping: grouping
  }
  action[:builder] = normalize_builder(builder) if builder

  signature = @signer.sign_l1_action(
    action, nonce,
    vault_address: vault_address,
    expires_after: @expires_after
  )
  post_action(action, signature, nonce, vault_address)
end

#c_deposit(wei:) ⇒ Hash

Deposit native HYPE from the user's spot account into staking (cDeposit user-signed action).

Parameters:

  • wei (Integer)

    Amount of wei to deposit into staking (float * 1e8)

Returns:

  • (Hash)

    Exchange response



1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
# File 'lib/hyperliquid/exchange.rb', line 1183

def c_deposit(wei:)
  nonce = timestamp_ms
  wei_int = wei.to_i
  action = {
    type: 'cDeposit',
    signatureChainId: '0x66eee',
    hyperliquidChain: Signing::EIP712.hyperliquid_chain(testnet: @testnet),
    wei: wei_int,
    nonce: nonce
  }
  signature = @signer.sign_user_signed_action(
    { wei: wei_int, nonce: nonce },
    'HyperliquidTransaction:CDeposit',
    Signing::EIP712::C_DEPOSIT_TYPES
  )
  post_action(action, signature, nonce, nil)
end

#c_withdraw(wei:) ⇒ Hash

Withdraw native HYPE from staking back into the user's spot account (cWithdraw user-signed action).

Parameters:

  • wei (Integer)

    Amount of wei to withdraw from staking (float * 1e8)

Returns:

  • (Hash)

    Exchange response



1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
# File 'lib/hyperliquid/exchange.rb', line 1204

def c_withdraw(wei:)
  nonce = timestamp_ms
  wei_int = wei.to_i
  action = {
    type: 'cWithdraw',
    signatureChainId: '0x66eee',
    hyperliquidChain: Signing::EIP712.hyperliquid_chain(testnet: @testnet),
    wei: wei_int,
    nonce: nonce
  }
  signature = @signer.sign_user_signed_action(
    { wei: wei_int, nonce: nonce },
    'HyperliquidTransaction:CWithdraw',
    Signing::EIP712::C_WITHDRAW_TYPES
  )
  post_action(action, signature, nonce, nil)
end

#cancel(coin:, oid:, vault_address: nil, fast: nil) ⇒ Hash

Cancel a single order by order ID

Parameters:

  • coin (String)

    Asset symbol

  • oid (Integer)

    Order ID

  • vault_address (String, nil) (defaults to: nil)

    Vault address for vault trading (optional)

  • fast (Boolean, nil) (defaults to: nil)

    Whether to use fast cancel (optional)

Returns:

  • (Hash)

    Cancel response



149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
# File 'lib/hyperliquid/exchange.rb', line 149

def cancel(coin:, oid:, vault_address: nil, fast: nil)
  nonce = timestamp_ms

  cancel_entry = { a: asset_index(coin), o: oid }
  cancel_entry[:f] = true if fast

  action = {
    type: 'cancel',
    cancels: [cancel_entry]
  }

  signature = @signer.sign_l1_action(
    action, nonce,
    vault_address: vault_address,
    expires_after: @expires_after
  )
  post_action(action, signature, nonce, vault_address)
end

#cancel_by_cloid(coin:, cloid:, vault_address: nil, fast: nil) ⇒ Hash

Cancel a single order by client order ID

Parameters:

  • coin (String)

    Asset symbol

  • cloid (Cloid, String)

    Client order ID

  • vault_address (String, nil) (defaults to: nil)

    Vault address for vault trading (optional)

  • fast (Boolean, nil) (defaults to: nil)

    Whether to use fast cancel (optional)

Returns:

  • (Hash)

    Cancel response



174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
# File 'lib/hyperliquid/exchange.rb', line 174

def cancel_by_cloid(coin:, cloid:, vault_address: nil, fast: nil)
  nonce = timestamp_ms
  cloid_raw = normalize_cloid(cloid)

  cancel_entry = { asset: asset_index(coin), cloid: cloid_raw }
  cancel_entry[:f] = true if fast

  action = {
    type: 'cancelByCloid',
    cancels: [cancel_entry]
  }

  signature = @signer.sign_l1_action(
    action, nonce,
    vault_address: vault_address,
    expires_after: @expires_after
  )
  post_action(action, signature, nonce, vault_address)
end

#claim_rewardsHash

Claim accrued referral-program rewards (claimRewards L1 action).

Returns:

  • (Hash)

    Exchange response



850
851
852
853
854
855
856
857
858
# File 'lib/hyperliquid/exchange.rb', line 850

def claim_rewards
  nonce = timestamp_ms
  action = { type: 'claimRewards' }
  signature = @signer.sign_l1_action(
    action, nonce,
    expires_after: @expires_after
  )
  post_action(action, signature, nonce, nil)
end

#convert_to_multi_sig_user(authorized_users:, threshold:) ⇒ Hash

Convert this account into a multi-sig user (convertToMultiSigUser user-signed action). The set of authorized signers and the threshold are JSON-encoded into the action's signers field as required by the Hyperliquid protocol.

Parameters:

  • authorized_users (Array<String>)

    Authorized signer addresses; sorted before signing

  • threshold (Integer)

    Number of signatures required to authorize an action

Returns:

  • (Hash)

    Exchange response



795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
# File 'lib/hyperliquid/exchange.rb', line 795

def convert_to_multi_sig_user(authorized_users:, threshold:)
  nonce = timestamp_ms
  sorted_users = authorized_users.sort
  signers_json = JSON.generate({ authorizedUsers: sorted_users, threshold: threshold })
  action = {
    type: 'convertToMultiSigUser',
    signatureChainId: '0x66eee',
    hyperliquidChain: Signing::EIP712.hyperliquid_chain(testnet: @testnet),
    signers: signers_json,
    nonce: nonce
  }
  signature = @signer.sign_user_signed_action(
    { signers: signers_json, nonce: nonce },
    'HyperliquidTransaction:ConvertToMultiSigUser',
    Signing::EIP712::CONVERT_TO_MULTI_SIG_USER_TYPES
  )
  post_action(action, signature, nonce, nil)
end

#create_sub_account(name:) ⇒ Hash

Create a sub-account

Parameters:

  • name (String)

    Sub-account name

Returns:

  • (Hash)

    Creation response



517
518
519
520
521
522
# File 'lib/hyperliquid/exchange.rb', line 517

def (name:)
  nonce = timestamp_ms
  action = { type: 'createSubAccount', name: name }
  signature = @signer.sign_l1_action(action, nonce)
  post_action(action, signature, nonce, nil)
end

#create_vault(name:, description:, initial_usd:) ⇒ Hash

Returns Exchange response — on success response.data is the new vault address.

Returns:

  • (Hash)

    Exchange response — on success response.data is the new vault address



955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
# File 'lib/hyperliquid/exchange.rb', line 955

def create_vault(name:, description:, initial_usd:)
  nonce = timestamp_ms
  action = {
    type: 'createVault',
    name: name,
    description: description,
    initialUsd: float_to_usd_int(initial_usd),
    nonce: nonce
  }
  signature = @signer.sign_l1_action(
    action, nonce,
    expires_after: @expires_after
  )
  post_action(action, signature, nonce, nil)
end

#finalize_evm_contract(token:, input:) ⇒ Hash

Finalize the link between a HyperCore spot token and an ERC-20 contract on HyperEVM (finalizeEvmContract L1 action). input selects the verification method and is passed through verbatim — accepts a Hash { create: { nonce: <int> } } for an EOA-deployed contract, or one of the strings "firstStorageSlot" / "customStorageSlot" for contracts that store the finalizer address in a known storage slot.

Parameters:

  • token (Integer)

    HyperCore spot token identifier to link

  • input (Hash, String)

    Verification method (see above)

Returns:

  • (Hash)

    Exchange response



1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
# File 'lib/hyperliquid/exchange.rb', line 1385

def finalize_evm_contract(token:, input:)
  nonce = timestamp_ms
  action = {
    type: 'finalizeEvmContract',
    token: token,
    input: input
  }
  signature = @signer.sign_l1_action(
    action, nonce,
    expires_after: @expires_after
  )
  post_action(action, signature, nonce, nil)
end

#gossip_priority_bid(slot_id:, ip:, max_gas:, vault_address: nil) ⇒ Hash

Submit a priority-bid gossip message (L1 action gossipPriorityBid). Used by validators / priority bidders to gossip a bid for a given slot.

Parameters:

  • slot_id (Integer)

    Slot identifier the bid applies to

  • ip (String)

    Bidder IP address (string form expected by the protocol)

  • max_gas (Integer)

    Maximum gas the bidder is willing to pay

  • vault_address (String, nil) (defaults to: nil)

    Vault address if acting on behalf of a vault

Returns:

  • (Hash)

    Exchange response



778
779
780
781
782
783
784
785
786
787
# File 'lib/hyperliquid/exchange.rb', line 778

def gossip_priority_bid(slot_id:, ip:, max_gas:, vault_address: nil)
  nonce = timestamp_ms
  action = { type: 'gossipPriorityBid', slotId: slot_id, ip: ip, maxGas: max_gas }
  signature = @signer.sign_l1_action(
    action, nonce,
    vault_address: vault_address,
    expires_after: @expires_after
  )
  post_action(action, signature, nonce, vault_address)
end

#hip3_liquidator_transfer(dex:, ntl:, is_deposit:) ⇒ Hash

Deposit to or withdraw from an HIP-3 DEX's backstop liquidator (hip3LiquidatorTransfer L1 action). ntl is denominated in 1e-6 quote tokens and the protocol requires it to be a multiple of 1_000_000_000 (i.e. $1,000 increments).

Parameters:

  • dex (String)

    HIP-3 DEX identifier

  • ntl (Integer)

    Notional amount in 1e-6 quote tokens (multiple of 1_000_000_000)

  • is_deposit (Boolean)

    True to deposit into the backstop, false to withdraw

Returns:

  • (Hash)

    Exchange response



1103
1104
1105
1106
1107
1108
1109
1110
1111
# File 'lib/hyperliquid/exchange.rb', line 1103

def hip3_liquidator_transfer(dex:, ntl:, is_deposit:)
  nonce = timestamp_ms
  action = { type: 'hip3LiquidatorTransfer', dex: dex, ntl: ntl, isDeposit: is_deposit }
  signature = @signer.sign_l1_action(
    action, nonce,
    expires_after: @expires_after
  )
  post_action(action, signature, nonce, nil)
end

Link a staking account to a trading account for fee-discount attribution (linkStakingUser user-signed action). The trading user initiates with is_finalize: false; the staking user finalizes the permanent link with is_finalize: true. The user field is the other account address in each direction.

Parameters:

  • user (String)

    The counterpart account address (staking address when initiating, trading when finalizing)

  • is_finalize (Boolean)

    False = trading user initiates, true = staking user finalizes

Returns:

  • (Hash)

    Exchange response



1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
# File 'lib/hyperliquid/exchange.rb', line 1020

def link_staking_user(user:, is_finalize:)
  nonce = timestamp_ms
  action = {
    type: 'linkStakingUser',
    signatureChainId: '0x66eee',
    hyperliquidChain: Signing::EIP712.hyperliquid_chain(testnet: @testnet),
    user: user,
    isFinalize: is_finalize,
    nonce: nonce
  }
  signature = @signer.sign_user_signed_action(
    { user: user, isFinalize: is_finalize, nonce: nonce },
    'HyperliquidTransaction:LinkStakingUser',
    Signing::EIP712::LINK_STAKING_USER_TYPES
  )
  post_action(action, signature, nonce, nil)
end

#market_close(coin:, size: nil, slippage: DEFAULT_SLIPPAGE, cloid: nil, vault_address: nil, builder: nil) ⇒ Hash

Close a position at market price

Parameters:

  • coin (String)

    Asset symbol (perps only)

  • size (Numeric, nil) (defaults to: nil)

    Size to close (nil = close entire position)

  • slippage (Float) (defaults to: DEFAULT_SLIPPAGE)

    Slippage tolerance (default: 5%)

  • cloid (Cloid, String, nil) (defaults to: nil)

    Client order ID (optional)

  • vault_address (String, nil) (defaults to: nil)

    Vault address for vault trading (optional)

  • builder (Hash, nil) (defaults to: nil)

    Builder fee config { b: "0xaddress", f: fee_in_tenths_of_bp } (optional)

Returns:

  • (Hash)

    Order response

Raises:

  • (ArgumentError)


369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
# File 'lib/hyperliquid/exchange.rb', line 369

def market_close(coin:, size: nil, slippage: DEFAULT_SLIPPAGE, cloid: nil, vault_address: nil, builder: nil)
  address = vault_address || @signer.address
  position = find_position(coin, address)
  raise ArgumentError, "No open position found for #{coin}" unless position

  szi = position.dig('position', 'szi').to_f
  is_buy = szi.negative?
  close_size = size || szi.abs
  slippage_price = calculate_slippage_price(coin, get_mid_price(coin), is_buy, slippage)

  order(
    coin: coin, is_buy: is_buy, size: close_size, limit_px: slippage_price,
    order_type: { limit: { tif: 'Ioc' } }, reduce_only: true,
    cloid: cloid, vault_address: vault_address, builder: builder
  )
end

#market_order(coin:, is_buy:, size:, slippage: DEFAULT_SLIPPAGE, vault_address: nil, builder: nil) ⇒ Hash

Place a market order (aggressive limit IoC with slippage)

Parameters:

  • coin (String)

    Asset symbol

  • is_buy (Boolean)

    True for buy, false for sell

  • size (String, Numeric)

    Order size

  • slippage (Float) (defaults to: DEFAULT_SLIPPAGE)

    Slippage tolerance (default: 0.05 = 5%)

  • vault_address (String, nil) (defaults to: nil)

    Vault address for vault trading (optional)

  • builder (Hash, nil) (defaults to: nil)

    Builder fee config { b: "0xaddress", f: fee_in_tenths_of_bp } (optional)

Returns:

  • (Hash)

    Order response

Raises:

  • (ArgumentError)


122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
# File 'lib/hyperliquid/exchange.rb', line 122

def market_order(coin:, is_buy:, size:, slippage: DEFAULT_SLIPPAGE, vault_address: nil, builder: nil)
  # Get current mid price (use dex-specific endpoint for HIP-3 assets)
  dex_prefix = extract_dex_prefix(coin)
  mids = dex_prefix ? @info.all_mids(dex: dex_prefix) : @info.all_mids
  mid = mids[coin]&.to_f
  raise ArgumentError, "Unknown asset or no price available: #{coin}" unless mid&.positive?

  # Apply slippage and round to appropriate precision
  slippage_price = calculate_slippage_price(coin, mid, is_buy, slippage)

  order(
    coin: coin,
    is_buy: is_buy,
    size: size,
    limit_px: slippage_price,
    order_type: { limit: { tif: 'Ioc' } },
    vault_address: vault_address,
    builder: builder
  )
end

#merge_outcome(outcome:, amount: nil) ⇒ Hash

HIP-4: merge amount Yes and amount No shares of an outcome back into amount quote tokens (userOutcome L1 action, mergeOutcome variant). Pass amount: nil to merge the maximum available.

Parameters:

  • outcome (Integer)

    Outcome identifier

  • amount (String, Numeric, nil) (defaults to: nil)

    Amount of shares to merge; nil = maximum available

Returns:

  • (Hash)

    Exchange response



1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
# File 'lib/hyperliquid/exchange.rb', line 1311

def merge_outcome(outcome:, amount: nil)
  nonce = timestamp_ms
  action = {
    type: 'userOutcome',
    mergeOutcome: { outcome: outcome, amount: amount&.to_s }
  }
  signature = @signer.sign_l1_action(
    action, nonce,
    expires_after: @expires_after
  )
  post_action(action, signature, nonce, nil)
end

#merge_question(question:, amount: nil) ⇒ Hash

HIP-4: merge amount Yes shares from every outcome of a question into amount quote tokens (userOutcome L1 action, mergeQuestion variant). Pass amount: nil to merge the maximum available.

Parameters:

  • question (Integer)

    Question identifier

  • amount (String, Numeric, nil) (defaults to: nil)

    Amount of shares to merge; nil = maximum available

Returns:

  • (Hash)

    Exchange response



1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
# File 'lib/hyperliquid/exchange.rb', line 1330

def merge_question(question:, amount: nil)
  nonce = timestamp_ms
  action = {
    type: 'userOutcome',
    mergeQuestion: { question: question, amount: amount&.to_s }
  }
  signature = @signer.sign_l1_action(
    action, nonce,
    expires_after: @expires_after
  )
  post_action(action, signature, nonce, nil)
end

#modify_order(oid:, coin:, is_buy:, size:, limit_px:, order_type: { limit: { tif: 'Gtc' } }, reduce_only: false, cloid: nil, vault_address: nil, always_place: nil) ⇒ Hash

Modify a single existing order

Parameters:

  • oid (Integer, Cloid, String)

    Order ID or client order ID to modify

  • coin (String)

    Asset symbol (e.g., "BTC")

  • is_buy (Boolean)

    True for buy, false for sell

  • size (String, Numeric)

    New order size

  • limit_px (String, Numeric)

    New limit price

  • order_type (Hash) (defaults to: { limit: { tif: 'Gtc' } })

    Order type config (default: { limit: { tif: "Gtc" } })

  • reduce_only (Boolean) (defaults to: false)

    Reduce-only flag (default: false)

  • cloid (Cloid, String, nil) (defaults to: nil)

    Client order ID for the modified order (optional)

  • vault_address (String, nil) (defaults to: nil)

    Vault address for vault trading (optional)

  • always_place (Boolean, nil) (defaults to: nil)

    Always place the order even if cancel fails (optional)

Returns:

  • (Hash)

    Modify response



246
247
248
249
250
251
252
253
254
255
256
257
258
# File 'lib/hyperliquid/exchange.rb', line 246

def modify_order(oid:, coin:, is_buy:, size:, limit_px:,
                 order_type: { limit: { tif: 'Gtc' } },
                 reduce_only: false, cloid: nil, vault_address: nil, always_place: nil)
  batch_modify(
    modifies: [{
      oid: oid, coin: coin, is_buy: is_buy, size: size,
      limit_px: limit_px, order_type: order_type,
      reduce_only: reduce_only, cloid: cloid,
      always_place: always_place
    }],
    vault_address: vault_address
  )
end

#multi_sig(multi_sig_user:, inner_action:, signatures:, nonce: nil, vault_address: nil) ⇒ Hash

Submit a multi-signature action wrapping any inner exchange action with N pre-collected co-signer signatures (multiSig user-signed envelope). The submitter's outer signature authorises execution; co-signer signatures must be collected externally via Signing::MultiSig.sign_as_co_signer_l1 (for L1 inner actions) or Signing::MultiSig.sign_as_co_signer_user_signed (for user-signed inner actions).

Parameters:

  • multi_sig_user (String)

    Address of the multi-sig user being acted on

  • inner_action (Hash)

    The wrapped action body

  • signatures (Array<Hash>)

    Co-signer signatures (each :r, :s, :v)

  • nonce (Integer, nil) (defaults to: nil)

    Nonce timestamp; defaults to timestamp_ms. Must match the nonce used by every co-signer when they signed.

  • vault_address (String, nil) (defaults to: nil)

    Optional vault address (must match co-signer hashes)

Returns:

  • (Hash)

    Exchange response



826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
# File 'lib/hyperliquid/exchange.rb', line 826

def multi_sig(multi_sig_user:, inner_action:, signatures:, nonce: nil, vault_address: nil)
  nonce ||= timestamp_ms
  envelope = Signing::MultiSig.build_envelope(
    inner_action: inner_action,
    multi_sig_user: multi_sig_user,
    outer_signer: @signer.address,
    signatures: signatures
  )
  multi_sig_action_hash = Signing::MultiSig.envelope_action_hash(
    envelope: envelope,
    nonce: nonce,
    vault_address: vault_address,
    expires_after: @expires_after
  )
  signature = @signer.sign_user_signed_action(
    { multiSigActionHash: multi_sig_action_hash, nonce: nonce },
    Signing::MultiSig::OUTER_PRIMARY_TYPE,
    Signing::EIP712::MULTI_SIG_TYPES
  )
  post_action(envelope, signature, nonce, vault_address)
end

#negate_outcome(question:, outcome:, amount:) ⇒ Hash

HIP-4: convert amount No shares from one outcome of a question into amount Yes shares of every other outcome associated with that question (userOutcome L1 action, negateOutcome variant).

Parameters:

  • question (Integer)

    Question identifier

  • outcome (Integer)

    Outcome identifier whose No shares are being negated

  • amount (String, Numeric)

    Amount of No shares to negate (UnsignedDecimal, coerced via to_s)

Returns:

  • (Hash)

    Exchange response



1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
# File 'lib/hyperliquid/exchange.rb', line 1350

def negate_outcome(question:, outcome:, amount:)
  nonce = timestamp_ms
  action = {
    type: 'userOutcome',
    negateOutcome: { question: question, outcome: outcome, amount: amount.to_s }
  }
  signature = @signer.sign_l1_action(
    action, nonce,
    expires_after: @expires_after
  )
  post_action(action, signature, nonce, nil)
end

#noop(nonce: nil, vault_address: nil) ⇒ Hash

No-op L1 action — useful for burning a specific nonce slot without side effects.

Parameters:

  • nonce (Integer, nil) (defaults to: nil)

    Nonce to consume (defaults to current timestamp_ms)

  • vault_address (String, nil) (defaults to: nil)

    Vault address if acting on behalf of a vault

Returns:

  • (Hash)

    Exchange response



760
761
762
763
764
765
766
767
768
769
# File 'lib/hyperliquid/exchange.rb', line 760

def noop(nonce: nil, vault_address: nil)
  nonce ||= timestamp_ms
  action = { type: 'noop' }
  signature = @signer.sign_l1_action(
    action, nonce,
    vault_address: vault_address,
    expires_after: @expires_after
  )
  post_action(action, signature, nonce, vault_address)
end

#order(coin:, is_buy:, size:, limit_px:, order_type: { limit: { tif: 'Gtc' } }, reduce_only: false, cloid: nil, vault_address: nil, builder: nil) ⇒ Hash

Place a single order

Parameters:

  • coin (String)

    Asset symbol (e.g., "BTC")

  • is_buy (Boolean)

    True for buy, false for sell

  • size (String, Numeric)

    Order size

  • limit_px (String, Numeric)

    Limit price

  • order_type (Hash) (defaults to: { limit: { tif: 'Gtc' } })

    Order type config (default: { limit: { tif: "Gtc" } })

  • reduce_only (Boolean) (defaults to: false)

    Reduce-only flag (default: false)

  • cloid (Cloid, String, nil) (defaults to: nil)

    Client order ID (optional)

  • vault_address (String, nil) (defaults to: nil)

    Vault address for vault trading (optional)

  • builder (Hash, nil) (defaults to: nil)

    Builder fee config { b: "0xaddress", f: fee_in_tenths_of_bp } (optional)

Returns:

  • (Hash)

    Order response



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
# File 'lib/hyperliquid/exchange.rb', line 48

def order(coin:, is_buy:, size:, limit_px:, order_type: { limit: { tif: 'Gtc' } },
          reduce_only: false, cloid: nil, vault_address: nil, builder: nil)
  nonce = timestamp_ms

  order_wire = build_order_wire(
    coin: coin,
    is_buy: is_buy,
    size: size,
    limit_px: limit_px,
    order_type: order_type,
    reduce_only: reduce_only,
    cloid: cloid
  )

  action = {
    type: 'order',
    orders: [order_wire],
    grouping: 'na'
  }
  action[:builder] = normalize_builder(builder) if builder

  signature = @signer.sign_l1_action(
    action, nonce,
    vault_address: vault_address,
    expires_after: @expires_after
  )
  post_action(action, signature, nonce, vault_address)
end

#register_referrer(code:) ⇒ Hash

Register a new referral code for this account (registerReferrer L1 action). Distinct from set_referrer, which records a referrer the account was referred by.

Parameters:

  • code (String)

    Referral code to create (1–20 characters)

Returns:

  • (Hash)

    Exchange response



878
879
880
881
882
883
884
885
886
# File 'lib/hyperliquid/exchange.rb', line 878

def register_referrer(code:)
  nonce = timestamp_ms
  action = { type: 'registerReferrer', code: code }
  signature = @signer.sign_l1_action(
    action, nonce,
    expires_after: @expires_after
  )
  post_action(action, signature, nonce, nil)
end

#reload_metadata!Object

Clear the asset metadata cache Call this if metadata has been updated



1430
1431
1432
# File 'lib/hyperliquid/exchange.rb', line 1430

def reload_metadata!
  @asset_cache = nil
end

#reserve_request_weight(weight:, destination: nil) ⇒ Hash

Reserve additional rate-limited actions for a fee (reserveRequestWeight L1 action).

Parameters:

  • weight (Integer)

    Amount of request weight to reserve

  • destination (String, nil) (defaults to: nil)

    Address of an existing user to reserve the weight for; nil omits the field

Returns:

  • (Hash)

    Exchange response



1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
# File 'lib/hyperliquid/exchange.rb', line 1276

def reserve_request_weight(weight:, destination: nil)
  nonce = timestamp_ms
  action = { type: 'reserveRequestWeight', weight: weight }
  action[:destination] = destination unless destination.nil?
  signature = @signer.sign_l1_action(
    action, nonce,
    expires_after: @expires_after
  )
  post_action(action, signature, nonce, nil)
end

#schedule_cancel(time: nil, vault_address: nil) ⇒ Hash

Schedule automatic cancellation of all orders

Parameters:

  • time (Integer, nil) (defaults to: nil)

    UTC timestamp in milliseconds to cancel at (nil to activate with server default)

  • vault_address (String, nil) (defaults to: nil)

    Vault address for vault trading (optional)

Returns:

  • (Hash)

    Schedule cancel response



347
348
349
350
351
352
353
354
355
356
357
358
359
# File 'lib/hyperliquid/exchange.rb', line 347

def schedule_cancel(time: nil, vault_address: nil)
  nonce = timestamp_ms

  action = { type: 'scheduleCancel' }
  action[:time] = time if time

  signature = @signer.sign_l1_action(
    action, nonce,
    vault_address: vault_address,
    expires_after: @expires_after
  )
  post_action(action, signature, nonce, vault_address)
end

#send_asset(destination:, source_dex:, destination_dex:, token:, amount:) ⇒ Hash

Move assets between DEX instances

Parameters:

  • destination (String)

    Destination wallet address

  • source_dex (String)

    Source DEX identifier

  • destination_dex (String)

    Destination DEX identifier

  • token (String)

    Token identifier

  • amount (String, Numeric)

    Amount to send

Returns:

  • (Hash)

    Transfer response



489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
# File 'lib/hyperliquid/exchange.rb', line 489

def send_asset(destination:, source_dex:, destination_dex:, token:, amount:)
  nonce = timestamp_ms
  action = {
    type: 'sendAsset',
    signatureChainId: '0x66eee',
    hyperliquidChain: Signing::EIP712.hyperliquid_chain(testnet: @testnet),
    destination: destination,
    sourceDex: source_dex,
    destinationDex: destination_dex,
    token: token,
    amount: amount.to_s,
    fromSubAccount: '',
    nonce: nonce
  }
  signature = @signer.sign_user_signed_action(
    {
      destination: destination, sourceDex: source_dex, destinationDex: destination_dex,
      token: token, amount: amount.to_s, fromSubAccount: '', nonce: nonce
    },
    'HyperliquidTransaction:SendAsset',
    Signing::EIP712::SEND_ASSET_TYPES
  )
  post_action(action, signature, nonce, nil)
end

#send_to_evm_with_data(token:, amount:, source_dex:, destination_recipient:, address_encoding:, destination_chain_id:, gas_limit:, data: '0x') ⇒ Hash

Transfer an asset from Core to HyperEVM with an arbitrary calldata payload (sendToEvmWithData user-signed action). Intended for ICoreReceiveWithData contracts that react atomically to the deposit. data accepts a hex string ('0x' or '0x...'); the EIP-712 signer hashes it as bytes. destination_recipient is NOT lowercased — address_encoding may be 'base58' for non-EVM target chains, where lowercasing would corrupt the value.

Parameters:

  • token (String)

    Token symbol (e.g. "USDC")

  • amount (String, Numeric)

    Amount as UnsignedDecimal (NOT wei); coerced via to_s

  • source_dex (String)

    Source DEX identifier (e.g. "spot")

  • destination_recipient (String)

    Recipient address on the destination chain (hex or base58)

  • address_encoding (String)

    One of 'hex' or 'base58'

  • destination_chain_id (Integer)

    Target EVM chain id (e.g. 998 for HyperEVM testnet)

  • gas_limit (Integer)

    Gas limit for the destination EVM call

  • data (String) (defaults to: '0x')

    ABI calldata hex string ('0x' for empty payload)

Returns:

  • (Hash)

    Exchange response



1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
# File 'lib/hyperliquid/exchange.rb', line 1128

def send_to_evm_with_data(token:, amount:, source_dex:, destination_recipient:,
                          address_encoding:, destination_chain_id:, gas_limit:, data: '0x')
  nonce = timestamp_ms
  action = {
    type: 'sendToEvmWithData',
    signatureChainId: '0x66eee',
    hyperliquidChain: Signing::EIP712.hyperliquid_chain(testnet: @testnet),
    token: token,
    amount: amount.to_s,
    sourceDex: source_dex,
    destinationRecipient: destination_recipient,
    addressEncoding: address_encoding,
    destinationChainId: destination_chain_id.to_i,
    gasLimit: gas_limit.to_i,
    data: data,
    nonce: nonce
  }
  signature = @signer.sign_user_signed_action(
    { token: token, amount: amount.to_s, sourceDex: source_dex,
      destinationRecipient: destination_recipient, addressEncoding: address_encoding,
      destinationChainId: destination_chain_id.to_i, gasLimit: gas_limit.to_i,
      data: data, nonce: nonce },
    'HyperliquidTransaction:SendToEvmWithData',
    Signing::EIP712::SEND_TO_EVM_WITH_DATA_TYPES
  )
  post_action(action, signature, nonce, nil)
end

#set_display_name(display_name:) ⇒ Hash

Set the leaderboard display name (setDisplayName L1 action). Pass an empty string to remove the existing display name.

Parameters:

  • display_name (String)

    Display name (max 20 characters)

Returns:

  • (Hash)

    Exchange response



864
865
866
867
868
869
870
871
872
# File 'lib/hyperliquid/exchange.rb', line 864

def set_display_name(display_name:)
  nonce = timestamp_ms
  action = { type: 'setDisplayName', displayName: display_name }
  signature = @signer.sign_l1_action(
    action, nonce,
    expires_after: @expires_after
  )
  post_action(action, signature, nonce, nil)
end

#set_referrer(code:) ⇒ Hash

Set referral code

Parameters:

  • code (String)

    Referral code

Returns:

  • (Hash)

    Set referrer response



580
581
582
583
584
585
# File 'lib/hyperliquid/exchange.rb', line 580

def set_referrer(code:)
  nonce = timestamp_ms
  action = { type: 'setReferrer', code: code }
  signature = @signer.sign_l1_action(action, nonce)
  post_action(action, signature, nonce, nil)
end

#split_outcome(outcome:, amount:) ⇒ Hash

HIP-4: split amount quote tokens into amount Yes and amount No shares of an outcome (userOutcome L1 action, splitOutcome variant).

Parameters:

  • outcome (Integer)

    Outcome identifier

  • amount (String, Numeric)

    Amount of quote tokens to split (UnsignedDecimal, coerced via to_s)

Returns:

  • (Hash)

    Exchange response



1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
# File 'lib/hyperliquid/exchange.rb', line 1292

def split_outcome(outcome:, amount:)
  nonce = timestamp_ms
  action = {
    type: 'userOutcome',
    splitOutcome: { outcome: outcome, amount: amount.to_s }
  }
  signature = @signer.sign_l1_action(
    action, nonce,
    expires_after: @expires_after
  )
  post_action(action, signature, nonce, nil)
end

#spot_send(amount:, destination:, token:) ⇒ Hash

Transfer a spot token to another address

Parameters:

  • amount (String, Numeric)

    Amount to send

  • destination (String)

    Destination wallet address

  • token (String)

    Token identifier

Returns:

  • (Hash)

    Transfer response



413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
# File 'lib/hyperliquid/exchange.rb', line 413

def spot_send(amount:, destination:, token:)
  nonce = timestamp_ms
  action = {
    type: 'spotSend',
    signatureChainId: '0x66eee',
    hyperliquidChain: Signing::EIP712.hyperliquid_chain(testnet: @testnet),
    destination: destination,
    token: token,
    amount: amount.to_s,
    time: nonce
  }
  signature = @signer.sign_user_signed_action(
    { destination: destination, token: token, amount: amount.to_s, time: nonce },
    'HyperliquidTransaction:SpotSend',
    Signing::EIP712::SPOT_SEND_TYPES
  )
  post_action(action, signature, nonce, nil)
end

#spot_user(opt_out:) ⇒ Hash

Opt in or out of spot dusting (spotUser L1 action). Spot dusting is the protocol's automatic conversion of small spot balances. Despite the generic action name, this method exclusively toggles that opt-out flag.

Parameters:

  • opt_out (Boolean)

    True to opt out of spot dusting, false to opt in

Returns:

  • (Hash)

    Exchange response



1404
1405
1406
1407
1408
1409
1410
1411
1412
# File 'lib/hyperliquid/exchange.rb', line 1404

def spot_user(opt_out:)
  nonce = timestamp_ms
  action = { type: 'spotUser', toggleSpotDusting: { optOut: opt_out } }
  signature = @signer.sign_l1_action(
    action, nonce,
    expires_after: @expires_after
  )
  post_action(action, signature, nonce, nil)
end

Permanently disable a linked trading user, locking its funds (stakingLinkDisableTradingUser user-signed action). Sent by the staking user. After 1 year of locking, funds from the trading user are automatically transferred to the staking user. This action is irreversible. The trading_user address is lowercased to match the address-field convention used by other user-signed actions.

Parameters:

  • trading_user (String)

    Trading user address to disable

Returns:

  • (Hash)

    Exchange response



1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
# File 'lib/hyperliquid/exchange.rb', line 1045

def staking_link_disable_trading_user(trading_user:)
  nonce = timestamp_ms
  trading_user_lower = trading_user.downcase
  action = {
    type: 'stakingLinkDisableTradingUser',
    signatureChainId: '0x66eee',
    hyperliquidChain: Signing::EIP712.hyperliquid_chain(testnet: @testnet),
    tradingUser: trading_user_lower,
    nonce: nonce
  }
  signature = @signer.sign_user_signed_action(
    { tradingUser: trading_user_lower, nonce: nonce },
    'HyperliquidTransaction:StakingLinkDisableTradingUser',
    Signing::EIP712::STAKING_LINK_DISABLE_TRADING_USER_TYPES
  )
  post_action(action, signature, nonce, nil)
end

#sub_account_modify(sub_account_user:, name:) ⇒ Hash

Rename a sub-account (subAccountModify L1 action).

Parameters:

  • sub_account_user (String)

    Sub-account wallet address to rename

  • name (String)

    New sub-account name (1–16 characters)

Returns:

  • (Hash)

    Exchange response



998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
# File 'lib/hyperliquid/exchange.rb', line 998

def (sub_account_user:, name:)
  nonce = timestamp_ms
  action = {
    type: 'subAccountModify',
    subAccountUser: ,
    name: name
  }
  signature = @signer.sign_l1_action(
    action, nonce,
    expires_after: @expires_after
  )
  post_action(action, signature, nonce, nil)
end

#sub_account_spot_transfer(sub_account_user:, is_deposit:, token:, amount:) ⇒ Hash

Transfer spot tokens to/from a sub-account

Parameters:

  • sub_account_user (String)

    Sub-account wallet address

  • is_deposit (Boolean)

    True to deposit into sub-account, false to withdraw

  • token (String)

    Token identifier

  • amount (String, Numeric)

    Amount to transfer

Returns:

  • (Hash)

    Transfer response



547
548
549
550
551
552
553
554
555
556
557
558
# File 'lib/hyperliquid/exchange.rb', line 547

def (sub_account_user:, is_deposit:, token:, amount:)
  nonce = timestamp_ms
  action = {
    type: 'subAccountSpotTransfer',
    subAccountUser: ,
    isDeposit: is_deposit,
    token: token,
    amount: amount.to_s
  }
  signature = @signer.sign_l1_action(action, nonce)
  post_action(action, signature, nonce, nil)
end

#sub_account_transfer(sub_account_user:, is_deposit:, usd:) ⇒ Hash

Transfer USDC to/from a sub-account

Parameters:

  • sub_account_user (String)

    Sub-account wallet address

  • is_deposit (Boolean)

    True to deposit into sub-account, false to withdraw

  • usd (Numeric)

    Amount in USD

Returns:

  • (Hash)

    Transfer response



529
530
531
532
533
534
535
536
537
538
539
# File 'lib/hyperliquid/exchange.rb', line 529

def (sub_account_user:, is_deposit:, usd:)
  nonce = timestamp_ms
  action = {
    type: 'subAccountTransfer',
    subAccountUser: ,
    isDeposit: is_deposit,
    usd: float_to_usd_int(usd)
  }
  signature = @signer.sign_l1_action(action, nonce)
  post_action(action, signature, nonce, nil)
end

#token_delegate(validator:, wei:, is_undelegate:) ⇒ Hash

Delegate or undelegate HYPE tokens to a validator

Parameters:

  • validator (String)

    Validator's Ethereum address

  • wei (Integer)

    Amount as float * 1e8 (e.g., 1 HYPE = 100_000_000)

  • is_undelegate (Boolean)

    True to undelegate, false to delegate

Returns:

  • (Hash)

    Token delegate response



639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
# File 'lib/hyperliquid/exchange.rb', line 639

def token_delegate(validator:, wei:, is_undelegate:)
  nonce = timestamp_ms
  action = {
    type: 'tokenDelegate',
    signatureChainId: '0x66eee',
    hyperliquidChain: Signing::EIP712.hyperliquid_chain(testnet: @testnet),
    validator: validator,
    wei: wei,
    isUndelegate: is_undelegate,
    nonce: nonce
  }
  signature = @signer.sign_user_signed_action(
    { validator: validator, wei: wei, isUndelegate: is_undelegate, nonce: nonce },
    'HyperliquidTransaction:TokenDelegate',
    Signing::EIP712::TOKEN_DELEGATE_TYPES
  )
  post_action(action, signature, nonce, nil)
end

#top_up_isolated_only_margin(coin:, leverage:, vault_address: nil) ⇒ Hash

Top up isolated margin to target a specific leverage (topUpIsolatedOnlyMargin L1 action).

Parameters:

  • coin (String)

    Asset symbol (perps only)

  • leverage (String, Numeric)

    Target leverage (sent as float string per protocol)

  • vault_address (String, nil) (defaults to: nil)

    Vault address if acting on behalf of a vault

Returns:

  • (Hash)

    Exchange response



893
894
895
896
897
898
899
900
901
902
903
904
905
906
# File 'lib/hyperliquid/exchange.rb', line 893

def top_up_isolated_only_margin(coin:, leverage:, vault_address: nil)
  nonce = timestamp_ms
  action = {
    type: 'topUpIsolatedOnlyMargin',
    asset: asset_index(coin),
    leverage: leverage.to_s
  }
  signature = @signer.sign_l1_action(
    action, nonce,
    vault_address: vault_address,
    expires_after: @expires_after
  )
  post_action(action, signature, nonce, vault_address)
end

#twap_cancel(coin:, twap_id:, vault_address: nil) ⇒ Hash

Cancel a TWAP order by id (twapCancel L1 action).

Parameters:

  • coin (String)

    Asset symbol the TWAP applies to

  • twap_id (Integer)

    TWAP id returned by twap_order

  • vault_address (String, nil) (defaults to: nil)

    Vault address if acting on behalf of a vault

Returns:

  • (Hash)

    Exchange response



1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
# File 'lib/hyperliquid/exchange.rb', line 1261

def twap_cancel(coin:, twap_id:, vault_address: nil)
  nonce = timestamp_ms
  action = { type: 'twapCancel', a: asset_index(coin), t: twap_id }
  signature = @signer.sign_l1_action(
    action, nonce,
    vault_address: vault_address,
    expires_after: @expires_after
  )
  post_action(action, signature, nonce, vault_address)
end

#twap_order(coin:, is_buy:, size:, reduce_only:, minutes:, randomize:, vault_address: nil, details: nil) ⇒ Hash

Place a TWAP order (twapOrder L1 action). The order is sliced over minutes minutes (5..1440). When randomize is true the protocol randomizes the timing of individual child orders. size is denominated in base currency units.

Parameters:

  • coin (String)

    Asset symbol

  • is_buy (Boolean)

    True for buy/long, false for sell/short

  • size (String, Numeric)

    Total order size (base currency units)

  • reduce_only (Boolean)

    Reduce-only flag

  • minutes (Integer)

    TWAP duration in minutes (5..1440)

  • randomize (Boolean)

    Randomize order timing

  • vault_address (String, nil) (defaults to: nil)

    Vault address if acting on behalf of a vault

  • details (Hash, nil) (defaults to: nil)

    Optional trigger/stop price config: { t: { p:, a: } | nil, s: | nil }

Returns:

  • (Hash)

    Exchange response — on success response.data.status.running.twapId



1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
# File 'lib/hyperliquid/exchange.rb', line 1234

def twap_order(coin:, is_buy:, size:, reduce_only:, minutes:, randomize:, vault_address: nil, details: nil)
  nonce = timestamp_ms
  action = {
    type: 'twapOrder',
    twap: {
      a: asset_index(coin),
      b: is_buy,
      s: float_to_wire(size),
      r: reduce_only,
      m: minutes,
      t: randomize
    }
  }
  action[:details] = details unless details.nil?
  signature = @signer.sign_l1_action(
    action, nonce,
    vault_address: vault_address,
    expires_after: @expires_after
  )
  post_action(action, signature, nonce, vault_address)
end

#update_isolated_margin(coin:, amount:, vault_address: nil) ⇒ Hash

Add or remove isolated margin for a position

Parameters:

  • coin (String)

    Asset symbol (perps only)

  • amount (Numeric)

    Amount in USD (positive to add, negative to remove)

  • vault_address (String, nil) (defaults to: nil)

    Vault address for vault trading (optional)

Returns:

  • (Hash)

    Margin update response



325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
# File 'lib/hyperliquid/exchange.rb', line 325

def update_isolated_margin(coin:, amount:, vault_address: nil)
  nonce = timestamp_ms

  action = {
    type: 'updateIsolatedMargin',
    asset: asset_index(coin),
    isBuy: true,
    ntli: float_to_usd_int(amount)
  }

  signature = @signer.sign_l1_action(
    action, nonce,
    vault_address: vault_address,
    expires_after: @expires_after
  )
  post_action(action, signature, nonce, vault_address)
end

#update_leverage(coin:, leverage:, is_cross: true, vault_address: nil) ⇒ Hash

Set cross or isolated leverage for a coin

Parameters:

  • coin (String)

    Asset symbol (perps only)

  • leverage (Integer)

    Leverage value

  • is_cross (Boolean) (defaults to: true)

    True for cross margin, false for isolated (default: true)

  • vault_address (String, nil) (defaults to: nil)

    Vault address for vault trading (optional)

Returns:

  • (Hash)

    Leverage update response



302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
# File 'lib/hyperliquid/exchange.rb', line 302

def update_leverage(coin:, leverage:, is_cross: true, vault_address: nil)
  nonce = timestamp_ms

  action = {
    type: 'updateLeverage',
    asset: asset_index(coin),
    isCross: is_cross,
    leverage: leverage
  }

  signature = @signer.sign_l1_action(
    action, nonce,
    vault_address: vault_address,
    expires_after: @expires_after
  )
  post_action(action, signature, nonce, vault_address)
end

#usd_class_transfer(amount:, to_perp:, sub_account: nil) ⇒ Hash

Move USDC between perp and spot accounts

Parameters:

  • amount (String, Numeric)

    Amount to transfer

  • to_perp (Boolean)

    True to move to perp, false to move to spot

  • sub_account (String, nil) (defaults to: nil)

    Optional sub-account address (0x-prefixed hex). When provided, the transfer targets the sub-account rather than the master account; the suffix subaccount:<address> is appended to the signed amount string (mirrors TS SDK v0.33.1's amount union shape).

Returns:

  • (Hash)

    Transfer response



440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
# File 'lib/hyperliquid/exchange.rb', line 440

def usd_class_transfer(amount:, to_perp:, sub_account: nil)
  nonce = timestamp_ms
  amount_str = amount.to_s
  amount_str = "#{amount_str} subaccount:#{}" if 
  action = {
    type: 'usdClassTransfer',
    signatureChainId: '0x66eee',
    hyperliquidChain: Signing::EIP712.hyperliquid_chain(testnet: @testnet),
    amount: amount_str,
    toPerp: to_perp,
    nonce: nonce
  }
  signature = @signer.sign_user_signed_action(
    { amount: amount_str, toPerp: to_perp, nonce: nonce },
    'HyperliquidTransaction:UsdClassTransfer',
    Signing::EIP712::USD_CLASS_TRANSFER_TYPES
  )
  post_action(action, signature, nonce, nil)
end

#usd_send(amount:, destination:) ⇒ Hash

Transfer USDC to another address

Parameters:

  • amount (String, Numeric)

    Amount to send

  • destination (String)

    Destination wallet address

Returns:

  • (Hash)

    Transfer response



390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
# File 'lib/hyperliquid/exchange.rb', line 390

def usd_send(amount:, destination:)
  nonce = timestamp_ms
  action = {
    type: 'usdSend',
    signatureChainId: '0x66eee',
    hyperliquidChain: Signing::EIP712.hyperliquid_chain(testnet: @testnet),
    destination: destination,
    amount: amount.to_s,
    time: nonce
  }
  signature = @signer.sign_user_signed_action(
    { destination: destination, amount: amount.to_s, time: nonce },
    'HyperliquidTransaction:UsdSend',
    Signing::EIP712::USD_SEND_TYPES
  )
  post_action(action, signature, nonce, nil)
end

#use_big_blocks(enable:) ⇒ Hash

Toggle EVM big-blocks mode for this account (evmUserModify L1 action). When enabled, EVM transactions from this account are routed to big blocks.

Parameters:

  • enable (Boolean)

    True to enable big blocks, false to disable

Returns:

  • (Hash)

    Exchange response



746
747
748
749
750
751
752
753
754
# File 'lib/hyperliquid/exchange.rb', line 746

def use_big_blocks(enable:)
  nonce = timestamp_ms
  action = { type: 'evmUserModify', usingBigBlocks: enable }
  signature = @signer.sign_l1_action(
    action, nonce,
    expires_after: @expires_after
  )
  post_action(action, signature, nonce, nil)
end

#user_dex_abstraction(enabled:, user: nil) ⇒ Hash

Enable or disable HIP-3 DEX abstraction for automatic collateral transfers When enabled, collateral is automatically transferred to HIP-3 dexes when trading

Parameters:

  • enabled (Boolean)

    True to enable, false to disable DEX abstraction

  • user (String, nil) (defaults to: nil)

    User address (defaults to signer address)

Returns:

  • (Hash)

    User DEX abstraction response



663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
# File 'lib/hyperliquid/exchange.rb', line 663

def user_dex_abstraction(enabled:, user: nil)
  nonce = timestamp_ms
  user_address = user || @signer.address
  action = {
    type: 'userDexAbstraction',
    signatureChainId: '0x66eee',
    hyperliquidChain: Signing::EIP712.hyperliquid_chain(testnet: @testnet),
    user: user_address,
    enabled: enabled,
    nonce: nonce
  }
  signature = @signer.sign_user_signed_action(
    { user: user_address, enabled: enabled, nonce: nonce },
    'HyperliquidTransaction:UserDexAbstraction',
    Signing::EIP712::USER_DEX_ABSTRACTION_TYPES
  )
  post_action(action, signature, nonce, nil)
end

#user_portfolio_margin(user:, enabled:) ⇒ Hash

Toggle cross-portfolio-margin mode for a user (userPortfolioMargin user-signed action). The user address is lowercased to match the Python SDK and protocol expectations.

Parameters:

  • user (String)

    Wallet address whose portfolio-margin mode is being toggled

  • enabled (Boolean)

    True to enable cross-portfolio margin, false to disable

Returns:

  • (Hash)

    Exchange response



1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
# File 'lib/hyperliquid/exchange.rb', line 1161

def user_portfolio_margin(user:, enabled:)
  nonce = timestamp_ms
  user_lower = user.downcase
  action = {
    type: 'userPortfolioMargin',
    signatureChainId: '0x66eee',
    hyperliquidChain: Signing::EIP712.hyperliquid_chain(testnet: @testnet),
    user: user_lower,
    enabled: enabled,
    nonce: nonce
  }
  signature = @signer.sign_user_signed_action(
    { user: user_lower, enabled: enabled, nonce: nonce },
    'HyperliquidTransaction:UserPortfolioMargin',
    Signing::EIP712::USER_PORTFOLIO_MARGIN_TYPES
  )
  post_action(action, signature, nonce, nil)
end

#user_set_abstraction(user:, abstraction:) ⇒ Hash

Set the abstraction mode for a user (userSetAbstraction user-signed action). The user address is lowercased to match the Python SDK and protocol expectations.

Parameters:

  • user (String)

    Wallet address whose abstraction is being set

  • abstraction (String)

    One of 'u' (unified), 'p' (portfolio margin), 'i' (isolated/disabled)

Returns:

  • (Hash)

    Exchange response



717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
# File 'lib/hyperliquid/exchange.rb', line 717

def user_set_abstraction(user:, abstraction:)
  nonce = timestamp_ms
  user_lower = user.downcase
  action = {
    type: 'userSetAbstraction',
    signatureChainId: '0x66eee',
    hyperliquidChain: Signing::EIP712.hyperliquid_chain(testnet: @testnet),
    user: user_lower,
    abstraction: abstraction,
    nonce: nonce
  }
  signature = @signer.sign_user_signed_action(
    { user: user_lower, abstraction: abstraction, nonce: nonce },
    'HyperliquidTransaction:UserSetAbstraction',
    Signing::EIP712::USER_SET_ABSTRACTION_TYPES
  )
  post_action(action, signature, nonce, nil)
end

#vault_distribute(vault_address:, usd:) ⇒ Hash

Distribute funds from a vault to followers (vaultDistribute L1 action). Only the vault leader may submit this. Pass usd: 0 to close the vault.

Parameters:

  • vault_address (String)

    Vault address

  • usd (Numeric)

    USD amount to distribute (scaled to integer cents-of-cents internally)

Returns:

  • (Hash)

    Exchange response



934
935
936
937
938
939
940
941
942
943
944
945
946
# File 'lib/hyperliquid/exchange.rb', line 934

def vault_distribute(vault_address:, usd:)
  nonce = timestamp_ms
  action = {
    type: 'vaultDistribute',
    vaultAddress: vault_address,
    usd: float_to_usd_int(usd)
  }
  signature = @signer.sign_l1_action(
    action, nonce,
    expires_after: @expires_after
  )
  post_action(action, signature, nonce, nil)
end

#vault_modify(vault_address:, allow_deposits: nil, always_close_on_withdraw: nil) ⇒ Hash

Modify a vault's configuration (vaultModify L1 action). Only the vault leader may submit this. Either flag may be omitted (sent as null).

Parameters:

  • vault_address (String)

    Vault address being modified

  • allow_deposits (Boolean, nil) (defaults to: nil)

    Allow follower deposits (nil = unchanged)

  • always_close_on_withdraw (Boolean, nil) (defaults to: nil)

    Always close positions on withdrawal (nil = unchanged)

Returns:

  • (Hash)

    Exchange response



914
915
916
917
918
919
920
921
922
923
924
925
926
927
# File 'lib/hyperliquid/exchange.rb', line 914

def vault_modify(vault_address:, allow_deposits: nil, always_close_on_withdraw: nil)
  nonce = timestamp_ms
  action = {
    type: 'vaultModify',
    vaultAddress: vault_address,
    allowDeposits: allow_deposits,
    alwaysCloseOnWithdraw: always_close_on_withdraw
  }
  signature = @signer.sign_l1_action(
    action, nonce,
    expires_after: @expires_after
  )
  post_action(action, signature, nonce, nil)
end

#vault_transfer(vault_address:, is_deposit:, usd:) ⇒ Hash

Deposit or withdraw USDC to/from a vault

Parameters:

  • vault_address (String)

    Vault wallet address

  • is_deposit (Boolean)

    True to deposit, false to withdraw

  • usd (Numeric)

    Amount in USD

Returns:

  • (Hash)

    Vault transfer response



565
566
567
568
569
570
571
572
573
574
575
# File 'lib/hyperliquid/exchange.rb', line 565

def vault_transfer(vault_address:, is_deposit:, usd:)
  nonce = timestamp_ms
  action = {
    type: 'vaultTransfer',
    vaultAddress: vault_address,
    isDeposit: is_deposit,
    usd: float_to_usd_int(usd)
  }
  signature = @signer.sign_l1_action(action, nonce)
  post_action(action, signature, nonce, nil)
end

#withdraw_from_bridge(amount:, destination:) ⇒ Hash

Withdraw USDC via the bridge

Parameters:

  • amount (String, Numeric)

    Amount to withdraw

  • destination (String)

    Destination wallet address

Returns:

  • (Hash)

    Withdrawal response



464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
# File 'lib/hyperliquid/exchange.rb', line 464

def withdraw_from_bridge(amount:, destination:)
  nonce = timestamp_ms
  action = {
    type: 'withdraw3',
    signatureChainId: '0x66eee',
    hyperliquidChain: Signing::EIP712.hyperliquid_chain(testnet: @testnet),
    destination: destination,
    amount: amount.to_s,
    time: nonce
  }
  signature = @signer.sign_user_signed_action(
    { destination: destination, amount: amount.to_s, time: nonce },
    'HyperliquidTransaction:Withdraw',
    Signing::EIP712::WITHDRAW_TYPES
  )
  post_action(action, signature, nonce, nil)
end