|
| 1 | +import { Wallet, utils } from 'ethers'; |
| 2 | +import { Packr } from 'msgpackr'; |
| 3 | +import { ExchangeCredentials } from '../../BaseExchange'; |
| 4 | +import { AuthenticationError } from '../../errors'; |
| 5 | +import { EXCHANGE_CHAIN_ID } from './config'; |
| 6 | + |
| 7 | +// Standard msgpack encoder — variableMapSize ensures fixmap/fixarray encoding |
| 8 | +// which matches the Python/Rust msgpack libraries that Hyperliquid's server uses. |
| 9 | +const packr = new Packr({ useRecords: false, variableMapSize: true }); |
| 10 | + |
| 11 | +// ---------------------------------------------------------------------------- |
| 12 | +// EIP-712 domain and types for Hyperliquid L1 action signing |
| 13 | +// ---------------------------------------------------------------------------- |
| 14 | + |
| 15 | +const EIP712_DOMAIN = { |
| 16 | + name: 'Exchange', |
| 17 | + version: '1', |
| 18 | + chainId: EXCHANGE_CHAIN_ID, |
| 19 | + verifyingContract: '0x0000000000000000000000000000000000000000', |
| 20 | +}; |
| 21 | + |
| 22 | +const AGENT_TYPES = { |
| 23 | + Agent: [ |
| 24 | + { name: 'source', type: 'string' }, |
| 25 | + { name: 'connectionId', type: 'bytes32' }, |
| 26 | + ], |
| 27 | +}; |
| 28 | + |
| 29 | +// ---------------------------------------------------------------------------- |
| 30 | +// Signature type |
| 31 | +// ---------------------------------------------------------------------------- |
| 32 | + |
| 33 | +export interface HyperliquidSignature { |
| 34 | + r: string; |
| 35 | + s: string; |
| 36 | + v: number; |
| 37 | +} |
| 38 | + |
| 39 | +// ---------------------------------------------------------------------------- |
| 40 | +// msgpack helpers -- Hyperliquid requires int64 encoding for large integers |
| 41 | +// ---------------------------------------------------------------------------- |
| 42 | + |
| 43 | +function convertLargeInts(obj: unknown): unknown { |
| 44 | + if (typeof obj === 'number' && Number.isInteger(obj) && |
| 45 | + (obj >= 0x100000000 || obj < -0x80000000)) { |
| 46 | + return BigInt(obj); |
| 47 | + } |
| 48 | + if (Array.isArray(obj)) { |
| 49 | + return obj.map(convertLargeInts); |
| 50 | + } |
| 51 | + if (typeof obj === 'object' && obj !== null) { |
| 52 | + const result: Record<string, unknown> = {}; |
| 53 | + for (const [key, val] of Object.entries(obj)) { |
| 54 | + if (val !== undefined) { |
| 55 | + result[key] = convertLargeInts(val); |
| 56 | + } |
| 57 | + } |
| 58 | + return result; |
| 59 | + } |
| 60 | + return obj; |
| 61 | +} |
| 62 | + |
| 63 | +// ---------------------------------------------------------------------------- |
| 64 | +// Action hash -- constructs the connectionId for the phantom agent |
| 65 | +// ---------------------------------------------------------------------------- |
| 66 | + |
| 67 | +function computeActionHash( |
| 68 | + action: Record<string, unknown>, |
| 69 | + vaultAddress: string | null, |
| 70 | + nonce: number, |
| 71 | +): string { |
| 72 | + // 1. msgpack-encode the action (large ints as int64) |
| 73 | + const actionBytes = packr.pack(convertLargeInts(action)); |
| 74 | + |
| 75 | + // 2. nonce as 8 bytes big-endian |
| 76 | + const nonceBytes = Buffer.alloc(8); |
| 77 | + nonceBytes.writeBigUInt64BE(BigInt(nonce)); |
| 78 | + |
| 79 | + // 3. vault address marker |
| 80 | + const parts: Buffer[] = [Buffer.from(actionBytes), nonceBytes]; |
| 81 | + |
| 82 | + if (vaultAddress) { |
| 83 | + parts.push(Buffer.from([0x01])); |
| 84 | + parts.push(Buffer.from(vaultAddress.replace('0x', ''), 'hex')); |
| 85 | + } else { |
| 86 | + parts.push(Buffer.from([0x00])); |
| 87 | + } |
| 88 | + |
| 89 | + // 4. keccak256 of concatenated bytes |
| 90 | + return utils.keccak256(Buffer.concat(parts)); |
| 91 | +} |
| 92 | + |
| 93 | +// ---------------------------------------------------------------------------- |
| 94 | +// Price/size formatting -- must match Hyperliquid's wire format |
| 95 | +// ---------------------------------------------------------------------------- |
| 96 | + |
| 97 | +export function floatToWire(x: number): string { |
| 98 | + const rounded = x.toFixed(8); |
| 99 | + if (Math.abs(parseFloat(rounded) - x) >= 1e-12) { |
| 100 | + throw new Error(`floatToWire causes rounding: ${x}`); |
| 101 | + } |
| 102 | + return parseFloat(rounded).toString(); |
| 103 | +} |
| 104 | + |
| 105 | +// ---------------------------------------------------------------------------- |
| 106 | +// Auth class |
| 107 | +// ---------------------------------------------------------------------------- |
| 108 | + |
| 109 | +export class HyperliquidAuth { |
| 110 | + private readonly wallet: Wallet; |
| 111 | + private readonly isMainnet: boolean; |
| 112 | + |
| 113 | + constructor(credentials: ExchangeCredentials, testnet: boolean) { |
| 114 | + if (!credentials.privateKey) { |
| 115 | + throw new AuthenticationError( |
| 116 | + 'Hyperliquid trading requires a privateKey for EIP-712 signing.', |
| 117 | + 'Hyperliquid', |
| 118 | + ); |
| 119 | + } |
| 120 | + |
| 121 | + let privateKey = credentials.privateKey; |
| 122 | + if (privateKey.includes('\\n')) { |
| 123 | + privateKey = privateKey.replace(/\\n/g, '\n'); |
| 124 | + } |
| 125 | + |
| 126 | + const stripped = privateKey.startsWith('0x') ? privateKey.slice(2) : privateKey; |
| 127 | + if (!/^[0-9a-fA-F]{64}$/.test(stripped)) { |
| 128 | + throw new AuthenticationError( |
| 129 | + 'Invalid private key format. Hyperliquid requires a 32-byte hex EVM private key (e.g. 0xabc123...).', |
| 130 | + 'Hyperliquid', |
| 131 | + ); |
| 132 | + } |
| 133 | + |
| 134 | + this.wallet = new Wallet(privateKey); |
| 135 | + this.isMainnet = !testnet; |
| 136 | + } |
| 137 | + |
| 138 | + getAddress(): string { |
| 139 | + return this.wallet.address; |
| 140 | + } |
| 141 | + |
| 142 | + /** |
| 143 | + * Sign an L1 action using the phantom agent EIP-712 scheme. |
| 144 | + * |
| 145 | + * Flow: |
| 146 | + * 1. msgpack-encode the action |
| 147 | + * 2. Append nonce (8 bytes BE) + vault marker |
| 148 | + * 3. keccak256 -> connectionId |
| 149 | + * 4. EIP-712 sign {source, connectionId} with domain "Exchange" |
| 150 | + */ |
| 151 | + async signL1Action( |
| 152 | + action: Record<string, unknown>, |
| 153 | + vaultAddress: string | null = null, |
| 154 | + nonce: number = Date.now(), |
| 155 | + ): Promise<{ signature: HyperliquidSignature; nonce: number }> { |
| 156 | + const connectionId = computeActionHash(action, vaultAddress, nonce); |
| 157 | + |
| 158 | + const message = { |
| 159 | + source: this.isMainnet ? 'a' : 'b', |
| 160 | + connectionId, |
| 161 | + }; |
| 162 | + |
| 163 | + // ethers v5 uses _signTypedData (underscore prefix) |
| 164 | + const sig = await this.wallet._signTypedData(EIP712_DOMAIN, AGENT_TYPES, message); |
| 165 | + const split = utils.splitSignature(sig); |
| 166 | + |
| 167 | + return { |
| 168 | + signature: { |
| 169 | + r: split.r, |
| 170 | + s: split.s, |
| 171 | + v: split.v, |
| 172 | + }, |
| 173 | + nonce, |
| 174 | + }; |
| 175 | + } |
| 176 | + |
| 177 | + /** |
| 178 | + * Build and sign a complete exchange request body. |
| 179 | + */ |
| 180 | + async signExchangeRequest( |
| 181 | + action: Record<string, unknown>, |
| 182 | + vaultAddress: string | null = null, |
| 183 | + ): Promise<Record<string, unknown>> { |
| 184 | + const nonce = Date.now(); |
| 185 | + const { signature } = await this.signL1Action(action, vaultAddress, nonce); |
| 186 | + |
| 187 | + return { |
| 188 | + action, |
| 189 | + nonce, |
| 190 | + signature, |
| 191 | + vaultAddress, |
| 192 | + }; |
| 193 | + } |
| 194 | +} |
0 commit comments