@avalabs/hypercore-module 3.13.2 → 3.14.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.cjs +40 -36
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +44 -4
- package/dist/index.d.ts +44 -4
- package/dist/index.js +3 -3
- package/dist/index.js.map +1 -1
- package/package.json +2 -2
package/dist/index.d.cts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import * as _metamask_rpc_errors from '@metamask/rpc-errors';
|
|
2
2
|
import * as _avalabs_vm_module_types from '@avalabs/vm-module-types';
|
|
3
|
-
import { Module, ConstructorParams, Network, Manifest, GetBalancesParams, GetTransactionHistory, NetworkFeeParam, NetworkFees, GetAddressParams, GetAddressResponse, BuildDerivationPathParams, DeriveAddressParams, DeriveAddressesParams, RpcRequest, HypercoreSpotToken, Transaction } from '@avalabs/vm-module-types';
|
|
3
|
+
import { Module, ConstructorParams, Network, Manifest, GetBalancesParams, GetTransactionHistory, NetworkFeeParam, NetworkFees, GetAddressParams, GetAddressResponse, BuildDerivationPathParams, DeriveAddressParams, DeriveAddressesParams, RpcRequest, Environment, HypercoreSpotToken, Transaction } from '@avalabs/vm-module-types';
|
|
4
4
|
export { HypercoreSpotToken } from '@avalabs/vm-module-types';
|
|
5
5
|
import { z } from 'zod';
|
|
6
6
|
import Big from 'big.js';
|
|
@@ -36,6 +36,20 @@ declare const HYPERCORE_USDC_SYMBOL = "USDC";
|
|
|
36
36
|
declare const HYPERCORE_USDC_NAME = "USD Coin";
|
|
37
37
|
declare const HYPERCORE_USDC_DECIMALS = 8;
|
|
38
38
|
|
|
39
|
+
type Env = {
|
|
40
|
+
proxyApiUrl: string;
|
|
41
|
+
/** Proxy-first Hyperliquid `/info` endpoint. */
|
|
42
|
+
infoUrl: string;
|
|
43
|
+
/**
|
|
44
|
+
* Fallback for activity endpoints if the proxy does not support fills/ledger.
|
|
45
|
+
* Prefer `infoUrl` when possible.
|
|
46
|
+
*/
|
|
47
|
+
activityInfoUrl: string;
|
|
48
|
+
};
|
|
49
|
+
declare const prodEnv: Env;
|
|
50
|
+
declare const devEnv: Env;
|
|
51
|
+
declare const getEnv: (environment: Environment) => Env;
|
|
52
|
+
|
|
39
53
|
/** `type: "spotMeta"` — registry mapping spot token index → display metadata. */
|
|
40
54
|
declare const spotMetaResponseSchema: z.ZodObject<{
|
|
41
55
|
tokens: z.ZodArray<z.ZodObject<{
|
|
@@ -127,8 +141,8 @@ declare const spotClearinghouseStateSchema: z.ZodObject<{
|
|
|
127
141
|
}[];
|
|
128
142
|
}>;
|
|
129
143
|
/**
|
|
130
|
-
* `type: "clearinghouseState"` —
|
|
131
|
-
*
|
|
144
|
+
* `type: "clearinghouseState"` — fields for PnL-excluded perp collateral
|
|
145
|
+
* fold-in and Hyperliquid `withdrawable` (used by swap / withdraw UIs).
|
|
132
146
|
*/
|
|
133
147
|
declare const clearinghouseStateSchema: z.ZodObject<{
|
|
134
148
|
assetPositions: z.ZodArray<z.ZodObject<{
|
|
@@ -164,6 +178,8 @@ declare const clearinghouseStateSchema: z.ZodObject<{
|
|
|
164
178
|
totalNtlPos?: string | undefined;
|
|
165
179
|
totalRawUsd?: string | undefined;
|
|
166
180
|
}>;
|
|
181
|
+
/** USD string (or number) Hyperliquid will release; may be absent on partial payloads. */
|
|
182
|
+
withdrawable: z.ZodOptional<z.ZodUnion<[z.ZodString, z.ZodNumber]>>;
|
|
167
183
|
}, "strip", z.ZodTypeAny, {
|
|
168
184
|
assetPositions: {
|
|
169
185
|
position: {
|
|
@@ -176,6 +192,7 @@ declare const clearinghouseStateSchema: z.ZodObject<{
|
|
|
176
192
|
totalNtlPos?: string | undefined;
|
|
177
193
|
totalRawUsd?: string | undefined;
|
|
178
194
|
};
|
|
195
|
+
withdrawable?: string | number | undefined;
|
|
179
196
|
}, {
|
|
180
197
|
assetPositions: {
|
|
181
198
|
position: {
|
|
@@ -188,6 +205,7 @@ declare const clearinghouseStateSchema: z.ZodObject<{
|
|
|
188
205
|
totalNtlPos?: string | undefined;
|
|
189
206
|
totalRawUsd?: string | undefined;
|
|
190
207
|
};
|
|
208
|
+
withdrawable?: string | number | undefined;
|
|
191
209
|
}>;
|
|
192
210
|
type UserAbstractionMode = 'unifiedAccount' | 'portfolioMargin' | 'dexAbstraction' | 'disabled' | 'default';
|
|
193
211
|
/**
|
|
@@ -494,6 +512,12 @@ type PostInfoOptions = {
|
|
|
494
512
|
/** Overrides the client default URL for this call. */
|
|
495
513
|
url?: string;
|
|
496
514
|
};
|
|
515
|
+
type HypercoreWithdrawableState = {
|
|
516
|
+
withdrawableUsd: Big;
|
|
517
|
+
abstractionMode: UserAbstractionMode | undefined;
|
|
518
|
+
clearinghouse: ClearinghouseState | undefined;
|
|
519
|
+
spotClearinghouse: SpotClearinghouseState | undefined;
|
|
520
|
+
};
|
|
497
521
|
declare class HypercoreInfoClient {
|
|
498
522
|
#private;
|
|
499
523
|
constructor(config: HypercoreInfoClientConfig);
|
|
@@ -502,6 +526,13 @@ declare class HypercoreInfoClient {
|
|
|
502
526
|
getSpotClearinghouseState(user: string, options?: PostInfoOptions): Promise<SpotClearinghouseState>;
|
|
503
527
|
getClearinghouseState(user: string, options?: PostInfoOptions): Promise<ClearinghouseState>;
|
|
504
528
|
getUserAbstraction(user: string, options?: PostInfoOptions): Promise<UserAbstractionMode>;
|
|
529
|
+
/**
|
|
530
|
+
* Fetches clearinghouse + spot + abstraction and returns Hyperliquid's
|
|
531
|
+
* withdrawable USD (unified accounts include free spot USDC).
|
|
532
|
+
*
|
|
533
|
+
* Partial `/info` failures degrade gracefully (missing legs → 0 contribution).
|
|
534
|
+
*/
|
|
535
|
+
fetchWithdrawableState(user: string, options?: PostInfoOptions): Promise<HypercoreWithdrawableState>;
|
|
505
536
|
getUserFills(user: string, options?: PostInfoOptions): Promise<UserFill[]>;
|
|
506
537
|
getUserNonFundingLedgerUpdates(user: string, startTime: number, options?: PostInfoOptions): Promise<HypercoreLedgerUpdate[]>;
|
|
507
538
|
}
|
|
@@ -556,6 +587,15 @@ declare const buildHypercoreTokens: ({ spotBalances, perpState, abstractionMode,
|
|
|
556
587
|
spotTokens: HypercoreSpotToken[];
|
|
557
588
|
}) => HypercoreTokenBalance[];
|
|
558
589
|
|
|
590
|
+
/**
|
|
591
|
+
* Hyperliquid USD that can actually be withdrawn / swapped via Markr.
|
|
592
|
+
*
|
|
593
|
+
* Mirrors fusion-sdk `hyperliquidGetWithdrawable` / core-web `getWithdrawableUsd`:
|
|
594
|
+
* - `unifiedAccount` → perp `withdrawable` + free spot USDC
|
|
595
|
+
* - other modes → perp `withdrawable` only (spot USDC is stranded on a separate ledger)
|
|
596
|
+
*/
|
|
597
|
+
declare const getWithdrawableUsd: (perp: ClearinghouseState | undefined, spot: SpotClearinghouseState | undefined, abstractionMode: UserAbstractionMode | undefined) => Big.Big;
|
|
598
|
+
|
|
559
599
|
declare const HYPERLIQUID_COIN_SVG_BASE = "https://app.hyperliquid.xyz/coins";
|
|
560
600
|
declare const hyperliquidCoinSvgKey: (coin: string) => string;
|
|
561
601
|
declare const hyperliquidCoinSvgUrl: (coin: string) => string;
|
|
@@ -646,4 +686,4 @@ declare const fetchHypercoreActivity: (client: HypercoreInfoClient, evmAddress:
|
|
|
646
686
|
|
|
647
687
|
declare const mapHypercoreActivityToTransactions: (items: readonly HypercoreActivityItem[], evmAddress: string, network: Pick<Network, "explorerUrl" | "caipId" | "chainId">) => Transaction[];
|
|
648
688
|
|
|
649
|
-
export { ClearinghouseState, FillLabel, HYPERCORE_CAIP_ID, HYPERCORE_CHAIN_ID, HYPERCORE_USDC_DECIMALS, HYPERCORE_USDC_NAME, HYPERCORE_USDC_SYMBOL, HYPERLIQUID_COIN_SVG_BASE, HypercoreActivityItem, HypercoreFillMeta, HypercoreInfoClient, HypercoreInfoClientConfig, HypercoreInfoRequest, HypercoreLedgerDisplay, HypercoreLedgerLabel, HypercoreLedgerUpdate, HypercoreModule, HypercoreNativeTokenBalance, HypercoreSpotTokenBalance, HypercoreTokenBalance, LEDGER_LOOKBACK_MS, MAX_LEDGER_PAGES, PostInfoOptions, SpotBalance, SpotClearinghouseState, SpotMetaResponse, UserAbstractionMode, UserFill, buildHypercoreTokens, clearinghouseStateSchema, closedPnlTone, encodeHypercoreFillMethod, fetchHypercoreActivity, fillLabel, formatHypercoreFillPx, getHypercoreLedgerDisplay, getPerpCollateralUsd, hypercoreLedgerDeltaSchema, hypercoreLedgerUpdateSchema, hypercoreLedgerUpdatesSchema, hyperliquidCoinSvgKey, hyperliquidCoinSvgUrl, mapHypercoreActivityToTransactions, parseHypercoreFillMethod, spotClearinghouseStateSchema, spotCountsAsPerpCollateral, spotMetaResponseSchema, tickerOfCoin, toHypercoreSpotTokens, toTimeMs, userAbstractionSchema, userFillSchema, userFillsSchema };
|
|
689
|
+
export { ClearinghouseState, FillLabel, HYPERCORE_CAIP_ID, HYPERCORE_CHAIN_ID, HYPERCORE_USDC_DECIMALS, HYPERCORE_USDC_NAME, HYPERCORE_USDC_SYMBOL, HYPERLIQUID_COIN_SVG_BASE, HypercoreActivityItem, HypercoreFillMeta, HypercoreInfoClient, HypercoreInfoClientConfig, HypercoreInfoRequest, HypercoreLedgerDisplay, HypercoreLedgerLabel, HypercoreLedgerUpdate, HypercoreModule, HypercoreNativeTokenBalance, HypercoreSpotTokenBalance, HypercoreTokenBalance, HypercoreWithdrawableState, LEDGER_LOOKBACK_MS, MAX_LEDGER_PAGES, PostInfoOptions, SpotBalance, SpotClearinghouseState, SpotMetaResponse, UserAbstractionMode, UserFill, buildHypercoreTokens, clearinghouseStateSchema, closedPnlTone, devEnv, encodeHypercoreFillMethod, fetchHypercoreActivity, fillLabel, formatHypercoreFillPx, getEnv, getHypercoreLedgerDisplay, getPerpCollateralUsd, getWithdrawableUsd, hypercoreLedgerDeltaSchema, hypercoreLedgerUpdateSchema, hypercoreLedgerUpdatesSchema, hyperliquidCoinSvgKey, hyperliquidCoinSvgUrl, mapHypercoreActivityToTransactions, parseHypercoreFillMethod, prodEnv, spotClearinghouseStateSchema, spotCountsAsPerpCollateral, spotMetaResponseSchema, tickerOfCoin, toHypercoreSpotTokens, toTimeMs, userAbstractionSchema, userFillSchema, userFillsSchema };
|
package/dist/index.d.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import * as _metamask_rpc_errors from '@metamask/rpc-errors';
|
|
2
2
|
import * as _avalabs_vm_module_types from '@avalabs/vm-module-types';
|
|
3
|
-
import { Module, ConstructorParams, Network, Manifest, GetBalancesParams, GetTransactionHistory, NetworkFeeParam, NetworkFees, GetAddressParams, GetAddressResponse, BuildDerivationPathParams, DeriveAddressParams, DeriveAddressesParams, RpcRequest, HypercoreSpotToken, Transaction } from '@avalabs/vm-module-types';
|
|
3
|
+
import { Module, ConstructorParams, Network, Manifest, GetBalancesParams, GetTransactionHistory, NetworkFeeParam, NetworkFees, GetAddressParams, GetAddressResponse, BuildDerivationPathParams, DeriveAddressParams, DeriveAddressesParams, RpcRequest, Environment, HypercoreSpotToken, Transaction } from '@avalabs/vm-module-types';
|
|
4
4
|
export { HypercoreSpotToken } from '@avalabs/vm-module-types';
|
|
5
5
|
import { z } from 'zod';
|
|
6
6
|
import Big from 'big.js';
|
|
@@ -36,6 +36,20 @@ declare const HYPERCORE_USDC_SYMBOL = "USDC";
|
|
|
36
36
|
declare const HYPERCORE_USDC_NAME = "USD Coin";
|
|
37
37
|
declare const HYPERCORE_USDC_DECIMALS = 8;
|
|
38
38
|
|
|
39
|
+
type Env = {
|
|
40
|
+
proxyApiUrl: string;
|
|
41
|
+
/** Proxy-first Hyperliquid `/info` endpoint. */
|
|
42
|
+
infoUrl: string;
|
|
43
|
+
/**
|
|
44
|
+
* Fallback for activity endpoints if the proxy does not support fills/ledger.
|
|
45
|
+
* Prefer `infoUrl` when possible.
|
|
46
|
+
*/
|
|
47
|
+
activityInfoUrl: string;
|
|
48
|
+
};
|
|
49
|
+
declare const prodEnv: Env;
|
|
50
|
+
declare const devEnv: Env;
|
|
51
|
+
declare const getEnv: (environment: Environment) => Env;
|
|
52
|
+
|
|
39
53
|
/** `type: "spotMeta"` — registry mapping spot token index → display metadata. */
|
|
40
54
|
declare const spotMetaResponseSchema: z.ZodObject<{
|
|
41
55
|
tokens: z.ZodArray<z.ZodObject<{
|
|
@@ -127,8 +141,8 @@ declare const spotClearinghouseStateSchema: z.ZodObject<{
|
|
|
127
141
|
}[];
|
|
128
142
|
}>;
|
|
129
143
|
/**
|
|
130
|
-
* `type: "clearinghouseState"` —
|
|
131
|
-
*
|
|
144
|
+
* `type: "clearinghouseState"` — fields for PnL-excluded perp collateral
|
|
145
|
+
* fold-in and Hyperliquid `withdrawable` (used by swap / withdraw UIs).
|
|
132
146
|
*/
|
|
133
147
|
declare const clearinghouseStateSchema: z.ZodObject<{
|
|
134
148
|
assetPositions: z.ZodArray<z.ZodObject<{
|
|
@@ -164,6 +178,8 @@ declare const clearinghouseStateSchema: z.ZodObject<{
|
|
|
164
178
|
totalNtlPos?: string | undefined;
|
|
165
179
|
totalRawUsd?: string | undefined;
|
|
166
180
|
}>;
|
|
181
|
+
/** USD string (or number) Hyperliquid will release; may be absent on partial payloads. */
|
|
182
|
+
withdrawable: z.ZodOptional<z.ZodUnion<[z.ZodString, z.ZodNumber]>>;
|
|
167
183
|
}, "strip", z.ZodTypeAny, {
|
|
168
184
|
assetPositions: {
|
|
169
185
|
position: {
|
|
@@ -176,6 +192,7 @@ declare const clearinghouseStateSchema: z.ZodObject<{
|
|
|
176
192
|
totalNtlPos?: string | undefined;
|
|
177
193
|
totalRawUsd?: string | undefined;
|
|
178
194
|
};
|
|
195
|
+
withdrawable?: string | number | undefined;
|
|
179
196
|
}, {
|
|
180
197
|
assetPositions: {
|
|
181
198
|
position: {
|
|
@@ -188,6 +205,7 @@ declare const clearinghouseStateSchema: z.ZodObject<{
|
|
|
188
205
|
totalNtlPos?: string | undefined;
|
|
189
206
|
totalRawUsd?: string | undefined;
|
|
190
207
|
};
|
|
208
|
+
withdrawable?: string | number | undefined;
|
|
191
209
|
}>;
|
|
192
210
|
type UserAbstractionMode = 'unifiedAccount' | 'portfolioMargin' | 'dexAbstraction' | 'disabled' | 'default';
|
|
193
211
|
/**
|
|
@@ -494,6 +512,12 @@ type PostInfoOptions = {
|
|
|
494
512
|
/** Overrides the client default URL for this call. */
|
|
495
513
|
url?: string;
|
|
496
514
|
};
|
|
515
|
+
type HypercoreWithdrawableState = {
|
|
516
|
+
withdrawableUsd: Big;
|
|
517
|
+
abstractionMode: UserAbstractionMode | undefined;
|
|
518
|
+
clearinghouse: ClearinghouseState | undefined;
|
|
519
|
+
spotClearinghouse: SpotClearinghouseState | undefined;
|
|
520
|
+
};
|
|
497
521
|
declare class HypercoreInfoClient {
|
|
498
522
|
#private;
|
|
499
523
|
constructor(config: HypercoreInfoClientConfig);
|
|
@@ -502,6 +526,13 @@ declare class HypercoreInfoClient {
|
|
|
502
526
|
getSpotClearinghouseState(user: string, options?: PostInfoOptions): Promise<SpotClearinghouseState>;
|
|
503
527
|
getClearinghouseState(user: string, options?: PostInfoOptions): Promise<ClearinghouseState>;
|
|
504
528
|
getUserAbstraction(user: string, options?: PostInfoOptions): Promise<UserAbstractionMode>;
|
|
529
|
+
/**
|
|
530
|
+
* Fetches clearinghouse + spot + abstraction and returns Hyperliquid's
|
|
531
|
+
* withdrawable USD (unified accounts include free spot USDC).
|
|
532
|
+
*
|
|
533
|
+
* Partial `/info` failures degrade gracefully (missing legs → 0 contribution).
|
|
534
|
+
*/
|
|
535
|
+
fetchWithdrawableState(user: string, options?: PostInfoOptions): Promise<HypercoreWithdrawableState>;
|
|
505
536
|
getUserFills(user: string, options?: PostInfoOptions): Promise<UserFill[]>;
|
|
506
537
|
getUserNonFundingLedgerUpdates(user: string, startTime: number, options?: PostInfoOptions): Promise<HypercoreLedgerUpdate[]>;
|
|
507
538
|
}
|
|
@@ -556,6 +587,15 @@ declare const buildHypercoreTokens: ({ spotBalances, perpState, abstractionMode,
|
|
|
556
587
|
spotTokens: HypercoreSpotToken[];
|
|
557
588
|
}) => HypercoreTokenBalance[];
|
|
558
589
|
|
|
590
|
+
/**
|
|
591
|
+
* Hyperliquid USD that can actually be withdrawn / swapped via Markr.
|
|
592
|
+
*
|
|
593
|
+
* Mirrors fusion-sdk `hyperliquidGetWithdrawable` / core-web `getWithdrawableUsd`:
|
|
594
|
+
* - `unifiedAccount` → perp `withdrawable` + free spot USDC
|
|
595
|
+
* - other modes → perp `withdrawable` only (spot USDC is stranded on a separate ledger)
|
|
596
|
+
*/
|
|
597
|
+
declare const getWithdrawableUsd: (perp: ClearinghouseState | undefined, spot: SpotClearinghouseState | undefined, abstractionMode: UserAbstractionMode | undefined) => Big.Big;
|
|
598
|
+
|
|
559
599
|
declare const HYPERLIQUID_COIN_SVG_BASE = "https://app.hyperliquid.xyz/coins";
|
|
560
600
|
declare const hyperliquidCoinSvgKey: (coin: string) => string;
|
|
561
601
|
declare const hyperliquidCoinSvgUrl: (coin: string) => string;
|
|
@@ -646,4 +686,4 @@ declare const fetchHypercoreActivity: (client: HypercoreInfoClient, evmAddress:
|
|
|
646
686
|
|
|
647
687
|
declare const mapHypercoreActivityToTransactions: (items: readonly HypercoreActivityItem[], evmAddress: string, network: Pick<Network, "explorerUrl" | "caipId" | "chainId">) => Transaction[];
|
|
648
688
|
|
|
649
|
-
export { ClearinghouseState, FillLabel, HYPERCORE_CAIP_ID, HYPERCORE_CHAIN_ID, HYPERCORE_USDC_DECIMALS, HYPERCORE_USDC_NAME, HYPERCORE_USDC_SYMBOL, HYPERLIQUID_COIN_SVG_BASE, HypercoreActivityItem, HypercoreFillMeta, HypercoreInfoClient, HypercoreInfoClientConfig, HypercoreInfoRequest, HypercoreLedgerDisplay, HypercoreLedgerLabel, HypercoreLedgerUpdate, HypercoreModule, HypercoreNativeTokenBalance, HypercoreSpotTokenBalance, HypercoreTokenBalance, LEDGER_LOOKBACK_MS, MAX_LEDGER_PAGES, PostInfoOptions, SpotBalance, SpotClearinghouseState, SpotMetaResponse, UserAbstractionMode, UserFill, buildHypercoreTokens, clearinghouseStateSchema, closedPnlTone, encodeHypercoreFillMethod, fetchHypercoreActivity, fillLabel, formatHypercoreFillPx, getHypercoreLedgerDisplay, getPerpCollateralUsd, hypercoreLedgerDeltaSchema, hypercoreLedgerUpdateSchema, hypercoreLedgerUpdatesSchema, hyperliquidCoinSvgKey, hyperliquidCoinSvgUrl, mapHypercoreActivityToTransactions, parseHypercoreFillMethod, spotClearinghouseStateSchema, spotCountsAsPerpCollateral, spotMetaResponseSchema, tickerOfCoin, toHypercoreSpotTokens, toTimeMs, userAbstractionSchema, userFillSchema, userFillsSchema };
|
|
689
|
+
export { ClearinghouseState, FillLabel, HYPERCORE_CAIP_ID, HYPERCORE_CHAIN_ID, HYPERCORE_USDC_DECIMALS, HYPERCORE_USDC_NAME, HYPERCORE_USDC_SYMBOL, HYPERLIQUID_COIN_SVG_BASE, HypercoreActivityItem, HypercoreFillMeta, HypercoreInfoClient, HypercoreInfoClientConfig, HypercoreInfoRequest, HypercoreLedgerDisplay, HypercoreLedgerLabel, HypercoreLedgerUpdate, HypercoreModule, HypercoreNativeTokenBalance, HypercoreSpotTokenBalance, HypercoreTokenBalance, HypercoreWithdrawableState, LEDGER_LOOKBACK_MS, MAX_LEDGER_PAGES, PostInfoOptions, SpotBalance, SpotClearinghouseState, SpotMetaResponse, UserAbstractionMode, UserFill, buildHypercoreTokens, clearinghouseStateSchema, closedPnlTone, devEnv, encodeHypercoreFillMethod, fetchHypercoreActivity, fillLabel, formatHypercoreFillPx, getEnv, getHypercoreLedgerDisplay, getPerpCollateralUsd, getWithdrawableUsd, hypercoreLedgerDeltaSchema, hypercoreLedgerUpdateSchema, hypercoreLedgerUpdatesSchema, hyperliquidCoinSvgKey, hyperliquidCoinSvgUrl, mapHypercoreActivityToTransactions, parseHypercoreFillMethod, prodEnv, spotClearinghouseStateSchema, spotCountsAsPerpCollateral, spotMetaResponseSchema, tickerOfCoin, toHypercoreSpotTokens, toTimeMs, userAbstractionSchema, userFillSchema, userFillsSchema };
|
package/dist/index.js
CHANGED
|
@@ -1,13 +1,13 @@
|
|
|
1
1
|
import { Environment, TokenType, TransactionType, WalletType, NetworkVMType, parseManifest } from '@avalabs/vm-module-types';
|
|
2
2
|
import { rpcErrors } from '@metamask/rpc-errors';
|
|
3
3
|
import { z as z$1 } from 'zod';
|
|
4
|
-
import
|
|
4
|
+
import w from 'big.js';
|
|
5
5
|
import { getEvmAddressFromPubKey, getAddressFromXPub } from '@avalabs/core-wallets-sdk';
|
|
6
6
|
import { computeAddress } from 'ethers';
|
|
7
7
|
import { init, deriveAddressesForEvm } from '@avalabs/crypto-sdk';
|
|
8
8
|
|
|
9
|
-
var He=Object.defineProperty;var n=(e,t)=>He(e,"name",{value:t,configurable:!0});var V=(e,t,r)=>{if(!t.has(e))throw TypeError("Cannot "+r)};var u=(e,t,r)=>(V(e,t,"read from private field"),r?r.call(e):t.get(e)),g=(e,t,r)=>{if(t.has(e))throw TypeError("Cannot add the same private member more than once");t instanceof WeakSet?t.add(e):t.set(e,r);},h=(e,t,r,o)=>(V(e,t,"write to private field"),o?o.call(e,r):t.set(e,r),r);var G={name:"HyperCore",description:"Read-only Hyperliquid HyperCore module (balances, tokens, activity).",version:"0.0.1",sources:{module:{checksum:"",location:{npm:{filePath:"dist/index.js",packageName:"@avalabs/hypercore-module",registry:"https://registry.npmjs.org"}}}},network:{chainIds:["hlcore:mainnet"],namespaces:["hlcore"]},cointype:"60",permissions:{rpc:{dapps:!1,methods:[],nonRestrictedMethods:[]}},manifestVersion:"0.1"};var $="/proxy/nownodes/hype/info",j="https://api.hyperliquid.xyz/info",Ae={proxyApiUrl:"https://proxy-api.avax.network",infoUrl:`https://proxy-api.avax.network${$}`,activityInfoUrl:j},Re={proxyApiUrl:"https://proxy-api-dev.avax.network",infoUrl:`https://proxy-api-dev.avax.network${$}`,activityInfoUrl:j},q=n(e=>{switch(e){case Environment.PRODUCTION:return Ae;case Environment.DEV:return Re}},"getEnv");var Ee=z$1.coerce.number(),z=z$1.object({tokens:z$1.array(z$1.object({name:z$1.string(),index:z$1.number(),weiDecimals:z$1.number(),fullName:z$1.string().nullish(),evmContract:z$1.object({address:z$1.string()}).nullish()}))}),Ie=z$1.object({coin:z$1.string(),token:Ee,total:z$1.string(),hold:z$1.string(),entryNtl:z$1.string().optional()}),K=z$1.object({balances:z$1.array(Ie)}),De=z$1.object({accountValue:z$1.string(),totalMarginUsed:z$1.string().optional(),totalNtlPos:z$1.string().optional(),totalRawUsd:z$1.string().optional()}),W=z$1.object({assetPositions:z$1.array(z$1.object({position:z$1.object({unrealizedPnl:z$1.string()})})),crossMarginSummary:De}),J=z$1.string().transform(e=>{switch(e){case"unifiedAccount":case"portfolioMargin":case"dexAbstraction":case"disabled":case"default":return e;default:return "default"}}),Me=z$1.object({closedPnl:z$1.string(),coin:z$1.string(),crossed:z$1.boolean(),dir:z$1.string(),hash:z$1.string(),oid:z$1.number(),px:z$1.string(),side:z$1.string(),startPosition:z$1.string(),sz:z$1.string(),time:z$1.number(),fee:z$1.string().optional(),tid:z$1.number().optional()}),X=z$1.array(Me),Ne=z$1.object({type:z$1.string(),usdc:z$1.string().optional(),amount:z$1.string().optional(),usdcValue:z$1.string().optional(),token:z$1.string().optional(),user:z$1.string().optional(),destination:z$1.string().optional(),fee:z$1.string().optional(),toPerp:z$1.boolean().optional()}),Oe=z$1.object({time:z$1.number(),hash:z$1.string(),delta:Ne}),Z=z$1.array(Oe);var Fe=n(e=>{if(typeof e=="function")return e;if(typeof globalThis.fetch=="function")return globalThis.fetch.bind(globalThis);throw new Error("HypercoreInfoClient requires a fetch implementation. Pass config.fetch when globalThis.fetch is unavailable (e.g. React Native).")},"resolveFetch"),k,C,A,O=class O{constructor(t){g(this,k,void 0);g(this,C,void 0);g(this,A,void 0);h(this,k,t.infoUrl),h(this,C,t.activityInfoUrl??t.infoUrl),h(this,A,Fe(t.fetch));}async postInfo(t,r,o){let i=await u(this,A).call(this,o?.url??u(this,k),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t),signal:o?.signal});if(!i.ok)throw new Error(`Hyperliquid /info failed: ${i.status} ${i.statusText}`);let a=await i.json();return r.parse(a)}getSpotMeta(t){return this.postInfo({type:"spotMeta"},z,t)}getSpotClearinghouseState(t,r){return this.postInfo({type:"spotClearinghouseState",user:t.toLowerCase(),dex:""},K,r)}getClearinghouseState(t,r){return this.postInfo({type:"clearinghouseState",user:t.toLowerCase(),dex:""},W,r)}getUserAbstraction(t,r){return this.postInfo({type:"userAbstraction",user:t.toLowerCase()},J,r)}getUserFills(t,r){return this.postInfo({type:"userFills",user:t.toLowerCase()},X,{...r,url:r?.url??u(this,C)})}getUserNonFundingLedgerUpdates(t,r,o){return this.postInfo({type:"userNonFundingLedgerUpdates",user:t.toLowerCase(),startTime:r},Z,{...o,url:o?.url??u(this,C)})}};k=new WeakMap,C=new WeakMap,A=new WeakMap,n(O,"HypercoreInfoClient");var I=O;var F=n(e=>`HyperCore does not support ${e}: read-only module (balances, tokens, activity).`,"unsupportedHypercoreCapabilityMessage");var Q="hlcore:mainnet",Pt=9999,D="USDC",ee="USD Coin",L=8;var b=new S(0),Le=n(e=>e==="unifiedAccount","spotCountsAsPerpCollateral"),te=n((e,t)=>e.times(new S(10).pow(t)).round(0,S.roundDown).toFixed(0),"toRawBalance"),Be=n(e=>{if(!e)return b;let t=new S(e.crossMarginSummary.accountValue??"0"),r=e.assetPositions.reduce((i,{position:a})=>i.plus(a.unrealizedPnl),b),o=t.minus(r);return o.gt(b)?o:b},"getPerpCollateralUsd"),re=n(({spotBalances:e,perpState:t,abstractionMode:r,spotTokens:o})=>{let i=new Map(o.map(d=>[d.index,d])),a=Le(r)?b:Be(t),p=e.find(d=>d.coin.toUpperCase()===D),l=new S(p?.total??"0").plus(a),c=[];l.gt(b)&&c.push({kind:"native",name:ee,symbol:D,decimals:8,balance:l.toString(),balanceRaw:te(l,8),priceUsd:1,balanceUsd:l.toString()});for(let d of e){if(d.coin.toUpperCase()===D)continue;let m=i.get(d.token),y=new S(d.total);!m||!y.gt(b)||c.push({kind:"spot",name:m.name,symbol:m.symbol,decimals:m.decimals,balance:y.toString(),balanceRaw:te(y,m.decimals),index:m.index,evmContract:m.evmContract});}return c},"buildHypercoreTokens");var _e="https://app.hyperliquid.xyz/coins",Ve=n(e=>{let t=e.trim(),r=t.indexOf(":");return r===-1?t.toUpperCase():`${t.slice(0,r)}:${t.slice(r+1).toUpperCase()}`},"hyperliquidCoinSvgKey"),f=n(e=>`${_e}/${encodeURIComponent(Ve(e))}.svg`,"hyperliquidCoinSvgUrl");var Ye=n(e=>/^0x[a-fA-F0-9]{40}$/.test(e),"isValidEvmAddress"),M=n(e=>e.map(t=>{let r=t.evmContract?.address.toLowerCase();return {type:TokenType.HYPERCORE_SPOT,index:t.index,name:t.fullName??t.name,symbol:t.name,decimals:t.weiDecimals,evmContract:r&&Ye(r)?r:void 0}}),"toHypercoreSpotTokens");var $e=n(e=>e instanceof Error?e.message:String(e),"toErrorMessage"),je=n((e,t)=>{if(e.kind==="native"){let i=BigInt(e.balanceRaw),a=Number(e.balanceUsd),p={...t,name:e.name,symbol:e.symbol,decimals:e.decimals,logoUri:t.logoUri??f(e.symbol),coingeckoId:"usd-coin",type:TokenType.NATIVE,balance:i,balanceDisplayValue:e.balance,balanceInCurrency:Number.isFinite(a)?a:0,balanceCurrencyDisplayValue:e.balanceUsd,priceInCurrency:e.priceUsd};return {key:e.symbol,value:p}}let r=BigInt(e.balanceRaw),o={type:TokenType.HYPERCORE_SPOT,name:e.name,symbol:e.symbol,decimals:e.decimals,index:e.index,evmContract:e.evmContract,logoUri:f(e.symbol),reputation:null,balance:r,balanceDisplayValue:e.balance};return {key:`spot:${e.index}`,value:o}},"toTokenWithBalance"),oe=n(async({addresses:e,network:t,infoClient:r,tokenTypes:o=[TokenType.NATIVE,TokenType.HYPERCORE_SPOT]})=>{let i=o.includes(TokenType.NATIVE),a=o.includes(TokenType.HYPERCORE_SPOT);if(!i&&!a)return Object.fromEntries(e.map(c=>[c,{}]));let p=a?M((await r.getSpotMeta()).tokens):[];return (await Promise.allSettled(e.map(async c=>{let[d,m,y]=await Promise.all([r.getSpotClearinghouseState(c),i?r.getClearinghouseState(c):Promise.resolve(void 0),i?r.getUserAbstraction(c):Promise.resolve(void 0)]),Se=re({spotBalances:d.balances,perpState:m,abstractionMode:y,spotTokens:p}).filter(N=>N.kind==="native"?i:a),Te=Object.fromEntries(Se.map(N=>{let{key:we,value:Ue}=je(N,t.networkToken);return [we,Ue]}));return {[c]:Te}}))).reduce((c,d,m)=>{if(d.status==="fulfilled")return {...c,...d.value};let y=e[m];return y?{...c,[y]:{error:$e(d.reason)}}:c},{})},"getBalances");var ne=n(async({infoClient:e})=>{let t=await e.getSpotMeta();return M(t.tokens).map(r=>({...r,logoUri:r.logoUri??f(r.symbol)}))},"getTokens");var R=n(e=>e<1e10?e*1e3:e,"toTimeMs");var qe=20,ze=30*24*60*60*1e3,Ke=n(e=>e instanceof DOMException&&e.name==="AbortError"||e instanceof Error&&e.name==="AbortError","isAbortError"),se=n(async(e,t)=>{try{return await e}catch(r){if(Ke(r))throw r;return t}},"softFail"),We=n(async(e,t,r)=>{let o=[],i=Date.now()-ze,a=0;for(;a<qe;){if(r?.signal?.aborted)throw new DOMException("The operation was aborted.","AbortError");let p=await e.getUserNonFundingLedgerUpdates(t,i,r);if(a+=1,p.length===0)break;o.push(...p);let l=p[p.length-1];if(!l)break;let c=l.time+1;if(c<=i)break;i=c;}return o},"fetchLedgerUpdates"),ie=n(async(e,t,r)=>{let[o,i]=await Promise.all([se(e.getUserFills(t,r),[]),se(We(e,t,r),[])]);return [...o.map(p=>({kind:"fill",timeMs:R(p.time),hash:p.hash,fill:p})),...i.map(p=>({kind:"ledger",timeMs:R(p.time),hash:p.hash,update:p}))].sort((p,l)=>l.timeMs-p.timeMs)},"fetchHypercoreActivity");var v=n(e=>{if(e===void 0||e==="")return "";let t=Number.parseFloat(e);return Number.isFinite(t)?new Intl.NumberFormat("en-US",{maximumFractionDigits:6}).format(t):e},"formatAmount"),x=n((e,t)=>{if(e===void 0||e==="")return;let r=Number.parseFloat(e);return Number.isFinite(r)?r*(t===0?1:t):void 0},"toUsd"),ae=n((e,t)=>{let{delta:r}=e,o=t.toLowerCase(),i=r.user?.toLowerCase()===o;switch(r.type){case"deposit":return {label:"deposit",amount:v(r.usdc),symbol:"USDC",usdValue:x(r.usdc,1),direction:"positive",to:t,rawType:r.type};case"withdraw":return {label:"withdraw",amount:v(r.usdc),symbol:"USDC",usdValue:x(r.usdc,-1),direction:"negative",from:t,rawType:r.type};case"send":case"spotTransfer":return {label:i?"sent":"received",amount:v(r.amount),symbol:r.token??"USDC",usdValue:x(r.usdcValue,i?-1:1),direction:i?"negative":"positive",from:r.user,to:r.destination,rawType:r.type};case"internalTransfer":return {label:"transfer",amount:v(r.usdc),symbol:"USDC",usdValue:x(r.usdc,i?-1:1),direction:i?"negative":"positive",from:r.user,to:r.destination,rawType:r.type};case"accountClassTransfer":return {label:r.toPerp?"transferToPerp":"transferToSpot",amount:v(r.usdc),symbol:"USDC",usdValue:x(r.usdc,0),direction:"neutral",rawType:r.type};case"liquidation":return {label:"liquidation",amount:v(r.usdcValue??r.usdc),symbol:"USDC",usdValue:x(r.usdcValue??r.usdc,-1),direction:"negative",rawType:r.type};default:return {label:"other",amount:v(r.usdcValue??r.usdc),symbol:"USDC",usdValue:x(r.usdcValue??r.usdc,0),direction:"neutral",rawType:r.type}}},"getHypercoreLedgerDisplay");var B="hypercoreFill:v1:",pe=n(e=>{let t=e.indexOf(":");return t===-1?e:e.slice(t+1)},"tickerOfCoin"),Je=n(e=>{if(e===void 0)return;let t=Number.parseFloat(e);if(!(!Number.isFinite(t)||t===0))return t>0?"profit":"loss"},"closedPnlTone"),Wt=n((e,t)=>{let r=Je(t),o=e.toLowerCase();return o.includes("close")&&o.includes("long")?{text:"Long closed",direction:"up",tone:r}:o.includes("close")&&o.includes("short")?{text:"Short closed",direction:"down",tone:r}:o.includes("open")&&(o.includes("long")||o.includes("short"))?{text:"Order opened"}:o.includes("cancel")?{text:"Order cancelled"}:{text:e}},"fillLabel"),Jt=n(e=>{let t=Number.parseFloat(e);return Number.isFinite(t)?`$${t.toLocaleString(void 0,{maximumFractionDigits:8})}`:e},"formatHypercoreFillPx"),ce=n(e=>`${B}${encodeURIComponent(JSON.stringify(e))}`,"encodeHypercoreFillMethod"),Xt=n(e=>{if(e?.startsWith(B))try{let t=JSON.parse(decodeURIComponent(e.slice(B.length)));if(typeof t!="object"||t===null||!("dir"in t)||!("px"in t)||!("closedPnl"in t)||!("coin"in t))return;let{dir:r,px:o,closedPnl:i,coin:a}=t;return typeof r!="string"||typeof o!="string"||typeof i!="string"||typeof a!="string"?void 0:{dir:r,px:o,closedPnl:i,coin:a}}catch{return}},"parseHypercoreFillMethod");var de=n((e,t)=>{let r=(e.explorerUrl??"").replace(/\/$/,"");return r?`${r}/tx/${t}`:t},"explorerTxLink"),me=n(e=>e.caipId??Q,"chainIdForNetwork"),Xe=n((e,t,r)=>{let o=e.side==="B",i=pe(e.coin),a={type:TokenType.NATIVE,name:e.coin,symbol:i,amount:e.sz,imageUri:f(e.coin)};return {isContractCall:!1,isIncoming:o,isOutgoing:!o,isSender:!o,timestamp:t,hash:e.hash,from:"",to:"",tokens:[a],gasUsed:"0",txType:TransactionType.FILL_ORDER,method:ce({dir:e.dir??"",px:e.px,closedPnl:e.closedPnl,coin:e.coin}),chainId:me(r),explorerLink:de(r,e.hash)}},"mapFillToTransaction"),Ze=n((e,t,r)=>{let o=ae(e,t),i=o.direction==="positive",a=o.direction==="negative",p=TransactionType.TRANSFER;switch(o.label){case"deposit":case"received":p=TransactionType.RECEIVE;break;case"withdraw":case"sent":p=TransactionType.SEND;break;case"liquidation":p=TransactionType.UNKNOWN;break;default:p=TransactionType.TRANSFER;}let l=o.amount||"0",c={type:TokenType.NATIVE,name:o.symbol,symbol:o.symbol,amount:l,imageUri:f(o.symbol)};return {isContractCall:!1,isIncoming:i,isOutgoing:a,isSender:a,timestamp:R(e.time),hash:e.hash,from:o.from??(a?t:""),to:o.to??(i?t:""),tokens:[c],gasUsed:"0",txType:p,chainId:me(r),explorerLink:de(r,e.hash)}},"mapLedgerToTransaction"),ue=n((e,t,r)=>e.map(o=>o.kind==="fill"?Xe(o.fill,o.timeMs,r):Ze(o.update,t,r)),"mapHypercoreActivityToTransactions");var ye=n(async({address:e,network:t,infoClient:r})=>{let o=await ie(r,e);return {transactions:ue(o,e,t)}},"getTransactionHistory");var ge=n(async({accountIndex:e,xpub:t,walletType:r})=>{switch(r){case WalletType.Mnemonic:case WalletType.Ledger:case WalletType.Keystone:return {[NetworkVMType.HYPERCORE]:getAddressFromXPub(t,e)};case WalletType.LedgerLive:case WalletType.Seedless:{let o=Buffer.from(t,"hex");return {[NetworkVMType.HYPERCORE]:getEvmAddressFromPubKey(o)}}default:throw rpcErrors.invalidParams(`Unsupported wallet type: ${r}`)}},"getAddress");var he=n(e=>"derivationPathType"in e&&"accountIndex"in e&&typeof e.accountIndex=="number"&&typeof e.derivationPathType=="string","hasDerivationDetails");var U=n(({accountIndex:e,derivationPathType:t})=>{if(e<0)throw rpcErrors.invalidParams("Account index must be a non-negative integer");switch(t){case"bip44":return {[NetworkVMType.HYPERCORE]:`m/44'/60'/0'/0/${e}`};case"ledger_live":return {[NetworkVMType.HYPERCORE]:`m/44'/60'/${e}'/0/0`};default:throw rpcErrors.invalidParams(`Unsupported derivation path type: ${t}`)}},"buildDerivationPath");var xe=n(async e=>{let{secretId:t,approvalController:r}=e,o=he(e)?U({accountIndex:e.accountIndex,derivationPathType:e.derivationPathType,addressIndex:e.addressIndex}).HYPERCORE:void 0,i=await r.requestPublicKey({curve:"secp256k1",secretId:t,derivationPath:o});return {[NetworkVMType.HYPERCORE]:computeAddress(`0x${i}`)}},"deriveAddress");var Pe=n(async e=>{let{approvalController:t,secretId:r,accountIndices:o,derivationPathType:i}=e;if(o.length===0)return [];await init();let a=await Promise.all(o.map(async l=>{let c=U({accountIndex:l,derivationPathType:i}).HYPERCORE,d=await t.requestPublicKey({curve:"secp256k1",secretId:r,derivationPath:c});return Uint8Array.from(Buffer.from(d,"hex"))}));return (await deriveAddressesForEvm(a)).map(l=>({[NetworkVMType.HYPERCORE]:l}))},"deriveAddresses");var H,P,_=class _{constructor({environment:t,approvalController:r,runtime:o}){g(this,H,void 0);g(this,P,void 0);let{infoUrl:i,activityInfoUrl:a}=q(t);h(this,H,r),h(this,P,new I({infoUrl:i,activityInfoUrl:a,fetch:o?.fetch}));}getProvider(t){return Promise.reject(new Error(F("getProvider")))}getManifest(){let t=parseManifest(G);return t.success?t.data:void 0}getBalances(t){return oe({...t,infoClient:u(this,P)})}getTransactionHistory(t){return ye({...t,infoClient:u(this,P)})}getNetworkFee(t){return Promise.reject(new Error(F("getNetworkFee")))}getAddress(t){return ge(t)}buildDerivationPath(t){return U(t)}deriveAddress(t){return xe({...t,approvalController:u(this,H)})}deriveAddresses(t){return Pe({...t,approvalController:u(this,H)})}getTokens(t){return ne({network:t,infoClient:u(this,P)})}async onRpcRequest(t,r){return {error:rpcErrors.methodNotSupported(`HyperCore is read-only; method ${t.method} is not supported`)}}};H=new WeakMap,P=new WeakMap,n(_,"HypercoreModule");var Ce=_;
|
|
9
|
+
var Ie=Object.defineProperty;var n=(e,t)=>Ie(e,"name",{value:t,configurable:!0});var $=(e,t,r)=>{if(!t.has(e))throw TypeError("Cannot "+r)};var u=(e,t,r)=>($(e,t,"read from private field"),r?r.call(e):t.get(e)),g=(e,t,r)=>{if(t.has(e))throw TypeError("Cannot add the same private member more than once");t instanceof WeakSet?t.add(e):t.set(e,r);},h=(e,t,r,o)=>($(e,t,"write to private field"),o?o.call(e,r):t.set(e,r),r);var j={name:"HyperCore",description:"Read-only Hyperliquid HyperCore module (balances, tokens, activity).",version:"0.0.1",sources:{module:{checksum:"",location:{npm:{filePath:"dist/index.js",packageName:"@avalabs/hypercore-module",registry:"https://registry.npmjs.org"}}}},network:{chainIds:["hlcore:mainnet"],namespaces:["hlcore"]},cointype:"60",permissions:{rpc:{dapps:!1,methods:[],nonRestrictedMethods:[]}},manifestVersion:"0.1"};var z="/proxy/nownodes/hype/info",W="https://api.hyperliquid.xyz/info",Me={proxyApiUrl:"https://proxy-api.avax.network",infoUrl:`https://proxy-api.avax.network${z}`,activityInfoUrl:W},Oe={proxyApiUrl:"https://proxy-api-dev.avax.network",infoUrl:`https://proxy-api-dev.avax.network${z}`,activityInfoUrl:W},K=n(e=>{switch(e){case Environment.PRODUCTION:return Me;case Environment.DEV:return Oe}},"getEnv");var Ne=z$1.coerce.number(),J=z$1.object({tokens:z$1.array(z$1.object({name:z$1.string(),index:z$1.number(),weiDecimals:z$1.number(),fullName:z$1.string().nullish(),evmContract:z$1.object({address:z$1.string()}).nullish()}))}),Fe=z$1.object({coin:z$1.string(),token:Ne,total:z$1.string(),hold:z$1.string(),entryNtl:z$1.string().optional()}),X=z$1.object({balances:z$1.array(Fe)}),Le=z$1.object({accountValue:z$1.string(),totalMarginUsed:z$1.string().optional(),totalNtlPos:z$1.string().optional(),totalRawUsd:z$1.string().optional()}),Z=z$1.object({assetPositions:z$1.array(z$1.object({position:z$1.object({unrealizedPnl:z$1.string()})})),crossMarginSummary:Le,withdrawable:z$1.union([z$1.string(),z$1.number()]).optional()}),Q=z$1.string().transform(e=>{switch(e){case"unifiedAccount":case"portfolioMargin":case"dexAbstraction":case"disabled":case"default":return e;default:return "default"}}),Be=z$1.object({closedPnl:z$1.string(),coin:z$1.string(),crossed:z$1.boolean(),dir:z$1.string(),hash:z$1.string(),oid:z$1.number(),px:z$1.string(),side:z$1.string(),startPosition:z$1.string(),sz:z$1.string(),time:z$1.number(),fee:z$1.string().optional(),tid:z$1.number().optional()}),ee=z$1.array(Be),_e=z$1.object({type:z$1.string(),usdc:z$1.string().optional(),amount:z$1.string().optional(),usdcValue:z$1.string().optional(),token:z$1.string().optional(),user:z$1.string().optional(),destination:z$1.string().optional(),fee:z$1.string().optional(),toPerp:z$1.boolean().optional()}),Ve=z$1.object({time:z$1.number(),hash:z$1.string(),delta:_e}),te=z$1.array(Ve);var re="hlcore:mainnet",Pt=9999,v="USDC",oe="USD Coin",F=8;var b=new w(0),L=n(e=>e==="unifiedAccount","spotCountsAsPerpCollateral"),ne=n((e,t)=>e.times(new w(10).pow(t)).round(0,w.roundDown).toFixed(0),"toRawBalance"),Ge=n(e=>{if(!e)return b;let t=new w(e.crossMarginSummary.accountValue??"0"),r=e.assetPositions.reduce((i,{position:a})=>i.plus(a.unrealizedPnl),b),o=t.minus(r);return o.gt(b)?o:b},"getPerpCollateralUsd"),se=n(({spotBalances:e,perpState:t,abstractionMode:r,spotTokens:o})=>{let i=new Map(o.map(d=>[d.index,d])),a=L(r)?b:Ge(t),p=e.find(d=>d.coin.toUpperCase()===v),l=new w(p?.total??"0").plus(a),c=[];l.gt(b)&&c.push({kind:"native",name:oe,symbol:v,decimals:8,balance:l.toString(),balanceRaw:ne(l,8),priceUsd:1,balanceUsd:l.toString()});for(let d of e){if(d.coin.toUpperCase()===v)continue;let m=i.get(d.token),y=new w(d.total);!m||!y.gt(b)||c.push({kind:"spot",name:m.name,symbol:m.symbol,decimals:m.decimals,balance:y.toString(),balanceRaw:ne(y,m.decimals),index:m.index,evmContract:m.evmContract});}return c},"buildHypercoreTokens");var C=new w(0),B=n(e=>{if(e===void 0)return C;try{let t=new w(e);return t.gte(C)?t:C}catch{return C}},"parseUsd"),Ye=n(e=>{let t=e?.balances.find(o=>o.coin.toUpperCase()===v);if(!t)return C;let r=B(t.total).minus(B(t.hold));return r.gt(C)?r:C},"getFreeSpotUsdcUsd"),ae=n((e,t,r)=>{let o=B(e?.withdrawable);return L(r)?o.plus(Ye(t)):o},"getWithdrawableUsd");var $e=n(e=>{if(typeof e=="function")return e;if(typeof globalThis.fetch=="function")return globalThis.fetch.bind(globalThis);throw new Error("HypercoreInfoClient requires a fetch implementation. Pass config.fetch when globalThis.fetch is unavailable (e.g. React Native).")},"resolveFetch"),R,T,E,_=class _{constructor(t){g(this,R,void 0);g(this,T,void 0);g(this,E,void 0);h(this,R,t.infoUrl),h(this,T,t.activityInfoUrl??t.infoUrl),h(this,E,$e(t.fetch));}async postInfo(t,r,o){let i=await u(this,E).call(this,o?.url??u(this,R),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t),signal:o?.signal});if(!i.ok)throw new Error(`Hyperliquid /info failed: ${i.status} ${i.statusText}`);let a=await i.json();return r.parse(a)}getSpotMeta(t){return this.postInfo({type:"spotMeta"},J,t)}getSpotClearinghouseState(t,r){return this.postInfo({type:"spotClearinghouseState",user:t.toLowerCase(),dex:""},X,r)}getClearinghouseState(t,r){return this.postInfo({type:"clearinghouseState",user:t.toLowerCase(),dex:""},Z,r)}getUserAbstraction(t,r){return this.postInfo({type:"userAbstraction",user:t.toLowerCase()},Q,r)}async fetchWithdrawableState(t,r){let o=t.toLowerCase(),[i,a,p]=await Promise.all([this.getClearinghouseState(o,r).catch(()=>{}),this.getSpotClearinghouseState(o,r).catch(()=>{}),this.getUserAbstraction(o,r).catch(()=>{})]);return {withdrawableUsd:ae(i,a,p),abstractionMode:p,clearinghouse:i,spotClearinghouse:a}}getUserFills(t,r){return this.postInfo({type:"userFills",user:t.toLowerCase()},ee,{...r,url:r?.url??u(this,T)})}getUserNonFundingLedgerUpdates(t,r,o){return this.postInfo({type:"userNonFundingLedgerUpdates",user:t.toLowerCase(),startTime:r},te,{...o,url:o?.url??u(this,T)})}};R=new WeakMap,T=new WeakMap,E=new WeakMap,n(_,"HypercoreInfoClient");var M=_;var V=n(e=>`HyperCore does not support ${e}: read-only module (balances, tokens, activity).`,"unsupportedHypercoreCapabilityMessage");var je="https://app.hyperliquid.xyz/coins",qe=n(e=>{let t=e.trim(),r=t.indexOf(":");return r===-1?t.toUpperCase():`${t.slice(0,r)}:${t.slice(r+1).toUpperCase()}`},"hyperliquidCoinSvgKey"),f=n(e=>`${je}/${encodeURIComponent(qe(e))}.svg`,"hyperliquidCoinSvgUrl");var We=n(e=>/^0x[a-fA-F0-9]{40}$/.test(e),"isValidEvmAddress"),O=n(e=>e.map(t=>{let r=t.evmContract?.address.toLowerCase();return {type:TokenType.HYPERCORE_SPOT,index:t.index,name:t.fullName??t.name,symbol:t.name,decimals:t.weiDecimals,evmContract:r&&We(r)?r:void 0}}),"toHypercoreSpotTokens");var Ke=n(e=>e instanceof Error?e.message:String(e),"toErrorMessage"),Je=n((e,t)=>{if(e.kind==="native"){let i=BigInt(e.balanceRaw),a=Number(e.balanceUsd),p={...t,name:e.name,symbol:e.symbol,decimals:e.decimals,logoUri:t.logoUri??f(e.symbol),coingeckoId:"usd-coin",type:TokenType.NATIVE,balance:i,balanceDisplayValue:e.balance,balanceInCurrency:Number.isFinite(a)?a:0,balanceCurrencyDisplayValue:e.balanceUsd,priceInCurrency:e.priceUsd};return {key:e.symbol,value:p}}let r=BigInt(e.balanceRaw),o={type:TokenType.HYPERCORE_SPOT,name:e.name,symbol:e.symbol,decimals:e.decimals,index:e.index,evmContract:e.evmContract,logoUri:f(e.symbol),reputation:null,balance:r,balanceDisplayValue:e.balance};return {key:`spot:${e.index}`,value:o}},"toTokenWithBalance"),pe=n(async({addresses:e,network:t,infoClient:r,tokenTypes:o=[TokenType.NATIVE,TokenType.HYPERCORE_SPOT]})=>{let i=o.includes(TokenType.NATIVE),a=o.includes(TokenType.HYPERCORE_SPOT);if(!i&&!a)return Object.fromEntries(e.map(c=>[c,{}]));let p=a?O((await r.getSpotMeta()).tokens):[];return (await Promise.allSettled(e.map(async c=>{let[d,m,y]=await Promise.all([r.getSpotClearinghouseState(c),i?r.getClearinghouseState(c):Promise.resolve(void 0),i?r.getUserAbstraction(c):Promise.resolve(void 0)]),Ae=se({spotBalances:d.balances,perpState:m,abstractionMode:y,spotTokens:p}).filter(N=>N.kind==="native"?i:a),ke=Object.fromEntries(Ae.map(N=>{let{key:Re,value:Ee}=Je(N,t.networkToken);return [Re,Ee]}));return {[c]:ke}}))).reduce((c,d,m)=>{if(d.status==="fulfilled")return {...c,...d.value};let y=e[m];return y?{...c,[y]:{error:Ke(d.reason)}}:c},{})},"getBalances");var ce=n(async({infoClient:e})=>{let t=await e.getSpotMeta();return O(t.tokens).map(r=>({...r,logoUri:r.logoUri??f(r.symbol)}))},"getTokens");var I=n(e=>e<1e10?e*1e3:e,"toTimeMs");var Xe=20,Ze=30*24*60*60*1e3,Qe=n(e=>e instanceof DOMException&&e.name==="AbortError"||e instanceof Error&&e.name==="AbortError","isAbortError"),le=n(async(e,t)=>{try{return await e}catch(r){if(Qe(r))throw r;return t}},"softFail"),et=n(async(e,t,r)=>{let o=[],i=Date.now()-Ze,a=0;for(;a<Xe;){if(r?.signal?.aborted)throw new DOMException("The operation was aborted.","AbortError");let p=await e.getUserNonFundingLedgerUpdates(t,i,r);if(a+=1,p.length===0)break;o.push(...p);let l=p[p.length-1];if(!l)break;let c=l.time+1;if(c<=i)break;i=c;}return o},"fetchLedgerUpdates"),de=n(async(e,t,r)=>{let[o,i]=await Promise.all([le(e.getUserFills(t,r),[]),le(et(e,t,r),[])]);return [...o.map(p=>({kind:"fill",timeMs:I(p.time),hash:p.hash,fill:p})),...i.map(p=>({kind:"ledger",timeMs:I(p.time),hash:p.hash,update:p}))].sort((p,l)=>l.timeMs-p.timeMs)},"fetchHypercoreActivity");var x=n(e=>{if(e===void 0||e==="")return "";let t=Number.parseFloat(e);return Number.isFinite(t)?new Intl.NumberFormat("en-US",{maximumFractionDigits:6}).format(t):e},"formatAmount"),P=n((e,t)=>{if(e===void 0||e==="")return;let r=Number.parseFloat(e);return Number.isFinite(r)?r*(t===0?1:t):void 0},"toUsd"),me=n((e,t)=>{let{delta:r}=e,o=t.toLowerCase(),i=r.user?.toLowerCase()===o;switch(r.type){case"deposit":return {label:"deposit",amount:x(r.usdc),symbol:"USDC",usdValue:P(r.usdc,1),direction:"positive",to:t,rawType:r.type};case"withdraw":return {label:"withdraw",amount:x(r.usdc),symbol:"USDC",usdValue:P(r.usdc,-1),direction:"negative",from:t,rawType:r.type};case"send":case"spotTransfer":return {label:i?"sent":"received",amount:x(r.amount),symbol:r.token??"USDC",usdValue:P(r.usdcValue,i?-1:1),direction:i?"negative":"positive",from:r.user,to:r.destination,rawType:r.type};case"internalTransfer":return {label:"transfer",amount:x(r.usdc),symbol:"USDC",usdValue:P(r.usdc,i?-1:1),direction:i?"negative":"positive",from:r.user,to:r.destination,rawType:r.type};case"accountClassTransfer":return {label:r.toPerp?"transferToPerp":"transferToSpot",amount:x(r.usdc),symbol:"USDC",usdValue:P(r.usdc,0),direction:"neutral",rawType:r.type};case"liquidation":return {label:"liquidation",amount:x(r.usdcValue??r.usdc),symbol:"USDC",usdValue:P(r.usdcValue??r.usdc,-1),direction:"negative",rawType:r.type};default:return {label:"other",amount:x(r.usdcValue??r.usdc),symbol:"USDC",usdValue:P(r.usdcValue??r.usdc,0),direction:"neutral",rawType:r.type}}},"getHypercoreLedgerDisplay");var G="hypercoreFill:v1:",ue=n(e=>{let t=e.indexOf(":");return t===-1?e:e.slice(t+1)},"tickerOfCoin"),tt=n(e=>{if(e===void 0)return;let t=Number.parseFloat(e);if(!(!Number.isFinite(t)||t===0))return t>0?"profit":"loss"},"closedPnlTone"),ir=n((e,t)=>{let r=tt(t),o=e.toLowerCase();return o.includes("close")&&o.includes("long")?{text:"Long closed",direction:"up",tone:r}:o.includes("close")&&o.includes("short")?{text:"Short closed",direction:"down",tone:r}:o.includes("open")&&(o.includes("long")||o.includes("short"))?{text:"Order opened"}:o.includes("cancel")?{text:"Order cancelled"}:{text:e}},"fillLabel"),ar=n(e=>{let t=Number.parseFloat(e);return Number.isFinite(t)?`$${t.toLocaleString(void 0,{maximumFractionDigits:8})}`:e},"formatHypercoreFillPx"),ye=n(e=>`${G}${encodeURIComponent(JSON.stringify(e))}`,"encodeHypercoreFillMethod"),pr=n(e=>{if(e?.startsWith(G))try{let t=JSON.parse(decodeURIComponent(e.slice(G.length)));if(typeof t!="object"||t===null||!("dir"in t)||!("px"in t)||!("closedPnl"in t)||!("coin"in t))return;let{dir:r,px:o,closedPnl:i,coin:a}=t;return typeof r!="string"||typeof o!="string"||typeof i!="string"||typeof a!="string"?void 0:{dir:r,px:o,closedPnl:i,coin:a}}catch{return}},"parseHypercoreFillMethod");var ge=n((e,t)=>{let r=(e.explorerUrl??"").replace(/\/$/,"");return r?`${r}/tx/${t}`:t},"explorerTxLink"),he=n(e=>e.caipId??re,"chainIdForNetwork"),rt=n((e,t,r)=>{let o=e.side==="B",i=ue(e.coin),a={type:TokenType.NATIVE,name:e.coin,symbol:i,amount:e.sz,imageUri:f(e.coin)};return {isContractCall:!1,isIncoming:o,isOutgoing:!o,isSender:!o,timestamp:t,hash:e.hash,from:"",to:"",tokens:[a],gasUsed:"0",txType:TransactionType.FILL_ORDER,method:ye({dir:e.dir??"",px:e.px,closedPnl:e.closedPnl,coin:e.coin}),chainId:he(r),explorerLink:ge(r,e.hash)}},"mapFillToTransaction"),ot=n((e,t,r)=>{let o=me(e,t),i=o.direction==="positive",a=o.direction==="negative",p=TransactionType.TRANSFER;switch(o.label){case"deposit":case"received":p=TransactionType.RECEIVE;break;case"withdraw":case"sent":p=TransactionType.SEND;break;case"liquidation":p=TransactionType.UNKNOWN;break;default:p=TransactionType.TRANSFER;}let l=o.amount||"0",c={type:TokenType.NATIVE,name:o.symbol,symbol:o.symbol,amount:l,imageUri:f(o.symbol)};return {isContractCall:!1,isIncoming:i,isOutgoing:a,isSender:a,timestamp:I(e.time),hash:e.hash,from:o.from??(a?t:""),to:o.to??(i?t:""),tokens:[c],gasUsed:"0",txType:p,chainId:he(r),explorerLink:ge(r,e.hash)}},"mapLedgerToTransaction"),be=n((e,t,r)=>e.map(o=>o.kind==="fill"?rt(o.fill,o.timeMs,r):ot(o.update,t,r)),"mapHypercoreActivityToTransactions");var Ce=n(async({address:e,network:t,infoClient:r})=>{let o=await de(r,e);return {transactions:be(o,e,t)}},"getTransactionHistory");var Pe=n(async({accountIndex:e,xpub:t,walletType:r})=>{switch(r){case WalletType.Mnemonic:case WalletType.Ledger:case WalletType.Keystone:return {[NetworkVMType.HYPERCORE]:getAddressFromXPub(t,e)};case WalletType.LedgerLive:case WalletType.Seedless:{let o=Buffer.from(t,"hex");return {[NetworkVMType.HYPERCORE]:getEvmAddressFromPubKey(o)}}default:throw rpcErrors.invalidParams(`Unsupported wallet type: ${r}`)}},"getAddress");var Se=n(e=>"derivationPathType"in e&&"accountIndex"in e&&typeof e.accountIndex=="number"&&typeof e.derivationPathType=="string","hasDerivationDetails");var A=n(({accountIndex:e,derivationPathType:t})=>{if(e<0)throw rpcErrors.invalidParams("Account index must be a non-negative integer");switch(t){case"bip44":return {[NetworkVMType.HYPERCORE]:`m/44'/60'/0'/0/${e}`};case"ledger_live":return {[NetworkVMType.HYPERCORE]:`m/44'/60'/${e}'/0/0`};default:throw rpcErrors.invalidParams(`Unsupported derivation path type: ${t}`)}},"buildDerivationPath");var Te=n(async e=>{let{secretId:t,approvalController:r}=e,o=Se(e)?A({accountIndex:e.accountIndex,derivationPathType:e.derivationPathType,addressIndex:e.addressIndex}).HYPERCORE:void 0,i=await r.requestPublicKey({curve:"secp256k1",secretId:t,derivationPath:o});return {[NetworkVMType.HYPERCORE]:computeAddress(`0x${i}`)}},"deriveAddress");var Ue=n(async e=>{let{approvalController:t,secretId:r,accountIndices:o,derivationPathType:i}=e;if(o.length===0)return [];await init();let a=await Promise.all(o.map(async l=>{let c=A({accountIndex:l,derivationPathType:i}).HYPERCORE,d=await t.requestPublicKey({curve:"secp256k1",secretId:r,derivationPath:c});return Uint8Array.from(Buffer.from(d,"hex"))}));return (await deriveAddressesForEvm(a)).map(l=>({[NetworkVMType.HYPERCORE]:l}))},"deriveAddresses");var k,S,Y=class Y{constructor({environment:t,approvalController:r,runtime:o}){g(this,k,void 0);g(this,S,void 0);let{infoUrl:i,activityInfoUrl:a}=K(t);h(this,k,r),h(this,S,new M({infoUrl:i,activityInfoUrl:a,fetch:o?.fetch}));}getProvider(t){return Promise.reject(new Error(V("getProvider")))}getManifest(){let t=parseManifest(j);return t.success?t.data:void 0}getBalances(t){return pe({...t,infoClient:u(this,S)})}getTransactionHistory(t){return Ce({...t,infoClient:u(this,S)})}getNetworkFee(t){return Promise.reject(new Error(V("getNetworkFee")))}getAddress(t){return Pe(t)}buildDerivationPath(t){return A(t)}deriveAddress(t){return Te({...t,approvalController:u(this,k)})}deriveAddresses(t){return Ue({...t,approvalController:u(this,k)})}getTokens(t){return ce({network:t,infoClient:u(this,S)})}async onRpcRequest(t,r){return {error:rpcErrors.methodNotSupported(`HyperCore is read-only; method ${t.method} is not supported`)}}};k=new WeakMap,S=new WeakMap,n(Y,"HypercoreModule");var He=Y;
|
|
10
10
|
|
|
11
|
-
export {
|
|
11
|
+
export { re as HYPERCORE_CAIP_ID, Pt as HYPERCORE_CHAIN_ID, F as HYPERCORE_USDC_DECIMALS, oe as HYPERCORE_USDC_NAME, v as HYPERCORE_USDC_SYMBOL, je as HYPERLIQUID_COIN_SVG_BASE, M as HypercoreInfoClient, He as HypercoreModule, Ze as LEDGER_LOOKBACK_MS, Xe as MAX_LEDGER_PAGES, se as buildHypercoreTokens, Z as clearinghouseStateSchema, tt as closedPnlTone, Oe as devEnv, ye as encodeHypercoreFillMethod, de as fetchHypercoreActivity, ir as fillLabel, ar as formatHypercoreFillPx, K as getEnv, me as getHypercoreLedgerDisplay, Ge as getPerpCollateralUsd, ae as getWithdrawableUsd, _e as hypercoreLedgerDeltaSchema, Ve as hypercoreLedgerUpdateSchema, te as hypercoreLedgerUpdatesSchema, qe as hyperliquidCoinSvgKey, f as hyperliquidCoinSvgUrl, be as mapHypercoreActivityToTransactions, pr as parseHypercoreFillMethod, Me as prodEnv, X as spotClearinghouseStateSchema, L as spotCountsAsPerpCollateral, J as spotMetaResponseSchema, ue as tickerOfCoin, O as toHypercoreSpotTokens, I as toTimeMs, Q as userAbstractionSchema, Be as userFillSchema, ee as userFillsSchema };
|
|
12
12
|
//# sourceMappingURL=out.js.map
|
|
13
13
|
//# sourceMappingURL=index.js.map
|