@avalabs/hypercore-module 3.10.0 → 3.12.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/LICENSE ADDED
@@ -0,0 +1,9 @@
1
+ Copyright (C) 2021, Ava Labs, Inc. All rights reserved.
2
+
3
+ Subject to the limited license below (**”License””), you may not, and you may not permit anyone else to, copy, reproduce, aggregate, republish, download, post, distribute, license, sublicense, reverse engineer, modify, or create derivative works based on this software (collectively, **“Software”**).
4
+
5
+ You are hereby granted a limited, non-exclusive, non-sublicensable and non-transferable license to download and use the Software as-is solely (i) for use in connection with the Avalanche Public Blockchain platform, having a NetworkID of 1 (Mainnet) or 5 (Fuji), and associated blockchains, comprised exclusively of the Avalanche X-Chain, C-Chain, P-Chain and any subnets linked to the P-Chain (**“Avalanche Authorized Platform”**) or (ii) for non-production, testing or research purposes without any commercial application within the Avalanche ecosystem (**“Non-Commercial Use”**); provided that, in each case, you may not use or allow use of the Software (a) in connection with any forks of the Avalanche Authorized Platform, (b) in any manner not operationally connected to the Avalanche Authorized Platform other than for Non-Commercial Use, or (c) to the extent the number of monthly active users or the number of total installs of any software that uses the Software across all versions thereof exceeds 10,000 at any time. You may not modify or alter the Software in any way.
6
+
7
+ You hereby acknowledge and agree to the terms set forth at www.avalabs.org/important-notice.
8
+
9
+ **TO THE MAXIMUM EXTENT PERMITTED BY LAW, THE SOFTWARE IS PROVIDED ON AN “AS IS” BASIS, AND AVA LABS EXPRESSLY DISCLAIMS AND EXCLUDES ALL REPRESENTATIONS, WARRANTIES AND OTHER TERMS AND CONDITIONS, WHETHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION BY OPERATION OF LAW OR BY CUSTOM, STATUTE OR OTHERWISE, AND INCLUDING, BUT NOT LIMITED TO, ANY IMPLIED WARRANTY, TERM, OR CONDITION OF NON-INFRINGEMENT, MERCHANTABILITY, TITLE, OR FITNESS FOR PARTICULAR PURPOSE. YOU USE THE SOFTWARE AT YOUR OWN RISK. AVA LABS EXPRESSLY DISCLAIMS ALL LIABILITY (INCLUDING FOR ALL DIRECT, CONSEQUENTIAL OR OTHER DAMAGES OR LOSSES) RELATED TO ANY USE OF THE SOFTWARE.**
package/dist/index.cjs CHANGED
@@ -3,53 +3,51 @@
3
3
  var vmModuleTypes = require('@avalabs/vm-module-types');
4
4
  var rpcErrors = require('@metamask/rpc-errors');
5
5
  var zod = require('zod');
6
- var C = require('big.js');
6
+ var S = require('big.js');
7
7
  var coreWalletsSdk = require('@avalabs/core-wallets-sdk');
8
8
  var ethers = require('ethers');
9
9
  var cryptoSdk = require('@avalabs/crypto-sdk');
10
10
 
11
11
  function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
12
12
 
13
- var C__default = /*#__PURE__*/_interopDefault(C);
13
+ var S__default = /*#__PURE__*/_interopDefault(S);
14
14
 
15
- var we=Object.defineProperty;var n=(e,t)=>we(e,"name",{value:t,configurable:!0});var _=(e,t,r)=>{if(!t.has(e))throw TypeError("Cannot "+r)};var m=(e,t,r)=>(_(e,t,"read from private field"),r?r.call(e):t.get(e)),f=(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);},g=(e,t,r,o)=>(_(e,t,"write to private field"),o?o.call(e,r):t.set(e,r),r);var V={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 Y="/proxy/nownodes/hype/info",$="https://api.hyperliquid.xyz/info",ke={proxyApiUrl:"https://proxy-api.avax.network",infoUrl:`https://proxy-api.avax.network${Y}`,activityInfoUrl:$},Ae={proxyApiUrl:"https://proxy-api-dev.avax.network",infoUrl:`https://proxy-api-dev.avax.network${Y}`,activityInfoUrl:$},j=n(e=>{switch(e){case vmModuleTypes.Environment.PRODUCTION:return ke;case vmModuleTypes.Environment.DEV:return Ae}},"getEnv");var Re=zod.z.coerce.number(),q=zod.z.object({tokens:zod.z.array(zod.z.object({name:zod.z.string(),index:zod.z.number(),weiDecimals:zod.z.number(),fullName:zod.z.string().nullish(),evmContract:zod.z.object({address:zod.z.string()}).nullish()}))}),Ie=zod.z.object({coin:zod.z.string(),token:Re,total:zod.z.string(),hold:zod.z.string(),entryNtl:zod.z.string().optional()}),W=zod.z.object({balances:zod.z.array(Ie)}),Ee=zod.z.object({accountValue:zod.z.string(),totalMarginUsed:zod.z.string().optional(),totalNtlPos:zod.z.string().optional(),totalRawUsd:zod.z.string().optional()}),z=zod.z.object({assetPositions:zod.z.array(zod.z.object({position:zod.z.object({unrealizedPnl:zod.z.string()})})),crossMarginSummary:Ee}),K=zod.z.string().transform(e=>{switch(e){case"unifiedAccount":case"portfolioMargin":case"dexAbstraction":case"disabled":case"default":return e;default:return "default"}}),De=zod.z.object({closedPnl:zod.z.string(),coin:zod.z.string(),crossed:zod.z.boolean(),dir:zod.z.string(),hash:zod.z.string(),oid:zod.z.number(),px:zod.z.string(),side:zod.z.string(),startPosition:zod.z.string(),sz:zod.z.string(),time:zod.z.number(),fee:zod.z.string().optional(),tid:zod.z.number().optional()}),J=zod.z.array(De),Me=zod.z.object({type:zod.z.string(),usdc:zod.z.string().optional(),amount:zod.z.string().optional(),usdcValue:zod.z.string().optional(),token:zod.z.string().optional(),user:zod.z.string().optional(),destination:zod.z.string().optional(),fee:zod.z.string().optional(),toPerp:zod.z.boolean().optional()}),Oe=zod.z.object({time:zod.z.number(),hash:zod.z.string(),delta:Me}),X=zod.z.array(Oe);var H=n(e=>e.toLowerCase(),"lowercaseUser"),k,P,A,O=class O{constructor(t){f(this,k,void 0);f(this,P,void 0);f(this,A,void 0);g(this,k,t.infoUrl),g(this,P,t.activityInfoUrl??t.infoUrl),g(this,A,t.fetch??globalThis.fetch.bind(globalThis));}async postInfo(t,r,o){let i=await m(this,A).call(this,o?.url??m(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 p=await i.json();return r.parse(p)}getSpotMeta(t){return this.postInfo({type:"spotMeta"},q,t)}getSpotClearinghouseState(t,r){return this.postInfo({type:"spotClearinghouseState",user:H(t),dex:""},W,r)}getClearinghouseState(t,r){return this.postInfo({type:"clearinghouseState",user:H(t),dex:""},z,r)}getUserAbstraction(t,r){return this.postInfo({type:"userAbstraction",user:H(t)},K,r)}getUserFills(t,r){return this.postInfo({type:"userFills",user:H(t)},J,{...r,url:r?.url??m(this,P)})}getUserNonFundingLedgerUpdates(t,r,o){return this.postInfo({type:"userNonFundingLedgerUpdates",user:H(t),startTime:r},X,{...o,url:o?.url??m(this,P)})}};k=new WeakMap,P=new WeakMap,A=new WeakMap,n(O,"HypercoreInfoClient");var E=O;var N=n(e=>`HyperCore does not support ${e}: read-only module (balances, tokens, activity).`,"unsupportedHypercoreCapabilityMessage");var Z="hlcore:mainnet",vt=9999,D="USDC",Q="USD Coin",F=8;var h=new C__default.default(0),Ne=n(e=>e==="unifiedAccount","spotCountsAsPerpCollateral"),ee=n((e,t)=>e.times(new C__default.default(10).pow(t)).round(0,C__default.default.roundDown).toFixed(0),"toRawBalance"),Fe=n(e=>{if(!e)return h;let t=new C__default.default(e.crossMarginSummary.accountValue??"0"),r=e.assetPositions.reduce((i,{position:p})=>i.plus(p.unrealizedPnl),h),o=t.minus(r);return o.gt(h)?o:h},"getPerpCollateralUsd"),te=n(({spotBalances:e,perpState:t,abstractionMode:r,spotTokens:o})=>{let i=new Map(o.map(d=>[d.index,d])),p=Ne(r)?h:Fe(t),a=e.find(d=>d.coin.toUpperCase()===D),c=new C__default.default(a?.total??"0").plus(p),l=[];c.gt(h)&&l.push({kind:"native",name:Q,symbol:D,decimals:8,balance:c.toString(),balanceRaw:ee(c,8),priceUsd:1,balanceUsd:c.toString()});for(let d of e){if(d.coin.toUpperCase()===D)continue;let u=i.get(d.token),w=new C__default.default(d.total);!u||!w.gt(h)||l.push({kind:"spot",name:u.name,symbol:u.symbol,decimals:u.decimals,balance:w.toString(),balanceRaw:ee(w,u.decimals),index:u.index,evmContract:u.evmContract});}return l},"buildHypercoreTokens");var Le="https://app.hyperliquid.xyz/coins",Be=n(e=>{let t=e.trim(),r=t.indexOf(":");return r===-1?t.toUpperCase():`${t.slice(0,r)}:${t.slice(r+1).toUpperCase()}`},"hyperliquidCoinSvgKey"),y=n(e=>`${Le}/${encodeURIComponent(Be(e))}.svg`,"hyperliquidCoinSvgUrl");var Ve=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:vmModuleTypes.TokenType.HYPERCORE_SPOT,index:t.index,name:t.fullName??t.name,symbol:t.name,decimals:t.weiDecimals,evmContract:r&&Ve(r)?r:void 0}}),"toHypercoreSpotTokens");var Ge=n((e,t)=>{if(e.kind==="native"){let i=BigInt(e.balanceRaw),p=Number(e.balanceUsd),a={...t,name:e.name,symbol:e.symbol,decimals:e.decimals,logoUri:t.logoUri??y(e.symbol),coingeckoId:"usd-coin",type:vmModuleTypes.TokenType.NATIVE,balance:i,balanceDisplayValue:e.balance,balanceInCurrency:Number.isFinite(p)?p:0,balanceCurrencyDisplayValue:e.balanceUsd,priceInCurrency:e.priceUsd};return {key:e.symbol,value:a}}let r=BigInt(e.balanceRaw),o={type:vmModuleTypes.TokenType.HYPERCORE_SPOT,name:e.name,symbol:e.symbol,decimals:e.decimals,index:e.index,evmContract:e.evmContract,logoUri:y(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})=>{let o=await r.getSpotMeta(),i=M(o.tokens);return (await Promise.allSettled(e.map(async a=>{try{let[c,l,d]=await Promise.all([r.getSpotClearinghouseState(a),r.getClearinghouseState(a).catch(()=>{}),r.getUserAbstraction(a).catch(()=>{})]),u=te({spotBalances:c.balances,perpState:l,abstractionMode:d,spotTokens:i}),w=Object.fromEntries(u.map(Se=>{let{key:Te,value:Ue}=Ge(Se,t.networkToken);return [Te,Ue]}));return {[a]:w}}catch(c){return {[a]:{error:c.toString()}}}}))).reduce((a,c)=>c.status==="fulfilled"?{...a,...c.value}:a,{})},"getBalances");var ne=n(async({infoClient:e})=>{let t=await e.getSpotMeta();return M(t.tokens).map(r=>({...r,logoUri:r.logoUri??y(r.symbol)}))},"getTokens");var R=n(e=>e<1e10?e*1e3:e,"toTimeMs");var Ye=20,$e=365*24*60*60*1e3,je=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(je(r))throw r;return t}},"softFail"),qe=n(async(e,t,r)=>{let o=[],i=Date.now()-$e,p=0;for(;p<Ye;){if(r?.signal?.aborted)throw new DOMException("The operation was aborted.","AbortError");let a=await e.getUserNonFundingLedgerUpdates(t,i,r);if(p+=1,a.length===0)break;o.push(...a);let c=a[a.length-1];if(!c)break;let l=c.time+1;if(l<=i)break;i=l;}return o},"fetchLedgerUpdates"),ie=n(async(e,t,r)=>{let[o,i]=await Promise.all([se(e.getUserFills(t,r),[]),se(qe(e,t,r),[])]);return [...o.map(a=>({kind:"fill",timeMs:R(a.time),hash:a.hash,fill:a})),...i.map(a=>({kind:"ledger",timeMs:R(a.time),hash:a.hash,update:a}))].sort((a,c)=>c.timeMs-a.timeMs)},"fetchHypercoreActivity");var b=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:b(r.usdc),symbol:"USDC",usdValue:x(r.usdc,1),direction:"positive",to:t,rawType:r.type};case"withdraw":return {label:"withdraw",amount:b(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:b(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:b(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:b(r.usdc),symbol:"USDC",usdValue:x(r.usdc,0),direction:"neutral",rawType:r.type};case"liquidation":return {label:"liquidation",amount:b(r.usdcValue??r.usdc),symbol:"USDC",usdValue:x(r.usdcValue??r.usdc,-1),direction:"negative",rawType:r.type};default:return {label:"other",amount:b(r.usdcValue??r.usdc),symbol:"USDC",usdValue:x(r.usdcValue??r.usdc,0),direction:"neutral",rawType:r.type}}},"getHypercoreLedgerDisplay");var L="hypercoreFill:v1:",We="\u25B2",ze="\u25BC",pe=n(e=>{let t=e.indexOf(":");return t===-1?e:e.slice(t+1)},"tickerOfCoin"),Ke=n(e=>{if(e===void 0)return;let t=Number.parseFloat(e);if(!(!Number.isFinite(t)||t===0))return t>0?"profit":"loss"},"closedPnlTone"),zt=n((e,t)=>{let r=Ke(t),o=e.toLowerCase();return o.includes("close")&&o.includes("long")?{text:"Long closed",arrow:We,tone:r}:o.includes("close")&&o.includes("short")?{text:"Short closed",arrow:ze,tone:r}:o.includes("open")&&(o.includes("long")||o.includes("short"))?{text:"Order opened"}:o.includes("cancel")?{text:"Order cancelled"}:{text:e}},"fillLabel"),Kt=n(e=>{let t=Number.parseFloat(e);return Number.isFinite(t)?`$${t.toLocaleString(void 0,{maximumFractionDigits:8})}`:e},"formatHypercoreFillPx"),ce=n(e=>`${L}${encodeURIComponent(JSON.stringify(e))}`,"encodeHypercoreFillMethod"),Jt=n(e=>{if(e?.startsWith(L))try{let t=JSON.parse(decodeURIComponent(e.slice(L.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:p}=t;return typeof r!="string"||typeof o!="string"||typeof i!="string"||typeof p!="string"?void 0:{dir:r,px:o,closedPnl:i,coin:p}}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??Z,"chainIdForNetwork"),Je=n((e,t,r)=>{let o=e.side==="B",i=pe(e.coin),p={type:vmModuleTypes.TokenType.NATIVE,name:e.coin,symbol:i,amount:e.sz,imageUri:y(e.coin)};return {isContractCall:!1,isIncoming:o,isOutgoing:!o,isSender:!o,timestamp:t,hash:e.hash,from:"",to:"",tokens:[p],gasUsed:"0",txType:vmModuleTypes.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"),Xe=n((e,t,r)=>{let o=ae(e,t),i=o.direction==="positive",p=o.direction==="negative",a=vmModuleTypes.TransactionType.TRANSFER;switch(o.label){case"deposit":case"received":a=vmModuleTypes.TransactionType.RECEIVE;break;case"withdraw":case"sent":a=vmModuleTypes.TransactionType.SEND;break;case"liquidation":a=vmModuleTypes.TransactionType.UNKNOWN;break;default:a=vmModuleTypes.TransactionType.TRANSFER;}let c=o.amount||"0",l={type:vmModuleTypes.TokenType.NATIVE,name:o.symbol,symbol:o.symbol,amount:c,imageUri:y(o.symbol)};return {isContractCall:!1,isIncoming:i,isOutgoing:p,isSender:p,timestamp:R(e.time),hash:e.hash,from:o.from??(p?t:""),to:o.to??(i?t:""),tokens:[l],gasUsed:"0",txType:a,chainId:me(r),explorerLink:de(r,e.hash)}},"mapLedgerToTransaction"),ue=n((e,t,r)=>e.map(o=>o.kind==="fill"?Je(o.fill,o.timeMs,r):Xe(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 vmModuleTypes.WalletType.Mnemonic:case vmModuleTypes.WalletType.Ledger:case vmModuleTypes.WalletType.Keystone:return {[vmModuleTypes.NetworkVMType.HYPERCORE]:coreWalletsSdk.getAddressFromXPub(t,e)};case vmModuleTypes.WalletType.LedgerLive:case vmModuleTypes.WalletType.Seedless:{let o=Buffer.from(t,"hex");return {[vmModuleTypes.NetworkVMType.HYPERCORE]:coreWalletsSdk.getEvmAddressFromPubKey(o)}}default:throw rpcErrors.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 T=n(({accountIndex:e,derivationPathType:t})=>{if(e<0)throw rpcErrors.rpcErrors.invalidParams("Account index must be a non-negative integer");switch(t){case"bip44":return {[vmModuleTypes.NetworkVMType.HYPERCORE]:`m/44'/60'/0'/0/${e}`};case"ledger_live":return {[vmModuleTypes.NetworkVMType.HYPERCORE]:`m/44'/60'/${e}'/0/0`};default:throw rpcErrors.rpcErrors.invalidParams(`Unsupported derivation path type: ${t}`)}},"buildDerivationPath");var ve=n(async e=>{let{secretId:t,approvalController:r}=e,o=he(e)?T({accountIndex:e.accountIndex,derivationPathType:e.derivationPathType,addressIndex:e.addressIndex}).HYPERCORE:void 0,i=await r.requestPublicKey({curve:"secp256k1",secretId:t,derivationPath:o});return {[vmModuleTypes.NetworkVMType.HYPERCORE]:ethers.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 cryptoSdk.init();let p=await Promise.all(o.map(async c=>{let l=T({accountIndex:c,derivationPathType:i}).HYPERCORE,d=await t.requestPublicKey({curve:"secp256k1",secretId:r,derivationPath:l});return Uint8Array.from(Buffer.from(d,"hex"))}));return (await cryptoSdk.deriveAddressesForEvm(p)).map(c=>({[vmModuleTypes.NetworkVMType.HYPERCORE]:c}))},"deriveAddresses");var U,v,B=class B{constructor({environment:t,approvalController:r,runtime:o}){f(this,U,void 0);f(this,v,void 0);let{infoUrl:i,activityInfoUrl:p}=j(t);g(this,U,r),g(this,v,new E({infoUrl:i,activityInfoUrl:p,fetch:o?.fetch}));}getProvider(t){return Promise.reject(new Error(N("getProvider")))}getManifest(){let t=vmModuleTypes.parseManifest(V);return t.success?t.data:void 0}getBalances(t){return oe({...t,infoClient:m(this,v)})}getTransactionHistory(t){return ye({...t,infoClient:m(this,v)})}getNetworkFee(t){return Promise.reject(new Error(N("getNetworkFee")))}getAddress(t){return ge(t)}buildDerivationPath(t){return T(t)}deriveAddress(t){return ve({...t,approvalController:m(this,U)})}deriveAddresses(t){return Pe({...t,approvalController:m(this,U)})}getTokens(t){return ne({network:t,infoClient:m(this,v)})}async onRpcRequest(t,r){return {error:rpcErrors.rpcErrors.methodNotSupported(`HyperCore is read-only; method ${t.method} is not supported`)}}};U=new WeakMap,v=new WeakMap,n(B,"HypercoreModule");var Ce=B;
15
+ 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 vmModuleTypes.Environment.PRODUCTION:return Ae;case vmModuleTypes.Environment.DEV:return Re}},"getEnv");var Ee=zod.z.coerce.number(),z=zod.z.object({tokens:zod.z.array(zod.z.object({name:zod.z.string(),index:zod.z.number(),weiDecimals:zod.z.number(),fullName:zod.z.string().nullish(),evmContract:zod.z.object({address:zod.z.string()}).nullish()}))}),Ie=zod.z.object({coin:zod.z.string(),token:Ee,total:zod.z.string(),hold:zod.z.string(),entryNtl:zod.z.string().optional()}),K=zod.z.object({balances:zod.z.array(Ie)}),De=zod.z.object({accountValue:zod.z.string(),totalMarginUsed:zod.z.string().optional(),totalNtlPos:zod.z.string().optional(),totalRawUsd:zod.z.string().optional()}),W=zod.z.object({assetPositions:zod.z.array(zod.z.object({position:zod.z.object({unrealizedPnl:zod.z.string()})})),crossMarginSummary:De}),J=zod.z.string().transform(e=>{switch(e){case"unifiedAccount":case"portfolioMargin":case"dexAbstraction":case"disabled":case"default":return e;default:return "default"}}),Me=zod.z.object({closedPnl:zod.z.string(),coin:zod.z.string(),crossed:zod.z.boolean(),dir:zod.z.string(),hash:zod.z.string(),oid:zod.z.number(),px:zod.z.string(),side:zod.z.string(),startPosition:zod.z.string(),sz:zod.z.string(),time:zod.z.number(),fee:zod.z.string().optional(),tid:zod.z.number().optional()}),X=zod.z.array(Me),Ne=zod.z.object({type:zod.z.string(),usdc:zod.z.string().optional(),amount:zod.z.string().optional(),usdcValue:zod.z.string().optional(),token:zod.z.string().optional(),user:zod.z.string().optional(),destination:zod.z.string().optional(),fee:zod.z.string().optional(),toPerp:zod.z.boolean().optional()}),Oe=zod.z.object({time:zod.z.number(),hash:zod.z.string(),delta:Ne}),Z=zod.z.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__default.default(0),Le=n(e=>e==="unifiedAccount","spotCountsAsPerpCollateral"),te=n((e,t)=>e.times(new S__default.default(10).pow(t)).round(0,S__default.default.roundDown).toFixed(0),"toRawBalance"),Be=n(e=>{if(!e)return b;let t=new S__default.default(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__default.default(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__default.default(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:vmModuleTypes.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:vmModuleTypes.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:vmModuleTypes.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=[vmModuleTypes.TokenType.NATIVE,vmModuleTypes.TokenType.HYPERCORE_SPOT]})=>{let i=o.includes(vmModuleTypes.TokenType.NATIVE),a=o.includes(vmModuleTypes.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:vmModuleTypes.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:vmModuleTypes.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=vmModuleTypes.TransactionType.TRANSFER;switch(o.label){case"deposit":case"received":p=vmModuleTypes.TransactionType.RECEIVE;break;case"withdraw":case"sent":p=vmModuleTypes.TransactionType.SEND;break;case"liquidation":p=vmModuleTypes.TransactionType.UNKNOWN;break;default:p=vmModuleTypes.TransactionType.TRANSFER;}let l=o.amount||"0",c={type:vmModuleTypes.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 vmModuleTypes.WalletType.Mnemonic:case vmModuleTypes.WalletType.Ledger:case vmModuleTypes.WalletType.Keystone:return {[vmModuleTypes.NetworkVMType.HYPERCORE]:coreWalletsSdk.getAddressFromXPub(t,e)};case vmModuleTypes.WalletType.LedgerLive:case vmModuleTypes.WalletType.Seedless:{let o=Buffer.from(t,"hex");return {[vmModuleTypes.NetworkVMType.HYPERCORE]:coreWalletsSdk.getEvmAddressFromPubKey(o)}}default:throw rpcErrors.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.rpcErrors.invalidParams("Account index must be a non-negative integer");switch(t){case"bip44":return {[vmModuleTypes.NetworkVMType.HYPERCORE]:`m/44'/60'/0'/0/${e}`};case"ledger_live":return {[vmModuleTypes.NetworkVMType.HYPERCORE]:`m/44'/60'/${e}'/0/0`};default:throw rpcErrors.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 {[vmModuleTypes.NetworkVMType.HYPERCORE]:ethers.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 cryptoSdk.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 cryptoSdk.deriveAddressesForEvm(a)).map(l=>({[vmModuleTypes.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=vmModuleTypes.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.rpcErrors.methodNotSupported(`HyperCore is read-only; method ${t.method} is not supported`)}}};H=new WeakMap,P=new WeakMap,n(_,"HypercoreModule");var Ce=_;
16
16
 
17
- exports.FILL_ARROW_DOWN = ze;
18
- exports.FILL_ARROW_UP = We;
19
- exports.HYPERCORE_CAIP_ID = Z;
20
- exports.HYPERCORE_CHAIN_ID = vt;
21
- exports.HYPERCORE_USDC_DECIMALS = F;
22
- exports.HYPERCORE_USDC_NAME = Q;
17
+ exports.HYPERCORE_CAIP_ID = Q;
18
+ exports.HYPERCORE_CHAIN_ID = Pt;
19
+ exports.HYPERCORE_USDC_DECIMALS = L;
20
+ exports.HYPERCORE_USDC_NAME = ee;
23
21
  exports.HYPERCORE_USDC_SYMBOL = D;
24
- exports.HYPERLIQUID_COIN_SVG_BASE = Le;
25
- exports.HypercoreInfoClient = E;
22
+ exports.HYPERLIQUID_COIN_SVG_BASE = _e;
23
+ exports.HypercoreInfoClient = I;
26
24
  exports.HypercoreModule = Ce;
27
- exports.LEDGER_LOOKBACK_MS = $e;
28
- exports.MAX_LEDGER_PAGES = Ye;
29
- exports.buildHypercoreTokens = te;
30
- exports.clearinghouseStateSchema = z;
31
- exports.closedPnlTone = Ke;
25
+ exports.LEDGER_LOOKBACK_MS = ze;
26
+ exports.MAX_LEDGER_PAGES = qe;
27
+ exports.buildHypercoreTokens = re;
28
+ exports.clearinghouseStateSchema = W;
29
+ exports.closedPnlTone = Je;
32
30
  exports.encodeHypercoreFillMethod = ce;
33
31
  exports.fetchHypercoreActivity = ie;
34
- exports.fillLabel = zt;
35
- exports.formatHypercoreFillPx = Kt;
32
+ exports.fillLabel = Wt;
33
+ exports.formatHypercoreFillPx = Jt;
36
34
  exports.getHypercoreLedgerDisplay = ae;
37
- exports.getPerpCollateralUsd = Fe;
38
- exports.hypercoreLedgerDeltaSchema = Me;
35
+ exports.getPerpCollateralUsd = Be;
36
+ exports.hypercoreLedgerDeltaSchema = Ne;
39
37
  exports.hypercoreLedgerUpdateSchema = Oe;
40
- exports.hypercoreLedgerUpdatesSchema = X;
41
- exports.hyperliquidCoinSvgKey = Be;
42
- exports.hyperliquidCoinSvgUrl = y;
38
+ exports.hypercoreLedgerUpdatesSchema = Z;
39
+ exports.hyperliquidCoinSvgKey = Ve;
40
+ exports.hyperliquidCoinSvgUrl = f;
43
41
  exports.mapHypercoreActivityToTransactions = ue;
44
- exports.parseHypercoreFillMethod = Jt;
45
- exports.spotClearinghouseStateSchema = W;
46
- exports.spotCountsAsPerpCollateral = Ne;
47
- exports.spotMetaResponseSchema = q;
42
+ exports.parseHypercoreFillMethod = Xt;
43
+ exports.spotClearinghouseStateSchema = K;
44
+ exports.spotCountsAsPerpCollateral = Le;
45
+ exports.spotMetaResponseSchema = z;
48
46
  exports.tickerOfCoin = pe;
49
47
  exports.toHypercoreSpotTokens = M;
50
48
  exports.toTimeMs = R;
51
- exports.userAbstractionSchema = K;
52
- exports.userFillSchema = De;
53
- exports.userFillsSchema = J;
49
+ exports.userAbstractionSchema = J;
50
+ exports.userFillSchema = Me;
51
+ exports.userFillsSchema = X;
54
52
  //# sourceMappingURL=out.js.map
55
53
  //# sourceMappingURL=index.cjs.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/module.ts","../manifest.json","../src/env.ts","../src/utils/schemas.ts","../src/utils/info-client.ts","../src/utils/unsupported.ts","../src/handlers/get-balances/get-balances.ts","../src/utils/build-hypercore-tokens.ts","../src/constants.ts","../src/utils/hyperliquid-coin-svg-url.ts","../src/utils/spot-tokens.ts","../src/handlers/get-tokens/get-tokens.ts","../src/utils/activity/types.ts","../src/utils/activity/fetch-hypercore-activity.ts","../src/utils/activity/map-hypercore-activity-to-transactions.ts","../src/utils/activity/get-hypercore-ledger-display.ts","../src/utils/activity/hypercore-fill-meta.ts","../src/handlers/get-transaction-history/get-transaction-history.ts","../src/handlers/get-address/get-address.ts","../src/handlers/derive-address/derive-address.ts","../../../packages-internal/utils/src/utils/address-derivation.ts","../src/handlers/build-derivation-path/build-derivation-path.ts","../src/handlers/derive-addresses/derive-addresses.ts"],"names":["parseManifest","rpcErrors","manifest_default","Environment","INFO_PATH","PUBLIC_ACTIVITY_INFO_URL","prodEnv","devEnv","getEnv","__name","environment","z","tokenIndexSchema","spotMetaResponseSchema","spotBalanceSchema","spotClearinghouseStateSchema","marginSummarySchema","clearinghouseStateSchema","userAbstractionSchema","value","userFillSchema","userFillsSchema","hypercoreLedgerDeltaSchema","hypercoreLedgerUpdateSchema","hypercoreLedgerUpdatesSchema","lowercaseUser","user","_infoUrl","_activityInfoUrl","_fetch","_HypercoreInfoClient","config","__privateAdd","__privateSet","body","schema","options","response","__privateGet","json","startTime","HypercoreInfoClient","unsupportedHypercoreCapabilityMessage","capability","TokenType","Big","HYPERCORE_CAIP_ID","HYPERCORE_CHAIN_ID","HYPERCORE_USDC_SYMBOL","HYPERCORE_USDC_NAME","HYPERCORE_USDC_DECIMALS","BIG_ZERO","spotCountsAsPerpCollateral","mode","toRawBalance","humanAmount","decimals","getPerpCollateralUsd","perp","accountValue","unrealizedPnl","sum","position","collateral","buildHypercoreTokens","spotBalances","perpState","abstractionMode","spotTokens","tokensByIndex","token","perpCollateralUsd","spotUsdc","balance","usdcTotal","tokens","meta","total","HYPERLIQUID_COIN_SVG_BASE","hyperliquidCoinSvgKey","coin","trimmed","separatorIndex","hyperliquidCoinSvgUrl","isValidEvmAddress","address","toHypercoreSpotTokens","toTokenWithBalance","networkToken","balanceInCurrency","native","spot","getBalances","addresses","network","infoClient","spotMeta","spotState","bySymbol","key","err","acc","curr","getTokens","toTimeMs","time","MAX_LEDGER_PAGES","LEDGER_LOOKBACK_MS","isAbortError","softFail","promise","fallback","fetchLedgerUpdates","client","evmAddress","all","pages","page","last","next","fetchHypercoreActivity","fills","ledgerUpdates","fill","update","b","TransactionType","formatAmount","parsed","toUsd","sign","getHypercoreLedgerDisplay","delta","owner","isOutgoing","METHOD_PREFIX","FILL_ARROW_UP","FILL_ARROW_DOWN","tickerOfCoin","i","closedPnlTone","closedPnl","n","fillLabel","dir","tone","d","formatHypercoreFillPx","px","encodeHypercoreFillMethod","parseHypercoreFillMethod","method","explorerTxLink","hash","base","chainIdForNetwork","mapFillToTransaction","timeMs","isBuy","ticker","mapLedgerToTransaction","display","isIncoming","txType","amount","mapHypercoreActivityToTransactions","items","item","getTransactionHistory","NetworkVMType","WalletType","getAddressFromXPub","getEvmAddressFromPubKey","getAddress","accountIndex","xpub","walletType","pubKeyBuffer","computeAddress","hasDerivationDetails","params","buildDerivationPath","derivationPathType","deriveAddress","secretId","approvalController","derivationPath","publicKeyHex","deriveAddressesForEvm","init","deriveAddresses","accountIndices","publicKeys","_approvalController","_infoClient","_HypercoreModule","runtime","infoUrl","activityInfoUrl","_network","result","request","HypercoreModule"],"mappings":"oaAiBA,OAAS,iBAAAA,OAAqB,2BAC9B,OAAS,aAAAC,OAAiB,uBClB1B,IAAAC,EAAA,CACE,KAAQ,YACR,YAAe,uEACf,QAAW,QACX,QAAW,CACT,OAAU,CACR,SAAY,GACZ,SAAY,CACV,IAAO,CACL,SAAY,gBACZ,YAAe,4BACf,SAAY,4BACd,CACF,CACF,CACF,EACA,QAAW,CACT,SAAY,C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M,CAC1B,CAEA,oBAAoBA,EAAmC,CACrD,OAAOC,EAAoBD,CAAM,CACnC,CAEA,cAAcA,EAA6B,CACzC,OAAOG,GAAc,CACnB,GAAGH,EACH,mBAAoB9I,EAAA,KAAK2J,EAC3B,CAAC,CACH,CAEA,gBAAgBb,EAA+B,CAC7C,OAAOU,GAAgB,CACrB,GAAGV,EACH,mBAAoB9I,EAAA,KAAK2J,EAC3B,CAAC,CACH,CAEA,UAAUnG,EAAkB,CAC1B,OAAOS,GAAU,CAAE,QAAAT,EAAS,WAAYxD,EAAA,KAAK4J,EAAY,CAAC,CAC5D,CAEA,MAAM,aAAaO,EAAqBF,EAAmB,CACzD,MAAO,CACL,MAAOtM,GAAU,mBAAmB,kCAAkCwM,EAAQ,MAAM,mBAAmB,CACzG,CACF,CACF,EAxEER,EAAA,YACAC,EAAA,YAF6CzL,EAAA0L,EAAA,mBAAxC,IAAMO,GAANP","sourcesContent":["import type {\n Module,\n Manifest,\n ConstructorParams,\n ApprovalController,\n RpcRequest,\n Network,\n NetworkFees,\n GetBalancesParams,\n GetAddressParams,\n GetAddressResponse,\n DeriveAddressParams,\n DeriveAddressesParams,\n BuildDerivationPathParams,\n GetTransactionHistory,\n NetworkFeeParam,\n} from '@avalabs/vm-module-types';\nimport { parseManifest } from '@avalabs/vm-module-types';\nimport { rpcErrors } from '@metamask/rpc-errors';\n\nimport ManifestJson from '../manifest.json';\nimport { getEnv } from './env';\nimport { HypercoreInfoClient } from './utils/info-client';\nimport { unsupportedHypercoreCapabilityMessage } from './utils/unsupported';\nimport { getBalances } from './handlers/get-balances/get-balances';\nimport { getTokens } from './handlers/get-tokens/get-tokens';\nimport { getTransactionHistory } from './handlers/get-transaction-history/get-transaction-history';\nimport { getAddress } from './handlers/get-address/get-address';\nimport { deriveAddress } from './handlers/derive-address/derive-address';\nimport { deriveAddresses } from './handlers/derive-addresses/derive-addresses';\nimport { buildDerivationPath } from './handlers/build-derivation-path/build-derivation-path';\n\nexport class HypercoreModule implements Module {\n #approvalController: ApprovalController;\n #infoClient: HypercoreInfoClient;\n\n constructor({ environment, approvalController, runtime }: ConstructorParams) {\n const { infoUrl, activityInfoUrl } = getEnv(environment);\n\n this.#approvalController = approvalController;\n this.#infoClient = new HypercoreInfoClient({\n infoUrl,\n activityInfoUrl,\n fetch: runtime?.fetch,\n });\n }\n\n getProvider(_network: Network): Promise<never> {\n return Promise.reject(new Error(unsupportedHypercoreCapabilityMessage('getProvider')));\n }\n\n getManifest(): Manifest | undefined {\n const result = parseManifest(ManifestJson);\n return result.success ? result.data : undefined;\n }\n\n getBalances(params: GetBalancesParams) {\n return getBalances({\n ...params,\n infoClient: this.#infoClient,\n });\n }\n\n getTransactionHistory(params: GetTransactionHistory) {\n return getTransactionHistory({\n ...params,\n infoClient: this.#infoClient,\n });\n }\n\n getNetworkFee(_network: NetworkFeeParam): Promise<NetworkFees> {\n return Promise.reject(new Error(unsupportedHypercoreCapabilityMessage('getNetworkFee')));\n }\n\n getAddress(params: GetAddressParams): Promise<GetAddressResponse> {\n return getAddress(params);\n }\n\n buildDerivationPath(params: BuildDerivationPathParams) {\n return buildDerivationPath(params);\n }\n\n deriveAddress(params: DeriveAddressParams) {\n return deriveAddress({\n ...params,\n approvalController: this.#approvalController,\n });\n }\n\n deriveAddresses(params: DeriveAddressesParams) {\n return deriveAddresses({\n ...params,\n approvalController: this.#approvalController,\n });\n }\n\n getTokens(network: Network) {\n return getTokens({ network, infoClient: this.#infoClient });\n }\n\n async onRpcRequest(request: RpcRequest, _network: Network) {\n return {\n error: rpcErrors.methodNotSupported(`HyperCore is read-only; method ${request.method} is not supported`),\n };\n }\n}\n","{\n \"name\": \"HyperCore\",\n \"description\": \"Read-only Hyperliquid HyperCore module (balances, tokens, activity).\",\n \"version\": \"0.0.1\",\n \"sources\": {\n \"module\": {\n \"checksum\": \"\",\n \"location\": {\n \"npm\": {\n \"filePath\": \"dist/index.js\",\n \"packageName\": \"@avalabs/hypercore-module\",\n \"registry\": \"https://registry.npmjs.org\"\n }\n }\n }\n },\n \"network\": {\n \"chainIds\": [\"hlcore:mainnet\"],\n \"namespaces\": [\"hlcore\"]\n },\n \"cointype\": \"60\",\n \"permissions\": {\n \"rpc\": {\n \"dapps\": false,\n \"methods\": [],\n \"nonRestrictedMethods\": []\n }\n },\n \"manifestVersion\": \"0.1\"\n}\n","import { Environment } from '@avalabs/vm-module-types';\n\ntype Env = {\n proxyApiUrl: string;\n /** Proxy-first Hyperliquid `/info` endpoint. */\n infoUrl: string;\n /**\n * Fallback for activity endpoints if the proxy does not support fills/ledger.\n * Prefer `infoUrl` when possible.\n */\n activityInfoUrl: string;\n};\n\nconst INFO_PATH = '/proxy/nownodes/hype/info';\nconst PUBLIC_ACTIVITY_INFO_URL = 'https://api.hyperliquid.xyz/info';\n\nexport const prodEnv: Env = {\n proxyApiUrl: 'https://proxy-api.avax.network',\n infoUrl: `https://proxy-api.avax.network${INFO_PATH}`,\n activityInfoUrl: PUBLIC_ACTIVITY_INFO_URL,\n};\n\nexport const devEnv: Env = {\n proxyApiUrl: 'https://proxy-api-dev.avax.network',\n infoUrl: `https://proxy-api-dev.avax.network${INFO_PATH}`,\n activityInfoUrl: PUBLIC_ACTIVITY_INFO_URL,\n};\n\nexport const getEnv = (environment: Environment): Env => {\n switch (environment) {\n case Environment.PRODUCTION:\n return prodEnv;\n case Environment.DEV:\n return devEnv;\n }\n};\n","import { z } from 'zod';\n\nconst tokenIndexSchema = z.coerce.number();\n\n/** `type: \"spotMeta\"` — registry mapping spot token index → display metadata. */\nexport const spotMetaResponseSchema = z.object({\n tokens: z.array(\n z.object({\n name: z.string(),\n index: z.number(),\n weiDecimals: z.number(),\n fullName: z.string().nullish(),\n evmContract: z.object({ address: z.string() }).nullish(),\n }),\n ),\n});\n\nconst spotBalanceSchema = z.object({\n coin: z.string(),\n token: tokenIndexSchema,\n total: z.string(),\n hold: z.string(),\n entryNtl: z.string().optional(),\n});\n\n/** `type: \"spotClearinghouseState\"` */\nexport const spotClearinghouseStateSchema = z.object({\n balances: z.array(spotBalanceSchema),\n});\n\nconst marginSummarySchema = z.object({\n accountValue: z.string(),\n totalMarginUsed: z.string().optional(),\n totalNtlPos: z.string().optional(),\n totalRawUsd: z.string().optional(),\n});\n\n/**\n * `type: \"clearinghouseState\"` — only fields needed for PnL-excluded\n * perp collateral fold-in.\n */\nexport const clearinghouseStateSchema = z.object({\n assetPositions: z.array(\n z.object({\n position: z.object({\n unrealizedPnl: z.string(),\n }),\n }),\n ),\n crossMarginSummary: marginSummarySchema,\n});\n\nexport type UserAbstractionMode = 'unifiedAccount' | 'portfolioMargin' | 'dexAbstraction' | 'disabled' | 'default';\n\n/**\n * `type: \"userAbstraction\"` — bare JSON string. Unknown future values coerce\n * to `\"default\"` so balance math stays conservative.\n */\nexport const userAbstractionSchema = z.string().transform((value): UserAbstractionMode => {\n switch (value) {\n case 'unifiedAccount':\n case 'portfolioMargin':\n case 'dexAbstraction':\n case 'disabled':\n case 'default':\n return value;\n default:\n return 'default';\n }\n});\n\n/** `type: \"userFills\"` */\nexport const userFillSchema = z.object({\n closedPnl: z.string(),\n coin: z.string(),\n crossed: z.boolean(),\n dir: z.string(),\n hash: z.string(),\n oid: z.number(),\n px: z.string(),\n side: z.string(),\n startPosition: z.string(),\n sz: z.string(),\n time: z.number(),\n fee: z.string().optional(),\n tid: z.number().optional(),\n});\n\nexport const userFillsSchema = z.array(userFillSchema);\n\n/**\n * `userNonFundingLedgerUpdates` deltas — permissive so unknown delta types\n * still parse and can render generically later.\n */\nexport const hypercoreLedgerDeltaSchema = z.object({\n type: z.string(),\n usdc: z.string().optional(),\n amount: z.string().optional(),\n usdcValue: z.string().optional(),\n token: z.string().optional(),\n user: z.string().optional(),\n destination: z.string().optional(),\n fee: z.string().optional(),\n toPerp: z.boolean().optional(),\n});\n\nexport const hypercoreLedgerUpdateSchema = z.object({\n time: z.number(),\n hash: z.string(),\n delta: hypercoreLedgerDeltaSchema,\n});\n\nexport const hypercoreLedgerUpdatesSchema = z.array(hypercoreLedgerUpdateSchema);\n\nexport type SpotMetaResponse = z.infer<typeof spotMetaResponseSchema>;\nexport type SpotBalance = {\n coin: string;\n token: number;\n total: string;\n hold: string;\n entryNtl?: string;\n};\nexport type SpotClearinghouseState = {\n balances: SpotBalance[];\n};\nexport type ClearinghouseState = z.infer<typeof clearinghouseStateSchema>;\nexport type UserFill = z.infer<typeof userFillSchema>;\nexport type HypercoreLedgerUpdate = z.infer<typeof hypercoreLedgerUpdateSchema>;\n","import type { z } from 'zod';\nimport {\n clearinghouseStateSchema,\n hypercoreLedgerUpdatesSchema,\n spotClearinghouseStateSchema,\n spotMetaResponseSchema,\n userAbstractionSchema,\n userFillsSchema,\n type ClearinghouseState,\n type HypercoreLedgerUpdate,\n type SpotClearinghouseState,\n type SpotMetaResponse,\n type UserAbstractionMode,\n type UserFill,\n} from './schemas';\n\nexport type HypercoreInfoRequest =\n | { type: 'spotMeta' }\n | { type: 'spotClearinghouseState'; user: string; dex?: string }\n | { type: 'clearinghouseState'; user: string; dex?: string }\n | { type: 'userAbstraction'; user: string }\n | { type: 'userFills'; user: string }\n | {\n type: 'userNonFundingLedgerUpdates';\n user: string;\n startTime: number;\n };\n\nexport type HypercoreInfoClientConfig = {\n /** Proxy-first `/info` URL used for balances and spot meta. */\n infoUrl: string;\n /**\n * Activity URL. Defaults to `infoUrl`; may be the public HL endpoint when\n * the proxy does not yet support fills/ledger types.\n */\n activityInfoUrl?: string;\n fetch?: typeof globalThis.fetch;\n};\n\nexport type PostInfoOptions = {\n signal?: AbortSignal;\n /** Overrides the client default URL for this call. */\n url?: string;\n};\n\nconst lowercaseUser = (user: string) => user.toLowerCase();\n\nexport class HypercoreInfoClient {\n readonly #infoUrl: string;\n readonly #activityInfoUrl: string;\n readonly #fetch: typeof globalThis.fetch;\n\n constructor(config: HypercoreInfoClientConfig) {\n this.#infoUrl = config.infoUrl;\n this.#activityInfoUrl = config.activityInfoUrl ?? config.infoUrl;\n this.#fetch = config.fetch ?? globalThis.fetch.bind(globalThis);\n }\n\n async postInfo<T>(body: HypercoreInfoRequest, schema: z.ZodType<T>, options?: PostInfoOptions) {\n const response = await this.#fetch(options?.url ?? this.#infoUrl, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify(body),\n signal: options?.signal,\n });\n\n if (!response.ok) {\n throw new Error(`Hyperliquid /info failed: ${response.status} ${response.statusText}`);\n }\n\n const json: unknown = await response.json();\n return schema.parse(json);\n }\n\n getSpotMeta(options?: PostInfoOptions): Promise<SpotMetaResponse> {\n return this.postInfo({ type: 'spotMeta' }, spotMetaResponseSchema, options);\n }\n\n getSpotClearinghouseState(user: string, options?: PostInfoOptions): Promise<SpotClearinghouseState> {\n return this.postInfo(\n {\n type: 'spotClearinghouseState',\n user: lowercaseUser(user),\n dex: '',\n },\n spotClearinghouseStateSchema,\n options,\n ) as Promise<SpotClearinghouseState>;\n }\n\n getClearinghouseState(user: string, options?: PostInfoOptions): Promise<ClearinghouseState> {\n return this.postInfo(\n {\n type: 'clearinghouseState',\n user: lowercaseUser(user),\n dex: '',\n },\n clearinghouseStateSchema,\n options,\n );\n }\n\n getUserAbstraction(user: string, options?: PostInfoOptions): Promise<UserAbstractionMode> {\n return this.postInfo(\n { type: 'userAbstraction', user: lowercaseUser(user) },\n userAbstractionSchema,\n options,\n ) as Promise<UserAbstractionMode>;\n }\n\n getUserFills(user: string, options?: PostInfoOptions): Promise<UserFill[]> {\n return this.postInfo({ type: 'userFills', user: lowercaseUser(user) }, userFillsSchema, {\n ...options,\n url: options?.url ?? this.#activityInfoUrl,\n });\n }\n\n getUserNonFundingLedgerUpdates(\n user: string,\n startTime: number,\n options?: PostInfoOptions,\n ): Promise<HypercoreLedgerUpdate[]> {\n return this.postInfo(\n {\n type: 'userNonFundingLedgerUpdates',\n user: lowercaseUser(user),\n startTime,\n },\n hypercoreLedgerUpdatesSchema,\n {\n ...options,\n url: options?.url ?? this.#activityInfoUrl,\n },\n );\n }\n}\n","/**\n * Loud failure message for HyperCore capabilities that do not exist (no RPC, no gas).\n * Prefer rejecting with this over empty success so clients and agents see intentional gaps.\n */\nexport const unsupportedHypercoreCapabilityMessage = (capability: string) =>\n `HyperCore does not support ${capability}: read-only module (balances, tokens, activity).`;\n\nexport const unsupportedHypercoreCapability = (capability: string): never => {\n throw new Error(unsupportedHypercoreCapabilityMessage(capability));\n};\n","import {\n TokenType,\n type GetBalancesParams,\n type GetBalancesResponse,\n type NetworkTokenWithBalance,\n type TokenWithBalance,\n type TokenWithBalanceHypercoreSpot,\n} from '@avalabs/vm-module-types';\nimport type { HypercoreInfoClient } from '../../utils/info-client';\nimport { buildHypercoreTokens, type HypercoreTokenBalance } from '../../utils/build-hypercore-tokens';\nimport { hyperliquidCoinSvgUrl } from '../../utils/hyperliquid-coin-svg-url';\nimport { toHypercoreSpotTokens } from '../../utils/spot-tokens';\n\ntype GetHypercoreBalancesParams = Omit<GetBalancesParams, 'currency' | 'customTokens' | 'tokenTypes'> & {\n infoClient: HypercoreInfoClient;\n};\n\nconst toTokenWithBalance = (\n token: HypercoreTokenBalance,\n networkToken: GetBalancesParams['network']['networkToken'],\n): { key: string; value: TokenWithBalance } => {\n if (token.kind === 'native') {\n const balance = BigInt(token.balanceRaw);\n const balanceInCurrency = Number(token.balanceUsd);\n const native: NetworkTokenWithBalance = {\n ...networkToken,\n name: token.name,\n symbol: token.symbol,\n decimals: token.decimals,\n logoUri: networkToken.logoUri ?? hyperliquidCoinSvgUrl(token.symbol),\n coingeckoId: 'usd-coin',\n type: TokenType.NATIVE,\n balance,\n balanceDisplayValue: token.balance,\n balanceInCurrency: Number.isFinite(balanceInCurrency) ? balanceInCurrency : 0,\n balanceCurrencyDisplayValue: token.balanceUsd,\n priceInCurrency: token.priceUsd,\n };\n return { key: token.symbol, value: native };\n }\n\n const balance = BigInt(token.balanceRaw);\n const spot: TokenWithBalanceHypercoreSpot = {\n type: TokenType.HYPERCORE_SPOT,\n name: token.name,\n symbol: token.symbol,\n decimals: token.decimals,\n index: token.index,\n evmContract: token.evmContract,\n logoUri: hyperliquidCoinSvgUrl(token.symbol),\n reputation: null,\n balance,\n balanceDisplayValue: token.balance,\n };\n return { key: `spot:${token.index}`, value: spot };\n};\n\nexport const getBalances = async ({\n addresses,\n network,\n infoClient,\n}: GetHypercoreBalancesParams): Promise<GetBalancesResponse> => {\n const spotMeta = await infoClient.getSpotMeta();\n const spotTokens = toHypercoreSpotTokens(spotMeta.tokens);\n\n const results = await Promise.allSettled(\n addresses.map(async (address) => {\n try {\n const [spotState, perpState, abstractionMode] = await Promise.all([\n infoClient.getSpotClearinghouseState(address),\n infoClient.getClearinghouseState(address).catch(() => undefined),\n infoClient.getUserAbstraction(address).catch(() => undefined),\n ]);\n\n const tokens = buildHypercoreTokens({\n spotBalances: spotState.balances,\n perpState,\n abstractionMode,\n spotTokens,\n });\n\n const bySymbol = Object.fromEntries(\n tokens.map((token) => {\n const { key, value } = toTokenWithBalance(token, network.networkToken);\n return [key, value];\n }),\n );\n\n return { [address]: bySymbol };\n } catch (err) {\n return { [address]: { error: (err as Error).toString() } };\n }\n }),\n );\n\n return results.reduce((acc, curr) => {\n if (curr.status === 'fulfilled') {\n return { ...acc, ...curr.value };\n }\n return acc;\n }, {} as GetBalancesResponse);\n};\n","import Big from 'big.js';\nimport type { HypercoreSpotToken } from '@avalabs/vm-module-types';\nimport { HYPERCORE_USDC_DECIMALS, HYPERCORE_USDC_NAME, HYPERCORE_USDC_SYMBOL } from '../constants';\nimport type { ClearinghouseState, SpotBalance, UserAbstractionMode } from './schemas';\n\nconst BIG_ZERO = new Big(0);\n\nexport type HypercoreNativeTokenBalance = {\n kind: 'native';\n name: string;\n symbol: typeof HYPERCORE_USDC_SYMBOL;\n decimals: number;\n /** Human-readable amount (decimal string). */\n balance: string;\n /** Integer raw amount as a decimal string (no fractional part). */\n balanceRaw: string;\n priceUsd: 1;\n balanceUsd: string;\n};\n\nexport type HypercoreSpotTokenBalance = {\n kind: 'spot';\n name: string;\n symbol: string;\n decimals: number;\n balance: string;\n balanceRaw: string;\n index: number;\n evmContract?: string;\n};\n\nexport type HypercoreTokenBalance = HypercoreNativeTokenBalance | HypercoreSpotTokenBalance;\n\n/**\n * `true` when spot balances already back perps for this account mode\n * (`unifiedAccount`). Other modes keep perp collateral on a separate ledger.\n */\nexport const spotCountsAsPerpCollateral = (mode: UserAbstractionMode | undefined) => mode === 'unifiedAccount';\n\n/** Tokens carry no native gas balance on HyperCore — amounts are human decimals. */\nconst toRawBalance = (humanAmount: Big, decimals: number) =>\n humanAmount.times(new Big(10).pow(decimals)).round(0, Big.roundDown).toFixed(0);\n\n/**\n * Perp collateral in USDC, excluding unrealized PnL.\n * `crossMarginSummary.accountValue` is collateral ± PnL; we back PnL out.\n */\nexport const getPerpCollateralUsd = (perp: ClearinghouseState | undefined) => {\n if (!perp) {\n return BIG_ZERO;\n }\n\n const accountValue = new Big(perp.crossMarginSummary.accountValue ?? '0');\n const unrealizedPnl = perp.assetPositions.reduce((sum, { position }) => sum.plus(position.unrealizedPnl), BIG_ZERO);\n const collateral = accountValue.minus(unrealizedPnl);\n\n return collateral.gt(BIG_ZERO) ? collateral : BIG_ZERO;\n};\n\n/**\n * USDC merges spot + (non-unified) PnL-excluded perp collateral at $1.\n * Other spot inventory is `HYPERCORE_SPOT` (no synthetic ERC20 addresses).\n */\nexport const buildHypercoreTokens = ({\n spotBalances,\n perpState,\n abstractionMode,\n spotTokens,\n}: {\n spotBalances: readonly SpotBalance[];\n perpState: ClearinghouseState | undefined;\n abstractionMode: UserAbstractionMode | undefined;\n spotTokens: HypercoreSpotToken[];\n}): HypercoreTokenBalance[] => {\n const tokensByIndex = new Map(spotTokens.map((token) => [token.index, token]));\n\n const perpCollateralUsd = spotCountsAsPerpCollateral(abstractionMode) ? BIG_ZERO : getPerpCollateralUsd(perpState);\n\n const spotUsdc = spotBalances.find((balance) => balance.coin.toUpperCase() === HYPERCORE_USDC_SYMBOL);\n const usdcTotal = new Big(spotUsdc?.total ?? '0').plus(perpCollateralUsd);\n\n const tokens: HypercoreTokenBalance[] = [];\n\n if (usdcTotal.gt(BIG_ZERO)) {\n tokens.push({\n kind: 'native',\n name: HYPERCORE_USDC_NAME,\n symbol: HYPERCORE_USDC_SYMBOL,\n decimals: HYPERCORE_USDC_DECIMALS,\n balance: usdcTotal.toString(),\n balanceRaw: toRawBalance(usdcTotal, HYPERCORE_USDC_DECIMALS),\n priceUsd: 1,\n balanceUsd: usdcTotal.toString(),\n });\n }\n\n for (const balance of spotBalances) {\n if (balance.coin.toUpperCase() === HYPERCORE_USDC_SYMBOL) {\n continue;\n }\n\n const meta = tokensByIndex.get(balance.token);\n const total = new Big(balance.total);\n if (!meta || !total.gt(BIG_ZERO)) {\n continue;\n }\n\n tokens.push({\n kind: 'spot',\n name: meta.name,\n symbol: meta.symbol,\n decimals: meta.decimals,\n balance: total.toString(),\n balanceRaw: toRawBalance(total, meta.decimals),\n index: meta.index,\n evmContract: meta.evmContract,\n });\n }\n\n return tokens;\n};\n","/** CAIP-2 id for HyperCore mainnet. Namespace must be 3–8 chars (CAIP-2). */\nexport const HYPERCORE_CAIP_ID = 'hlcore:mainnet';\n\n/**\n * Synthetic numeric id used by Core network lists / storage keys.\n * Not an EVM chain id — module routing uses {@link HYPERCORE_CAIP_ID}.\n */\nexport const HYPERCORE_CHAIN_ID = 9999;\n\nexport const HYPERCORE_USDC_SYMBOL = 'USDC';\nexport const HYPERCORE_USDC_NAME = 'USD Coin';\nexport const HYPERCORE_USDC_DECIMALS = 8;\n","export const HYPERLIQUID_COIN_SVG_BASE = 'https://app.hyperliquid.xyz/coins';\n\nexport const hyperliquidCoinSvgKey = (coin: string) => {\n const trimmed = coin.trim();\n const separatorIndex = trimmed.indexOf(':');\n if (separatorIndex === -1) {\n return trimmed.toUpperCase();\n }\n // HIP-3 logos are keyed as `marketname:TICKER` (dex prefix is case-significant).\n return `${trimmed.slice(0, separatorIndex)}:${trimmed.slice(separatorIndex + 1).toUpperCase()}`;\n};\n\nexport const hyperliquidCoinSvgUrl = (coin: string) =>\n `${HYPERLIQUID_COIN_SVG_BASE}/${encodeURIComponent(hyperliquidCoinSvgKey(coin))}.svg`;\n","import { TokenType, type HypercoreSpotToken } from '@avalabs/vm-module-types';\nimport type { SpotMetaResponse } from './schemas';\n\nconst isValidEvmAddress = (address: string) => /^0x[a-fA-F0-9]{40}$/.test(address);\n\n/**\n * Maps `spotMeta` tokens to the registry used when resolving spot balances.\n * Keeps every spot token (including HyperCore-only ones without an EVM contract).\n */\nexport const toHypercoreSpotTokens = (tokens: SpotMetaResponse['tokens']): HypercoreSpotToken[] =>\n tokens.map((token) => {\n const address = token.evmContract?.address.toLowerCase();\n\n return {\n type: TokenType.HYPERCORE_SPOT,\n index: token.index,\n name: token.fullName ?? token.name,\n symbol: token.name,\n decimals: token.weiDecimals,\n evmContract: address && isValidEvmAddress(address) ? address : undefined,\n };\n });\n","import type { HypercoreSpotToken, Network } from '@avalabs/vm-module-types';\nimport type { HypercoreInfoClient } from '../../utils/info-client';\nimport { hyperliquidCoinSvgUrl } from '../../utils/hyperliquid-coin-svg-url';\nimport { toHypercoreSpotTokens } from '../../utils/spot-tokens';\n\nexport const getTokens = async ({\n infoClient,\n}: {\n network: Network;\n infoClient: HypercoreInfoClient;\n}): Promise<HypercoreSpotToken[]> => {\n const spotMeta = await infoClient.getSpotMeta();\n return toHypercoreSpotTokens(spotMeta.tokens).map((token) => ({\n ...token,\n logoUri: token.logoUri ?? hyperliquidCoinSvgUrl(token.symbol),\n }));\n};\n","import type { HypercoreLedgerUpdate, UserFill } from '../schemas';\n\nexport type HypercoreActivityItem =\n | {\n readonly kind: 'fill';\n readonly timeMs: number;\n readonly hash: string;\n readonly fill: UserFill;\n }\n | {\n readonly kind: 'ledger';\n readonly timeMs: number;\n readonly hash: string;\n readonly update: HypercoreLedgerUpdate;\n };\n\n/** Normalize a Unix timestamp to milliseconds. */\nexport const toTimeMs = (time: number) => (time < 10_000_000_000 ? time * 1000 : time);\n","import type { HypercoreInfoClient } from '../info-client';\nimport type { HypercoreLedgerUpdate } from '../schemas';\nimport type { HypercoreActivityItem } from './types';\nimport { toTimeMs } from './types';\n\n/** Bound ledger pagination so busy accounts cannot trigger unbounded requests. */\nexport const MAX_LEDGER_PAGES = 20;\n\n/** Prefer recent ledger history; paging from `0` would return the oldest pages first. */\nexport const LEDGER_LOOKBACK_MS = 365 * 24 * 60 * 60 * 1000;\n\ntype FetchHypercoreActivityOptions = {\n signal?: AbortSignal;\n};\n\nconst isAbortError = (err: unknown) =>\n (err instanceof DOMException && err.name === 'AbortError') || (err instanceof Error && err.name === 'AbortError');\n\nconst softFail = async <T>(promise: Promise<T>, fallback: T): Promise<T> => {\n try {\n return await promise;\n } catch (err) {\n if (isAbortError(err)) {\n throw err;\n }\n return fallback;\n }\n};\n\n/**\n * `userNonFundingLedgerUpdates` returns an ascending, capped page (~500) from\n * `startTime`. Start within a lookback window and page forward until empty,\n * aborted, or `MAX_LEDGER_PAGES`, so recent activity is included without an\n * unbounded crawl from epoch.\n */\nconst fetchLedgerUpdates = async (\n client: HypercoreInfoClient,\n evmAddress: string,\n options?: FetchHypercoreActivityOptions,\n) => {\n const all: HypercoreLedgerUpdate[] = [];\n let startTime = Date.now() - LEDGER_LOOKBACK_MS;\n let pages = 0;\n\n while (pages < MAX_LEDGER_PAGES) {\n if (options?.signal?.aborted) {\n throw new DOMException('The operation was aborted.', 'AbortError');\n }\n\n const page = await client.getUserNonFundingLedgerUpdates(evmAddress, startTime, options);\n pages += 1;\n if (page.length === 0) {\n break;\n }\n all.push(...page);\n const last = page[page.length - 1];\n if (!last) {\n break;\n }\n const next = last.time + 1;\n if (next <= startTime) {\n break;\n }\n startTime = next;\n }\n\n return all;\n};\n\n/**\n * Fetches HyperCore fills + non-funding ledger updates and sorts newest-first.\n * Soft-fails individual endpoints so a flaky fills or ledger call still yields\n * partial history (abort errors are rethrown).\n */\nexport const fetchHypercoreActivity = async (\n client: HypercoreInfoClient,\n evmAddress: string,\n options?: FetchHypercoreActivityOptions,\n): Promise<HypercoreActivityItem[]> => {\n const [fills, ledgerUpdates] = await Promise.all([\n softFail(client.getUserFills(evmAddress, options), []),\n softFail(fetchLedgerUpdates(client, evmAddress, options), []),\n ]);\n\n const items: HypercoreActivityItem[] = [\n ...fills.map((fill) => ({\n kind: 'fill' as const,\n timeMs: toTimeMs(fill.time),\n hash: fill.hash,\n fill,\n })),\n ...ledgerUpdates.map((update) => ({\n kind: 'ledger' as const,\n timeMs: toTimeMs(update.time),\n hash: update.hash,\n update,\n })),\n ];\n\n return items.sort((a, b) => b.timeMs - a.timeMs);\n};\n","import { TokenType, TransactionType, type Network, type Transaction, type TxToken } from '@avalabs/vm-module-types';\nimport { HYPERCORE_CAIP_ID } from '../../constants';\nimport { hyperliquidCoinSvgUrl } from '../hyperliquid-coin-svg-url';\nimport type { HypercoreLedgerUpdate, UserFill } from '../schemas';\nimport { getHypercoreLedgerDisplay } from './get-hypercore-ledger-display';\nimport { encodeHypercoreFillMethod, tickerOfCoin } from './hypercore-fill-meta';\nimport type { HypercoreActivityItem } from './types';\nimport { toTimeMs } from './types';\n\nconst explorerTxLink = (network: Pick<Network, 'explorerUrl'>, hash: string) => {\n const base = (network.explorerUrl ?? '').replace(/\\/$/, '');\n return base ? `${base}/tx/${hash}` : hash;\n};\n\nconst chainIdForNetwork = (network: Pick<Network, 'caipId' | 'chainId'>) => network.caipId ?? HYPERCORE_CAIP_ID;\n\nconst mapFillToTransaction = (\n fill: UserFill,\n timeMs: number,\n network: Pick<Network, 'explorerUrl' | 'caipId' | 'chainId'>,\n): Transaction => {\n const isBuy = fill.side === 'B';\n const ticker = tickerOfCoin(fill.coin);\n\n const token: TxToken = {\n type: TokenType.NATIVE,\n name: fill.coin,\n symbol: ticker,\n amount: fill.sz,\n imageUri: hyperliquidCoinSvgUrl(fill.coin),\n };\n\n return {\n isContractCall: false,\n isIncoming: isBuy,\n isOutgoing: !isBuy,\n isSender: !isBuy,\n timestamp: timeMs,\n hash: fill.hash,\n from: '',\n to: '',\n tokens: [token],\n gasUsed: '0',\n txType: TransactionType.FILL_ORDER,\n method: encodeHypercoreFillMethod({\n dir: fill.dir ?? '',\n px: fill.px,\n closedPnl: fill.closedPnl,\n coin: fill.coin,\n }),\n chainId: chainIdForNetwork(network),\n explorerLink: explorerTxLink(network, fill.hash),\n };\n};\n\nconst mapLedgerToTransaction = (\n update: HypercoreLedgerUpdate,\n evmAddress: string,\n network: Pick<Network, 'explorerUrl' | 'caipId' | 'chainId'>,\n): Transaction => {\n const display = getHypercoreLedgerDisplay(update, evmAddress);\n const isIncoming = display.direction === 'positive';\n const isOutgoing = display.direction === 'negative';\n\n let txType: TransactionType = TransactionType.TRANSFER;\n switch (display.label) {\n case 'deposit':\n case 'received':\n txType = TransactionType.RECEIVE;\n break;\n case 'withdraw':\n case 'sent':\n txType = TransactionType.SEND;\n break;\n case 'liquidation':\n txType = TransactionType.UNKNOWN;\n break;\n default:\n txType = TransactionType.TRANSFER;\n }\n\n const amount = display.amount || '0';\n const token: TxToken = {\n type: TokenType.NATIVE,\n name: display.symbol,\n symbol: display.symbol,\n amount,\n imageUri: hyperliquidCoinSvgUrl(display.symbol),\n };\n\n return {\n isContractCall: false,\n isIncoming,\n isOutgoing,\n isSender: isOutgoing,\n timestamp: toTimeMs(update.time),\n hash: update.hash,\n from: display.from ?? (isOutgoing ? evmAddress : ''),\n to: display.to ?? (isIncoming ? evmAddress : ''),\n tokens: [token],\n gasUsed: '0',\n txType,\n chainId: chainIdForNetwork(network),\n explorerLink: explorerTxLink(network, update.hash),\n };\n};\n\nexport const mapHypercoreActivityToTransactions = (\n items: readonly HypercoreActivityItem[],\n evmAddress: string,\n network: Pick<Network, 'explorerUrl' | 'caipId' | 'chainId'>,\n): Transaction[] =>\n items.map((item) =>\n item.kind === 'fill'\n ? mapFillToTransaction(item.fill, item.timeMs, network)\n : mapLedgerToTransaction(item.update, evmAddress, network),\n );\n","import type { HypercoreLedgerUpdate } from '../schemas';\n\n/**\n * Semantic label key for a ledger row.\n */\nexport type HypercoreLedgerLabel =\n | 'deposit'\n | 'withdraw'\n | 'sent'\n | 'received'\n | 'transferToPerp'\n | 'transferToSpot'\n | 'transfer'\n | 'liquidation'\n | 'other';\n\nexport type HypercoreLedgerDisplay = {\n readonly label: HypercoreLedgerLabel;\n /** Unsigned token amount, e.g. `0.1`. */\n readonly amount: string;\n readonly symbol: string;\n /** Signed USD value for the fiat line; undefined when there's nothing to show. */\n readonly usdValue?: number;\n readonly direction: 'positive' | 'negative' | 'neutral';\n readonly from?: string;\n readonly to?: string;\n readonly rawType: string;\n};\n\nconst formatAmount = (value: string | undefined) => {\n if (value === undefined || value === '') {\n return '';\n }\n const parsed = Number.parseFloat(value);\n if (!Number.isFinite(parsed)) {\n return value;\n }\n return new Intl.NumberFormat('en-US', { maximumFractionDigits: 6 }).format(parsed);\n};\n\nconst toUsd = (value: string | undefined, sign: 1 | -1 | 0) => {\n if (value === undefined || value === '') {\n return undefined;\n }\n const parsed = Number.parseFloat(value);\n return Number.isFinite(parsed) ? parsed * (sign === 0 ? 1 : sign) : undefined;\n};\n\n/**\n * Derives label, amount, signed USD value, and counterparties for a HyperCore\n * ledger update from the owner's perspective.\n */\nexport const getHypercoreLedgerDisplay = (\n update: HypercoreLedgerUpdate,\n evmAddress: string,\n): HypercoreLedgerDisplay => {\n const { delta } = update;\n const owner = evmAddress.toLowerCase();\n const isOutgoing = delta.user?.toLowerCase() === owner;\n\n switch (delta.type) {\n case 'deposit':\n return {\n label: 'deposit',\n amount: formatAmount(delta.usdc),\n symbol: 'USDC',\n usdValue: toUsd(delta.usdc, 1),\n direction: 'positive',\n to: evmAddress,\n rawType: delta.type,\n };\n case 'withdraw':\n return {\n label: 'withdraw',\n amount: formatAmount(delta.usdc),\n symbol: 'USDC',\n usdValue: toUsd(delta.usdc, -1),\n direction: 'negative',\n from: evmAddress,\n rawType: delta.type,\n };\n case 'send':\n case 'spotTransfer':\n return {\n label: isOutgoing ? 'sent' : 'received',\n amount: formatAmount(delta.amount),\n symbol: delta.token ?? 'USDC',\n usdValue: toUsd(delta.usdcValue, isOutgoing ? -1 : 1),\n direction: isOutgoing ? 'negative' : 'positive',\n from: delta.user,\n to: delta.destination,\n rawType: delta.type,\n };\n case 'internalTransfer':\n return {\n label: 'transfer',\n amount: formatAmount(delta.usdc),\n symbol: 'USDC',\n usdValue: toUsd(delta.usdc, isOutgoing ? -1 : 1),\n direction: isOutgoing ? 'negative' : 'positive',\n from: delta.user,\n to: delta.destination,\n rawType: delta.type,\n };\n case 'accountClassTransfer':\n return {\n label: delta.toPerp ? 'transferToPerp' : 'transferToSpot',\n amount: formatAmount(delta.usdc),\n symbol: 'USDC',\n usdValue: toUsd(delta.usdc, 0),\n direction: 'neutral',\n rawType: delta.type,\n };\n case 'liquidation':\n return {\n label: 'liquidation',\n amount: formatAmount(delta.usdcValue ?? delta.usdc),\n symbol: 'USDC',\n usdValue: toUsd(delta.usdcValue ?? delta.usdc, -1),\n direction: 'negative',\n rawType: delta.type,\n };\n default:\n return {\n label: 'other',\n amount: formatAmount(delta.usdcValue ?? delta.usdc),\n symbol: 'USDC',\n usdValue: toUsd(delta.usdcValue ?? delta.usdc, 0),\n direction: 'neutral',\n rawType: delta.type,\n };\n }\n};\n","const METHOD_PREFIX = 'hypercoreFill:v1:';\n\nexport const FILL_ARROW_UP = '\\u25B2';\nexport const FILL_ARROW_DOWN = '\\u25BC';\n\nexport type HypercoreFillMeta = {\n readonly dir: string;\n readonly px: string;\n readonly closedPnl: string;\n readonly coin: string;\n};\n\nexport type FillLabel = {\n readonly text: string;\n readonly arrow?: typeof FILL_ARROW_UP | typeof FILL_ARROW_DOWN;\n readonly tone?: 'profit' | 'loss';\n};\n\n/** Display ticker with any `dex:` prefix stripped (`xyz:GOLD` → `GOLD`). */\nexport const tickerOfCoin = (coin: string) => {\n const i = coin.indexOf(':');\n return i === -1 ? coin : coin.slice(i + 1);\n};\n\n/** PnL tone from `closedPnl` — `dir` alone does not indicate profit vs loss. */\nexport const closedPnlTone = (closedPnl: string | undefined): 'profit' | 'loss' | undefined => {\n if (closedPnl === undefined) {\n return undefined;\n }\n const n = Number.parseFloat(closedPnl);\n if (!Number.isFinite(n) || n === 0) {\n return undefined;\n }\n return n > 0 ? 'profit' : 'loss';\n};\n\n/**\n * Map a fill's `dir` into a display label. Arrow direction follows side\n * (long ▲ / short ▼); success/error tone comes from `closedPnl` when provided.\n */\nexport const fillLabel = (dir: string, closedPnl?: string): FillLabel => {\n const tone = closedPnlTone(closedPnl);\n const d = dir.toLowerCase();\n if (d.includes('close') && d.includes('long')) {\n return { text: 'Long closed', arrow: FILL_ARROW_UP, tone };\n }\n if (d.includes('close') && d.includes('short')) {\n return { text: 'Short closed', arrow: FILL_ARROW_DOWN, tone };\n }\n if (d.includes('open') && (d.includes('long') || d.includes('short'))) {\n return { text: 'Order opened' };\n }\n if (d.includes('cancel')) {\n return { text: 'Order cancelled' };\n }\n return { text: dir };\n};\n\n/** Compact USD price for fill rows (`$1,684.7`). */\nexport const formatHypercoreFillPx = (px: string) => {\n const n = Number.parseFloat(px);\n if (!Number.isFinite(n)) {\n return px;\n }\n return `$${n.toLocaleString(undefined, { maximumFractionDigits: 8 })}`;\n};\n\nexport const encodeHypercoreFillMethod = (meta: HypercoreFillMeta) =>\n `${METHOD_PREFIX}${encodeURIComponent(JSON.stringify(meta))}`;\n\nexport const parseHypercoreFillMethod = (method: string | undefined): HypercoreFillMeta | undefined => {\n if (!method?.startsWith(METHOD_PREFIX)) {\n return undefined;\n }\n try {\n const parsed: unknown = JSON.parse(decodeURIComponent(method.slice(METHOD_PREFIX.length)));\n if (\n typeof parsed !== 'object' ||\n parsed === null ||\n !('dir' in parsed) ||\n !('px' in parsed) ||\n !('closedPnl' in parsed) ||\n !('coin' in parsed)\n ) {\n return undefined;\n }\n const { dir, px, closedPnl, coin } = parsed as Record<string, unknown>;\n if (\n typeof dir !== 'string' ||\n typeof px !== 'string' ||\n typeof closedPnl !== 'string' ||\n typeof coin !== 'string'\n ) {\n return undefined;\n }\n return { dir, px, closedPnl, coin };\n } catch {\n return undefined;\n }\n};\n","import type { GetTransactionHistory, TransactionHistoryResponse } from '@avalabs/vm-module-types';\nimport type { HypercoreInfoClient } from '../../utils/info-client';\nimport { fetchHypercoreActivity } from '../../utils/activity/fetch-hypercore-activity';\nimport { mapHypercoreActivityToTransactions } from '../../utils/activity/map-hypercore-activity-to-transactions';\n\nexport const getTransactionHistory = async ({\n address,\n network,\n infoClient,\n}: GetTransactionHistory & {\n infoClient: HypercoreInfoClient;\n}): Promise<TransactionHistoryResponse> => {\n const items = await fetchHypercoreActivity(infoClient, address);\n return {\n transactions: mapHypercoreActivityToTransactions(items, address, network),\n };\n};\n","import { NetworkVMType, WalletType, type GetAddressParams, type GetAddressResponse } from '@avalabs/vm-module-types';\nimport { getAddressFromXPub, getEvmAddressFromPubKey } from '@avalabs/core-wallets-sdk';\nimport { rpcErrors } from '@metamask/rpc-errors';\n\ntype GetAddress = Omit<GetAddressParams, 'isTestnet' | 'xpubXP' | 'network'>;\n\nexport const getAddress = async ({ accountIndex, xpub, walletType }: GetAddress): Promise<GetAddressResponse> => {\n switch (walletType) {\n case WalletType.Mnemonic:\n case WalletType.Ledger:\n case WalletType.Keystone: {\n return {\n [NetworkVMType.HYPERCORE]: getAddressFromXPub(xpub, accountIndex),\n };\n }\n case WalletType.LedgerLive:\n case WalletType.Seedless: {\n const pubKeyBuffer = Buffer.from(xpub, 'hex');\n return {\n [NetworkVMType.HYPERCORE]: getEvmAddressFromPubKey(pubKeyBuffer),\n };\n }\n default:\n throw rpcErrors.invalidParams(`Unsupported wallet type: ${walletType}`);\n }\n};\n","import {\n NetworkVMType,\n type ApprovalController,\n type DeriveAddressParams,\n type DeriveAddressResponse,\n} from '@avalabs/vm-module-types';\nimport { computeAddress } from 'ethers';\nimport { hasDerivationDetails } from '@internal/utils/src/utils/address-derivation';\nimport { buildDerivationPath } from '../build-derivation-path/build-derivation-path';\n\nexport const deriveAddress = async (\n params: DeriveAddressParams & { approvalController: ApprovalController },\n): Promise<DeriveAddressResponse> => {\n const { secretId, approvalController } = params;\n\n // Narrow before calling buildDerivationPath — the type guard alone is not\n // enough when `params` is intersected with `{ approvalController }`.\n const derivationPath = hasDerivationDetails(params)\n ? buildDerivationPath({\n accountIndex: params.accountIndex,\n derivationPathType: params.derivationPathType,\n addressIndex: params.addressIndex,\n }).HYPERCORE\n : undefined;\n const publicKeyHex = await approvalController.requestPublicKey({\n curve: 'secp256k1',\n secretId,\n derivationPath,\n });\n\n return {\n [NetworkVMType.HYPERCORE]: computeAddress(`0x${publicKeyHex}`),\n };\n};\n","import type { DeriveAddressParams, DetailedDeriveAddressParams } from '@avalabs/vm-module-types';\n\nexport const hasDerivationDetails = (params: DeriveAddressParams): params is DetailedDeriveAddressParams =>\n 'derivationPathType' in params &&\n 'accountIndex' in params &&\n typeof params.accountIndex === 'number' &&\n typeof params.derivationPathType === 'string';\n","import { rpcErrors } from '@metamask/rpc-errors';\nimport {\n NetworkVMType,\n type BuildDerivationPathParams,\n type BuildDerivationPathResponse,\n} from '@avalabs/vm-module-types';\n\n/**\n * HyperCore identity is an EVM address (cointype 60). Paths match the EVM module;\n * the result is keyed as `HYPERCORE`.\n */\nexport const buildDerivationPath = ({\n accountIndex,\n derivationPathType,\n}: BuildDerivationPathParams): Pick<BuildDerivationPathResponse, NetworkVMType.HYPERCORE> => {\n if (accountIndex < 0) {\n throw rpcErrors.invalidParams('Account index must be a non-negative integer');\n }\n\n switch (derivationPathType) {\n case 'bip44':\n return {\n [NetworkVMType.HYPERCORE]: `m/44'/60'/0'/0/${accountIndex}`,\n };\n\n case 'ledger_live':\n return {\n [NetworkVMType.HYPERCORE]: `m/44'/60'/${accountIndex}'/0/0`,\n };\n\n default:\n throw rpcErrors.invalidParams(`Unsupported derivation path type: ${derivationPathType}`);\n }\n};\n","import {\n NetworkVMType,\n type ApprovalController,\n type DeriveAddressesParams,\n type DeriveAddressesResponse,\n} from '@avalabs/vm-module-types';\nimport { deriveAddressesForEvm, init } from '@avalabs/crypto-sdk';\nimport { buildDerivationPath } from '../build-derivation-path/build-derivation-path';\n\nexport const deriveAddresses = async (\n params: DeriveAddressesParams & { approvalController: ApprovalController },\n): Promise<DeriveAddressesResponse> => {\n const { approvalController, secretId, accountIndices, derivationPathType } = params;\n\n if (accountIndices.length === 0) {\n return [];\n }\n\n await init();\n\n const publicKeys = await Promise.all(\n accountIndices.map(async (accountIndex) => {\n const derivationPath = buildDerivationPath({ accountIndex, derivationPathType }).HYPERCORE;\n const publicKeyHex = await approvalController.requestPublicKey({\n curve: 'secp256k1',\n secretId,\n derivationPath,\n });\n return Uint8Array.from(Buffer.from(publicKeyHex, 'hex'));\n }),\n );\n\n const addresses = await deriveAddressesForEvm(publicKeys);\n\n return addresses.map((address) => ({ [NetworkVMType.HYPERCORE]: address }));\n};\n"]}
1
+ {"version":3,"sources":["../src/module.ts","../manifest.json","../src/env.ts","../src/utils/schemas.ts","../src/utils/info-client.ts","../src/utils/unsupported.ts","../src/handlers/get-balances/get-balances.ts","../src/utils/build-hypercore-tokens.ts","../src/constants.ts","../src/utils/hyperliquid-coin-svg-url.ts","../src/utils/spot-tokens.ts","../src/handlers/get-tokens/get-tokens.ts","../src/utils/activity/types.ts","../src/utils/activity/fetch-hypercore-activity.ts","../src/utils/activity/map-hypercore-activity-to-transactions.ts","../src/utils/activity/get-hypercore-ledger-display.ts","../src/utils/activity/hypercore-fill-meta.ts","../src/handlers/get-transaction-history/get-transaction-history.ts","../src/handlers/get-address/get-address.ts","../src/handlers/derive-address/derive-address.ts","../../../packages-internal/utils/src/utils/address-derivation.ts","../src/handlers/build-derivation-path/build-derivation-path.ts","../src/handlers/derive-addresses/derive-addresses.ts"],"names":["parseManifest","rpcErrors","manifest_default","Environment","INFO_PATH","PUBLIC_ACTIVITY_INFO_URL","prodEnv","devEnv","getEnv","__name","environment","z","tokenIndexSchema","spotMetaResponseSchema","spotBalanceSchema","spotClearinghouseStateSchema","marginSummarySchema","clearinghouseStateSchema","userAbstractionSchema","value","userFillSchema","userFillsSchema","hypercoreLedgerDeltaSchema","hypercoreLedgerUpdateSchema","hypercoreLedgerUpdatesSchema","resolveFetch","fetchFn","_infoUrl","_activityInfoUrl","_fetch","_HypercoreInfoClient","config","__privateAdd","__privateSet","body","schema","options","response","__privateGet","json","user","startTime","HypercoreInfoClient","unsupportedHypercoreCapabilityMessage","capability","TokenType","Big","HYPERCORE_CAIP_ID","HYPERCORE_CHAIN_ID","HYPERCORE_USDC_SYMBOL","HYPERCORE_USDC_NAME","HYPERCORE_USDC_DECIMALS","BIG_ZERO","spotCountsAsPerpCollateral","mode","toRawBalance","humanAmount","decimals","getPerpCollateralUsd","perp","accountValue","unrealizedPnl","sum","position","collateral","buildHypercoreTokens","spotBalances","perpState","abstractionMode","spotTokens","tokensByIndex","token","perpCollateralUsd","spotUsdc","balance","usdcTotal","tokens","meta","total","HYPERLIQUID_COIN_SVG_BASE","hyperliquidCoinSvgKey","coin","trimmed","separatorIndex","hyperliquidCoinSvgUrl","isValidEvmAddress","address","toHypercoreSpotTokens","toErrorMessage","err","toTokenWithBalance","networkToken","balanceInCurrency","native","spot","getBalances","addresses","network","infoClient","tokenTypes","includeNative","includeSpot","spotState","bySymbol","key","acc","curr","index","getTokens","spotMeta","toTimeMs","time","MAX_LEDGER_PAGES","LEDGER_LOOKBACK_MS","isAbortError","softFail","promise","fallback","fetchLedgerUpdates","client","evmAddress","all","pages","page","last","next","fetchHypercoreActivity","fills","ledgerUpdates","fill","update","a","b","TransactionType","formatAmount","parsed","toUsd","sign","getHypercoreLedgerDisplay","delta","owner","isOutgoing","METHOD_PREFIX","tickerOfCoin","i","closedPnlTone","closedPnl","n","fillLabel","dir","tone","d","formatHypercoreFillPx","px","encodeHypercoreFillMethod","parseHypercoreFillMethod","method","explorerTxLink","hash","base","chainIdForNetwork","mapFillToTransaction","timeMs","isBuy","ticker","mapLedgerToTransaction","display","isIncoming","txType","amount","mapHypercoreActivityToTransactions","items","item","getTransactionHistory","NetworkVMType","WalletType","getAddressFromXPub","getEvmAddressFromPubKey","getAddress","accountIndex","xpub","walletType","pubKeyBuffer","computeAddress","hasDerivationDetails","params","buildDerivationPath","derivationPathType","deriveAddress","secretId","approvalController","derivationPath","publicKeyHex","deriveAddressesForEvm","init","deriveAddresses","accountIndices","publicKeys","_approvalController","_infoClient","_HypercoreModule","runtime","infoUrl","activityInfoUrl","_network","result","request","HypercoreModule"],"mappings":"oaAiBA,OAAS,iBAAAA,OAAqB,2BAC9B,OAAS,aAAAC,OAAiB,uBClB1B,IAAAC,EAAA,CACE,KAAQ,YACR,YAAe,uEACf,QAAW,QACX,QAAW,CACT,OAAU,CACR,SAAY,GACZ,SAAY,CACV,IAAO,CACL,SAAY,gBACZ,YAAe,4BACf,SAAY,4BACd,CACF,CACF,CACF,EACA,QAAW,CACT,SAAY,CAAC,gBAAgB,EAC7B,WAAc,CAAC,QAAQ,CACzB,EACA,SAAY,KACZ,YAAe,CACb,IAAO,CACL,MAAS,GACT,QAAW,CAAC,EACZ,qBAAwB,CAAC,CAC3B,CACF,EACA,gBAAmB,KACrB,EC7BA,OAAS,eAAAC,MAAmB,2BAa5B,IAAMC,EAAY,4BACZC,EAA2B,mCAEpBC,GAAe,CAC1B,YAAa,iCACb,QAAS,iCAAiCF,CAAS,GACnD,gBAAiBC,CACnB,EAEaE,GAAc,CACzB,YAAa,qCACb,QAAS,qCAAqCH,CAAS,GACvD,gBAAiBC,CACnB,EAEaG,EAASC,EAACC,GAAkC,CACvD,OAAQA,EAAa,CACnB,KAAKP,EAAY,WACf,OAAOG,GACT,KAAKH,EAAY,IACf,OAAOI,EACX,CACF,EAPsB,UC5BtB,OAAS,KAAAI,MAAS,MAElB,IAAMC,GAAmBD,EAAE,OAAO,OAAO,EAG5BE,EAAyBF,EAAE,OAAO,CAC7C,OAAQA,EAAE,MACRA,EAAE,OAAO,CACP,KAAMA,EAAE,OAAO,EACf,MAAOA,EAAE,OAAO,EAChB,YAAaA,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BAAoBnJ,EAAA,KAAKgK,EAC3B,CAAC,CACH,CAEA,gBAAgBb,EAA+B,CAC7C,OAAOU,GAAgB,CACrB,GAAGV,EACH,mBAAoBnJ,EAAA,KAAKgK,EAC3B,CAAC,CACH,CAEA,UAAUrG,EAAkB,CAC1B,OAAOW,GAAU,CAAE,QAAAX,EAAS,WAAY3D,EAAA,KAAKiK,EAAY,CAAC,CAC5D,CAEA,MAAM,aAAaO,EAAqBF,EAAmB,CACzD,MAAO,CACL,MAAO3M,GAAU,mBAAmB,kCAAkC6M,EAAQ,MAAM,mBAAmB,CACzG,CACF,CACF,EAxEER,EAAA,YACAC,EAAA,YAF6C9L,EAAA+L,EAAA,mBAAxC,IAAMO,GAANP","sourcesContent":["import type {\n Module,\n Manifest,\n ConstructorParams,\n ApprovalController,\n RpcRequest,\n Network,\n NetworkFees,\n GetBalancesParams,\n GetAddressParams,\n GetAddressResponse,\n DeriveAddressParams,\n DeriveAddressesParams,\n BuildDerivationPathParams,\n GetTransactionHistory,\n NetworkFeeParam,\n} from '@avalabs/vm-module-types';\nimport { parseManifest } from '@avalabs/vm-module-types';\nimport { rpcErrors } from '@metamask/rpc-errors';\n\nimport ManifestJson from '../manifest.json';\nimport { getEnv } from './env';\nimport { HypercoreInfoClient } from './utils/info-client';\nimport { unsupportedHypercoreCapabilityMessage } from './utils/unsupported';\nimport { getBalances } from './handlers/get-balances/get-balances';\nimport { getTokens } from './handlers/get-tokens/get-tokens';\nimport { getTransactionHistory } from './handlers/get-transaction-history/get-transaction-history';\nimport { getAddress } from './handlers/get-address/get-address';\nimport { deriveAddress } from './handlers/derive-address/derive-address';\nimport { deriveAddresses } from './handlers/derive-addresses/derive-addresses';\nimport { buildDerivationPath } from './handlers/build-derivation-path/build-derivation-path';\n\nexport class HypercoreModule implements Module {\n #approvalController: ApprovalController;\n #infoClient: HypercoreInfoClient;\n\n constructor({ environment, approvalController, runtime }: ConstructorParams) {\n const { infoUrl, activityInfoUrl } = getEnv(environment);\n\n this.#approvalController = approvalController;\n this.#infoClient = new HypercoreInfoClient({\n infoUrl,\n activityInfoUrl,\n fetch: runtime?.fetch,\n });\n }\n\n getProvider(_network: Network): Promise<never> {\n return Promise.reject(new Error(unsupportedHypercoreCapabilityMessage('getProvider')));\n }\n\n getManifest(): Manifest | undefined {\n const result = parseManifest(ManifestJson);\n return result.success ? result.data : undefined;\n }\n\n getBalances(params: GetBalancesParams) {\n return getBalances({\n ...params,\n infoClient: this.#infoClient,\n });\n }\n\n getTransactionHistory(params: GetTransactionHistory) {\n return getTransactionHistory({\n ...params,\n infoClient: this.#infoClient,\n });\n }\n\n getNetworkFee(_network: NetworkFeeParam): Promise<NetworkFees> {\n return Promise.reject(new Error(unsupportedHypercoreCapabilityMessage('getNetworkFee')));\n }\n\n getAddress(params: GetAddressParams): Promise<GetAddressResponse> {\n return getAddress(params);\n }\n\n buildDerivationPath(params: BuildDerivationPathParams) {\n return buildDerivationPath(params);\n }\n\n deriveAddress(params: DeriveAddressParams) {\n return deriveAddress({\n ...params,\n approvalController: this.#approvalController,\n });\n }\n\n deriveAddresses(params: DeriveAddressesParams) {\n return deriveAddresses({\n ...params,\n approvalController: this.#approvalController,\n });\n }\n\n getTokens(network: Network) {\n return getTokens({ network, infoClient: this.#infoClient });\n }\n\n async onRpcRequest(request: RpcRequest, _network: Network) {\n return {\n error: rpcErrors.methodNotSupported(`HyperCore is read-only; method ${request.method} is not supported`),\n };\n }\n}\n","{\n \"name\": \"HyperCore\",\n \"description\": \"Read-only Hyperliquid HyperCore module (balances, tokens, activity).\",\n \"version\": \"0.0.1\",\n \"sources\": {\n \"module\": {\n \"checksum\": \"\",\n \"location\": {\n \"npm\": {\n \"filePath\": \"dist/index.js\",\n \"packageName\": \"@avalabs/hypercore-module\",\n \"registry\": \"https://registry.npmjs.org\"\n }\n }\n }\n },\n \"network\": {\n \"chainIds\": [\"hlcore:mainnet\"],\n \"namespaces\": [\"hlcore\"]\n },\n \"cointype\": \"60\",\n \"permissions\": {\n \"rpc\": {\n \"dapps\": false,\n \"methods\": [],\n \"nonRestrictedMethods\": []\n }\n },\n \"manifestVersion\": \"0.1\"\n}\n","import { Environment } from '@avalabs/vm-module-types';\n\ntype Env = {\n proxyApiUrl: string;\n /** Proxy-first Hyperliquid `/info` endpoint. */\n infoUrl: string;\n /**\n * Fallback for activity endpoints if the proxy does not support fills/ledger.\n * Prefer `infoUrl` when possible.\n */\n activityInfoUrl: string;\n};\n\nconst INFO_PATH = '/proxy/nownodes/hype/info';\nconst PUBLIC_ACTIVITY_INFO_URL = 'https://api.hyperliquid.xyz/info';\n\nexport const prodEnv: Env = {\n proxyApiUrl: 'https://proxy-api.avax.network',\n infoUrl: `https://proxy-api.avax.network${INFO_PATH}`,\n activityInfoUrl: PUBLIC_ACTIVITY_INFO_URL,\n};\n\nexport const devEnv: Env = {\n proxyApiUrl: 'https://proxy-api-dev.avax.network',\n infoUrl: `https://proxy-api-dev.avax.network${INFO_PATH}`,\n activityInfoUrl: PUBLIC_ACTIVITY_INFO_URL,\n};\n\nexport const getEnv = (environment: Environment): Env => {\n switch (environment) {\n case Environment.PRODUCTION:\n return prodEnv;\n case Environment.DEV:\n return devEnv;\n }\n};\n","import { z } from 'zod';\n\nconst tokenIndexSchema = z.coerce.number();\n\n/** `type: \"spotMeta\"` — registry mapping spot token index → display metadata. */\nexport const spotMetaResponseSchema = z.object({\n tokens: z.array(\n z.object({\n name: z.string(),\n index: z.number(),\n weiDecimals: z.number(),\n fullName: z.string().nullish(),\n evmContract: z.object({ address: z.string() }).nullish(),\n }),\n ),\n});\n\nconst spotBalanceSchema = z.object({\n coin: z.string(),\n token: tokenIndexSchema,\n total: z.string(),\n hold: z.string(),\n entryNtl: z.string().optional(),\n});\n\n/** `type: \"spotClearinghouseState\"` */\nexport const spotClearinghouseStateSchema = z.object({\n balances: z.array(spotBalanceSchema),\n});\n\nconst marginSummarySchema = z.object({\n accountValue: z.string(),\n totalMarginUsed: z.string().optional(),\n totalNtlPos: z.string().optional(),\n totalRawUsd: z.string().optional(),\n});\n\n/**\n * `type: \"clearinghouseState\"` — only fields needed for PnL-excluded\n * perp collateral fold-in.\n */\nexport const clearinghouseStateSchema = z.object({\n assetPositions: z.array(\n z.object({\n position: z.object({\n unrealizedPnl: z.string(),\n }),\n }),\n ),\n crossMarginSummary: marginSummarySchema,\n});\n\nexport type UserAbstractionMode = 'unifiedAccount' | 'portfolioMargin' | 'dexAbstraction' | 'disabled' | 'default';\n\n/**\n * `type: \"userAbstraction\"` — bare JSON string. Unknown future values coerce\n * to `\"default\"` so balance math stays conservative.\n */\nexport const userAbstractionSchema = z.string().transform((value): UserAbstractionMode => {\n switch (value) {\n case 'unifiedAccount':\n case 'portfolioMargin':\n case 'dexAbstraction':\n case 'disabled':\n case 'default':\n return value;\n default:\n return 'default';\n }\n});\n\n/** `type: \"userFills\"` */\nexport const userFillSchema = z.object({\n closedPnl: z.string(),\n coin: z.string(),\n crossed: z.boolean(),\n dir: z.string(),\n hash: z.string(),\n oid: z.number(),\n px: z.string(),\n side: z.string(),\n startPosition: z.string(),\n sz: z.string(),\n time: z.number(),\n fee: z.string().optional(),\n tid: z.number().optional(),\n});\n\nexport const userFillsSchema = z.array(userFillSchema);\n\n/**\n * `userNonFundingLedgerUpdates` deltas — permissive so unknown delta types\n * still parse and can render generically later.\n */\nexport const hypercoreLedgerDeltaSchema = z.object({\n type: z.string(),\n usdc: z.string().optional(),\n amount: z.string().optional(),\n usdcValue: z.string().optional(),\n token: z.string().optional(),\n user: z.string().optional(),\n destination: z.string().optional(),\n fee: z.string().optional(),\n toPerp: z.boolean().optional(),\n});\n\nexport const hypercoreLedgerUpdateSchema = z.object({\n time: z.number(),\n hash: z.string(),\n delta: hypercoreLedgerDeltaSchema,\n});\n\nexport const hypercoreLedgerUpdatesSchema = z.array(hypercoreLedgerUpdateSchema);\n\nexport type SpotMetaResponse = z.infer<typeof spotMetaResponseSchema>;\nexport type SpotBalance = {\n coin: string;\n token: number;\n total: string;\n hold: string;\n entryNtl?: string;\n};\nexport type SpotClearinghouseState = {\n balances: SpotBalance[];\n};\nexport type ClearinghouseState = z.infer<typeof clearinghouseStateSchema>;\nexport type UserFill = z.infer<typeof userFillSchema>;\nexport type HypercoreLedgerUpdate = z.infer<typeof hypercoreLedgerUpdateSchema>;\n","import type { z } from 'zod';\nimport {\n clearinghouseStateSchema,\n hypercoreLedgerUpdatesSchema,\n spotClearinghouseStateSchema,\n spotMetaResponseSchema,\n userAbstractionSchema,\n userFillsSchema,\n type ClearinghouseState,\n type HypercoreLedgerUpdate,\n type SpotClearinghouseState,\n type SpotMetaResponse,\n type UserAbstractionMode,\n type UserFill,\n} from './schemas';\n\nexport type HypercoreInfoRequest =\n | { type: 'spotMeta' }\n | { type: 'spotClearinghouseState'; user: string; dex?: string }\n | { type: 'clearinghouseState'; user: string; dex?: string }\n | { type: 'userAbstraction'; user: string }\n | { type: 'userFills'; user: string }\n | {\n type: 'userNonFundingLedgerUpdates';\n user: string;\n startTime: number;\n };\n\nexport type HypercoreInfoClientConfig = {\n /** Proxy-first `/info` URL used for balances and spot meta. */\n infoUrl: string;\n /**\n * Activity URL. Defaults to `infoUrl`; may be the public HL endpoint when\n * the proxy does not yet support fills/ledger types.\n */\n activityInfoUrl?: string;\n fetch?: typeof globalThis.fetch;\n};\n\nexport type PostInfoOptions = {\n signal?: AbortSignal;\n /** Overrides the client default URL for this call. */\n url?: string;\n};\n\nconst resolveFetch = (fetchFn?: typeof globalThis.fetch): typeof globalThis.fetch => {\n if (typeof fetchFn === 'function') {\n return fetchFn;\n }\n\n if (typeof globalThis.fetch === 'function') {\n return globalThis.fetch.bind(globalThis);\n }\n\n throw new Error(\n 'HypercoreInfoClient requires a fetch implementation. Pass config.fetch when globalThis.fetch is unavailable (e.g. React Native).',\n );\n};\n\nexport class HypercoreInfoClient {\n readonly #infoUrl: string;\n readonly #activityInfoUrl: string;\n readonly #fetch: typeof globalThis.fetch;\n\n constructor(config: HypercoreInfoClientConfig) {\n this.#infoUrl = config.infoUrl;\n this.#activityInfoUrl = config.activityInfoUrl ?? config.infoUrl;\n this.#fetch = resolveFetch(config.fetch);\n }\n\n async postInfo<T>(body: HypercoreInfoRequest, schema: z.ZodType<T>, options?: PostInfoOptions) {\n const response = await this.#fetch(options?.url ?? this.#infoUrl, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify(body),\n signal: options?.signal,\n });\n\n if (!response.ok) {\n throw new Error(`Hyperliquid /info failed: ${response.status} ${response.statusText}`);\n }\n\n const json: unknown = await response.json();\n return schema.parse(json);\n }\n\n getSpotMeta(options?: PostInfoOptions): Promise<SpotMetaResponse> {\n return this.postInfo({ type: 'spotMeta' }, spotMetaResponseSchema, options);\n }\n\n getSpotClearinghouseState(user: string, options?: PostInfoOptions): Promise<SpotClearinghouseState> {\n return this.postInfo(\n {\n type: 'spotClearinghouseState',\n user: user.toLowerCase(),\n dex: '',\n },\n spotClearinghouseStateSchema,\n options,\n ) as Promise<SpotClearinghouseState>;\n }\n\n getClearinghouseState(user: string, options?: PostInfoOptions): Promise<ClearinghouseState> {\n return this.postInfo(\n {\n type: 'clearinghouseState',\n user: user.toLowerCase(),\n dex: '',\n },\n clearinghouseStateSchema,\n options,\n );\n }\n\n getUserAbstraction(user: string, options?: PostInfoOptions): Promise<UserAbstractionMode> {\n return this.postInfo(\n { type: 'userAbstraction', user: user.toLowerCase() },\n userAbstractionSchema,\n options,\n ) as Promise<UserAbstractionMode>;\n }\n\n getUserFills(user: string, options?: PostInfoOptions): Promise<UserFill[]> {\n return this.postInfo({ type: 'userFills', user: user.toLowerCase() }, userFillsSchema, {\n ...options,\n url: options?.url ?? this.#activityInfoUrl,\n });\n }\n\n getUserNonFundingLedgerUpdates(\n user: string,\n startTime: number,\n options?: PostInfoOptions,\n ): Promise<HypercoreLedgerUpdate[]> {\n return this.postInfo(\n {\n type: 'userNonFundingLedgerUpdates',\n user: user.toLowerCase(),\n startTime,\n },\n hypercoreLedgerUpdatesSchema,\n {\n ...options,\n url: options?.url ?? this.#activityInfoUrl,\n },\n );\n }\n}\n","/**\n * Loud failure message for HyperCore capabilities that do not exist (no RPC, no gas).\n * Prefer rejecting with this over empty success so clients and agents see intentional gaps.\n */\nexport const unsupportedHypercoreCapabilityMessage = (capability: string) =>\n `HyperCore does not support ${capability}: read-only module (balances, tokens, activity).`;\n\nexport const unsupportedHypercoreCapability = (capability: string): never => {\n throw new Error(unsupportedHypercoreCapabilityMessage(capability));\n};\n","import {\n TokenType,\n type GetBalancesParams,\n type GetBalancesResponse,\n type NetworkTokenWithBalance,\n type TokenWithBalance,\n type TokenWithBalanceHypercoreSpot,\n} from '@avalabs/vm-module-types';\nimport type { HypercoreInfoClient } from '../../utils/info-client';\nimport { buildHypercoreTokens, type HypercoreTokenBalance } from '../../utils/build-hypercore-tokens';\nimport { hyperliquidCoinSvgUrl } from '../../utils/hyperliquid-coin-svg-url';\nimport { toHypercoreSpotTokens } from '../../utils/spot-tokens';\n\ntype GetHypercoreBalancesParams = Omit<GetBalancesParams, 'currency' | 'customTokens'> & {\n infoClient: HypercoreInfoClient;\n};\n\nconst toErrorMessage = (err: unknown) => (err instanceof Error ? err.message : String(err));\n\nconst toTokenWithBalance = (\n token: HypercoreTokenBalance,\n networkToken: GetBalancesParams['network']['networkToken'],\n): { key: string; value: TokenWithBalance } => {\n if (token.kind === 'native') {\n const balance = BigInt(token.balanceRaw);\n const balanceInCurrency = Number(token.balanceUsd);\n const native: NetworkTokenWithBalance = {\n ...networkToken,\n name: token.name,\n symbol: token.symbol,\n decimals: token.decimals,\n logoUri: networkToken.logoUri ?? hyperliquidCoinSvgUrl(token.symbol),\n coingeckoId: 'usd-coin',\n type: TokenType.NATIVE,\n balance,\n balanceDisplayValue: token.balance,\n balanceInCurrency: Number.isFinite(balanceInCurrency) ? balanceInCurrency : 0,\n balanceCurrencyDisplayValue: token.balanceUsd,\n priceInCurrency: token.priceUsd,\n };\n return { key: token.symbol, value: native };\n }\n\n const balance = BigInt(token.balanceRaw);\n const spot: TokenWithBalanceHypercoreSpot = {\n type: TokenType.HYPERCORE_SPOT,\n name: token.name,\n symbol: token.symbol,\n decimals: token.decimals,\n index: token.index,\n evmContract: token.evmContract,\n logoUri: hyperliquidCoinSvgUrl(token.symbol),\n reputation: null,\n balance,\n balanceDisplayValue: token.balance,\n };\n return { key: `spot:${token.index}`, value: spot };\n};\n\nexport const getBalances = async ({\n addresses,\n network,\n infoClient,\n tokenTypes = [TokenType.NATIVE, TokenType.HYPERCORE_SPOT],\n}: GetHypercoreBalancesParams): Promise<GetBalancesResponse> => {\n const includeNative = tokenTypes.includes(TokenType.NATIVE);\n const includeSpot = tokenTypes.includes(TokenType.HYPERCORE_SPOT);\n\n if (!includeNative && !includeSpot) {\n return Object.fromEntries(addresses.map((address) => [address, {}]));\n }\n\n // Spot meta is only required to label non-USDC spot inventory. Native USDC is\n // derived from spot clearinghouse balances (+ optional perp collateral).\n const spotTokens = includeSpot ? toHypercoreSpotTokens((await infoClient.getSpotMeta()).tokens) : [];\n\n const results = await Promise.allSettled(\n addresses.map(async (address) => {\n const [spotState, perpState, abstractionMode] = await Promise.all([\n infoClient.getSpotClearinghouseState(address),\n includeNative ? infoClient.getClearinghouseState(address) : Promise.resolve(undefined),\n includeNative ? infoClient.getUserAbstraction(address) : Promise.resolve(undefined),\n ]);\n\n const tokens = buildHypercoreTokens({\n spotBalances: spotState.balances,\n perpState,\n abstractionMode,\n spotTokens,\n }).filter((token) => (token.kind === 'native' ? includeNative : includeSpot));\n\n const bySymbol = Object.fromEntries(\n tokens.map((token) => {\n const { key, value } = toTokenWithBalance(token, network.networkToken);\n return [key, value];\n }),\n );\n\n return { [address]: bySymbol };\n }),\n );\n\n return results.reduce((acc, curr, index) => {\n if (curr.status === 'fulfilled') {\n return { ...acc, ...curr.value };\n }\n const address = addresses[index];\n if (!address) {\n return acc;\n }\n return { ...acc, [address]: { error: toErrorMessage(curr.reason) } };\n }, {} as GetBalancesResponse);\n};\n","import Big from 'big.js';\nimport type { HypercoreSpotToken } from '@avalabs/vm-module-types';\nimport { HYPERCORE_USDC_DECIMALS, HYPERCORE_USDC_NAME, HYPERCORE_USDC_SYMBOL } from '../constants';\nimport type { ClearinghouseState, SpotBalance, UserAbstractionMode } from './schemas';\n\nconst BIG_ZERO = new Big(0);\n\nexport type HypercoreNativeTokenBalance = {\n kind: 'native';\n name: string;\n symbol: typeof HYPERCORE_USDC_SYMBOL;\n decimals: number;\n /** Human-readable amount (decimal string). */\n balance: string;\n /** Integer raw amount as a decimal string (no fractional part). */\n balanceRaw: string;\n priceUsd: 1;\n balanceUsd: string;\n};\n\nexport type HypercoreSpotTokenBalance = {\n kind: 'spot';\n name: string;\n symbol: string;\n decimals: number;\n balance: string;\n balanceRaw: string;\n index: number;\n evmContract?: string;\n};\n\nexport type HypercoreTokenBalance = HypercoreNativeTokenBalance | HypercoreSpotTokenBalance;\n\n/**\n * `true` when spot balances already back perps for this account mode\n * (`unifiedAccount`). Other modes keep perp collateral on a separate ledger.\n */\nexport const spotCountsAsPerpCollateral = (mode: UserAbstractionMode | undefined) => mode === 'unifiedAccount';\n\n/** Tokens carry no native gas balance on HyperCore — amounts are human decimals. */\nconst toRawBalance = (humanAmount: Big, decimals: number) =>\n humanAmount.times(new Big(10).pow(decimals)).round(0, Big.roundDown).toFixed(0);\n\n/**\n * Perp collateral in USDC, excluding unrealized PnL.\n * `crossMarginSummary.accountValue` is collateral ± PnL; we back PnL out.\n */\nexport const getPerpCollateralUsd = (perp: ClearinghouseState | undefined) => {\n if (!perp) {\n return BIG_ZERO;\n }\n\n const accountValue = new Big(perp.crossMarginSummary.accountValue ?? '0');\n const unrealizedPnl = perp.assetPositions.reduce((sum, { position }) => sum.plus(position.unrealizedPnl), BIG_ZERO);\n const collateral = accountValue.minus(unrealizedPnl);\n\n return collateral.gt(BIG_ZERO) ? collateral : BIG_ZERO;\n};\n\n/**\n * USDC merges spot + (non-unified) PnL-excluded perp collateral at $1.\n * Other spot inventory is `HYPERCORE_SPOT` (no synthetic ERC20 addresses).\n */\nexport const buildHypercoreTokens = ({\n spotBalances,\n perpState,\n abstractionMode,\n spotTokens,\n}: {\n spotBalances: readonly SpotBalance[];\n perpState: ClearinghouseState | undefined;\n abstractionMode: UserAbstractionMode | undefined;\n spotTokens: HypercoreSpotToken[];\n}): HypercoreTokenBalance[] => {\n const tokensByIndex = new Map(spotTokens.map((token) => [token.index, token]));\n\n const perpCollateralUsd = spotCountsAsPerpCollateral(abstractionMode) ? BIG_ZERO : getPerpCollateralUsd(perpState);\n\n const spotUsdc = spotBalances.find((balance) => balance.coin.toUpperCase() === HYPERCORE_USDC_SYMBOL);\n const usdcTotal = new Big(spotUsdc?.total ?? '0').plus(perpCollateralUsd);\n\n const tokens: HypercoreTokenBalance[] = [];\n\n if (usdcTotal.gt(BIG_ZERO)) {\n tokens.push({\n kind: 'native',\n name: HYPERCORE_USDC_NAME,\n symbol: HYPERCORE_USDC_SYMBOL,\n decimals: HYPERCORE_USDC_DECIMALS,\n balance: usdcTotal.toString(),\n balanceRaw: toRawBalance(usdcTotal, HYPERCORE_USDC_DECIMALS),\n priceUsd: 1,\n balanceUsd: usdcTotal.toString(),\n });\n }\n\n for (const balance of spotBalances) {\n if (balance.coin.toUpperCase() === HYPERCORE_USDC_SYMBOL) {\n continue;\n }\n\n const meta = tokensByIndex.get(balance.token);\n const total = new Big(balance.total);\n if (!meta || !total.gt(BIG_ZERO)) {\n continue;\n }\n\n tokens.push({\n kind: 'spot',\n name: meta.name,\n symbol: meta.symbol,\n decimals: meta.decimals,\n balance: total.toString(),\n balanceRaw: toRawBalance(total, meta.decimals),\n index: meta.index,\n evmContract: meta.evmContract,\n });\n }\n\n return tokens;\n};\n","/** CAIP-2 id for HyperCore mainnet. Namespace must be 3–8 chars (CAIP-2).\n * This is a synthetic CAIP-2 for the HyperCore network as HyperCore does not have a chain id.\n */\nexport const HYPERCORE_CAIP_ID = 'hlcore:mainnet';\n\n/**\n * Synthetic numeric id used by Core network lists / storage keys.\n * Not an EVM chain id — module routing uses {@link HYPERCORE_CAIP_ID}.\n */\nexport const HYPERCORE_CHAIN_ID = 9999;\n\nexport const HYPERCORE_USDC_SYMBOL = 'USDC';\nexport const HYPERCORE_USDC_NAME = 'USD Coin';\nexport const HYPERCORE_USDC_DECIMALS = 8;\n","export const HYPERLIQUID_COIN_SVG_BASE = 'https://app.hyperliquid.xyz/coins';\n\nexport const hyperliquidCoinSvgKey = (coin: string) => {\n const trimmed = coin.trim();\n const separatorIndex = trimmed.indexOf(':');\n if (separatorIndex === -1) {\n return trimmed.toUpperCase();\n }\n // HIP-3 logos are keyed as `marketname:TICKER` (dex prefix is case-significant).\n return `${trimmed.slice(0, separatorIndex)}:${trimmed.slice(separatorIndex + 1).toUpperCase()}`;\n};\n\nexport const hyperliquidCoinSvgUrl = (coin: string) =>\n `${HYPERLIQUID_COIN_SVG_BASE}/${encodeURIComponent(hyperliquidCoinSvgKey(coin))}.svg`;\n","import { TokenType, type HypercoreSpotToken } from '@avalabs/vm-module-types';\nimport type { SpotMetaResponse } from './schemas';\n\nconst isValidEvmAddress = (address: string) => /^0x[a-fA-F0-9]{40}$/.test(address);\n\n/**\n * Maps `spotMeta` tokens to the registry used when resolving spot balances.\n * Keeps every spot token (including HyperCore-only ones without an EVM contract).\n */\nexport const toHypercoreSpotTokens = (tokens: SpotMetaResponse['tokens']): HypercoreSpotToken[] =>\n tokens.map((token) => {\n const address = token.evmContract?.address.toLowerCase();\n\n return {\n type: TokenType.HYPERCORE_SPOT,\n index: token.index,\n name: token.fullName ?? token.name,\n symbol: token.name,\n decimals: token.weiDecimals,\n evmContract: address && isValidEvmAddress(address) ? address : undefined,\n };\n });\n","import type { HypercoreSpotToken, Network } from '@avalabs/vm-module-types';\nimport type { HypercoreInfoClient } from '../../utils/info-client';\nimport { hyperliquidCoinSvgUrl } from '../../utils/hyperliquid-coin-svg-url';\nimport { toHypercoreSpotTokens } from '../../utils/spot-tokens';\n\nexport const getTokens = async ({\n infoClient,\n}: {\n network: Network;\n infoClient: HypercoreInfoClient;\n}): Promise<HypercoreSpotToken[]> => {\n const spotMeta = await infoClient.getSpotMeta();\n return toHypercoreSpotTokens(spotMeta.tokens).map((token) => ({\n ...token,\n logoUri: token.logoUri ?? hyperliquidCoinSvgUrl(token.symbol),\n }));\n};\n","import type { HypercoreLedgerUpdate, UserFill } from '../schemas';\n\nexport type HypercoreActivityItem =\n | {\n readonly kind: 'fill';\n readonly timeMs: number;\n readonly hash: string;\n readonly fill: UserFill;\n }\n | {\n readonly kind: 'ledger';\n readonly timeMs: number;\n readonly hash: string;\n readonly update: HypercoreLedgerUpdate;\n };\n\n/** Normalize a Unix timestamp to milliseconds. */\nexport const toTimeMs = (time: number) => (time < 10_000_000_000 ? time * 1000 : time);\n","import type { HypercoreInfoClient } from '../info-client';\nimport type { HypercoreLedgerUpdate } from '../schemas';\nimport type { HypercoreActivityItem } from './types';\nimport { toTimeMs } from './types';\n\n/**\n * Safety cap only — ledger events are infrequent vs fills, so we normally stop\n * on an empty page well before this. Hitting the cap would truncate the *newest*\n * updates (pages are ascending from `startTime`).\n */\nexport const MAX_LEDGER_PAGES = 20;\n\n/** Default ledger window; keep short so a capped crawl still covers recent activity. */\nexport const LEDGER_LOOKBACK_MS = 30 * 24 * 60 * 60 * 1000;\n\ntype FetchHypercoreActivityOptions = {\n signal?: AbortSignal;\n};\n\nconst isAbortError = (err: unknown) =>\n (err instanceof DOMException && err.name === 'AbortError') || (err instanceof Error && err.name === 'AbortError');\n\nconst softFail = async <T>(promise: Promise<T>, fallback: T): Promise<T> => {\n try {\n return await promise;\n } catch (err) {\n if (isAbortError(err)) {\n throw err;\n }\n return fallback;\n }\n};\n\n/**\n * `userNonFundingLedgerUpdates` returns an ascending, capped page (~500) from\n * `startTime`. A single request therefore returns the *oldest* rows in the\n * window and can omit recent activity. Page forward — advancing past the last\n * row's time — until empty (or the safety page cap), so the newest updates in\n * the lookback window are included.\n */\nconst fetchLedgerUpdates = async (\n client: HypercoreInfoClient,\n evmAddress: string,\n options?: FetchHypercoreActivityOptions,\n) => {\n const all: HypercoreLedgerUpdate[] = [];\n let startTime = Date.now() - LEDGER_LOOKBACK_MS;\n let pages = 0;\n\n while (pages < MAX_LEDGER_PAGES) {\n if (options?.signal?.aborted) {\n throw new DOMException('The operation was aborted.', 'AbortError');\n }\n\n const page = await client.getUserNonFundingLedgerUpdates(evmAddress, startTime, options);\n pages += 1;\n if (page.length === 0) {\n break;\n }\n all.push(...page);\n const last = page[page.length - 1];\n if (!last) {\n break;\n }\n const next = last.time + 1;\n if (next <= startTime) {\n break;\n }\n startTime = next;\n }\n\n return all;\n};\n\n/**\n * Fetches HyperCore fills + non-funding ledger updates and sorts newest-first.\n * Soft-fails individual endpoints so a flaky fills or ledger call still yields\n * partial history (abort errors are rethrown).\n */\nexport const fetchHypercoreActivity = async (\n client: HypercoreInfoClient,\n evmAddress: string,\n options?: FetchHypercoreActivityOptions,\n): Promise<HypercoreActivityItem[]> => {\n const [fills, ledgerUpdates] = await Promise.all([\n softFail(client.getUserFills(evmAddress, options), []),\n softFail(fetchLedgerUpdates(client, evmAddress, options), []),\n ]);\n\n const items: HypercoreActivityItem[] = [\n ...fills.map((fill) => ({\n kind: 'fill' as const,\n timeMs: toTimeMs(fill.time),\n hash: fill.hash,\n fill,\n })),\n ...ledgerUpdates.map((update) => ({\n kind: 'ledger' as const,\n timeMs: toTimeMs(update.time),\n hash: update.hash,\n update,\n })),\n ];\n\n return items.sort((a, b) => b.timeMs - a.timeMs);\n};\n","import { TokenType, TransactionType, type Network, type Transaction, type TxToken } from '@avalabs/vm-module-types';\nimport { HYPERCORE_CAIP_ID } from '../../constants';\nimport { hyperliquidCoinSvgUrl } from '../hyperliquid-coin-svg-url';\nimport type { HypercoreLedgerUpdate, UserFill } from '../schemas';\nimport { getHypercoreLedgerDisplay } from './get-hypercore-ledger-display';\nimport { encodeHypercoreFillMethod, tickerOfCoin } from './hypercore-fill-meta';\nimport type { HypercoreActivityItem } from './types';\nimport { toTimeMs } from './types';\n\nconst explorerTxLink = (network: Pick<Network, 'explorerUrl'>, hash: string) => {\n const base = (network.explorerUrl ?? '').replace(/\\/$/, '');\n return base ? `${base}/tx/${hash}` : hash;\n};\n\nconst chainIdForNetwork = (network: Pick<Network, 'caipId' | 'chainId'>) => network.caipId ?? HYPERCORE_CAIP_ID;\n\nconst mapFillToTransaction = (\n fill: UserFill,\n timeMs: number,\n network: Pick<Network, 'explorerUrl' | 'caipId' | 'chainId'>,\n): Transaction => {\n const isBuy = fill.side === 'B';\n const ticker = tickerOfCoin(fill.coin);\n\n const token: TxToken = {\n type: TokenType.NATIVE,\n name: fill.coin,\n symbol: ticker,\n amount: fill.sz,\n imageUri: hyperliquidCoinSvgUrl(fill.coin),\n };\n\n return {\n isContractCall: false,\n isIncoming: isBuy,\n isOutgoing: !isBuy,\n isSender: !isBuy,\n timestamp: timeMs,\n hash: fill.hash,\n from: '',\n to: '',\n tokens: [token],\n gasUsed: '0',\n txType: TransactionType.FILL_ORDER,\n method: encodeHypercoreFillMethod({\n dir: fill.dir ?? '',\n px: fill.px,\n closedPnl: fill.closedPnl,\n coin: fill.coin,\n }),\n chainId: chainIdForNetwork(network),\n explorerLink: explorerTxLink(network, fill.hash),\n };\n};\n\nconst mapLedgerToTransaction = (\n update: HypercoreLedgerUpdate,\n evmAddress: string,\n network: Pick<Network, 'explorerUrl' | 'caipId' | 'chainId'>,\n): Transaction => {\n const display = getHypercoreLedgerDisplay(update, evmAddress);\n const isIncoming = display.direction === 'positive';\n const isOutgoing = display.direction === 'negative';\n\n let txType: TransactionType = TransactionType.TRANSFER;\n switch (display.label) {\n case 'deposit':\n case 'received':\n txType = TransactionType.RECEIVE;\n break;\n case 'withdraw':\n case 'sent':\n txType = TransactionType.SEND;\n break;\n case 'liquidation':\n txType = TransactionType.UNKNOWN;\n break;\n default:\n txType = TransactionType.TRANSFER;\n }\n\n const amount = display.amount || '0';\n const token: TxToken = {\n type: TokenType.NATIVE,\n name: display.symbol,\n symbol: display.symbol,\n amount,\n imageUri: hyperliquidCoinSvgUrl(display.symbol),\n };\n\n return {\n isContractCall: false,\n isIncoming,\n isOutgoing,\n isSender: isOutgoing,\n timestamp: toTimeMs(update.time),\n hash: update.hash,\n from: display.from ?? (isOutgoing ? evmAddress : ''),\n to: display.to ?? (isIncoming ? evmAddress : ''),\n tokens: [token],\n gasUsed: '0',\n txType,\n chainId: chainIdForNetwork(network),\n explorerLink: explorerTxLink(network, update.hash),\n };\n};\n\nexport const mapHypercoreActivityToTransactions = (\n items: readonly HypercoreActivityItem[],\n evmAddress: string,\n network: Pick<Network, 'explorerUrl' | 'caipId' | 'chainId'>,\n): Transaction[] =>\n items.map((item) =>\n item.kind === 'fill'\n ? mapFillToTransaction(item.fill, item.timeMs, network)\n : mapLedgerToTransaction(item.update, evmAddress, network),\n );\n","import type { HypercoreLedgerUpdate } from '../schemas';\n\n/**\n * Semantic label key for a ledger row.\n */\nexport type HypercoreLedgerLabel =\n | 'deposit'\n | 'withdraw'\n | 'sent'\n | 'received'\n | 'transferToPerp'\n | 'transferToSpot'\n | 'transfer'\n | 'liquidation'\n | 'other';\n\nexport type HypercoreLedgerDisplay = {\n readonly label: HypercoreLedgerLabel;\n /** Unsigned token amount, e.g. `0.1`. */\n readonly amount: string;\n readonly symbol: string;\n /** Signed USD value for the fiat line; undefined when there's nothing to show. */\n readonly usdValue?: number;\n readonly direction: 'positive' | 'negative' | 'neutral';\n readonly from?: string;\n readonly to?: string;\n readonly rawType: string;\n};\n\nconst formatAmount = (value: string | undefined) => {\n if (value === undefined || value === '') {\n return '';\n }\n const parsed = Number.parseFloat(value);\n if (!Number.isFinite(parsed)) {\n return value;\n }\n return new Intl.NumberFormat('en-US', { maximumFractionDigits: 6 }).format(parsed);\n};\n\nconst toUsd = (value: string | undefined, sign: 1 | -1 | 0) => {\n if (value === undefined || value === '') {\n return undefined;\n }\n const parsed = Number.parseFloat(value);\n return Number.isFinite(parsed) ? parsed * (sign === 0 ? 1 : sign) : undefined;\n};\n\n/**\n * Derives label, amount, signed USD value, and counterparties for a HyperCore\n * ledger update from the owner's perspective.\n */\nexport const getHypercoreLedgerDisplay = (\n update: HypercoreLedgerUpdate,\n evmAddress: string,\n): HypercoreLedgerDisplay => {\n const { delta } = update;\n const owner = evmAddress.toLowerCase();\n const isOutgoing = delta.user?.toLowerCase() === owner;\n\n switch (delta.type) {\n case 'deposit':\n return {\n label: 'deposit',\n amount: formatAmount(delta.usdc),\n symbol: 'USDC',\n usdValue: toUsd(delta.usdc, 1),\n direction: 'positive',\n to: evmAddress,\n rawType: delta.type,\n };\n case 'withdraw':\n return {\n label: 'withdraw',\n amount: formatAmount(delta.usdc),\n symbol: 'USDC',\n usdValue: toUsd(delta.usdc, -1),\n direction: 'negative',\n from: evmAddress,\n rawType: delta.type,\n };\n case 'send':\n case 'spotTransfer':\n return {\n label: isOutgoing ? 'sent' : 'received',\n amount: formatAmount(delta.amount),\n symbol: delta.token ?? 'USDC',\n usdValue: toUsd(delta.usdcValue, isOutgoing ? -1 : 1),\n direction: isOutgoing ? 'negative' : 'positive',\n from: delta.user,\n to: delta.destination,\n rawType: delta.type,\n };\n case 'internalTransfer':\n return {\n label: 'transfer',\n amount: formatAmount(delta.usdc),\n symbol: 'USDC',\n usdValue: toUsd(delta.usdc, isOutgoing ? -1 : 1),\n direction: isOutgoing ? 'negative' : 'positive',\n from: delta.user,\n to: delta.destination,\n rawType: delta.type,\n };\n case 'accountClassTransfer':\n return {\n label: delta.toPerp ? 'transferToPerp' : 'transferToSpot',\n amount: formatAmount(delta.usdc),\n symbol: 'USDC',\n usdValue: toUsd(delta.usdc, 0),\n direction: 'neutral',\n rawType: delta.type,\n };\n case 'liquidation':\n return {\n label: 'liquidation',\n amount: formatAmount(delta.usdcValue ?? delta.usdc),\n symbol: 'USDC',\n usdValue: toUsd(delta.usdcValue ?? delta.usdc, -1),\n direction: 'negative',\n rawType: delta.type,\n };\n default:\n return {\n label: 'other',\n amount: formatAmount(delta.usdcValue ?? delta.usdc),\n symbol: 'USDC',\n usdValue: toUsd(delta.usdcValue ?? delta.usdc, 0),\n direction: 'neutral',\n rawType: delta.type,\n };\n }\n};\n","const METHOD_PREFIX = 'hypercoreFill:v1:';\n\nexport type HypercoreFillMeta = {\n /** Fill side / action from Hyperliquid (`Open Long`, `Close Short`, …). */\n readonly dir: string;\n /** Fill price as a decimal string (Hyperliquid `px`). */\n readonly px: string;\n /** Realized PnL for the fill as a decimal string; `\"0\"` when none. */\n readonly closedPnl: string;\n /** Market coin id (`ETH`, or HIP-3 `dex:TICKER`). */\n readonly coin: string;\n};\n\nexport type FillLabel = {\n readonly text: string;\n /** Long / short cue for the UI to pick an icon. */\n readonly direction?: 'up' | 'down';\n readonly tone?: 'profit' | 'loss';\n};\n\n/** Display ticker with any `dex:` prefix stripped (`xyz:GOLD` → `GOLD`). */\nexport const tickerOfCoin = (coin: string) => {\n const i = coin.indexOf(':');\n return i === -1 ? coin : coin.slice(i + 1);\n};\n\n/** PnL tone from `closedPnl` — `dir` alone does not indicate profit vs loss. */\nexport const closedPnlTone = (closedPnl: string | undefined): 'profit' | 'loss' | undefined => {\n if (closedPnl === undefined) {\n return undefined;\n }\n const n = Number.parseFloat(closedPnl);\n if (!Number.isFinite(n) || n === 0) {\n return undefined;\n }\n return n > 0 ? 'profit' : 'loss';\n};\n\n/**\n * Map a fill's `dir` into a display label. Direction follows side\n * (long → up / short → down); success/error tone comes from `closedPnl` when provided.\n */\nexport const fillLabel = (dir: string, closedPnl?: string): FillLabel => {\n const tone = closedPnlTone(closedPnl);\n const d = dir.toLowerCase();\n if (d.includes('close') && d.includes('long')) {\n return { text: 'Long closed', direction: 'up', tone };\n }\n if (d.includes('close') && d.includes('short')) {\n return { text: 'Short closed', direction: 'down', tone };\n }\n if (d.includes('open') && (d.includes('long') || d.includes('short'))) {\n return { text: 'Order opened' };\n }\n if (d.includes('cancel')) {\n return { text: 'Order cancelled' };\n }\n return { text: dir };\n};\n\n/** Compact USD price for fill rows (`$1,684.7`). */\nexport const formatHypercoreFillPx = (px: string) => {\n const n = Number.parseFloat(px);\n if (!Number.isFinite(n)) {\n return px;\n }\n return `$${n.toLocaleString(undefined, { maximumFractionDigits: 8 })}`;\n};\n\nexport const encodeHypercoreFillMethod = (meta: HypercoreFillMeta) =>\n `${METHOD_PREFIX}${encodeURIComponent(JSON.stringify(meta))}`;\n\nexport const parseHypercoreFillMethod = (method: string | undefined): HypercoreFillMeta | undefined => {\n if (!method?.startsWith(METHOD_PREFIX)) {\n return undefined;\n }\n try {\n const parsed: unknown = JSON.parse(decodeURIComponent(method.slice(METHOD_PREFIX.length)));\n if (\n typeof parsed !== 'object' ||\n parsed === null ||\n !('dir' in parsed) ||\n !('px' in parsed) ||\n !('closedPnl' in parsed) ||\n !('coin' in parsed)\n ) {\n return undefined;\n }\n const { dir, px, closedPnl, coin } = parsed as Record<string, unknown>;\n if (\n typeof dir !== 'string' ||\n typeof px !== 'string' ||\n typeof closedPnl !== 'string' ||\n typeof coin !== 'string'\n ) {\n return undefined;\n }\n return { dir, px, closedPnl, coin };\n } catch {\n return undefined;\n }\n};\n","import type { GetTransactionHistory, TransactionHistoryResponse } from '@avalabs/vm-module-types';\nimport type { HypercoreInfoClient } from '../../utils/info-client';\nimport { fetchHypercoreActivity } from '../../utils/activity/fetch-hypercore-activity';\nimport { mapHypercoreActivityToTransactions } from '../../utils/activity/map-hypercore-activity-to-transactions';\n\nexport const getTransactionHistory = async ({\n address,\n network,\n infoClient,\n}: GetTransactionHistory & {\n infoClient: HypercoreInfoClient;\n}): Promise<TransactionHistoryResponse> => {\n const items = await fetchHypercoreActivity(infoClient, address);\n return {\n transactions: mapHypercoreActivityToTransactions(items, address, network),\n };\n};\n","import { NetworkVMType, WalletType, type GetAddressParams, type GetAddressResponse } from '@avalabs/vm-module-types';\nimport { getAddressFromXPub, getEvmAddressFromPubKey } from '@avalabs/core-wallets-sdk';\nimport { rpcErrors } from '@metamask/rpc-errors';\n\ntype GetAddress = Omit<GetAddressParams, 'isTestnet' | 'xpubXP' | 'network'>;\n\nexport const getAddress = async ({ accountIndex, xpub, walletType }: GetAddress): Promise<GetAddressResponse> => {\n switch (walletType) {\n case WalletType.Mnemonic:\n case WalletType.Ledger:\n case WalletType.Keystone: {\n return {\n [NetworkVMType.HYPERCORE]: getAddressFromXPub(xpub, accountIndex),\n };\n }\n case WalletType.LedgerLive:\n case WalletType.Seedless: {\n const pubKeyBuffer = Buffer.from(xpub, 'hex');\n return {\n [NetworkVMType.HYPERCORE]: getEvmAddressFromPubKey(pubKeyBuffer),\n };\n }\n default:\n throw rpcErrors.invalidParams(`Unsupported wallet type: ${walletType}`);\n }\n};\n","import {\n NetworkVMType,\n type ApprovalController,\n type DeriveAddressParams,\n type DeriveAddressResponse,\n} from '@avalabs/vm-module-types';\nimport { computeAddress } from 'ethers';\nimport { hasDerivationDetails } from '@internal/utils/src/utils/address-derivation';\nimport { buildDerivationPath } from '../build-derivation-path/build-derivation-path';\n\nexport const deriveAddress = async (\n params: DeriveAddressParams & { approvalController: ApprovalController },\n): Promise<DeriveAddressResponse> => {\n const { secretId, approvalController } = params;\n\n // Narrow before calling buildDerivationPath — the type guard alone is not\n // enough when `params` is intersected with `{ approvalController }`.\n const derivationPath = hasDerivationDetails(params)\n ? buildDerivationPath({\n accountIndex: params.accountIndex,\n derivationPathType: params.derivationPathType,\n addressIndex: params.addressIndex,\n }).HYPERCORE\n : undefined;\n const publicKeyHex = await approvalController.requestPublicKey({\n curve: 'secp256k1',\n secretId,\n derivationPath,\n });\n\n return {\n [NetworkVMType.HYPERCORE]: computeAddress(`0x${publicKeyHex}`),\n };\n};\n","import type { DeriveAddressParams, DetailedDeriveAddressParams } from '@avalabs/vm-module-types';\n\nexport const hasDerivationDetails = (params: DeriveAddressParams): params is DetailedDeriveAddressParams =>\n 'derivationPathType' in params &&\n 'accountIndex' in params &&\n typeof params.accountIndex === 'number' &&\n typeof params.derivationPathType === 'string';\n","import { rpcErrors } from '@metamask/rpc-errors';\nimport {\n NetworkVMType,\n type BuildDerivationPathParams,\n type BuildDerivationPathResponse,\n} from '@avalabs/vm-module-types';\n\n/**\n * HyperCore identity is an EVM address (cointype 60). Paths match the EVM module;\n * the result is keyed as `HYPERCORE`.\n */\nexport const buildDerivationPath = ({\n accountIndex,\n derivationPathType,\n}: BuildDerivationPathParams): Pick<BuildDerivationPathResponse, NetworkVMType.HYPERCORE> => {\n if (accountIndex < 0) {\n throw rpcErrors.invalidParams('Account index must be a non-negative integer');\n }\n\n switch (derivationPathType) {\n case 'bip44':\n return {\n [NetworkVMType.HYPERCORE]: `m/44'/60'/0'/0/${accountIndex}`,\n };\n\n case 'ledger_live':\n return {\n [NetworkVMType.HYPERCORE]: `m/44'/60'/${accountIndex}'/0/0`,\n };\n\n default:\n throw rpcErrors.invalidParams(`Unsupported derivation path type: ${derivationPathType}`);\n }\n};\n","import {\n NetworkVMType,\n type ApprovalController,\n type DeriveAddressesParams,\n type DeriveAddressesResponse,\n} from '@avalabs/vm-module-types';\nimport { deriveAddressesForEvm, init } from '@avalabs/crypto-sdk';\nimport { buildDerivationPath } from '../build-derivation-path/build-derivation-path';\n\nexport const deriveAddresses = async (\n params: DeriveAddressesParams & { approvalController: ApprovalController },\n): Promise<DeriveAddressesResponse> => {\n const { approvalController, secretId, accountIndices, derivationPathType } = params;\n\n if (accountIndices.length === 0) {\n return [];\n }\n\n await init();\n\n const publicKeys = await Promise.all(\n accountIndices.map(async (accountIndex) => {\n const derivationPath = buildDerivationPath({ accountIndex, derivationPathType }).HYPERCORE;\n const publicKeyHex = await approvalController.requestPublicKey({\n curve: 'secp256k1',\n secretId,\n derivationPath,\n });\n return Uint8Array.from(Buffer.from(publicKeyHex, 'hex'));\n }),\n );\n\n const addresses = await deriveAddressesForEvm(publicKeys);\n\n return addresses.map((address) => ({ [NetworkVMType.HYPERCORE]: address }));\n};\n"]}
package/dist/index.d.cts CHANGED
@@ -23,7 +23,9 @@ declare class HypercoreModule implements Module {
23
23
  }>;
24
24
  }
25
25
 
26
- /** CAIP-2 id for HyperCore mainnet. Namespace must be 3–8 chars (CAIP-2). */
26
+ /** CAIP-2 id for HyperCore mainnet. Namespace must be 3–8 chars (CAIP-2).
27
+ * This is a synthetic CAIP-2 for the HyperCore network as HyperCore does not have a chain id.
28
+ */
27
29
  declare const HYPERCORE_CAIP_ID = "hlcore:mainnet";
28
30
  /**
29
31
  * Synthetic numeric id used by Core network lists / storage keys.
@@ -572,17 +574,20 @@ type HypercoreActivityItem = {
572
574
  /** Normalize a Unix timestamp to milliseconds. */
573
575
  declare const toTimeMs: (time: number) => number;
574
576
 
575
- declare const FILL_ARROW_UP = "\u25B2";
576
- declare const FILL_ARROW_DOWN = "\u25BC";
577
577
  type HypercoreFillMeta = {
578
+ /** Fill side / action from Hyperliquid (`Open Long`, `Close Short`, …). */
578
579
  readonly dir: string;
580
+ /** Fill price as a decimal string (Hyperliquid `px`). */
579
581
  readonly px: string;
582
+ /** Realized PnL for the fill as a decimal string; `"0"` when none. */
580
583
  readonly closedPnl: string;
584
+ /** Market coin id (`ETH`, or HIP-3 `dex:TICKER`). */
581
585
  readonly coin: string;
582
586
  };
583
587
  type FillLabel = {
584
588
  readonly text: string;
585
- readonly arrow?: typeof FILL_ARROW_UP | typeof FILL_ARROW_DOWN;
589
+ /** Long / short cue for the UI to pick an icon. */
590
+ readonly direction?: 'up' | 'down';
586
591
  readonly tone?: 'profit' | 'loss';
587
592
  };
588
593
  /** Display ticker with any `dex:` prefix stripped (`xyz:GOLD` → `GOLD`). */
@@ -590,8 +595,8 @@ declare const tickerOfCoin: (coin: string) => string;
590
595
  /** PnL tone from `closedPnl` — `dir` alone does not indicate profit vs loss. */
591
596
  declare const closedPnlTone: (closedPnl: string | undefined) => "profit" | "loss" | undefined;
592
597
  /**
593
- * Map a fill's `dir` into a display label. Arrow direction follows side
594
- * (long / short ); success/error tone comes from `closedPnl` when provided.
598
+ * Map a fill's `dir` into a display label. Direction follows side
599
+ * (long up / short → down); success/error tone comes from `closedPnl` when provided.
595
600
  */
596
601
  declare const fillLabel: (dir: string, closedPnl?: string) => FillLabel;
597
602
  /** Compact USD price for fill rows (`$1,684.7`). */
@@ -621,9 +626,13 @@ type HypercoreLedgerDisplay = {
621
626
  */
622
627
  declare const getHypercoreLedgerDisplay: (update: HypercoreLedgerUpdate, evmAddress: string) => HypercoreLedgerDisplay;
623
628
 
624
- /** Bound ledger pagination so busy accounts cannot trigger unbounded requests. */
629
+ /**
630
+ * Safety cap only — ledger events are infrequent vs fills, so we normally stop
631
+ * on an empty page well before this. Hitting the cap would truncate the *newest*
632
+ * updates (pages are ascending from `startTime`).
633
+ */
625
634
  declare const MAX_LEDGER_PAGES = 20;
626
- /** Prefer recent ledger history; paging from `0` would return the oldest pages first. */
635
+ /** Default ledger window; keep short so a capped crawl still covers recent activity. */
627
636
  declare const LEDGER_LOOKBACK_MS: number;
628
637
  type FetchHypercoreActivityOptions = {
629
638
  signal?: AbortSignal;
@@ -637,4 +646,4 @@ declare const fetchHypercoreActivity: (client: HypercoreInfoClient, evmAddress:
637
646
 
638
647
  declare const mapHypercoreActivityToTransactions: (items: readonly HypercoreActivityItem[], evmAddress: string, network: Pick<Network, "explorerUrl" | "caipId" | "chainId">) => Transaction[];
639
648
 
640
- export { ClearinghouseState, FILL_ARROW_DOWN, FILL_ARROW_UP, 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 };
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 };
package/dist/index.d.ts CHANGED
@@ -23,7 +23,9 @@ declare class HypercoreModule implements Module {
23
23
  }>;
24
24
  }
25
25
 
26
- /** CAIP-2 id for HyperCore mainnet. Namespace must be 3–8 chars (CAIP-2). */
26
+ /** CAIP-2 id for HyperCore mainnet. Namespace must be 3–8 chars (CAIP-2).
27
+ * This is a synthetic CAIP-2 for the HyperCore network as HyperCore does not have a chain id.
28
+ */
27
29
  declare const HYPERCORE_CAIP_ID = "hlcore:mainnet";
28
30
  /**
29
31
  * Synthetic numeric id used by Core network lists / storage keys.
@@ -572,17 +574,20 @@ type HypercoreActivityItem = {
572
574
  /** Normalize a Unix timestamp to milliseconds. */
573
575
  declare const toTimeMs: (time: number) => number;
574
576
 
575
- declare const FILL_ARROW_UP = "\u25B2";
576
- declare const FILL_ARROW_DOWN = "\u25BC";
577
577
  type HypercoreFillMeta = {
578
+ /** Fill side / action from Hyperliquid (`Open Long`, `Close Short`, …). */
578
579
  readonly dir: string;
580
+ /** Fill price as a decimal string (Hyperliquid `px`). */
579
581
  readonly px: string;
582
+ /** Realized PnL for the fill as a decimal string; `"0"` when none. */
580
583
  readonly closedPnl: string;
584
+ /** Market coin id (`ETH`, or HIP-3 `dex:TICKER`). */
581
585
  readonly coin: string;
582
586
  };
583
587
  type FillLabel = {
584
588
  readonly text: string;
585
- readonly arrow?: typeof FILL_ARROW_UP | typeof FILL_ARROW_DOWN;
589
+ /** Long / short cue for the UI to pick an icon. */
590
+ readonly direction?: 'up' | 'down';
586
591
  readonly tone?: 'profit' | 'loss';
587
592
  };
588
593
  /** Display ticker with any `dex:` prefix stripped (`xyz:GOLD` → `GOLD`). */
@@ -590,8 +595,8 @@ declare const tickerOfCoin: (coin: string) => string;
590
595
  /** PnL tone from `closedPnl` — `dir` alone does not indicate profit vs loss. */
591
596
  declare const closedPnlTone: (closedPnl: string | undefined) => "profit" | "loss" | undefined;
592
597
  /**
593
- * Map a fill's `dir` into a display label. Arrow direction follows side
594
- * (long / short ); success/error tone comes from `closedPnl` when provided.
598
+ * Map a fill's `dir` into a display label. Direction follows side
599
+ * (long up / short → down); success/error tone comes from `closedPnl` when provided.
595
600
  */
596
601
  declare const fillLabel: (dir: string, closedPnl?: string) => FillLabel;
597
602
  /** Compact USD price for fill rows (`$1,684.7`). */
@@ -621,9 +626,13 @@ type HypercoreLedgerDisplay = {
621
626
  */
622
627
  declare const getHypercoreLedgerDisplay: (update: HypercoreLedgerUpdate, evmAddress: string) => HypercoreLedgerDisplay;
623
628
 
624
- /** Bound ledger pagination so busy accounts cannot trigger unbounded requests. */
629
+ /**
630
+ * Safety cap only — ledger events are infrequent vs fills, so we normally stop
631
+ * on an empty page well before this. Hitting the cap would truncate the *newest*
632
+ * updates (pages are ascending from `startTime`).
633
+ */
625
634
  declare const MAX_LEDGER_PAGES = 20;
626
- /** Prefer recent ledger history; paging from `0` would return the oldest pages first. */
635
+ /** Default ledger window; keep short so a capped crawl still covers recent activity. */
627
636
  declare const LEDGER_LOOKBACK_MS: number;
628
637
  type FetchHypercoreActivityOptions = {
629
638
  signal?: AbortSignal;
@@ -637,4 +646,4 @@ declare const fetchHypercoreActivity: (client: HypercoreInfoClient, evmAddress:
637
646
 
638
647
  declare const mapHypercoreActivityToTransactions: (items: readonly HypercoreActivityItem[], evmAddress: string, network: Pick<Network, "explorerUrl" | "caipId" | "chainId">) => Transaction[];
639
648
 
640
- export { ClearinghouseState, FILL_ARROW_DOWN, FILL_ARROW_UP, 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 };
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 };
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 C from 'big.js';
4
+ import S 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 we=Object.defineProperty;var n=(e,t)=>we(e,"name",{value:t,configurable:!0});var _=(e,t,r)=>{if(!t.has(e))throw TypeError("Cannot "+r)};var m=(e,t,r)=>(_(e,t,"read from private field"),r?r.call(e):t.get(e)),f=(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);},g=(e,t,r,o)=>(_(e,t,"write to private field"),o?o.call(e,r):t.set(e,r),r);var V={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 Y="/proxy/nownodes/hype/info",$="https://api.hyperliquid.xyz/info",ke={proxyApiUrl:"https://proxy-api.avax.network",infoUrl:`https://proxy-api.avax.network${Y}`,activityInfoUrl:$},Ae={proxyApiUrl:"https://proxy-api-dev.avax.network",infoUrl:`https://proxy-api-dev.avax.network${Y}`,activityInfoUrl:$},j=n(e=>{switch(e){case Environment.PRODUCTION:return ke;case Environment.DEV:return Ae}},"getEnv");var Re=z$1.coerce.number(),q=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:Re,total:z$1.string(),hold:z$1.string(),entryNtl:z$1.string().optional()}),W=z$1.object({balances:z$1.array(Ie)}),Ee=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:Ee}),K=z$1.string().transform(e=>{switch(e){case"unifiedAccount":case"portfolioMargin":case"dexAbstraction":case"disabled":case"default":return e;default:return "default"}}),De=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()}),J=z$1.array(De),Me=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:Me}),X=z$1.array(Oe);var H=n(e=>e.toLowerCase(),"lowercaseUser"),k,P,A,O=class O{constructor(t){f(this,k,void 0);f(this,P,void 0);f(this,A,void 0);g(this,k,t.infoUrl),g(this,P,t.activityInfoUrl??t.infoUrl),g(this,A,t.fetch??globalThis.fetch.bind(globalThis));}async postInfo(t,r,o){let i=await m(this,A).call(this,o?.url??m(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 p=await i.json();return r.parse(p)}getSpotMeta(t){return this.postInfo({type:"spotMeta"},q,t)}getSpotClearinghouseState(t,r){return this.postInfo({type:"spotClearinghouseState",user:H(t),dex:""},W,r)}getClearinghouseState(t,r){return this.postInfo({type:"clearinghouseState",user:H(t),dex:""},z,r)}getUserAbstraction(t,r){return this.postInfo({type:"userAbstraction",user:H(t)},K,r)}getUserFills(t,r){return this.postInfo({type:"userFills",user:H(t)},J,{...r,url:r?.url??m(this,P)})}getUserNonFundingLedgerUpdates(t,r,o){return this.postInfo({type:"userNonFundingLedgerUpdates",user:H(t),startTime:r},X,{...o,url:o?.url??m(this,P)})}};k=new WeakMap,P=new WeakMap,A=new WeakMap,n(O,"HypercoreInfoClient");var E=O;var N=n(e=>`HyperCore does not support ${e}: read-only module (balances, tokens, activity).`,"unsupportedHypercoreCapabilityMessage");var Z="hlcore:mainnet",vt=9999,D="USDC",Q="USD Coin",F=8;var h=new C(0),Ne=n(e=>e==="unifiedAccount","spotCountsAsPerpCollateral"),ee=n((e,t)=>e.times(new C(10).pow(t)).round(0,C.roundDown).toFixed(0),"toRawBalance"),Fe=n(e=>{if(!e)return h;let t=new C(e.crossMarginSummary.accountValue??"0"),r=e.assetPositions.reduce((i,{position:p})=>i.plus(p.unrealizedPnl),h),o=t.minus(r);return o.gt(h)?o:h},"getPerpCollateralUsd"),te=n(({spotBalances:e,perpState:t,abstractionMode:r,spotTokens:o})=>{let i=new Map(o.map(d=>[d.index,d])),p=Ne(r)?h:Fe(t),a=e.find(d=>d.coin.toUpperCase()===D),c=new C(a?.total??"0").plus(p),l=[];c.gt(h)&&l.push({kind:"native",name:Q,symbol:D,decimals:8,balance:c.toString(),balanceRaw:ee(c,8),priceUsd:1,balanceUsd:c.toString()});for(let d of e){if(d.coin.toUpperCase()===D)continue;let u=i.get(d.token),w=new C(d.total);!u||!w.gt(h)||l.push({kind:"spot",name:u.name,symbol:u.symbol,decimals:u.decimals,balance:w.toString(),balanceRaw:ee(w,u.decimals),index:u.index,evmContract:u.evmContract});}return l},"buildHypercoreTokens");var Le="https://app.hyperliquid.xyz/coins",Be=n(e=>{let t=e.trim(),r=t.indexOf(":");return r===-1?t.toUpperCase():`${t.slice(0,r)}:${t.slice(r+1).toUpperCase()}`},"hyperliquidCoinSvgKey"),y=n(e=>`${Le}/${encodeURIComponent(Be(e))}.svg`,"hyperliquidCoinSvgUrl");var Ve=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&&Ve(r)?r:void 0}}),"toHypercoreSpotTokens");var Ge=n((e,t)=>{if(e.kind==="native"){let i=BigInt(e.balanceRaw),p=Number(e.balanceUsd),a={...t,name:e.name,symbol:e.symbol,decimals:e.decimals,logoUri:t.logoUri??y(e.symbol),coingeckoId:"usd-coin",type:TokenType.NATIVE,balance:i,balanceDisplayValue:e.balance,balanceInCurrency:Number.isFinite(p)?p:0,balanceCurrencyDisplayValue:e.balanceUsd,priceInCurrency:e.priceUsd};return {key:e.symbol,value:a}}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:y(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})=>{let o=await r.getSpotMeta(),i=M(o.tokens);return (await Promise.allSettled(e.map(async a=>{try{let[c,l,d]=await Promise.all([r.getSpotClearinghouseState(a),r.getClearinghouseState(a).catch(()=>{}),r.getUserAbstraction(a).catch(()=>{})]),u=te({spotBalances:c.balances,perpState:l,abstractionMode:d,spotTokens:i}),w=Object.fromEntries(u.map(Se=>{let{key:Te,value:Ue}=Ge(Se,t.networkToken);return [Te,Ue]}));return {[a]:w}}catch(c){return {[a]:{error:c.toString()}}}}))).reduce((a,c)=>c.status==="fulfilled"?{...a,...c.value}:a,{})},"getBalances");var ne=n(async({infoClient:e})=>{let t=await e.getSpotMeta();return M(t.tokens).map(r=>({...r,logoUri:r.logoUri??y(r.symbol)}))},"getTokens");var R=n(e=>e<1e10?e*1e3:e,"toTimeMs");var Ye=20,$e=365*24*60*60*1e3,je=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(je(r))throw r;return t}},"softFail"),qe=n(async(e,t,r)=>{let o=[],i=Date.now()-$e,p=0;for(;p<Ye;){if(r?.signal?.aborted)throw new DOMException("The operation was aborted.","AbortError");let a=await e.getUserNonFundingLedgerUpdates(t,i,r);if(p+=1,a.length===0)break;o.push(...a);let c=a[a.length-1];if(!c)break;let l=c.time+1;if(l<=i)break;i=l;}return o},"fetchLedgerUpdates"),ie=n(async(e,t,r)=>{let[o,i]=await Promise.all([se(e.getUserFills(t,r),[]),se(qe(e,t,r),[])]);return [...o.map(a=>({kind:"fill",timeMs:R(a.time),hash:a.hash,fill:a})),...i.map(a=>({kind:"ledger",timeMs:R(a.time),hash:a.hash,update:a}))].sort((a,c)=>c.timeMs-a.timeMs)},"fetchHypercoreActivity");var b=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:b(r.usdc),symbol:"USDC",usdValue:x(r.usdc,1),direction:"positive",to:t,rawType:r.type};case"withdraw":return {label:"withdraw",amount:b(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:b(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:b(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:b(r.usdc),symbol:"USDC",usdValue:x(r.usdc,0),direction:"neutral",rawType:r.type};case"liquidation":return {label:"liquidation",amount:b(r.usdcValue??r.usdc),symbol:"USDC",usdValue:x(r.usdcValue??r.usdc,-1),direction:"negative",rawType:r.type};default:return {label:"other",amount:b(r.usdcValue??r.usdc),symbol:"USDC",usdValue:x(r.usdcValue??r.usdc,0),direction:"neutral",rawType:r.type}}},"getHypercoreLedgerDisplay");var L="hypercoreFill:v1:",We="\u25B2",ze="\u25BC",pe=n(e=>{let t=e.indexOf(":");return t===-1?e:e.slice(t+1)},"tickerOfCoin"),Ke=n(e=>{if(e===void 0)return;let t=Number.parseFloat(e);if(!(!Number.isFinite(t)||t===0))return t>0?"profit":"loss"},"closedPnlTone"),zt=n((e,t)=>{let r=Ke(t),o=e.toLowerCase();return o.includes("close")&&o.includes("long")?{text:"Long closed",arrow:We,tone:r}:o.includes("close")&&o.includes("short")?{text:"Short closed",arrow:ze,tone:r}:o.includes("open")&&(o.includes("long")||o.includes("short"))?{text:"Order opened"}:o.includes("cancel")?{text:"Order cancelled"}:{text:e}},"fillLabel"),Kt=n(e=>{let t=Number.parseFloat(e);return Number.isFinite(t)?`$${t.toLocaleString(void 0,{maximumFractionDigits:8})}`:e},"formatHypercoreFillPx"),ce=n(e=>`${L}${encodeURIComponent(JSON.stringify(e))}`,"encodeHypercoreFillMethod"),Jt=n(e=>{if(e?.startsWith(L))try{let t=JSON.parse(decodeURIComponent(e.slice(L.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:p}=t;return typeof r!="string"||typeof o!="string"||typeof i!="string"||typeof p!="string"?void 0:{dir:r,px:o,closedPnl:i,coin:p}}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??Z,"chainIdForNetwork"),Je=n((e,t,r)=>{let o=e.side==="B",i=pe(e.coin),p={type:TokenType.NATIVE,name:e.coin,symbol:i,amount:e.sz,imageUri:y(e.coin)};return {isContractCall:!1,isIncoming:o,isOutgoing:!o,isSender:!o,timestamp:t,hash:e.hash,from:"",to:"",tokens:[p],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"),Xe=n((e,t,r)=>{let o=ae(e,t),i=o.direction==="positive",p=o.direction==="negative",a=TransactionType.TRANSFER;switch(o.label){case"deposit":case"received":a=TransactionType.RECEIVE;break;case"withdraw":case"sent":a=TransactionType.SEND;break;case"liquidation":a=TransactionType.UNKNOWN;break;default:a=TransactionType.TRANSFER;}let c=o.amount||"0",l={type:TokenType.NATIVE,name:o.symbol,symbol:o.symbol,amount:c,imageUri:y(o.symbol)};return {isContractCall:!1,isIncoming:i,isOutgoing:p,isSender:p,timestamp:R(e.time),hash:e.hash,from:o.from??(p?t:""),to:o.to??(i?t:""),tokens:[l],gasUsed:"0",txType:a,chainId:me(r),explorerLink:de(r,e.hash)}},"mapLedgerToTransaction"),ue=n((e,t,r)=>e.map(o=>o.kind==="fill"?Je(o.fill,o.timeMs,r):Xe(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 T=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 ve=n(async e=>{let{secretId:t,approvalController:r}=e,o=he(e)?T({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 p=await Promise.all(o.map(async c=>{let l=T({accountIndex:c,derivationPathType:i}).HYPERCORE,d=await t.requestPublicKey({curve:"secp256k1",secretId:r,derivationPath:l});return Uint8Array.from(Buffer.from(d,"hex"))}));return (await deriveAddressesForEvm(p)).map(c=>({[NetworkVMType.HYPERCORE]:c}))},"deriveAddresses");var U,v,B=class B{constructor({environment:t,approvalController:r,runtime:o}){f(this,U,void 0);f(this,v,void 0);let{infoUrl:i,activityInfoUrl:p}=j(t);g(this,U,r),g(this,v,new E({infoUrl:i,activityInfoUrl:p,fetch:o?.fetch}));}getProvider(t){return Promise.reject(new Error(N("getProvider")))}getManifest(){let t=parseManifest(V);return t.success?t.data:void 0}getBalances(t){return oe({...t,infoClient:m(this,v)})}getTransactionHistory(t){return ye({...t,infoClient:m(this,v)})}getNetworkFee(t){return Promise.reject(new Error(N("getNetworkFee")))}getAddress(t){return ge(t)}buildDerivationPath(t){return T(t)}deriveAddress(t){return ve({...t,approvalController:m(this,U)})}deriveAddresses(t){return Pe({...t,approvalController:m(this,U)})}getTokens(t){return ne({network:t,infoClient:m(this,v)})}async onRpcRequest(t,r){return {error:rpcErrors.methodNotSupported(`HyperCore is read-only; method ${t.method} is not supported`)}}};U=new WeakMap,v=new WeakMap,n(B,"HypercoreModule");var Ce=B;
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=_;
10
10
 
11
- export { ze as FILL_ARROW_DOWN, We as FILL_ARROW_UP, Z as HYPERCORE_CAIP_ID, vt as HYPERCORE_CHAIN_ID, F as HYPERCORE_USDC_DECIMALS, Q as HYPERCORE_USDC_NAME, D as HYPERCORE_USDC_SYMBOL, Le as HYPERLIQUID_COIN_SVG_BASE, E as HypercoreInfoClient, Ce as HypercoreModule, $e as LEDGER_LOOKBACK_MS, Ye as MAX_LEDGER_PAGES, te as buildHypercoreTokens, z as clearinghouseStateSchema, Ke as closedPnlTone, ce as encodeHypercoreFillMethod, ie as fetchHypercoreActivity, zt as fillLabel, Kt as formatHypercoreFillPx, ae as getHypercoreLedgerDisplay, Fe as getPerpCollateralUsd, Me as hypercoreLedgerDeltaSchema, Oe as hypercoreLedgerUpdateSchema, X as hypercoreLedgerUpdatesSchema, Be as hyperliquidCoinSvgKey, y as hyperliquidCoinSvgUrl, ue as mapHypercoreActivityToTransactions, Jt as parseHypercoreFillMethod, W as spotClearinghouseStateSchema, Ne as spotCountsAsPerpCollateral, q as spotMetaResponseSchema, pe as tickerOfCoin, M as toHypercoreSpotTokens, R as toTimeMs, K as userAbstractionSchema, De as userFillSchema, J as userFillsSchema };
11
+ export { Q as HYPERCORE_CAIP_ID, Pt as HYPERCORE_CHAIN_ID, L as HYPERCORE_USDC_DECIMALS, ee as HYPERCORE_USDC_NAME, D as HYPERCORE_USDC_SYMBOL, _e as HYPERLIQUID_COIN_SVG_BASE, I as HypercoreInfoClient, Ce as HypercoreModule, ze as LEDGER_LOOKBACK_MS, qe as MAX_LEDGER_PAGES, re as buildHypercoreTokens, W as clearinghouseStateSchema, Je as closedPnlTone, ce as encodeHypercoreFillMethod, ie as fetchHypercoreActivity, Wt as fillLabel, Jt as formatHypercoreFillPx, ae as getHypercoreLedgerDisplay, Be as getPerpCollateralUsd, Ne as hypercoreLedgerDeltaSchema, Oe as hypercoreLedgerUpdateSchema, Z as hypercoreLedgerUpdatesSchema, Ve as hyperliquidCoinSvgKey, f as hyperliquidCoinSvgUrl, ue as mapHypercoreActivityToTransactions, Xt as parseHypercoreFillMethod, K as spotClearinghouseStateSchema, Le as spotCountsAsPerpCollateral, z as spotMetaResponseSchema, pe as tickerOfCoin, M as toHypercoreSpotTokens, R as toTimeMs, J as userAbstractionSchema, Me as userFillSchema, X as userFillsSchema };
12
12
  //# sourceMappingURL=out.js.map
13
13
  //# sourceMappingURL=index.js.map
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/module.ts","../manifest.json","../src/env.ts","../src/utils/schemas.ts","../src/utils/info-client.ts","../src/utils/unsupported.ts","../src/handlers/get-balances/get-balances.ts","../src/utils/build-hypercore-tokens.ts","../src/constants.ts","../src/utils/hyperliquid-coin-svg-url.ts","../src/utils/spot-tokens.ts","../src/handlers/get-tokens/get-tokens.ts","../src/utils/activity/types.ts","../src/utils/activity/fetch-hypercore-activity.ts","../src/utils/activity/map-hypercore-activity-to-transactions.ts","../src/utils/activity/get-hypercore-ledger-display.ts","../src/utils/activity/hypercore-fill-meta.ts","../src/handlers/get-transaction-history/get-transaction-history.ts","../src/handlers/get-address/get-address.ts","../src/handlers/derive-address/derive-address.ts","../../../packages-internal/utils/src/utils/address-derivation.ts","../src/handlers/build-derivation-path/build-derivation-path.ts","../src/handlers/derive-addresses/derive-addresses.ts"],"names":["parseManifest","rpcErrors","manifest_default","Environment","INFO_PATH","PUBLIC_ACTIVITY_INFO_URL","prodEnv","devEnv","getEnv","__name","environment","z","tokenIndexSchema","spotMetaResponseSchema","spotBalanceSchema","spotClearinghouseStateSchema","marginSummarySchema","clearinghouseStateSchema","userAbstractionSchema","value","userFillSchema","userFillsSchema","hypercoreLedgerDeltaSchema","hypercoreLedgerUpdateSchema","hypercoreLedgerUpdatesSchema","lowercaseUser","user","_infoUrl","_activityInfoUrl","_fetch","_HypercoreInfoClient","config","__privateAdd","__privateSet","body","schema","options","response","__privateGet","json","startTime","HypercoreInfoClient","unsupportedHypercoreCapabilityMessage","capability","TokenType","Big","HYPERCORE_CAIP_ID","HYPERCORE_CHAIN_ID","HYPERCORE_USDC_SYMBOL","HYPERCORE_USDC_NAME","HYPERCORE_USDC_DECIMALS","BIG_ZERO","spotCountsAsPerpCollateral","mode","toRawBalance","humanAmount","decimals","getPerpCollateralUsd","perp","accountValue","unrealizedPnl","sum","position","collateral","buildHypercoreTokens","spotBalances","perpState","abstractionMode","spotTokens","tokensByIndex","token","perpCollateralUsd","spotUsdc","balance","usdcTotal","tokens","meta","total","HYPERLIQUID_COIN_SVG_BASE","hyperliquidCoinSvgKey","coin","trimmed","separatorIndex","hyperliquidCoinSvgUrl","isValidEvmAddress","address","toHypercoreSpotTokens","toTokenWithBalance","networkToken","balanceInCurrency","native","spot","getBalances","addresses","network","infoClient","spotMeta","spotState","bySymbol","key","err","acc","curr","getTokens","toTimeMs","time","MAX_LEDGER_PAGES","LEDGER_LOOKBACK_MS","isAbortError","softFail","promise","fallback","fetchLedgerUpdates","client","evmAddress","all","pages","page","last","next","fetchHypercoreActivity","fills","ledgerUpdates","fill","update","b","TransactionType","formatAmount","parsed","toUsd","sign","getHypercoreLedgerDisplay","delta","owner","isOutgoing","METHOD_PREFIX","FILL_ARROW_UP","FILL_ARROW_DOWN","tickerOfCoin","i","closedPnlTone","closedPnl","n","fillLabel","dir","tone","d","formatHypercoreFillPx","px","encodeHypercoreFillMethod","parseHypercoreFillMethod","method","explorerTxLink","hash","base","chainIdForNetwork","mapFillToTransaction","timeMs","isBuy","ticker","mapLedgerToTransaction","display","isIncoming","txType","amount","mapHypercoreActivityToTransactions","items","item","getTransactionHistory","NetworkVMType","WalletType","getAddressFromXPub","getEvmAddressFromPubKey","getAddress","accountIndex","xpub","walletType","pubKeyBuffer","computeAddress","hasDerivationDetails","params","buildDerivationPath","derivationPathType","deriveAddress","secretId","approvalController","derivationPath","publicKeyHex","deriveAddressesForEvm","init","deriveAddresses","accountIndices","publicKeys","_approvalController","_infoClient","_HypercoreModule","runtime","infoUrl","activityInfoUrl","_network","result","request","HypercoreModule"],"mappings":"oaAiBA,OAAS,iBAAAA,OAAqB,2BAC9B,OAAS,aAAAC,OAAiB,uBClB1B,IAAAC,EAAA,CACE,KAAQ,YACR,YAAe,uEACf,QAAW,QACX,QAAW,CACT,OAAU,CACR,SAAY,GACZ,SAAY,CACV,IAAO,CACL,SAAY,gBACZ,YAAe,4BACf,SAAY,4BACd,CACF,CACF,CACF,EACA,QAAW,CACT,SAAY,CAAC,gBAAgB,EAC7B,WAAc,CAAC,QAAQ,CACzB,EACA,SAAY,KACZ,YAAe,CACb,IAAO,CACL,MAAS,GACT,QAAW,CAAC,EACZ,qBAAwB,CAAC,CAC3B,CACF,EACA,gBAAmB,KACrB,EC7BA,OAAS,eAAAC,MAAmB,2BAa5B,IAAMC,EAAY,4BACZC,EAA2B,mCAEpBC,GAAe,CAC1B,YAAa,iCACb,QAAS,iCAAiCF,CA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EA,UAAUnG,EAAkB,CAC1B,OAAOS,GAAU,CAAE,QAAAT,EAAS,WAAYxD,EAAA,KAAK4J,EAAY,CAAC,CAC5D,CAEA,MAAM,aAAaO,EAAqBF,EAAmB,CACzD,MAAO,CACL,MAAOtM,GAAU,mBAAmB,kCAAkCwM,EAAQ,MAAM,mBAAmB,CACzG,CACF,CACF,EAxEER,EAAA,YACAC,EAAA,YAF6CzL,EAAA0L,EAAA,mBAAxC,IAAMO,GAANP","sourcesContent":["import type {\n Module,\n Manifest,\n ConstructorParams,\n ApprovalController,\n RpcRequest,\n Network,\n NetworkFees,\n GetBalancesParams,\n GetAddressParams,\n GetAddressResponse,\n DeriveAddressParams,\n DeriveAddressesParams,\n BuildDerivationPathParams,\n GetTransactionHistory,\n NetworkFeeParam,\n} from '@avalabs/vm-module-types';\nimport { parseManifest } from '@avalabs/vm-module-types';\nimport { rpcErrors } from '@metamask/rpc-errors';\n\nimport ManifestJson from '../manifest.json';\nimport { getEnv } from './env';\nimport { HypercoreInfoClient } from './utils/info-client';\nimport { unsupportedHypercoreCapabilityMessage } from './utils/unsupported';\nimport { getBalances } from './handlers/get-balances/get-balances';\nimport { getTokens } from './handlers/get-tokens/get-tokens';\nimport { getTransactionHistory } from './handlers/get-transaction-history/get-transaction-history';\nimport { getAddress } from './handlers/get-address/get-address';\nimport { deriveAddress } from './handlers/derive-address/derive-address';\nimport { deriveAddresses } from './handlers/derive-addresses/derive-addresses';\nimport { buildDerivationPath } from './handlers/build-derivation-path/build-derivation-path';\n\nexport class HypercoreModule implements Module {\n #approvalController: ApprovalController;\n #infoClient: HypercoreInfoClient;\n\n constructor({ environment, approvalController, runtime }: ConstructorParams) {\n const { infoUrl, activityInfoUrl } = getEnv(environment);\n\n this.#approvalController = approvalController;\n this.#infoClient = new HypercoreInfoClient({\n infoUrl,\n activityInfoUrl,\n fetch: runtime?.fetch,\n });\n }\n\n getProvider(_network: Network): Promise<never> {\n return Promise.reject(new Error(unsupportedHypercoreCapabilityMessage('getProvider')));\n }\n\n getManifest(): Manifest | undefined {\n const result = parseManifest(ManifestJson);\n return result.success ? result.data : undefined;\n }\n\n getBalances(params: GetBalancesParams) {\n return getBalances({\n ...params,\n infoClient: this.#infoClient,\n });\n }\n\n getTransactionHistory(params: GetTransactionHistory) {\n return getTransactionHistory({\n ...params,\n infoClient: this.#infoClient,\n });\n }\n\n getNetworkFee(_network: NetworkFeeParam): Promise<NetworkFees> {\n return Promise.reject(new Error(unsupportedHypercoreCapabilityMessage('getNetworkFee')));\n }\n\n getAddress(params: GetAddressParams): Promise<GetAddressResponse> {\n return getAddress(params);\n }\n\n buildDerivationPath(params: BuildDerivationPathParams) {\n return buildDerivationPath(params);\n }\n\n deriveAddress(params: DeriveAddressParams) {\n return deriveAddress({\n ...params,\n approvalController: this.#approvalController,\n });\n }\n\n deriveAddresses(params: DeriveAddressesParams) {\n return deriveAddresses({\n ...params,\n approvalController: this.#approvalController,\n });\n }\n\n getTokens(network: Network) {\n return getTokens({ network, infoClient: this.#infoClient });\n }\n\n async onRpcRequest(request: RpcRequest, _network: Network) {\n return {\n error: rpcErrors.methodNotSupported(`HyperCore is read-only; method ${request.method} is not supported`),\n };\n }\n}\n","{\n \"name\": \"HyperCore\",\n \"description\": \"Read-only Hyperliquid HyperCore module (balances, tokens, activity).\",\n \"version\": \"0.0.1\",\n \"sources\": {\n \"module\": {\n \"checksum\": \"\",\n \"location\": {\n \"npm\": {\n \"filePath\": \"dist/index.js\",\n \"packageName\": \"@avalabs/hypercore-module\",\n \"registry\": \"https://registry.npmjs.org\"\n }\n }\n }\n },\n \"network\": {\n \"chainIds\": [\"hlcore:mainnet\"],\n \"namespaces\": [\"hlcore\"]\n },\n \"cointype\": \"60\",\n \"permissions\": {\n \"rpc\": {\n \"dapps\": false,\n \"methods\": [],\n \"nonRestrictedMethods\": []\n }\n },\n \"manifestVersion\": \"0.1\"\n}\n","import { Environment } from '@avalabs/vm-module-types';\n\ntype Env = {\n proxyApiUrl: string;\n /** Proxy-first Hyperliquid `/info` endpoint. */\n infoUrl: string;\n /**\n * Fallback for activity endpoints if the proxy does not support fills/ledger.\n * Prefer `infoUrl` when possible.\n */\n activityInfoUrl: string;\n};\n\nconst INFO_PATH = '/proxy/nownodes/hype/info';\nconst PUBLIC_ACTIVITY_INFO_URL = 'https://api.hyperliquid.xyz/info';\n\nexport const prodEnv: Env = {\n proxyApiUrl: 'https://proxy-api.avax.network',\n infoUrl: `https://proxy-api.avax.network${INFO_PATH}`,\n activityInfoUrl: PUBLIC_ACTIVITY_INFO_URL,\n};\n\nexport const devEnv: Env = {\n proxyApiUrl: 'https://proxy-api-dev.avax.network',\n infoUrl: `https://proxy-api-dev.avax.network${INFO_PATH}`,\n activityInfoUrl: PUBLIC_ACTIVITY_INFO_URL,\n};\n\nexport const getEnv = (environment: Environment): Env => {\n switch (environment) {\n case Environment.PRODUCTION:\n return prodEnv;\n case Environment.DEV:\n return devEnv;\n }\n};\n","import { z } from 'zod';\n\nconst tokenIndexSchema = z.coerce.number();\n\n/** `type: \"spotMeta\"` — registry mapping spot token index → display metadata. */\nexport const spotMetaResponseSchema = z.object({\n tokens: z.array(\n z.object({\n name: z.string(),\n index: z.number(),\n weiDecimals: z.number(),\n fullName: z.string().nullish(),\n evmContract: z.object({ address: z.string() }).nullish(),\n }),\n ),\n});\n\nconst spotBalanceSchema = z.object({\n coin: z.string(),\n token: tokenIndexSchema,\n total: z.string(),\n hold: z.string(),\n entryNtl: z.string().optional(),\n});\n\n/** `type: \"spotClearinghouseState\"` */\nexport const spotClearinghouseStateSchema = z.object({\n balances: z.array(spotBalanceSchema),\n});\n\nconst marginSummarySchema = z.object({\n accountValue: z.string(),\n totalMarginUsed: z.string().optional(),\n totalNtlPos: z.string().optional(),\n totalRawUsd: z.string().optional(),\n});\n\n/**\n * `type: \"clearinghouseState\"` — only fields needed for PnL-excluded\n * perp collateral fold-in.\n */\nexport const clearinghouseStateSchema = z.object({\n assetPositions: z.array(\n z.object({\n position: z.object({\n unrealizedPnl: z.string(),\n }),\n }),\n ),\n crossMarginSummary: marginSummarySchema,\n});\n\nexport type UserAbstractionMode = 'unifiedAccount' | 'portfolioMargin' | 'dexAbstraction' | 'disabled' | 'default';\n\n/**\n * `type: \"userAbstraction\"` — bare JSON string. Unknown future values coerce\n * to `\"default\"` so balance math stays conservative.\n */\nexport const userAbstractionSchema = z.string().transform((value): UserAbstractionMode => {\n switch (value) {\n case 'unifiedAccount':\n case 'portfolioMargin':\n case 'dexAbstraction':\n case 'disabled':\n case 'default':\n return value;\n default:\n return 'default';\n }\n});\n\n/** `type: \"userFills\"` */\nexport const userFillSchema = z.object({\n closedPnl: z.string(),\n coin: z.string(),\n crossed: z.boolean(),\n dir: z.string(),\n hash: z.string(),\n oid: z.number(),\n px: z.string(),\n side: z.string(),\n startPosition: z.string(),\n sz: z.string(),\n time: z.number(),\n fee: z.string().optional(),\n tid: z.number().optional(),\n});\n\nexport const userFillsSchema = z.array(userFillSchema);\n\n/**\n * `userNonFundingLedgerUpdates` deltas — permissive so unknown delta types\n * still parse and can render generically later.\n */\nexport const hypercoreLedgerDeltaSchema = z.object({\n type: z.string(),\n usdc: z.string().optional(),\n amount: z.string().optional(),\n usdcValue: z.string().optional(),\n token: z.string().optional(),\n user: z.string().optional(),\n destination: z.string().optional(),\n fee: z.string().optional(),\n toPerp: z.boolean().optional(),\n});\n\nexport const hypercoreLedgerUpdateSchema = z.object({\n time: z.number(),\n hash: z.string(),\n delta: hypercoreLedgerDeltaSchema,\n});\n\nexport const hypercoreLedgerUpdatesSchema = z.array(hypercoreLedgerUpdateSchema);\n\nexport type SpotMetaResponse = z.infer<typeof spotMetaResponseSchema>;\nexport type SpotBalance = {\n coin: string;\n token: number;\n total: string;\n hold: string;\n entryNtl?: string;\n};\nexport type SpotClearinghouseState = {\n balances: SpotBalance[];\n};\nexport type ClearinghouseState = z.infer<typeof clearinghouseStateSchema>;\nexport type UserFill = z.infer<typeof userFillSchema>;\nexport type HypercoreLedgerUpdate = z.infer<typeof hypercoreLedgerUpdateSchema>;\n","import type { z } from 'zod';\nimport {\n clearinghouseStateSchema,\n hypercoreLedgerUpdatesSchema,\n spotClearinghouseStateSchema,\n spotMetaResponseSchema,\n userAbstractionSchema,\n userFillsSchema,\n type ClearinghouseState,\n type HypercoreLedgerUpdate,\n type SpotClearinghouseState,\n type SpotMetaResponse,\n type UserAbstractionMode,\n type UserFill,\n} from './schemas';\n\nexport type HypercoreInfoRequest =\n | { type: 'spotMeta' }\n | { type: 'spotClearinghouseState'; user: string; dex?: string }\n | { type: 'clearinghouseState'; user: string; dex?: string }\n | { type: 'userAbstraction'; user: string }\n | { type: 'userFills'; user: string }\n | {\n type: 'userNonFundingLedgerUpdates';\n user: string;\n startTime: number;\n };\n\nexport type HypercoreInfoClientConfig = {\n /** Proxy-first `/info` URL used for balances and spot meta. */\n infoUrl: string;\n /**\n * Activity URL. Defaults to `infoUrl`; may be the public HL endpoint when\n * the proxy does not yet support fills/ledger types.\n */\n activityInfoUrl?: string;\n fetch?: typeof globalThis.fetch;\n};\n\nexport type PostInfoOptions = {\n signal?: AbortSignal;\n /** Overrides the client default URL for this call. */\n url?: string;\n};\n\nconst lowercaseUser = (user: string) => user.toLowerCase();\n\nexport class HypercoreInfoClient {\n readonly #infoUrl: string;\n readonly #activityInfoUrl: string;\n readonly #fetch: typeof globalThis.fetch;\n\n constructor(config: HypercoreInfoClientConfig) {\n this.#infoUrl = config.infoUrl;\n this.#activityInfoUrl = config.activityInfoUrl ?? config.infoUrl;\n this.#fetch = config.fetch ?? globalThis.fetch.bind(globalThis);\n }\n\n async postInfo<T>(body: HypercoreInfoRequest, schema: z.ZodType<T>, options?: PostInfoOptions) {\n const response = await this.#fetch(options?.url ?? this.#infoUrl, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify(body),\n signal: options?.signal,\n });\n\n if (!response.ok) {\n throw new Error(`Hyperliquid /info failed: ${response.status} ${response.statusText}`);\n }\n\n const json: unknown = await response.json();\n return schema.parse(json);\n }\n\n getSpotMeta(options?: PostInfoOptions): Promise<SpotMetaResponse> {\n return this.postInfo({ type: 'spotMeta' }, spotMetaResponseSchema, options);\n }\n\n getSpotClearinghouseState(user: string, options?: PostInfoOptions): Promise<SpotClearinghouseState> {\n return this.postInfo(\n {\n type: 'spotClearinghouseState',\n user: lowercaseUser(user),\n dex: '',\n },\n spotClearinghouseStateSchema,\n options,\n ) as Promise<SpotClearinghouseState>;\n }\n\n getClearinghouseState(user: string, options?: PostInfoOptions): Promise<ClearinghouseState> {\n return this.postInfo(\n {\n type: 'clearinghouseState',\n user: lowercaseUser(user),\n dex: '',\n },\n clearinghouseStateSchema,\n options,\n );\n }\n\n getUserAbstraction(user: string, options?: PostInfoOptions): Promise<UserAbstractionMode> {\n return this.postInfo(\n { type: 'userAbstraction', user: lowercaseUser(user) },\n userAbstractionSchema,\n options,\n ) as Promise<UserAbstractionMode>;\n }\n\n getUserFills(user: string, options?: PostInfoOptions): Promise<UserFill[]> {\n return this.postInfo({ type: 'userFills', user: lowercaseUser(user) }, userFillsSchema, {\n ...options,\n url: options?.url ?? this.#activityInfoUrl,\n });\n }\n\n getUserNonFundingLedgerUpdates(\n user: string,\n startTime: number,\n options?: PostInfoOptions,\n ): Promise<HypercoreLedgerUpdate[]> {\n return this.postInfo(\n {\n type: 'userNonFundingLedgerUpdates',\n user: lowercaseUser(user),\n startTime,\n },\n hypercoreLedgerUpdatesSchema,\n {\n ...options,\n url: options?.url ?? this.#activityInfoUrl,\n },\n );\n }\n}\n","/**\n * Loud failure message for HyperCore capabilities that do not exist (no RPC, no gas).\n * Prefer rejecting with this over empty success so clients and agents see intentional gaps.\n */\nexport const unsupportedHypercoreCapabilityMessage = (capability: string) =>\n `HyperCore does not support ${capability}: read-only module (balances, tokens, activity).`;\n\nexport const unsupportedHypercoreCapability = (capability: string): never => {\n throw new Error(unsupportedHypercoreCapabilityMessage(capability));\n};\n","import {\n TokenType,\n type GetBalancesParams,\n type GetBalancesResponse,\n type NetworkTokenWithBalance,\n type TokenWithBalance,\n type TokenWithBalanceHypercoreSpot,\n} from '@avalabs/vm-module-types';\nimport type { HypercoreInfoClient } from '../../utils/info-client';\nimport { buildHypercoreTokens, type HypercoreTokenBalance } from '../../utils/build-hypercore-tokens';\nimport { hyperliquidCoinSvgUrl } from '../../utils/hyperliquid-coin-svg-url';\nimport { toHypercoreSpotTokens } from '../../utils/spot-tokens';\n\ntype GetHypercoreBalancesParams = Omit<GetBalancesParams, 'currency' | 'customTokens' | 'tokenTypes'> & {\n infoClient: HypercoreInfoClient;\n};\n\nconst toTokenWithBalance = (\n token: HypercoreTokenBalance,\n networkToken: GetBalancesParams['network']['networkToken'],\n): { key: string; value: TokenWithBalance } => {\n if (token.kind === 'native') {\n const balance = BigInt(token.balanceRaw);\n const balanceInCurrency = Number(token.balanceUsd);\n const native: NetworkTokenWithBalance = {\n ...networkToken,\n name: token.name,\n symbol: token.symbol,\n decimals: token.decimals,\n logoUri: networkToken.logoUri ?? hyperliquidCoinSvgUrl(token.symbol),\n coingeckoId: 'usd-coin',\n type: TokenType.NATIVE,\n balance,\n balanceDisplayValue: token.balance,\n balanceInCurrency: Number.isFinite(balanceInCurrency) ? balanceInCurrency : 0,\n balanceCurrencyDisplayValue: token.balanceUsd,\n priceInCurrency: token.priceUsd,\n };\n return { key: token.symbol, value: native };\n }\n\n const balance = BigInt(token.balanceRaw);\n const spot: TokenWithBalanceHypercoreSpot = {\n type: TokenType.HYPERCORE_SPOT,\n name: token.name,\n symbol: token.symbol,\n decimals: token.decimals,\n index: token.index,\n evmContract: token.evmContract,\n logoUri: hyperliquidCoinSvgUrl(token.symbol),\n reputation: null,\n balance,\n balanceDisplayValue: token.balance,\n };\n return { key: `spot:${token.index}`, value: spot };\n};\n\nexport const getBalances = async ({\n addresses,\n network,\n infoClient,\n}: GetHypercoreBalancesParams): Promise<GetBalancesResponse> => {\n const spotMeta = await infoClient.getSpotMeta();\n const spotTokens = toHypercoreSpotTokens(spotMeta.tokens);\n\n const results = await Promise.allSettled(\n addresses.map(async (address) => {\n try {\n const [spotState, perpState, abstractionMode] = await Promise.all([\n infoClient.getSpotClearinghouseState(address),\n infoClient.getClearinghouseState(address).catch(() => undefined),\n infoClient.getUserAbstraction(address).catch(() => undefined),\n ]);\n\n const tokens = buildHypercoreTokens({\n spotBalances: spotState.balances,\n perpState,\n abstractionMode,\n spotTokens,\n });\n\n const bySymbol = Object.fromEntries(\n tokens.map((token) => {\n const { key, value } = toTokenWithBalance(token, network.networkToken);\n return [key, value];\n }),\n );\n\n return { [address]: bySymbol };\n } catch (err) {\n return { [address]: { error: (err as Error).toString() } };\n }\n }),\n );\n\n return results.reduce((acc, curr) => {\n if (curr.status === 'fulfilled') {\n return { ...acc, ...curr.value };\n }\n return acc;\n }, {} as GetBalancesResponse);\n};\n","import Big from 'big.js';\nimport type { HypercoreSpotToken } from '@avalabs/vm-module-types';\nimport { HYPERCORE_USDC_DECIMALS, HYPERCORE_USDC_NAME, HYPERCORE_USDC_SYMBOL } from '../constants';\nimport type { ClearinghouseState, SpotBalance, UserAbstractionMode } from './schemas';\n\nconst BIG_ZERO = new Big(0);\n\nexport type HypercoreNativeTokenBalance = {\n kind: 'native';\n name: string;\n symbol: typeof HYPERCORE_USDC_SYMBOL;\n decimals: number;\n /** Human-readable amount (decimal string). */\n balance: string;\n /** Integer raw amount as a decimal string (no fractional part). */\n balanceRaw: string;\n priceUsd: 1;\n balanceUsd: string;\n};\n\nexport type HypercoreSpotTokenBalance = {\n kind: 'spot';\n name: string;\n symbol: string;\n decimals: number;\n balance: string;\n balanceRaw: string;\n index: number;\n evmContract?: string;\n};\n\nexport type HypercoreTokenBalance = HypercoreNativeTokenBalance | HypercoreSpotTokenBalance;\n\n/**\n * `true` when spot balances already back perps for this account mode\n * (`unifiedAccount`). Other modes keep perp collateral on a separate ledger.\n */\nexport const spotCountsAsPerpCollateral = (mode: UserAbstractionMode | undefined) => mode === 'unifiedAccount';\n\n/** Tokens carry no native gas balance on HyperCore — amounts are human decimals. */\nconst toRawBalance = (humanAmount: Big, decimals: number) =>\n humanAmount.times(new Big(10).pow(decimals)).round(0, Big.roundDown).toFixed(0);\n\n/**\n * Perp collateral in USDC, excluding unrealized PnL.\n * `crossMarginSummary.accountValue` is collateral ± PnL; we back PnL out.\n */\nexport const getPerpCollateralUsd = (perp: ClearinghouseState | undefined) => {\n if (!perp) {\n return BIG_ZERO;\n }\n\n const accountValue = new Big(perp.crossMarginSummary.accountValue ?? '0');\n const unrealizedPnl = perp.assetPositions.reduce((sum, { position }) => sum.plus(position.unrealizedPnl), BIG_ZERO);\n const collateral = accountValue.minus(unrealizedPnl);\n\n return collateral.gt(BIG_ZERO) ? collateral : BIG_ZERO;\n};\n\n/**\n * USDC merges spot + (non-unified) PnL-excluded perp collateral at $1.\n * Other spot inventory is `HYPERCORE_SPOT` (no synthetic ERC20 addresses).\n */\nexport const buildHypercoreTokens = ({\n spotBalances,\n perpState,\n abstractionMode,\n spotTokens,\n}: {\n spotBalances: readonly SpotBalance[];\n perpState: ClearinghouseState | undefined;\n abstractionMode: UserAbstractionMode | undefined;\n spotTokens: HypercoreSpotToken[];\n}): HypercoreTokenBalance[] => {\n const tokensByIndex = new Map(spotTokens.map((token) => [token.index, token]));\n\n const perpCollateralUsd = spotCountsAsPerpCollateral(abstractionMode) ? BIG_ZERO : getPerpCollateralUsd(perpState);\n\n const spotUsdc = spotBalances.find((balance) => balance.coin.toUpperCase() === HYPERCORE_USDC_SYMBOL);\n const usdcTotal = new Big(spotUsdc?.total ?? '0').plus(perpCollateralUsd);\n\n const tokens: HypercoreTokenBalance[] = [];\n\n if (usdcTotal.gt(BIG_ZERO)) {\n tokens.push({\n kind: 'native',\n name: HYPERCORE_USDC_NAME,\n symbol: HYPERCORE_USDC_SYMBOL,\n decimals: HYPERCORE_USDC_DECIMALS,\n balance: usdcTotal.toString(),\n balanceRaw: toRawBalance(usdcTotal, HYPERCORE_USDC_DECIMALS),\n priceUsd: 1,\n balanceUsd: usdcTotal.toString(),\n });\n }\n\n for (const balance of spotBalances) {\n if (balance.coin.toUpperCase() === HYPERCORE_USDC_SYMBOL) {\n continue;\n }\n\n const meta = tokensByIndex.get(balance.token);\n const total = new Big(balance.total);\n if (!meta || !total.gt(BIG_ZERO)) {\n continue;\n }\n\n tokens.push({\n kind: 'spot',\n name: meta.name,\n symbol: meta.symbol,\n decimals: meta.decimals,\n balance: total.toString(),\n balanceRaw: toRawBalance(total, meta.decimals),\n index: meta.index,\n evmContract: meta.evmContract,\n });\n }\n\n return tokens;\n};\n","/** CAIP-2 id for HyperCore mainnet. Namespace must be 3–8 chars (CAIP-2). */\nexport const HYPERCORE_CAIP_ID = 'hlcore:mainnet';\n\n/**\n * Synthetic numeric id used by Core network lists / storage keys.\n * Not an EVM chain id — module routing uses {@link HYPERCORE_CAIP_ID}.\n */\nexport const HYPERCORE_CHAIN_ID = 9999;\n\nexport const HYPERCORE_USDC_SYMBOL = 'USDC';\nexport const HYPERCORE_USDC_NAME = 'USD Coin';\nexport const HYPERCORE_USDC_DECIMALS = 8;\n","export const HYPERLIQUID_COIN_SVG_BASE = 'https://app.hyperliquid.xyz/coins';\n\nexport const hyperliquidCoinSvgKey = (coin: string) => {\n const trimmed = coin.trim();\n const separatorIndex = trimmed.indexOf(':');\n if (separatorIndex === -1) {\n return trimmed.toUpperCase();\n }\n // HIP-3 logos are keyed as `marketname:TICKER` (dex prefix is case-significant).\n return `${trimmed.slice(0, separatorIndex)}:${trimmed.slice(separatorIndex + 1).toUpperCase()}`;\n};\n\nexport const hyperliquidCoinSvgUrl = (coin: string) =>\n `${HYPERLIQUID_COIN_SVG_BASE}/${encodeURIComponent(hyperliquidCoinSvgKey(coin))}.svg`;\n","import { TokenType, type HypercoreSpotToken } from '@avalabs/vm-module-types';\nimport type { SpotMetaResponse } from './schemas';\n\nconst isValidEvmAddress = (address: string) => /^0x[a-fA-F0-9]{40}$/.test(address);\n\n/**\n * Maps `spotMeta` tokens to the registry used when resolving spot balances.\n * Keeps every spot token (including HyperCore-only ones without an EVM contract).\n */\nexport const toHypercoreSpotTokens = (tokens: SpotMetaResponse['tokens']): HypercoreSpotToken[] =>\n tokens.map((token) => {\n const address = token.evmContract?.address.toLowerCase();\n\n return {\n type: TokenType.HYPERCORE_SPOT,\n index: token.index,\n name: token.fullName ?? token.name,\n symbol: token.name,\n decimals: token.weiDecimals,\n evmContract: address && isValidEvmAddress(address) ? address : undefined,\n };\n });\n","import type { HypercoreSpotToken, Network } from '@avalabs/vm-module-types';\nimport type { HypercoreInfoClient } from '../../utils/info-client';\nimport { hyperliquidCoinSvgUrl } from '../../utils/hyperliquid-coin-svg-url';\nimport { toHypercoreSpotTokens } from '../../utils/spot-tokens';\n\nexport const getTokens = async ({\n infoClient,\n}: {\n network: Network;\n infoClient: HypercoreInfoClient;\n}): Promise<HypercoreSpotToken[]> => {\n const spotMeta = await infoClient.getSpotMeta();\n return toHypercoreSpotTokens(spotMeta.tokens).map((token) => ({\n ...token,\n logoUri: token.logoUri ?? hyperliquidCoinSvgUrl(token.symbol),\n }));\n};\n","import type { HypercoreLedgerUpdate, UserFill } from '../schemas';\n\nexport type HypercoreActivityItem =\n | {\n readonly kind: 'fill';\n readonly timeMs: number;\n readonly hash: string;\n readonly fill: UserFill;\n }\n | {\n readonly kind: 'ledger';\n readonly timeMs: number;\n readonly hash: string;\n readonly update: HypercoreLedgerUpdate;\n };\n\n/** Normalize a Unix timestamp to milliseconds. */\nexport const toTimeMs = (time: number) => (time < 10_000_000_000 ? time * 1000 : time);\n","import type { HypercoreInfoClient } from '../info-client';\nimport type { HypercoreLedgerUpdate } from '../schemas';\nimport type { HypercoreActivityItem } from './types';\nimport { toTimeMs } from './types';\n\n/** Bound ledger pagination so busy accounts cannot trigger unbounded requests. */\nexport const MAX_LEDGER_PAGES = 20;\n\n/** Prefer recent ledger history; paging from `0` would return the oldest pages first. */\nexport const LEDGER_LOOKBACK_MS = 365 * 24 * 60 * 60 * 1000;\n\ntype FetchHypercoreActivityOptions = {\n signal?: AbortSignal;\n};\n\nconst isAbortError = (err: unknown) =>\n (err instanceof DOMException && err.name === 'AbortError') || (err instanceof Error && err.name === 'AbortError');\n\nconst softFail = async <T>(promise: Promise<T>, fallback: T): Promise<T> => {\n try {\n return await promise;\n } catch (err) {\n if (isAbortError(err)) {\n throw err;\n }\n return fallback;\n }\n};\n\n/**\n * `userNonFundingLedgerUpdates` returns an ascending, capped page (~500) from\n * `startTime`. Start within a lookback window and page forward until empty,\n * aborted, or `MAX_LEDGER_PAGES`, so recent activity is included without an\n * unbounded crawl from epoch.\n */\nconst fetchLedgerUpdates = async (\n client: HypercoreInfoClient,\n evmAddress: string,\n options?: FetchHypercoreActivityOptions,\n) => {\n const all: HypercoreLedgerUpdate[] = [];\n let startTime = Date.now() - LEDGER_LOOKBACK_MS;\n let pages = 0;\n\n while (pages < MAX_LEDGER_PAGES) {\n if (options?.signal?.aborted) {\n throw new DOMException('The operation was aborted.', 'AbortError');\n }\n\n const page = await client.getUserNonFundingLedgerUpdates(evmAddress, startTime, options);\n pages += 1;\n if (page.length === 0) {\n break;\n }\n all.push(...page);\n const last = page[page.length - 1];\n if (!last) {\n break;\n }\n const next = last.time + 1;\n if (next <= startTime) {\n break;\n }\n startTime = next;\n }\n\n return all;\n};\n\n/**\n * Fetches HyperCore fills + non-funding ledger updates and sorts newest-first.\n * Soft-fails individual endpoints so a flaky fills or ledger call still yields\n * partial history (abort errors are rethrown).\n */\nexport const fetchHypercoreActivity = async (\n client: HypercoreInfoClient,\n evmAddress: string,\n options?: FetchHypercoreActivityOptions,\n): Promise<HypercoreActivityItem[]> => {\n const [fills, ledgerUpdates] = await Promise.all([\n softFail(client.getUserFills(evmAddress, options), []),\n softFail(fetchLedgerUpdates(client, evmAddress, options), []),\n ]);\n\n const items: HypercoreActivityItem[] = [\n ...fills.map((fill) => ({\n kind: 'fill' as const,\n timeMs: toTimeMs(fill.time),\n hash: fill.hash,\n fill,\n })),\n ...ledgerUpdates.map((update) => ({\n kind: 'ledger' as const,\n timeMs: toTimeMs(update.time),\n hash: update.hash,\n update,\n })),\n ];\n\n return items.sort((a, b) => b.timeMs - a.timeMs);\n};\n","import { TokenType, TransactionType, type Network, type Transaction, type TxToken } from '@avalabs/vm-module-types';\nimport { HYPERCORE_CAIP_ID } from '../../constants';\nimport { hyperliquidCoinSvgUrl } from '../hyperliquid-coin-svg-url';\nimport type { HypercoreLedgerUpdate, UserFill } from '../schemas';\nimport { getHypercoreLedgerDisplay } from './get-hypercore-ledger-display';\nimport { encodeHypercoreFillMethod, tickerOfCoin } from './hypercore-fill-meta';\nimport type { HypercoreActivityItem } from './types';\nimport { toTimeMs } from './types';\n\nconst explorerTxLink = (network: Pick<Network, 'explorerUrl'>, hash: string) => {\n const base = (network.explorerUrl ?? '').replace(/\\/$/, '');\n return base ? `${base}/tx/${hash}` : hash;\n};\n\nconst chainIdForNetwork = (network: Pick<Network, 'caipId' | 'chainId'>) => network.caipId ?? HYPERCORE_CAIP_ID;\n\nconst mapFillToTransaction = (\n fill: UserFill,\n timeMs: number,\n network: Pick<Network, 'explorerUrl' | 'caipId' | 'chainId'>,\n): Transaction => {\n const isBuy = fill.side === 'B';\n const ticker = tickerOfCoin(fill.coin);\n\n const token: TxToken = {\n type: TokenType.NATIVE,\n name: fill.coin,\n symbol: ticker,\n amount: fill.sz,\n imageUri: hyperliquidCoinSvgUrl(fill.coin),\n };\n\n return {\n isContractCall: false,\n isIncoming: isBuy,\n isOutgoing: !isBuy,\n isSender: !isBuy,\n timestamp: timeMs,\n hash: fill.hash,\n from: '',\n to: '',\n tokens: [token],\n gasUsed: '0',\n txType: TransactionType.FILL_ORDER,\n method: encodeHypercoreFillMethod({\n dir: fill.dir ?? '',\n px: fill.px,\n closedPnl: fill.closedPnl,\n coin: fill.coin,\n }),\n chainId: chainIdForNetwork(network),\n explorerLink: explorerTxLink(network, fill.hash),\n };\n};\n\nconst mapLedgerToTransaction = (\n update: HypercoreLedgerUpdate,\n evmAddress: string,\n network: Pick<Network, 'explorerUrl' | 'caipId' | 'chainId'>,\n): Transaction => {\n const display = getHypercoreLedgerDisplay(update, evmAddress);\n const isIncoming = display.direction === 'positive';\n const isOutgoing = display.direction === 'negative';\n\n let txType: TransactionType = TransactionType.TRANSFER;\n switch (display.label) {\n case 'deposit':\n case 'received':\n txType = TransactionType.RECEIVE;\n break;\n case 'withdraw':\n case 'sent':\n txType = TransactionType.SEND;\n break;\n case 'liquidation':\n txType = TransactionType.UNKNOWN;\n break;\n default:\n txType = TransactionType.TRANSFER;\n }\n\n const amount = display.amount || '0';\n const token: TxToken = {\n type: TokenType.NATIVE,\n name: display.symbol,\n symbol: display.symbol,\n amount,\n imageUri: hyperliquidCoinSvgUrl(display.symbol),\n };\n\n return {\n isContractCall: false,\n isIncoming,\n isOutgoing,\n isSender: isOutgoing,\n timestamp: toTimeMs(update.time),\n hash: update.hash,\n from: display.from ?? (isOutgoing ? evmAddress : ''),\n to: display.to ?? (isIncoming ? evmAddress : ''),\n tokens: [token],\n gasUsed: '0',\n txType,\n chainId: chainIdForNetwork(network),\n explorerLink: explorerTxLink(network, update.hash),\n };\n};\n\nexport const mapHypercoreActivityToTransactions = (\n items: readonly HypercoreActivityItem[],\n evmAddress: string,\n network: Pick<Network, 'explorerUrl' | 'caipId' | 'chainId'>,\n): Transaction[] =>\n items.map((item) =>\n item.kind === 'fill'\n ? mapFillToTransaction(item.fill, item.timeMs, network)\n : mapLedgerToTransaction(item.update, evmAddress, network),\n );\n","import type { HypercoreLedgerUpdate } from '../schemas';\n\n/**\n * Semantic label key for a ledger row.\n */\nexport type HypercoreLedgerLabel =\n | 'deposit'\n | 'withdraw'\n | 'sent'\n | 'received'\n | 'transferToPerp'\n | 'transferToSpot'\n | 'transfer'\n | 'liquidation'\n | 'other';\n\nexport type HypercoreLedgerDisplay = {\n readonly label: HypercoreLedgerLabel;\n /** Unsigned token amount, e.g. `0.1`. */\n readonly amount: string;\n readonly symbol: string;\n /** Signed USD value for the fiat line; undefined when there's nothing to show. */\n readonly usdValue?: number;\n readonly direction: 'positive' | 'negative' | 'neutral';\n readonly from?: string;\n readonly to?: string;\n readonly rawType: string;\n};\n\nconst formatAmount = (value: string | undefined) => {\n if (value === undefined || value === '') {\n return '';\n }\n const parsed = Number.parseFloat(value);\n if (!Number.isFinite(parsed)) {\n return value;\n }\n return new Intl.NumberFormat('en-US', { maximumFractionDigits: 6 }).format(parsed);\n};\n\nconst toUsd = (value: string | undefined, sign: 1 | -1 | 0) => {\n if (value === undefined || value === '') {\n return undefined;\n }\n const parsed = Number.parseFloat(value);\n return Number.isFinite(parsed) ? parsed * (sign === 0 ? 1 : sign) : undefined;\n};\n\n/**\n * Derives label, amount, signed USD value, and counterparties for a HyperCore\n * ledger update from the owner's perspective.\n */\nexport const getHypercoreLedgerDisplay = (\n update: HypercoreLedgerUpdate,\n evmAddress: string,\n): HypercoreLedgerDisplay => {\n const { delta } = update;\n const owner = evmAddress.toLowerCase();\n const isOutgoing = delta.user?.toLowerCase() === owner;\n\n switch (delta.type) {\n case 'deposit':\n return {\n label: 'deposit',\n amount: formatAmount(delta.usdc),\n symbol: 'USDC',\n usdValue: toUsd(delta.usdc, 1),\n direction: 'positive',\n to: evmAddress,\n rawType: delta.type,\n };\n case 'withdraw':\n return {\n label: 'withdraw',\n amount: formatAmount(delta.usdc),\n symbol: 'USDC',\n usdValue: toUsd(delta.usdc, -1),\n direction: 'negative',\n from: evmAddress,\n rawType: delta.type,\n };\n case 'send':\n case 'spotTransfer':\n return {\n label: isOutgoing ? 'sent' : 'received',\n amount: formatAmount(delta.amount),\n symbol: delta.token ?? 'USDC',\n usdValue: toUsd(delta.usdcValue, isOutgoing ? -1 : 1),\n direction: isOutgoing ? 'negative' : 'positive',\n from: delta.user,\n to: delta.destination,\n rawType: delta.type,\n };\n case 'internalTransfer':\n return {\n label: 'transfer',\n amount: formatAmount(delta.usdc),\n symbol: 'USDC',\n usdValue: toUsd(delta.usdc, isOutgoing ? -1 : 1),\n direction: isOutgoing ? 'negative' : 'positive',\n from: delta.user,\n to: delta.destination,\n rawType: delta.type,\n };\n case 'accountClassTransfer':\n return {\n label: delta.toPerp ? 'transferToPerp' : 'transferToSpot',\n amount: formatAmount(delta.usdc),\n symbol: 'USDC',\n usdValue: toUsd(delta.usdc, 0),\n direction: 'neutral',\n rawType: delta.type,\n };\n case 'liquidation':\n return {\n label: 'liquidation',\n amount: formatAmount(delta.usdcValue ?? delta.usdc),\n symbol: 'USDC',\n usdValue: toUsd(delta.usdcValue ?? delta.usdc, -1),\n direction: 'negative',\n rawType: delta.type,\n };\n default:\n return {\n label: 'other',\n amount: formatAmount(delta.usdcValue ?? delta.usdc),\n symbol: 'USDC',\n usdValue: toUsd(delta.usdcValue ?? delta.usdc, 0),\n direction: 'neutral',\n rawType: delta.type,\n };\n }\n};\n","const METHOD_PREFIX = 'hypercoreFill:v1:';\n\nexport const FILL_ARROW_UP = '\\u25B2';\nexport const FILL_ARROW_DOWN = '\\u25BC';\n\nexport type HypercoreFillMeta = {\n readonly dir: string;\n readonly px: string;\n readonly closedPnl: string;\n readonly coin: string;\n};\n\nexport type FillLabel = {\n readonly text: string;\n readonly arrow?: typeof FILL_ARROW_UP | typeof FILL_ARROW_DOWN;\n readonly tone?: 'profit' | 'loss';\n};\n\n/** Display ticker with any `dex:` prefix stripped (`xyz:GOLD` → `GOLD`). */\nexport const tickerOfCoin = (coin: string) => {\n const i = coin.indexOf(':');\n return i === -1 ? coin : coin.slice(i + 1);\n};\n\n/** PnL tone from `closedPnl` — `dir` alone does not indicate profit vs loss. */\nexport const closedPnlTone = (closedPnl: string | undefined): 'profit' | 'loss' | undefined => {\n if (closedPnl === undefined) {\n return undefined;\n }\n const n = Number.parseFloat(closedPnl);\n if (!Number.isFinite(n) || n === 0) {\n return undefined;\n }\n return n > 0 ? 'profit' : 'loss';\n};\n\n/**\n * Map a fill's `dir` into a display label. Arrow direction follows side\n * (long ▲ / short ▼); success/error tone comes from `closedPnl` when provided.\n */\nexport const fillLabel = (dir: string, closedPnl?: string): FillLabel => {\n const tone = closedPnlTone(closedPnl);\n const d = dir.toLowerCase();\n if (d.includes('close') && d.includes('long')) {\n return { text: 'Long closed', arrow: FILL_ARROW_UP, tone };\n }\n if (d.includes('close') && d.includes('short')) {\n return { text: 'Short closed', arrow: FILL_ARROW_DOWN, tone };\n }\n if (d.includes('open') && (d.includes('long') || d.includes('short'))) {\n return { text: 'Order opened' };\n }\n if (d.includes('cancel')) {\n return { text: 'Order cancelled' };\n }\n return { text: dir };\n};\n\n/** Compact USD price for fill rows (`$1,684.7`). */\nexport const formatHypercoreFillPx = (px: string) => {\n const n = Number.parseFloat(px);\n if (!Number.isFinite(n)) {\n return px;\n }\n return `$${n.toLocaleString(undefined, { maximumFractionDigits: 8 })}`;\n};\n\nexport const encodeHypercoreFillMethod = (meta: HypercoreFillMeta) =>\n `${METHOD_PREFIX}${encodeURIComponent(JSON.stringify(meta))}`;\n\nexport const parseHypercoreFillMethod = (method: string | undefined): HypercoreFillMeta | undefined => {\n if (!method?.startsWith(METHOD_PREFIX)) {\n return undefined;\n }\n try {\n const parsed: unknown = JSON.parse(decodeURIComponent(method.slice(METHOD_PREFIX.length)));\n if (\n typeof parsed !== 'object' ||\n parsed === null ||\n !('dir' in parsed) ||\n !('px' in parsed) ||\n !('closedPnl' in parsed) ||\n !('coin' in parsed)\n ) {\n return undefined;\n }\n const { dir, px, closedPnl, coin } = parsed as Record<string, unknown>;\n if (\n typeof dir !== 'string' ||\n typeof px !== 'string' ||\n typeof closedPnl !== 'string' ||\n typeof coin !== 'string'\n ) {\n return undefined;\n }\n return { dir, px, closedPnl, coin };\n } catch {\n return undefined;\n }\n};\n","import type { GetTransactionHistory, TransactionHistoryResponse } from '@avalabs/vm-module-types';\nimport type { HypercoreInfoClient } from '../../utils/info-client';\nimport { fetchHypercoreActivity } from '../../utils/activity/fetch-hypercore-activity';\nimport { mapHypercoreActivityToTransactions } from '../../utils/activity/map-hypercore-activity-to-transactions';\n\nexport const getTransactionHistory = async ({\n address,\n network,\n infoClient,\n}: GetTransactionHistory & {\n infoClient: HypercoreInfoClient;\n}): Promise<TransactionHistoryResponse> => {\n const items = await fetchHypercoreActivity(infoClient, address);\n return {\n transactions: mapHypercoreActivityToTransactions(items, address, network),\n };\n};\n","import { NetworkVMType, WalletType, type GetAddressParams, type GetAddressResponse } from '@avalabs/vm-module-types';\nimport { getAddressFromXPub, getEvmAddressFromPubKey } from '@avalabs/core-wallets-sdk';\nimport { rpcErrors } from '@metamask/rpc-errors';\n\ntype GetAddress = Omit<GetAddressParams, 'isTestnet' | 'xpubXP' | 'network'>;\n\nexport const getAddress = async ({ accountIndex, xpub, walletType }: GetAddress): Promise<GetAddressResponse> => {\n switch (walletType) {\n case WalletType.Mnemonic:\n case WalletType.Ledger:\n case WalletType.Keystone: {\n return {\n [NetworkVMType.HYPERCORE]: getAddressFromXPub(xpub, accountIndex),\n };\n }\n case WalletType.LedgerLive:\n case WalletType.Seedless: {\n const pubKeyBuffer = Buffer.from(xpub, 'hex');\n return {\n [NetworkVMType.HYPERCORE]: getEvmAddressFromPubKey(pubKeyBuffer),\n };\n }\n default:\n throw rpcErrors.invalidParams(`Unsupported wallet type: ${walletType}`);\n }\n};\n","import {\n NetworkVMType,\n type ApprovalController,\n type DeriveAddressParams,\n type DeriveAddressResponse,\n} from '@avalabs/vm-module-types';\nimport { computeAddress } from 'ethers';\nimport { hasDerivationDetails } from '@internal/utils/src/utils/address-derivation';\nimport { buildDerivationPath } from '../build-derivation-path/build-derivation-path';\n\nexport const deriveAddress = async (\n params: DeriveAddressParams & { approvalController: ApprovalController },\n): Promise<DeriveAddressResponse> => {\n const { secretId, approvalController } = params;\n\n // Narrow before calling buildDerivationPath — the type guard alone is not\n // enough when `params` is intersected with `{ approvalController }`.\n const derivationPath = hasDerivationDetails(params)\n ? buildDerivationPath({\n accountIndex: params.accountIndex,\n derivationPathType: params.derivationPathType,\n addressIndex: params.addressIndex,\n }).HYPERCORE\n : undefined;\n const publicKeyHex = await approvalController.requestPublicKey({\n curve: 'secp256k1',\n secretId,\n derivationPath,\n });\n\n return {\n [NetworkVMType.HYPERCORE]: computeAddress(`0x${publicKeyHex}`),\n };\n};\n","import type { DeriveAddressParams, DetailedDeriveAddressParams } from '@avalabs/vm-module-types';\n\nexport const hasDerivationDetails = (params: DeriveAddressParams): params is DetailedDeriveAddressParams =>\n 'derivationPathType' in params &&\n 'accountIndex' in params &&\n typeof params.accountIndex === 'number' &&\n typeof params.derivationPathType === 'string';\n","import { rpcErrors } from '@metamask/rpc-errors';\nimport {\n NetworkVMType,\n type BuildDerivationPathParams,\n type BuildDerivationPathResponse,\n} from '@avalabs/vm-module-types';\n\n/**\n * HyperCore identity is an EVM address (cointype 60). Paths match the EVM module;\n * the result is keyed as `HYPERCORE`.\n */\nexport const buildDerivationPath = ({\n accountIndex,\n derivationPathType,\n}: BuildDerivationPathParams): Pick<BuildDerivationPathResponse, NetworkVMType.HYPERCORE> => {\n if (accountIndex < 0) {\n throw rpcErrors.invalidParams('Account index must be a non-negative integer');\n }\n\n switch (derivationPathType) {\n case 'bip44':\n return {\n [NetworkVMType.HYPERCORE]: `m/44'/60'/0'/0/${accountIndex}`,\n };\n\n case 'ledger_live':\n return {\n [NetworkVMType.HYPERCORE]: `m/44'/60'/${accountIndex}'/0/0`,\n };\n\n default:\n throw rpcErrors.invalidParams(`Unsupported derivation path type: ${derivationPathType}`);\n }\n};\n","import {\n NetworkVMType,\n type ApprovalController,\n type DeriveAddressesParams,\n type DeriveAddressesResponse,\n} from '@avalabs/vm-module-types';\nimport { deriveAddressesForEvm, init } from '@avalabs/crypto-sdk';\nimport { buildDerivationPath } from '../build-derivation-path/build-derivation-path';\n\nexport const deriveAddresses = async (\n params: DeriveAddressesParams & { approvalController: ApprovalController },\n): Promise<DeriveAddressesResponse> => {\n const { approvalController, secretId, accountIndices, derivationPathType } = params;\n\n if (accountIndices.length === 0) {\n return [];\n }\n\n await init();\n\n const publicKeys = await Promise.all(\n accountIndices.map(async (accountIndex) => {\n const derivationPath = buildDerivationPath({ accountIndex, derivationPathType }).HYPERCORE;\n const publicKeyHex = await approvalController.requestPublicKey({\n curve: 'secp256k1',\n secretId,\n derivationPath,\n });\n return Uint8Array.from(Buffer.from(publicKeyHex, 'hex'));\n }),\n );\n\n const addresses = await deriveAddressesForEvm(publicKeys);\n\n return addresses.map((address) => ({ [NetworkVMType.HYPERCORE]: address }));\n};\n"]}
1
+ {"version":3,"sources":["../src/module.ts","../manifest.json","../src/env.ts","../src/utils/schemas.ts","../src/utils/info-client.ts","../src/utils/unsupported.ts","../src/handlers/get-balances/get-balances.ts","../src/utils/build-hypercore-tokens.ts","../src/constants.ts","../src/utils/hyperliquid-coin-svg-url.ts","../src/utils/spot-tokens.ts","../src/handlers/get-tokens/get-tokens.ts","../src/utils/activity/types.ts","../src/utils/activity/fetch-hypercore-activity.ts","../src/utils/activity/map-hypercore-activity-to-transactions.ts","../src/utils/activity/get-hypercore-ledger-display.ts","../src/utils/activity/hypercore-fill-meta.ts","../src/handlers/get-transaction-history/get-transaction-history.ts","../src/handlers/get-address/get-address.ts","../src/handlers/derive-address/derive-address.ts","../../../packages-internal/utils/src/utils/address-derivation.ts","../src/handlers/build-derivation-path/build-derivation-path.ts","../src/handlers/derive-addresses/derive-addresses.ts"],"names":["parseManifest","rpcErrors","manifest_default","Environment","INFO_PATH","PUBLIC_ACTIVITY_INFO_URL","prodEnv","devEnv","getEnv","__name","environment","z","tokenIndexSchema","spotMetaResponseSchema","spotBalanceSchema","spotClearinghouseStateSchema","marginSummarySchema","clearinghouseStateSchema","userAbstractionSchema","value","userFillSchema","userFillsSchema","hypercoreLedgerDeltaSchema","hypercoreLedgerUpdateSchema","hypercoreLedgerUpdatesSchema","resolveFetch","fetchFn","_infoUrl","_activityInfoUrl","_fetch","_HypercoreInfoClient","config","__privateAdd","__privateSet","body","schema","options","response","__privateGet","json","user","startTime","HypercoreInfoClient","unsupportedHypercoreCapabilityMessage","capability","TokenType","Big","HYPERCORE_CAIP_ID","HYPERCORE_CHAIN_ID","HYPERCORE_USDC_SYMBOL","HYPERCORE_USDC_NAME","HYPERCORE_USDC_DECIMALS","BIG_ZERO","spotCountsAsPerpCollateral","mode","toRawBalance","humanAmount","decimals","getPerpCollateralUsd","perp","accountValue","unrealizedPnl","sum","position","collateral","buildHypercoreTokens","spotBalances","perpState","abstractionMode","spotTokens","tokensByIndex","token","perpCollateralUsd","spotUsdc","balance","usdcTotal","tokens","meta","total","HYPERLIQUID_COIN_SVG_BASE","hyperliquidCoinSvgKey","coin","trimmed","separatorIndex","hyperliquidCoinSvgUrl","isValidEvmAddress","address","toHypercoreSpotTokens","toErrorMessage","err","toTokenWithBalance","networkToken","balanceInCurrency","native","spot","getBalances","addresses","network","infoClient","tokenTypes","includeNative","includeSpot","spotState","bySymbol","key","acc","curr","index","getTokens","spotMeta","toTimeMs","time","MAX_LEDGER_PAGES","LEDGER_LOOKBACK_MS","isAbortError","softFail","promise","fallback","fetchLedgerUpdates","client","evmAddress","all","pages","page","last","next","fetchHypercoreActivity","fills","ledgerUpdates","fill","update","a","b","TransactionType","formatAmount","parsed","toUsd","sign","getHypercoreLedgerDisplay","delta","owner","isOutgoing","METHOD_PREFIX","tickerOfCoin","i","closedPnlTone","closedPnl","n","fillLabel","dir","tone","d","formatHypercoreFillPx","px","encodeHypercoreFillMethod","parseHypercoreFillMethod","method","explorerTxLink","hash","base","chainIdForNetwork","mapFillToTransaction","timeMs","isBuy","ticker","mapLedgerToTransaction","display","isIncoming","txType","amount","mapHypercoreActivityToTransactions","items","item","getTransactionHistory","NetworkVMType","WalletType","getAddressFromXPub","getEvmAddressFromPubKey","getAddress","accountIndex","xpub","walletType","pubKeyBuffer","computeAddress","hasDerivationDetails","params","buildDerivationPath","derivationPathType","deriveAddress","secretId","approvalController","derivationPath","publicKeyHex","deriveAddressesForEvm","init","deriveAddresses","accountIndices","publicKeys","_approvalController","_infoClient","_HypercoreModule","runtime","infoUrl","activityInfoUrl","_network","result","request","HypercoreMod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AqBF,EAAmB,CACzD,MAAO,CACL,MAAO3M,GAAU,mBAAmB,kCAAkC6M,EAAQ,MAAM,mBAAmB,CACzG,CACF,CACF,EAxEER,EAAA,YACAC,EAAA,YAF6C9L,EAAA+L,EAAA,mBAAxC,IAAMO,GAANP","sourcesContent":["import type {\n Module,\n Manifest,\n ConstructorParams,\n ApprovalController,\n RpcRequest,\n Network,\n NetworkFees,\n GetBalancesParams,\n GetAddressParams,\n GetAddressResponse,\n DeriveAddressParams,\n DeriveAddressesParams,\n BuildDerivationPathParams,\n GetTransactionHistory,\n NetworkFeeParam,\n} from '@avalabs/vm-module-types';\nimport { parseManifest } from '@avalabs/vm-module-types';\nimport { rpcErrors } from '@metamask/rpc-errors';\n\nimport ManifestJson from '../manifest.json';\nimport { getEnv } from './env';\nimport { HypercoreInfoClient } from './utils/info-client';\nimport { unsupportedHypercoreCapabilityMessage } from './utils/unsupported';\nimport { getBalances } from './handlers/get-balances/get-balances';\nimport { getTokens } from './handlers/get-tokens/get-tokens';\nimport { getTransactionHistory } from './handlers/get-transaction-history/get-transaction-history';\nimport { getAddress } from './handlers/get-address/get-address';\nimport { deriveAddress } from './handlers/derive-address/derive-address';\nimport { deriveAddresses } from './handlers/derive-addresses/derive-addresses';\nimport { buildDerivationPath } from './handlers/build-derivation-path/build-derivation-path';\n\nexport class HypercoreModule implements Module {\n #approvalController: ApprovalController;\n #infoClient: HypercoreInfoClient;\n\n constructor({ environment, approvalController, runtime }: ConstructorParams) {\n const { infoUrl, activityInfoUrl } = getEnv(environment);\n\n this.#approvalController = approvalController;\n this.#infoClient = new HypercoreInfoClient({\n infoUrl,\n activityInfoUrl,\n fetch: runtime?.fetch,\n });\n }\n\n getProvider(_network: Network): Promise<never> {\n return Promise.reject(new Error(unsupportedHypercoreCapabilityMessage('getProvider')));\n }\n\n getManifest(): Manifest | undefined {\n const result = parseManifest(ManifestJson);\n return result.success ? result.data : undefined;\n }\n\n getBalances(params: GetBalancesParams) {\n return getBalances({\n ...params,\n infoClient: this.#infoClient,\n });\n }\n\n getTransactionHistory(params: GetTransactionHistory) {\n return getTransactionHistory({\n ...params,\n infoClient: this.#infoClient,\n });\n }\n\n getNetworkFee(_network: NetworkFeeParam): Promise<NetworkFees> {\n return Promise.reject(new Error(unsupportedHypercoreCapabilityMessage('getNetworkFee')));\n }\n\n getAddress(params: GetAddressParams): Promise<GetAddressResponse> {\n return getAddress(params);\n }\n\n buildDerivationPath(params: BuildDerivationPathParams) {\n return buildDerivationPath(params);\n }\n\n deriveAddress(params: DeriveAddressParams) {\n return deriveAddress({\n ...params,\n approvalController: this.#approvalController,\n });\n }\n\n deriveAddresses(params: DeriveAddressesParams) {\n return deriveAddresses({\n ...params,\n approvalController: this.#approvalController,\n });\n }\n\n getTokens(network: Network) {\n return getTokens({ network, infoClient: this.#infoClient });\n }\n\n async onRpcRequest(request: RpcRequest, _network: Network) {\n return {\n error: rpcErrors.methodNotSupported(`HyperCore is read-only; method ${request.method} is not supported`),\n };\n }\n}\n","{\n \"name\": \"HyperCore\",\n \"description\": \"Read-only Hyperliquid HyperCore module (balances, tokens, activity).\",\n \"version\": \"0.0.1\",\n \"sources\": {\n \"module\": {\n \"checksum\": \"\",\n \"location\": {\n \"npm\": {\n \"filePath\": \"dist/index.js\",\n \"packageName\": \"@avalabs/hypercore-module\",\n \"registry\": \"https://registry.npmjs.org\"\n }\n }\n }\n },\n \"network\": {\n \"chainIds\": [\"hlcore:mainnet\"],\n \"namespaces\": [\"hlcore\"]\n },\n \"cointype\": \"60\",\n \"permissions\": {\n \"rpc\": {\n \"dapps\": false,\n \"methods\": [],\n \"nonRestrictedMethods\": []\n }\n },\n \"manifestVersion\": \"0.1\"\n}\n","import { Environment } from '@avalabs/vm-module-types';\n\ntype Env = {\n proxyApiUrl: string;\n /** Proxy-first Hyperliquid `/info` endpoint. */\n infoUrl: string;\n /**\n * Fallback for activity endpoints if the proxy does not support fills/ledger.\n * Prefer `infoUrl` when possible.\n */\n activityInfoUrl: string;\n};\n\nconst INFO_PATH = '/proxy/nownodes/hype/info';\nconst PUBLIC_ACTIVITY_INFO_URL = 'https://api.hyperliquid.xyz/info';\n\nexport const prodEnv: Env = {\n proxyApiUrl: 'https://proxy-api.avax.network',\n infoUrl: `https://proxy-api.avax.network${INFO_PATH}`,\n activityInfoUrl: PUBLIC_ACTIVITY_INFO_URL,\n};\n\nexport const devEnv: Env = {\n proxyApiUrl: 'https://proxy-api-dev.avax.network',\n infoUrl: `https://proxy-api-dev.avax.network${INFO_PATH}`,\n activityInfoUrl: PUBLIC_ACTIVITY_INFO_URL,\n};\n\nexport const getEnv = (environment: Environment): Env => {\n switch (environment) {\n case Environment.PRODUCTION:\n return prodEnv;\n case Environment.DEV:\n return devEnv;\n }\n};\n","import { z } from 'zod';\n\nconst tokenIndexSchema = z.coerce.number();\n\n/** `type: \"spotMeta\"` — registry mapping spot token index → display metadata. */\nexport const spotMetaResponseSchema = z.object({\n tokens: z.array(\n z.object({\n name: z.string(),\n index: z.number(),\n weiDecimals: z.number(),\n fullName: z.string().nullish(),\n evmContract: z.object({ address: z.string() }).nullish(),\n }),\n ),\n});\n\nconst spotBalanceSchema = z.object({\n coin: z.string(),\n token: tokenIndexSchema,\n total: z.string(),\n hold: z.string(),\n entryNtl: z.string().optional(),\n});\n\n/** `type: \"spotClearinghouseState\"` */\nexport const spotClearinghouseStateSchema = z.object({\n balances: z.array(spotBalanceSchema),\n});\n\nconst marginSummarySchema = z.object({\n accountValue: z.string(),\n totalMarginUsed: z.string().optional(),\n totalNtlPos: z.string().optional(),\n totalRawUsd: z.string().optional(),\n});\n\n/**\n * `type: \"clearinghouseState\"` — only fields needed for PnL-excluded\n * perp collateral fold-in.\n */\nexport const clearinghouseStateSchema = z.object({\n assetPositions: z.array(\n z.object({\n position: z.object({\n unrealizedPnl: z.string(),\n }),\n }),\n ),\n crossMarginSummary: marginSummarySchema,\n});\n\nexport type UserAbstractionMode = 'unifiedAccount' | 'portfolioMargin' | 'dexAbstraction' | 'disabled' | 'default';\n\n/**\n * `type: \"userAbstraction\"` — bare JSON string. Unknown future values coerce\n * to `\"default\"` so balance math stays conservative.\n */\nexport const userAbstractionSchema = z.string().transform((value): UserAbstractionMode => {\n switch (value) {\n case 'unifiedAccount':\n case 'portfolioMargin':\n case 'dexAbstraction':\n case 'disabled':\n case 'default':\n return value;\n default:\n return 'default';\n }\n});\n\n/** `type: \"userFills\"` */\nexport const userFillSchema = z.object({\n closedPnl: z.string(),\n coin: z.string(),\n crossed: z.boolean(),\n dir: z.string(),\n hash: z.string(),\n oid: z.number(),\n px: z.string(),\n side: z.string(),\n startPosition: z.string(),\n sz: z.string(),\n time: z.number(),\n fee: z.string().optional(),\n tid: z.number().optional(),\n});\n\nexport const userFillsSchema = z.array(userFillSchema);\n\n/**\n * `userNonFundingLedgerUpdates` deltas — permissive so unknown delta types\n * still parse and can render generically later.\n */\nexport const hypercoreLedgerDeltaSchema = z.object({\n type: z.string(),\n usdc: z.string().optional(),\n amount: z.string().optional(),\n usdcValue: z.string().optional(),\n token: z.string().optional(),\n user: z.string().optional(),\n destination: z.string().optional(),\n fee: z.string().optional(),\n toPerp: z.boolean().optional(),\n});\n\nexport const hypercoreLedgerUpdateSchema = z.object({\n time: z.number(),\n hash: z.string(),\n delta: hypercoreLedgerDeltaSchema,\n});\n\nexport const hypercoreLedgerUpdatesSchema = z.array(hypercoreLedgerUpdateSchema);\n\nexport type SpotMetaResponse = z.infer<typeof spotMetaResponseSchema>;\nexport type SpotBalance = {\n coin: string;\n token: number;\n total: string;\n hold: string;\n entryNtl?: string;\n};\nexport type SpotClearinghouseState = {\n balances: SpotBalance[];\n};\nexport type ClearinghouseState = z.infer<typeof clearinghouseStateSchema>;\nexport type UserFill = z.infer<typeof userFillSchema>;\nexport type HypercoreLedgerUpdate = z.infer<typeof hypercoreLedgerUpdateSchema>;\n","import type { z } from 'zod';\nimport {\n clearinghouseStateSchema,\n hypercoreLedgerUpdatesSchema,\n spotClearinghouseStateSchema,\n spotMetaResponseSchema,\n userAbstractionSchema,\n userFillsSchema,\n type ClearinghouseState,\n type HypercoreLedgerUpdate,\n type SpotClearinghouseState,\n type SpotMetaResponse,\n type UserAbstractionMode,\n type UserFill,\n} from './schemas';\n\nexport type HypercoreInfoRequest =\n | { type: 'spotMeta' }\n | { type: 'spotClearinghouseState'; user: string; dex?: string }\n | { type: 'clearinghouseState'; user: string; dex?: string }\n | { type: 'userAbstraction'; user: string }\n | { type: 'userFills'; user: string }\n | {\n type: 'userNonFundingLedgerUpdates';\n user: string;\n startTime: number;\n };\n\nexport type HypercoreInfoClientConfig = {\n /** Proxy-first `/info` URL used for balances and spot meta. */\n infoUrl: string;\n /**\n * Activity URL. Defaults to `infoUrl`; may be the public HL endpoint when\n * the proxy does not yet support fills/ledger types.\n */\n activityInfoUrl?: string;\n fetch?: typeof globalThis.fetch;\n};\n\nexport type PostInfoOptions = {\n signal?: AbortSignal;\n /** Overrides the client default URL for this call. */\n url?: string;\n};\n\nconst resolveFetch = (fetchFn?: typeof globalThis.fetch): typeof globalThis.fetch => {\n if (typeof fetchFn === 'function') {\n return fetchFn;\n }\n\n if (typeof globalThis.fetch === 'function') {\n return globalThis.fetch.bind(globalThis);\n }\n\n throw new Error(\n 'HypercoreInfoClient requires a fetch implementation. Pass config.fetch when globalThis.fetch is unavailable (e.g. React Native).',\n );\n};\n\nexport class HypercoreInfoClient {\n readonly #infoUrl: string;\n readonly #activityInfoUrl: string;\n readonly #fetch: typeof globalThis.fetch;\n\n constructor(config: HypercoreInfoClientConfig) {\n this.#infoUrl = config.infoUrl;\n this.#activityInfoUrl = config.activityInfoUrl ?? config.infoUrl;\n this.#fetch = resolveFetch(config.fetch);\n }\n\n async postInfo<T>(body: HypercoreInfoRequest, schema: z.ZodType<T>, options?: PostInfoOptions) {\n const response = await this.#fetch(options?.url ?? this.#infoUrl, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify(body),\n signal: options?.signal,\n });\n\n if (!response.ok) {\n throw new Error(`Hyperliquid /info failed: ${response.status} ${response.statusText}`);\n }\n\n const json: unknown = await response.json();\n return schema.parse(json);\n }\n\n getSpotMeta(options?: PostInfoOptions): Promise<SpotMetaResponse> {\n return this.postInfo({ type: 'spotMeta' }, spotMetaResponseSchema, options);\n }\n\n getSpotClearinghouseState(user: string, options?: PostInfoOptions): Promise<SpotClearinghouseState> {\n return this.postInfo(\n {\n type: 'spotClearinghouseState',\n user: user.toLowerCase(),\n dex: '',\n },\n spotClearinghouseStateSchema,\n options,\n ) as Promise<SpotClearinghouseState>;\n }\n\n getClearinghouseState(user: string, options?: PostInfoOptions): Promise<ClearinghouseState> {\n return this.postInfo(\n {\n type: 'clearinghouseState',\n user: user.toLowerCase(),\n dex: '',\n },\n clearinghouseStateSchema,\n options,\n );\n }\n\n getUserAbstraction(user: string, options?: PostInfoOptions): Promise<UserAbstractionMode> {\n return this.postInfo(\n { type: 'userAbstraction', user: user.toLowerCase() },\n userAbstractionSchema,\n options,\n ) as Promise<UserAbstractionMode>;\n }\n\n getUserFills(user: string, options?: PostInfoOptions): Promise<UserFill[]> {\n return this.postInfo({ type: 'userFills', user: user.toLowerCase() }, userFillsSchema, {\n ...options,\n url: options?.url ?? this.#activityInfoUrl,\n });\n }\n\n getUserNonFundingLedgerUpdates(\n user: string,\n startTime: number,\n options?: PostInfoOptions,\n ): Promise<HypercoreLedgerUpdate[]> {\n return this.postInfo(\n {\n type: 'userNonFundingLedgerUpdates',\n user: user.toLowerCase(),\n startTime,\n },\n hypercoreLedgerUpdatesSchema,\n {\n ...options,\n url: options?.url ?? this.#activityInfoUrl,\n },\n );\n }\n}\n","/**\n * Loud failure message for HyperCore capabilities that do not exist (no RPC, no gas).\n * Prefer rejecting with this over empty success so clients and agents see intentional gaps.\n */\nexport const unsupportedHypercoreCapabilityMessage = (capability: string) =>\n `HyperCore does not support ${capability}: read-only module (balances, tokens, activity).`;\n\nexport const unsupportedHypercoreCapability = (capability: string): never => {\n throw new Error(unsupportedHypercoreCapabilityMessage(capability));\n};\n","import {\n TokenType,\n type GetBalancesParams,\n type GetBalancesResponse,\n type NetworkTokenWithBalance,\n type TokenWithBalance,\n type TokenWithBalanceHypercoreSpot,\n} from '@avalabs/vm-module-types';\nimport type { HypercoreInfoClient } from '../../utils/info-client';\nimport { buildHypercoreTokens, type HypercoreTokenBalance } from '../../utils/build-hypercore-tokens';\nimport { hyperliquidCoinSvgUrl } from '../../utils/hyperliquid-coin-svg-url';\nimport { toHypercoreSpotTokens } from '../../utils/spot-tokens';\n\ntype GetHypercoreBalancesParams = Omit<GetBalancesParams, 'currency' | 'customTokens'> & {\n infoClient: HypercoreInfoClient;\n};\n\nconst toErrorMessage = (err: unknown) => (err instanceof Error ? err.message : String(err));\n\nconst toTokenWithBalance = (\n token: HypercoreTokenBalance,\n networkToken: GetBalancesParams['network']['networkToken'],\n): { key: string; value: TokenWithBalance } => {\n if (token.kind === 'native') {\n const balance = BigInt(token.balanceRaw);\n const balanceInCurrency = Number(token.balanceUsd);\n const native: NetworkTokenWithBalance = {\n ...networkToken,\n name: token.name,\n symbol: token.symbol,\n decimals: token.decimals,\n logoUri: networkToken.logoUri ?? hyperliquidCoinSvgUrl(token.symbol),\n coingeckoId: 'usd-coin',\n type: TokenType.NATIVE,\n balance,\n balanceDisplayValue: token.balance,\n balanceInCurrency: Number.isFinite(balanceInCurrency) ? balanceInCurrency : 0,\n balanceCurrencyDisplayValue: token.balanceUsd,\n priceInCurrency: token.priceUsd,\n };\n return { key: token.symbol, value: native };\n }\n\n const balance = BigInt(token.balanceRaw);\n const spot: TokenWithBalanceHypercoreSpot = {\n type: TokenType.HYPERCORE_SPOT,\n name: token.name,\n symbol: token.symbol,\n decimals: token.decimals,\n index: token.index,\n evmContract: token.evmContract,\n logoUri: hyperliquidCoinSvgUrl(token.symbol),\n reputation: null,\n balance,\n balanceDisplayValue: token.balance,\n };\n return { key: `spot:${token.index}`, value: spot };\n};\n\nexport const getBalances = async ({\n addresses,\n network,\n infoClient,\n tokenTypes = [TokenType.NATIVE, TokenType.HYPERCORE_SPOT],\n}: GetHypercoreBalancesParams): Promise<GetBalancesResponse> => {\n const includeNative = tokenTypes.includes(TokenType.NATIVE);\n const includeSpot = tokenTypes.includes(TokenType.HYPERCORE_SPOT);\n\n if (!includeNative && !includeSpot) {\n return Object.fromEntries(addresses.map((address) => [address, {}]));\n }\n\n // Spot meta is only required to label non-USDC spot inventory. Native USDC is\n // derived from spot clearinghouse balances (+ optional perp collateral).\n const spotTokens = includeSpot ? toHypercoreSpotTokens((await infoClient.getSpotMeta()).tokens) : [];\n\n const results = await Promise.allSettled(\n addresses.map(async (address) => {\n const [spotState, perpState, abstractionMode] = await Promise.all([\n infoClient.getSpotClearinghouseState(address),\n includeNative ? infoClient.getClearinghouseState(address) : Promise.resolve(undefined),\n includeNative ? infoClient.getUserAbstraction(address) : Promise.resolve(undefined),\n ]);\n\n const tokens = buildHypercoreTokens({\n spotBalances: spotState.balances,\n perpState,\n abstractionMode,\n spotTokens,\n }).filter((token) => (token.kind === 'native' ? includeNative : includeSpot));\n\n const bySymbol = Object.fromEntries(\n tokens.map((token) => {\n const { key, value } = toTokenWithBalance(token, network.networkToken);\n return [key, value];\n }),\n );\n\n return { [address]: bySymbol };\n }),\n );\n\n return results.reduce((acc, curr, index) => {\n if (curr.status === 'fulfilled') {\n return { ...acc, ...curr.value };\n }\n const address = addresses[index];\n if (!address) {\n return acc;\n }\n return { ...acc, [address]: { error: toErrorMessage(curr.reason) } };\n }, {} as GetBalancesResponse);\n};\n","import Big from 'big.js';\nimport type { HypercoreSpotToken } from '@avalabs/vm-module-types';\nimport { HYPERCORE_USDC_DECIMALS, HYPERCORE_USDC_NAME, HYPERCORE_USDC_SYMBOL } from '../constants';\nimport type { ClearinghouseState, SpotBalance, UserAbstractionMode } from './schemas';\n\nconst BIG_ZERO = new Big(0);\n\nexport type HypercoreNativeTokenBalance = {\n kind: 'native';\n name: string;\n symbol: typeof HYPERCORE_USDC_SYMBOL;\n decimals: number;\n /** Human-readable amount (decimal string). */\n balance: string;\n /** Integer raw amount as a decimal string (no fractional part). */\n balanceRaw: string;\n priceUsd: 1;\n balanceUsd: string;\n};\n\nexport type HypercoreSpotTokenBalance = {\n kind: 'spot';\n name: string;\n symbol: string;\n decimals: number;\n balance: string;\n balanceRaw: string;\n index: number;\n evmContract?: string;\n};\n\nexport type HypercoreTokenBalance = HypercoreNativeTokenBalance | HypercoreSpotTokenBalance;\n\n/**\n * `true` when spot balances already back perps for this account mode\n * (`unifiedAccount`). Other modes keep perp collateral on a separate ledger.\n */\nexport const spotCountsAsPerpCollateral = (mode: UserAbstractionMode | undefined) => mode === 'unifiedAccount';\n\n/** Tokens carry no native gas balance on HyperCore — amounts are human decimals. */\nconst toRawBalance = (humanAmount: Big, decimals: number) =>\n humanAmount.times(new Big(10).pow(decimals)).round(0, Big.roundDown).toFixed(0);\n\n/**\n * Perp collateral in USDC, excluding unrealized PnL.\n * `crossMarginSummary.accountValue` is collateral ± PnL; we back PnL out.\n */\nexport const getPerpCollateralUsd = (perp: ClearinghouseState | undefined) => {\n if (!perp) {\n return BIG_ZERO;\n }\n\n const accountValue = new Big(perp.crossMarginSummary.accountValue ?? '0');\n const unrealizedPnl = perp.assetPositions.reduce((sum, { position }) => sum.plus(position.unrealizedPnl), BIG_ZERO);\n const collateral = accountValue.minus(unrealizedPnl);\n\n return collateral.gt(BIG_ZERO) ? collateral : BIG_ZERO;\n};\n\n/**\n * USDC merges spot + (non-unified) PnL-excluded perp collateral at $1.\n * Other spot inventory is `HYPERCORE_SPOT` (no synthetic ERC20 addresses).\n */\nexport const buildHypercoreTokens = ({\n spotBalances,\n perpState,\n abstractionMode,\n spotTokens,\n}: {\n spotBalances: readonly SpotBalance[];\n perpState: ClearinghouseState | undefined;\n abstractionMode: UserAbstractionMode | undefined;\n spotTokens: HypercoreSpotToken[];\n}): HypercoreTokenBalance[] => {\n const tokensByIndex = new Map(spotTokens.map((token) => [token.index, token]));\n\n const perpCollateralUsd = spotCountsAsPerpCollateral(abstractionMode) ? BIG_ZERO : getPerpCollateralUsd(perpState);\n\n const spotUsdc = spotBalances.find((balance) => balance.coin.toUpperCase() === HYPERCORE_USDC_SYMBOL);\n const usdcTotal = new Big(spotUsdc?.total ?? '0').plus(perpCollateralUsd);\n\n const tokens: HypercoreTokenBalance[] = [];\n\n if (usdcTotal.gt(BIG_ZERO)) {\n tokens.push({\n kind: 'native',\n name: HYPERCORE_USDC_NAME,\n symbol: HYPERCORE_USDC_SYMBOL,\n decimals: HYPERCORE_USDC_DECIMALS,\n balance: usdcTotal.toString(),\n balanceRaw: toRawBalance(usdcTotal, HYPERCORE_USDC_DECIMALS),\n priceUsd: 1,\n balanceUsd: usdcTotal.toString(),\n });\n }\n\n for (const balance of spotBalances) {\n if (balance.coin.toUpperCase() === HYPERCORE_USDC_SYMBOL) {\n continue;\n }\n\n const meta = tokensByIndex.get(balance.token);\n const total = new Big(balance.total);\n if (!meta || !total.gt(BIG_ZERO)) {\n continue;\n }\n\n tokens.push({\n kind: 'spot',\n name: meta.name,\n symbol: meta.symbol,\n decimals: meta.decimals,\n balance: total.toString(),\n balanceRaw: toRawBalance(total, meta.decimals),\n index: meta.index,\n evmContract: meta.evmContract,\n });\n }\n\n return tokens;\n};\n","/** CAIP-2 id for HyperCore mainnet. Namespace must be 3–8 chars (CAIP-2).\n * This is a synthetic CAIP-2 for the HyperCore network as HyperCore does not have a chain id.\n */\nexport const HYPERCORE_CAIP_ID = 'hlcore:mainnet';\n\n/**\n * Synthetic numeric id used by Core network lists / storage keys.\n * Not an EVM chain id — module routing uses {@link HYPERCORE_CAIP_ID}.\n */\nexport const HYPERCORE_CHAIN_ID = 9999;\n\nexport const HYPERCORE_USDC_SYMBOL = 'USDC';\nexport const HYPERCORE_USDC_NAME = 'USD Coin';\nexport const HYPERCORE_USDC_DECIMALS = 8;\n","export const HYPERLIQUID_COIN_SVG_BASE = 'https://app.hyperliquid.xyz/coins';\n\nexport const hyperliquidCoinSvgKey = (coin: string) => {\n const trimmed = coin.trim();\n const separatorIndex = trimmed.indexOf(':');\n if (separatorIndex === -1) {\n return trimmed.toUpperCase();\n }\n // HIP-3 logos are keyed as `marketname:TICKER` (dex prefix is case-significant).\n return `${trimmed.slice(0, separatorIndex)}:${trimmed.slice(separatorIndex + 1).toUpperCase()}`;\n};\n\nexport const hyperliquidCoinSvgUrl = (coin: string) =>\n `${HYPERLIQUID_COIN_SVG_BASE}/${encodeURIComponent(hyperliquidCoinSvgKey(coin))}.svg`;\n","import { TokenType, type HypercoreSpotToken } from '@avalabs/vm-module-types';\nimport type { SpotMetaResponse } from './schemas';\n\nconst isValidEvmAddress = (address: string) => /^0x[a-fA-F0-9]{40}$/.test(address);\n\n/**\n * Maps `spotMeta` tokens to the registry used when resolving spot balances.\n * Keeps every spot token (including HyperCore-only ones without an EVM contract).\n */\nexport const toHypercoreSpotTokens = (tokens: SpotMetaResponse['tokens']): HypercoreSpotToken[] =>\n tokens.map((token) => {\n const address = token.evmContract?.address.toLowerCase();\n\n return {\n type: TokenType.HYPERCORE_SPOT,\n index: token.index,\n name: token.fullName ?? token.name,\n symbol: token.name,\n decimals: token.weiDecimals,\n evmContract: address && isValidEvmAddress(address) ? address : undefined,\n };\n });\n","import type { HypercoreSpotToken, Network } from '@avalabs/vm-module-types';\nimport type { HypercoreInfoClient } from '../../utils/info-client';\nimport { hyperliquidCoinSvgUrl } from '../../utils/hyperliquid-coin-svg-url';\nimport { toHypercoreSpotTokens } from '../../utils/spot-tokens';\n\nexport const getTokens = async ({\n infoClient,\n}: {\n network: Network;\n infoClient: HypercoreInfoClient;\n}): Promise<HypercoreSpotToken[]> => {\n const spotMeta = await infoClient.getSpotMeta();\n return toHypercoreSpotTokens(spotMeta.tokens).map((token) => ({\n ...token,\n logoUri: token.logoUri ?? hyperliquidCoinSvgUrl(token.symbol),\n }));\n};\n","import type { HypercoreLedgerUpdate, UserFill } from '../schemas';\n\nexport type HypercoreActivityItem =\n | {\n readonly kind: 'fill';\n readonly timeMs: number;\n readonly hash: string;\n readonly fill: UserFill;\n }\n | {\n readonly kind: 'ledger';\n readonly timeMs: number;\n readonly hash: string;\n readonly update: HypercoreLedgerUpdate;\n };\n\n/** Normalize a Unix timestamp to milliseconds. */\nexport const toTimeMs = (time: number) => (time < 10_000_000_000 ? time * 1000 : time);\n","import type { HypercoreInfoClient } from '../info-client';\nimport type { HypercoreLedgerUpdate } from '../schemas';\nimport type { HypercoreActivityItem } from './types';\nimport { toTimeMs } from './types';\n\n/**\n * Safety cap only — ledger events are infrequent vs fills, so we normally stop\n * on an empty page well before this. Hitting the cap would truncate the *newest*\n * updates (pages are ascending from `startTime`).\n */\nexport const MAX_LEDGER_PAGES = 20;\n\n/** Default ledger window; keep short so a capped crawl still covers recent activity. */\nexport const LEDGER_LOOKBACK_MS = 30 * 24 * 60 * 60 * 1000;\n\ntype FetchHypercoreActivityOptions = {\n signal?: AbortSignal;\n};\n\nconst isAbortError = (err: unknown) =>\n (err instanceof DOMException && err.name === 'AbortError') || (err instanceof Error && err.name === 'AbortError');\n\nconst softFail = async <T>(promise: Promise<T>, fallback: T): Promise<T> => {\n try {\n return await promise;\n } catch (err) {\n if (isAbortError(err)) {\n throw err;\n }\n return fallback;\n }\n};\n\n/**\n * `userNonFundingLedgerUpdates` returns an ascending, capped page (~500) from\n * `startTime`. A single request therefore returns the *oldest* rows in the\n * window and can omit recent activity. Page forward — advancing past the last\n * row's time — until empty (or the safety page cap), so the newest updates in\n * the lookback window are included.\n */\nconst fetchLedgerUpdates = async (\n client: HypercoreInfoClient,\n evmAddress: string,\n options?: FetchHypercoreActivityOptions,\n) => {\n const all: HypercoreLedgerUpdate[] = [];\n let startTime = Date.now() - LEDGER_LOOKBACK_MS;\n let pages = 0;\n\n while (pages < MAX_LEDGER_PAGES) {\n if (options?.signal?.aborted) {\n throw new DOMException('The operation was aborted.', 'AbortError');\n }\n\n const page = await client.getUserNonFundingLedgerUpdates(evmAddress, startTime, options);\n pages += 1;\n if (page.length === 0) {\n break;\n }\n all.push(...page);\n const last = page[page.length - 1];\n if (!last) {\n break;\n }\n const next = last.time + 1;\n if (next <= startTime) {\n break;\n }\n startTime = next;\n }\n\n return all;\n};\n\n/**\n * Fetches HyperCore fills + non-funding ledger updates and sorts newest-first.\n * Soft-fails individual endpoints so a flaky fills or ledger call still yields\n * partial history (abort errors are rethrown).\n */\nexport const fetchHypercoreActivity = async (\n client: HypercoreInfoClient,\n evmAddress: string,\n options?: FetchHypercoreActivityOptions,\n): Promise<HypercoreActivityItem[]> => {\n const [fills, ledgerUpdates] = await Promise.all([\n softFail(client.getUserFills(evmAddress, options), []),\n softFail(fetchLedgerUpdates(client, evmAddress, options), []),\n ]);\n\n const items: HypercoreActivityItem[] = [\n ...fills.map((fill) => ({\n kind: 'fill' as const,\n timeMs: toTimeMs(fill.time),\n hash: fill.hash,\n fill,\n })),\n ...ledgerUpdates.map((update) => ({\n kind: 'ledger' as const,\n timeMs: toTimeMs(update.time),\n hash: update.hash,\n update,\n })),\n ];\n\n return items.sort((a, b) => b.timeMs - a.timeMs);\n};\n","import { TokenType, TransactionType, type Network, type Transaction, type TxToken } from '@avalabs/vm-module-types';\nimport { HYPERCORE_CAIP_ID } from '../../constants';\nimport { hyperliquidCoinSvgUrl } from '../hyperliquid-coin-svg-url';\nimport type { HypercoreLedgerUpdate, UserFill } from '../schemas';\nimport { getHypercoreLedgerDisplay } from './get-hypercore-ledger-display';\nimport { encodeHypercoreFillMethod, tickerOfCoin } from './hypercore-fill-meta';\nimport type { HypercoreActivityItem } from './types';\nimport { toTimeMs } from './types';\n\nconst explorerTxLink = (network: Pick<Network, 'explorerUrl'>, hash: string) => {\n const base = (network.explorerUrl ?? '').replace(/\\/$/, '');\n return base ? `${base}/tx/${hash}` : hash;\n};\n\nconst chainIdForNetwork = (network: Pick<Network, 'caipId' | 'chainId'>) => network.caipId ?? HYPERCORE_CAIP_ID;\n\nconst mapFillToTransaction = (\n fill: UserFill,\n timeMs: number,\n network: Pick<Network, 'explorerUrl' | 'caipId' | 'chainId'>,\n): Transaction => {\n const isBuy = fill.side === 'B';\n const ticker = tickerOfCoin(fill.coin);\n\n const token: TxToken = {\n type: TokenType.NATIVE,\n name: fill.coin,\n symbol: ticker,\n amount: fill.sz,\n imageUri: hyperliquidCoinSvgUrl(fill.coin),\n };\n\n return {\n isContractCall: false,\n isIncoming: isBuy,\n isOutgoing: !isBuy,\n isSender: !isBuy,\n timestamp: timeMs,\n hash: fill.hash,\n from: '',\n to: '',\n tokens: [token],\n gasUsed: '0',\n txType: TransactionType.FILL_ORDER,\n method: encodeHypercoreFillMethod({\n dir: fill.dir ?? '',\n px: fill.px,\n closedPnl: fill.closedPnl,\n coin: fill.coin,\n }),\n chainId: chainIdForNetwork(network),\n explorerLink: explorerTxLink(network, fill.hash),\n };\n};\n\nconst mapLedgerToTransaction = (\n update: HypercoreLedgerUpdate,\n evmAddress: string,\n network: Pick<Network, 'explorerUrl' | 'caipId' | 'chainId'>,\n): Transaction => {\n const display = getHypercoreLedgerDisplay(update, evmAddress);\n const isIncoming = display.direction === 'positive';\n const isOutgoing = display.direction === 'negative';\n\n let txType: TransactionType = TransactionType.TRANSFER;\n switch (display.label) {\n case 'deposit':\n case 'received':\n txType = TransactionType.RECEIVE;\n break;\n case 'withdraw':\n case 'sent':\n txType = TransactionType.SEND;\n break;\n case 'liquidation':\n txType = TransactionType.UNKNOWN;\n break;\n default:\n txType = TransactionType.TRANSFER;\n }\n\n const amount = display.amount || '0';\n const token: TxToken = {\n type: TokenType.NATIVE,\n name: display.symbol,\n symbol: display.symbol,\n amount,\n imageUri: hyperliquidCoinSvgUrl(display.symbol),\n };\n\n return {\n isContractCall: false,\n isIncoming,\n isOutgoing,\n isSender: isOutgoing,\n timestamp: toTimeMs(update.time),\n hash: update.hash,\n from: display.from ?? (isOutgoing ? evmAddress : ''),\n to: display.to ?? (isIncoming ? evmAddress : ''),\n tokens: [token],\n gasUsed: '0',\n txType,\n chainId: chainIdForNetwork(network),\n explorerLink: explorerTxLink(network, update.hash),\n };\n};\n\nexport const mapHypercoreActivityToTransactions = (\n items: readonly HypercoreActivityItem[],\n evmAddress: string,\n network: Pick<Network, 'explorerUrl' | 'caipId' | 'chainId'>,\n): Transaction[] =>\n items.map((item) =>\n item.kind === 'fill'\n ? mapFillToTransaction(item.fill, item.timeMs, network)\n : mapLedgerToTransaction(item.update, evmAddress, network),\n );\n","import type { HypercoreLedgerUpdate } from '../schemas';\n\n/**\n * Semantic label key for a ledger row.\n */\nexport type HypercoreLedgerLabel =\n | 'deposit'\n | 'withdraw'\n | 'sent'\n | 'received'\n | 'transferToPerp'\n | 'transferToSpot'\n | 'transfer'\n | 'liquidation'\n | 'other';\n\nexport type HypercoreLedgerDisplay = {\n readonly label: HypercoreLedgerLabel;\n /** Unsigned token amount, e.g. `0.1`. */\n readonly amount: string;\n readonly symbol: string;\n /** Signed USD value for the fiat line; undefined when there's nothing to show. */\n readonly usdValue?: number;\n readonly direction: 'positive' | 'negative' | 'neutral';\n readonly from?: string;\n readonly to?: string;\n readonly rawType: string;\n};\n\nconst formatAmount = (value: string | undefined) => {\n if (value === undefined || value === '') {\n return '';\n }\n const parsed = Number.parseFloat(value);\n if (!Number.isFinite(parsed)) {\n return value;\n }\n return new Intl.NumberFormat('en-US', { maximumFractionDigits: 6 }).format(parsed);\n};\n\nconst toUsd = (value: string | undefined, sign: 1 | -1 | 0) => {\n if (value === undefined || value === '') {\n return undefined;\n }\n const parsed = Number.parseFloat(value);\n return Number.isFinite(parsed) ? parsed * (sign === 0 ? 1 : sign) : undefined;\n};\n\n/**\n * Derives label, amount, signed USD value, and counterparties for a HyperCore\n * ledger update from the owner's perspective.\n */\nexport const getHypercoreLedgerDisplay = (\n update: HypercoreLedgerUpdate,\n evmAddress: string,\n): HypercoreLedgerDisplay => {\n const { delta } = update;\n const owner = evmAddress.toLowerCase();\n const isOutgoing = delta.user?.toLowerCase() === owner;\n\n switch (delta.type) {\n case 'deposit':\n return {\n label: 'deposit',\n amount: formatAmount(delta.usdc),\n symbol: 'USDC',\n usdValue: toUsd(delta.usdc, 1),\n direction: 'positive',\n to: evmAddress,\n rawType: delta.type,\n };\n case 'withdraw':\n return {\n label: 'withdraw',\n amount: formatAmount(delta.usdc),\n symbol: 'USDC',\n usdValue: toUsd(delta.usdc, -1),\n direction: 'negative',\n from: evmAddress,\n rawType: delta.type,\n };\n case 'send':\n case 'spotTransfer':\n return {\n label: isOutgoing ? 'sent' : 'received',\n amount: formatAmount(delta.amount),\n symbol: delta.token ?? 'USDC',\n usdValue: toUsd(delta.usdcValue, isOutgoing ? -1 : 1),\n direction: isOutgoing ? 'negative' : 'positive',\n from: delta.user,\n to: delta.destination,\n rawType: delta.type,\n };\n case 'internalTransfer':\n return {\n label: 'transfer',\n amount: formatAmount(delta.usdc),\n symbol: 'USDC',\n usdValue: toUsd(delta.usdc, isOutgoing ? -1 : 1),\n direction: isOutgoing ? 'negative' : 'positive',\n from: delta.user,\n to: delta.destination,\n rawType: delta.type,\n };\n case 'accountClassTransfer':\n return {\n label: delta.toPerp ? 'transferToPerp' : 'transferToSpot',\n amount: formatAmount(delta.usdc),\n symbol: 'USDC',\n usdValue: toUsd(delta.usdc, 0),\n direction: 'neutral',\n rawType: delta.type,\n };\n case 'liquidation':\n return {\n label: 'liquidation',\n amount: formatAmount(delta.usdcValue ?? delta.usdc),\n symbol: 'USDC',\n usdValue: toUsd(delta.usdcValue ?? delta.usdc, -1),\n direction: 'negative',\n rawType: delta.type,\n };\n default:\n return {\n label: 'other',\n amount: formatAmount(delta.usdcValue ?? delta.usdc),\n symbol: 'USDC',\n usdValue: toUsd(delta.usdcValue ?? delta.usdc, 0),\n direction: 'neutral',\n rawType: delta.type,\n };\n }\n};\n","const METHOD_PREFIX = 'hypercoreFill:v1:';\n\nexport type HypercoreFillMeta = {\n /** Fill side / action from Hyperliquid (`Open Long`, `Close Short`, …). */\n readonly dir: string;\n /** Fill price as a decimal string (Hyperliquid `px`). */\n readonly px: string;\n /** Realized PnL for the fill as a decimal string; `\"0\"` when none. */\n readonly closedPnl: string;\n /** Market coin id (`ETH`, or HIP-3 `dex:TICKER`). */\n readonly coin: string;\n};\n\nexport type FillLabel = {\n readonly text: string;\n /** Long / short cue for the UI to pick an icon. */\n readonly direction?: 'up' | 'down';\n readonly tone?: 'profit' | 'loss';\n};\n\n/** Display ticker with any `dex:` prefix stripped (`xyz:GOLD` → `GOLD`). */\nexport const tickerOfCoin = (coin: string) => {\n const i = coin.indexOf(':');\n return i === -1 ? coin : coin.slice(i + 1);\n};\n\n/** PnL tone from `closedPnl` — `dir` alone does not indicate profit vs loss. */\nexport const closedPnlTone = (closedPnl: string | undefined): 'profit' | 'loss' | undefined => {\n if (closedPnl === undefined) {\n return undefined;\n }\n const n = Number.parseFloat(closedPnl);\n if (!Number.isFinite(n) || n === 0) {\n return undefined;\n }\n return n > 0 ? 'profit' : 'loss';\n};\n\n/**\n * Map a fill's `dir` into a display label. Direction follows side\n * (long → up / short → down); success/error tone comes from `closedPnl` when provided.\n */\nexport const fillLabel = (dir: string, closedPnl?: string): FillLabel => {\n const tone = closedPnlTone(closedPnl);\n const d = dir.toLowerCase();\n if (d.includes('close') && d.includes('long')) {\n return { text: 'Long closed', direction: 'up', tone };\n }\n if (d.includes('close') && d.includes('short')) {\n return { text: 'Short closed', direction: 'down', tone };\n }\n if (d.includes('open') && (d.includes('long') || d.includes('short'))) {\n return { text: 'Order opened' };\n }\n if (d.includes('cancel')) {\n return { text: 'Order cancelled' };\n }\n return { text: dir };\n};\n\n/** Compact USD price for fill rows (`$1,684.7`). */\nexport const formatHypercoreFillPx = (px: string) => {\n const n = Number.parseFloat(px);\n if (!Number.isFinite(n)) {\n return px;\n }\n return `$${n.toLocaleString(undefined, { maximumFractionDigits: 8 })}`;\n};\n\nexport const encodeHypercoreFillMethod = (meta: HypercoreFillMeta) =>\n `${METHOD_PREFIX}${encodeURIComponent(JSON.stringify(meta))}`;\n\nexport const parseHypercoreFillMethod = (method: string | undefined): HypercoreFillMeta | undefined => {\n if (!method?.startsWith(METHOD_PREFIX)) {\n return undefined;\n }\n try {\n const parsed: unknown = JSON.parse(decodeURIComponent(method.slice(METHOD_PREFIX.length)));\n if (\n typeof parsed !== 'object' ||\n parsed === null ||\n !('dir' in parsed) ||\n !('px' in parsed) ||\n !('closedPnl' in parsed) ||\n !('coin' in parsed)\n ) {\n return undefined;\n }\n const { dir, px, closedPnl, coin } = parsed as Record<string, unknown>;\n if (\n typeof dir !== 'string' ||\n typeof px !== 'string' ||\n typeof closedPnl !== 'string' ||\n typeof coin !== 'string'\n ) {\n return undefined;\n }\n return { dir, px, closedPnl, coin };\n } catch {\n return undefined;\n }\n};\n","import type { GetTransactionHistory, TransactionHistoryResponse } from '@avalabs/vm-module-types';\nimport type { HypercoreInfoClient } from '../../utils/info-client';\nimport { fetchHypercoreActivity } from '../../utils/activity/fetch-hypercore-activity';\nimport { mapHypercoreActivityToTransactions } from '../../utils/activity/map-hypercore-activity-to-transactions';\n\nexport const getTransactionHistory = async ({\n address,\n network,\n infoClient,\n}: GetTransactionHistory & {\n infoClient: HypercoreInfoClient;\n}): Promise<TransactionHistoryResponse> => {\n const items = await fetchHypercoreActivity(infoClient, address);\n return {\n transactions: mapHypercoreActivityToTransactions(items, address, network),\n };\n};\n","import { NetworkVMType, WalletType, type GetAddressParams, type GetAddressResponse } from '@avalabs/vm-module-types';\nimport { getAddressFromXPub, getEvmAddressFromPubKey } from '@avalabs/core-wallets-sdk';\nimport { rpcErrors } from '@metamask/rpc-errors';\n\ntype GetAddress = Omit<GetAddressParams, 'isTestnet' | 'xpubXP' | 'network'>;\n\nexport const getAddress = async ({ accountIndex, xpub, walletType }: GetAddress): Promise<GetAddressResponse> => {\n switch (walletType) {\n case WalletType.Mnemonic:\n case WalletType.Ledger:\n case WalletType.Keystone: {\n return {\n [NetworkVMType.HYPERCORE]: getAddressFromXPub(xpub, accountIndex),\n };\n }\n case WalletType.LedgerLive:\n case WalletType.Seedless: {\n const pubKeyBuffer = Buffer.from(xpub, 'hex');\n return {\n [NetworkVMType.HYPERCORE]: getEvmAddressFromPubKey(pubKeyBuffer),\n };\n }\n default:\n throw rpcErrors.invalidParams(`Unsupported wallet type: ${walletType}`);\n }\n};\n","import {\n NetworkVMType,\n type ApprovalController,\n type DeriveAddressParams,\n type DeriveAddressResponse,\n} from '@avalabs/vm-module-types';\nimport { computeAddress } from 'ethers';\nimport { hasDerivationDetails } from '@internal/utils/src/utils/address-derivation';\nimport { buildDerivationPath } from '../build-derivation-path/build-derivation-path';\n\nexport const deriveAddress = async (\n params: DeriveAddressParams & { approvalController: ApprovalController },\n): Promise<DeriveAddressResponse> => {\n const { secretId, approvalController } = params;\n\n // Narrow before calling buildDerivationPath — the type guard alone is not\n // enough when `params` is intersected with `{ approvalController }`.\n const derivationPath = hasDerivationDetails(params)\n ? buildDerivationPath({\n accountIndex: params.accountIndex,\n derivationPathType: params.derivationPathType,\n addressIndex: params.addressIndex,\n }).HYPERCORE\n : undefined;\n const publicKeyHex = await approvalController.requestPublicKey({\n curve: 'secp256k1',\n secretId,\n derivationPath,\n });\n\n return {\n [NetworkVMType.HYPERCORE]: computeAddress(`0x${publicKeyHex}`),\n };\n};\n","import type { DeriveAddressParams, DetailedDeriveAddressParams } from '@avalabs/vm-module-types';\n\nexport const hasDerivationDetails = (params: DeriveAddressParams): params is DetailedDeriveAddressParams =>\n 'derivationPathType' in params &&\n 'accountIndex' in params &&\n typeof params.accountIndex === 'number' &&\n typeof params.derivationPathType === 'string';\n","import { rpcErrors } from '@metamask/rpc-errors';\nimport {\n NetworkVMType,\n type BuildDerivationPathParams,\n type BuildDerivationPathResponse,\n} from '@avalabs/vm-module-types';\n\n/**\n * HyperCore identity is an EVM address (cointype 60). Paths match the EVM module;\n * the result is keyed as `HYPERCORE`.\n */\nexport const buildDerivationPath = ({\n accountIndex,\n derivationPathType,\n}: BuildDerivationPathParams): Pick<BuildDerivationPathResponse, NetworkVMType.HYPERCORE> => {\n if (accountIndex < 0) {\n throw rpcErrors.invalidParams('Account index must be a non-negative integer');\n }\n\n switch (derivationPathType) {\n case 'bip44':\n return {\n [NetworkVMType.HYPERCORE]: `m/44'/60'/0'/0/${accountIndex}`,\n };\n\n case 'ledger_live':\n return {\n [NetworkVMType.HYPERCORE]: `m/44'/60'/${accountIndex}'/0/0`,\n };\n\n default:\n throw rpcErrors.invalidParams(`Unsupported derivation path type: ${derivationPathType}`);\n }\n};\n","import {\n NetworkVMType,\n type ApprovalController,\n type DeriveAddressesParams,\n type DeriveAddressesResponse,\n} from '@avalabs/vm-module-types';\nimport { deriveAddressesForEvm, init } from '@avalabs/crypto-sdk';\nimport { buildDerivationPath } from '../build-derivation-path/build-derivation-path';\n\nexport const deriveAddresses = async (\n params: DeriveAddressesParams & { approvalController: ApprovalController },\n): Promise<DeriveAddressesResponse> => {\n const { approvalController, secretId, accountIndices, derivationPathType } = params;\n\n if (accountIndices.length === 0) {\n return [];\n }\n\n await init();\n\n const publicKeys = await Promise.all(\n accountIndices.map(async (accountIndex) => {\n const derivationPath = buildDerivationPath({ accountIndex, derivationPathType }).HYPERCORE;\n const publicKeyHex = await approvalController.requestPublicKey({\n curve: 'secp256k1',\n secretId,\n derivationPath,\n });\n return Uint8Array.from(Buffer.from(publicKeyHex, 'hex'));\n }),\n );\n\n const addresses = await deriveAddressesForEvm(publicKeys);\n\n return addresses.map((address) => ({ [NetworkVMType.HYPERCORE]: address }));\n};\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@avalabs/hypercore-module",
3
- "version": "3.10.0",
3
+ "version": "3.12.0",
4
4
  "repository": {
5
5
  "type": "git",
6
6
  "url": "https://github.com/ava-labs/core-vm-modules",
@@ -15,37 +15,33 @@
15
15
  "manifest.json"
16
16
  ],
17
17
  "license": "Limited Ecosystem License",
18
- "scripts": {
19
- "build": "tsup",
20
- "dev": "tsup --watch",
21
- "lint": "eslint \"src/**/*.ts\"",
22
- "test": "jest",
23
- "test:watch": "jest --watch"
24
- },
25
18
  "dependencies": {
26
19
  "@avalabs/core-wallets-sdk": "3.1.0-alpha.87",
27
20
  "@avalabs/crypto-sdk": "1.0.0",
28
- "@avalabs/vm-module-types": "workspace:*",
29
21
  "@metamask/rpc-errors": "6.3.0",
30
22
  "big.js": "6.2.1",
31
- "zod": "3.23.8"
23
+ "zod": "3.23.8",
24
+ "@avalabs/vm-module-types": "3.12.0"
32
25
  },
33
26
  "devDependencies": {
34
- "@internal/tsup-config": "workspace:*",
35
- "@internal/utils": "workspace:*",
36
27
  "@types/big.js": "6.2.2",
37
28
  "@types/jest": "29.5.7",
38
- "eslint-config-custom": "workspace:*",
39
29
  "ethers": "6.13.5",
40
30
  "jest": "29.7.0",
41
31
  "ts-jest": "29.1.1",
42
- "tsup": "7.2.0"
32
+ "tsup": "7.2.0",
33
+ "@internal/tsup-config": "0.1.1",
34
+ "@internal/utils": "0.8.0",
35
+ "eslint-config-custom": "0.1.0"
43
36
  },
44
37
  "peerDependencies": {
45
38
  "ethers": "6.13.5"
46
39
  },
47
- "volta": {
48
- "node": "20.11.0",
49
- "yarn": "1.22.19"
40
+ "scripts": {
41
+ "build": "tsup",
42
+ "dev": "tsup --watch",
43
+ "lint": "eslint \"src/**/*.ts\"",
44
+ "test": "jest",
45
+ "test:watch": "jest --watch"
50
46
  }
51
- }
47
+ }