@continuumdao/ctm-mpc-defi 0.2.22 → 0.2.25

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.
Files changed (43) hide show
  1. package/dist/agent/catalog.cjs +806 -18
  2. package/dist/agent/catalog.cjs.map +1 -1
  3. package/dist/agent/catalog.d.ts +2400 -43
  4. package/dist/agent/catalog.js +772 -19
  5. package/dist/agent/catalog.js.map +1 -1
  6. package/dist/agent/skills/arcus/SKILL.md +72 -0
  7. package/dist/agent/skills/gmx/SKILL.md +32 -0
  8. package/dist/agent/skills/hyperliquid/SKILL.md +44 -3
  9. package/dist/agent/skills/uniswap-v4/SKILL.md +31 -1
  10. package/dist/core/index.cjs +55 -0
  11. package/dist/core/index.cjs.map +1 -1
  12. package/dist/core/index.d.ts +15 -21
  13. package/dist/core/index.js +54 -1
  14. package/dist/core/index.js.map +1 -1
  15. package/dist/eip712Multisign-xhXpUYp3.d.ts +36 -0
  16. package/dist/index.cjs +399 -12
  17. package/dist/index.cjs.map +1 -1
  18. package/dist/index.d.ts +2 -1
  19. package/dist/index.js +398 -13
  20. package/dist/index.js.map +1 -1
  21. package/dist/protocols/evm/arcus/index.cjs +2061 -0
  22. package/dist/protocols/evm/arcus/index.cjs.map +1 -0
  23. package/dist/protocols/evm/arcus/index.d.ts +726 -0
  24. package/dist/protocols/evm/arcus/index.js +1964 -0
  25. package/dist/protocols/evm/arcus/index.js.map +1 -0
  26. package/dist/protocols/evm/gmx/index.cjs +39 -0
  27. package/dist/protocols/evm/gmx/index.cjs.map +1 -1
  28. package/dist/protocols/evm/gmx/index.d.ts +21 -1
  29. package/dist/protocols/evm/gmx/index.js +38 -1
  30. package/dist/protocols/evm/gmx/index.js.map +1 -1
  31. package/dist/protocols/evm/hyperliquid/index.cjs +478 -208
  32. package/dist/protocols/evm/hyperliquid/index.cjs.map +1 -1
  33. package/dist/protocols/evm/hyperliquid/index.d.ts +166 -51
  34. package/dist/protocols/evm/hyperliquid/index.js +467 -210
  35. package/dist/protocols/evm/hyperliquid/index.js.map +1 -1
  36. package/dist/protocols/evm/permit2/index.cjs.map +1 -1
  37. package/dist/protocols/evm/permit2/index.js.map +1 -1
  38. package/dist/protocols/evm/uniswap-v4/index.cjs +734 -15
  39. package/dist/protocols/evm/uniswap-v4/index.cjs.map +1 -1
  40. package/dist/protocols/evm/uniswap-v4/index.d.ts +189 -17
  41. package/dist/protocols/evm/uniswap-v4/index.js +698 -16
  42. package/dist/protocols/evm/uniswap-v4/index.js.map +1 -1
  43. package/package.json +6 -1
@@ -1,4 +1,4 @@
1
- import { parseAbi, encodeAbiParameters, getAddress, keccak256, parseUnits, encodeFunctionData, hashTypedData, defineChain, createPublicClient, http, parseGwei, serializeTransaction, stringToHex } from 'viem';
1
+ import { parseAbi, encodeAbiParameters, keccak256, getAddress, parseUnits, encodeFunctionData, hashTypedData, defineChain, createPublicClient, http, parseGwei, serializeTransaction, stringToHex } from 'viem';
2
2
  import { fetchChainFeeParams, gasLimitFromEstimateAndChainConfig, gweiToDecimalString, proposalTxParamsToFeeSnapshot, alignEip1559FeesWithLatestBase, getClientIdFromKeyGenResult } from '@continuumdao/continuum-node-sdk';
3
3
  import { encode } from '@msgpack/msgpack';
4
4
 
@@ -346,6 +346,12 @@ async function hyperliquidFetchOpenOrders(args) {
346
346
  const orders = await hyperliquidInfoPost(args.chainId, req);
347
347
  return { orders: orders ?? [] };
348
348
  }
349
+ async function hyperliquidFetchFrontendOpenOrders(args) {
350
+ const req = { type: "frontendOpenOrders", user: args.user };
351
+ if (args.dex?.trim()) req.dex = args.dex.trim();
352
+ const orders = await hyperliquidInfoPost(args.chainId, req);
353
+ return { orders: orders ?? [] };
354
+ }
349
355
  async function hyperliquidFetchUserVaultEquities(args) {
350
356
  const rows = await hyperliquidInfoPost(args.chainId, {
351
357
  type: "userVaultEquities",
@@ -1157,8 +1163,404 @@ async function buildEvmMultisignBatch(args) {
1157
1163
  }
1158
1164
  return result;
1159
1165
  }
1166
+ var EIP712_SIGN_REQUEST_KIND = "eip712";
1167
+ function msgHashNo0x(digest) {
1168
+ return digest.startsWith("0x") ? digest.slice(2) : digest;
1169
+ }
1170
+ function eip712SignatureText(domain, primaryType) {
1171
+ return JSON.stringify({
1172
+ kind: "EIP-712",
1173
+ ...typeof domain.name === "string" ? { name: domain.name } : {},
1174
+ primaryType
1175
+ });
1176
+ }
1177
+ function jsonStringifyForAudit(value) {
1178
+ return JSON.stringify(value, (_, v) => typeof v === "bigint" ? v.toString() : v);
1179
+ }
1180
+ function eip712MsgRawHex(typedData, delivery) {
1181
+ const envelope = {
1182
+ version: 1,
1183
+ ...typedData,
1184
+ delivery
1185
+ };
1186
+ return stringToHex(jsonStringifyForAudit(envelope));
1187
+ }
1188
+ function buildEip712MultisignBody(args) {
1189
+ const { typedData, delivery } = args;
1190
+ const digest = hashTypedData({
1191
+ domain: typedData.domain,
1192
+ types: typedData.types,
1193
+ primaryType: typedData.primaryType,
1194
+ message: typedData.message
1195
+ });
1196
+ const extraJSON = {
1197
+ signRequestKind: EIP712_SIGN_REQUEST_KIND,
1198
+ eip712: {
1199
+ version: 1,
1200
+ digest,
1201
+ domain: typedData.domain,
1202
+ types: typedData.types,
1203
+ primaryType: typedData.primaryType,
1204
+ message: typedData.message
1205
+ },
1206
+ delivery
1207
+ };
1208
+ return finalizeMultisign({
1209
+ keyGen: args.keyGen,
1210
+ purposeText: args.purposeText,
1211
+ purposeSuffix: args.purposeSuffix,
1212
+ destinationChainID: args.destinationChainID,
1213
+ destinationAddress: args.destinationAddress,
1214
+ extraJSON,
1215
+ expiryDate: args.expiryDate,
1216
+ legs: [
1217
+ {
1218
+ msgHash: msgHashNo0x(digest),
1219
+ msgRaw: eip712MsgRawHex(typedData, delivery),
1220
+ destinationAddress: args.destinationAddress,
1221
+ signatureText: eip712SignatureText(typedData.domain, typedData.primaryType),
1222
+ audit: {
1223
+ kind: "EIP712",
1224
+ primaryType: typedData.primaryType,
1225
+ deliveryKind: delivery.kind,
1226
+ ...args.audit ?? {}
1227
+ },
1228
+ feeSnapshot: {}
1229
+ }
1230
+ ]
1231
+ });
1232
+ }
1233
+ var EXCHANGE_DOMAIN = {
1234
+ name: "Exchange",
1235
+ version: "1",
1236
+ chainId: 1337,
1237
+ verifyingContract: "0x0000000000000000000000000000000000000000"
1238
+ };
1239
+ var AGENT_TYPES = {
1240
+ Agent: [
1241
+ { name: "source", type: "string" },
1242
+ { name: "connectionId", type: "bytes32" }
1243
+ ]
1244
+ };
1245
+ function adjustMsgpackValue(value) {
1246
+ if (Array.isArray(value)) return value.map(adjustMsgpackValue);
1247
+ if (typeof value === "object" && value !== null) {
1248
+ const result = {};
1249
+ for (const key of Object.keys(value)) {
1250
+ const entry = value[key];
1251
+ if (entry !== void 0) result[key] = adjustMsgpackValue(entry);
1252
+ }
1253
+ return result;
1254
+ }
1255
+ if (typeof value === "number" && Number.isInteger(value) && (value >= 4294967296 || value < -2147483648)) {
1256
+ return BigInt(value);
1257
+ }
1258
+ return value;
1259
+ }
1260
+ function toUint64Bytes(n) {
1261
+ const bytes = new Uint8Array(8);
1262
+ new DataView(bytes.buffer).setBigUint64(0, BigInt(n));
1263
+ return bytes;
1264
+ }
1265
+ function concatBytes(...parts) {
1266
+ const total = parts.reduce((sum, p) => sum + p.length, 0);
1267
+ const out = new Uint8Array(total);
1268
+ let offset = 0;
1269
+ for (const p of parts) {
1270
+ out.set(p, offset);
1271
+ offset += p.length;
1272
+ }
1273
+ return out;
1274
+ }
1275
+ function hexToBytes(hex) {
1276
+ const h = hex.startsWith("0x") ? hex.slice(2) : hex;
1277
+ const bytes = new Uint8Array(h.length / 2);
1278
+ for (let i = 0; i < bytes.length; i++) {
1279
+ bytes[i] = parseInt(h.slice(i * 2, i * 2 + 2), 16);
1280
+ }
1281
+ return bytes;
1282
+ }
1283
+ function createHyperliquidL1ActionHash(args) {
1284
+ const { action, nonce, vaultAddress, expiresAfter } = args;
1285
+ const actionBytes = encode(adjustMsgpackValue(action));
1286
+ const nonceBytes = toUint64Bytes(nonce);
1287
+ const vaultMarker = vaultAddress ? new Uint8Array([1]) : new Uint8Array([0]);
1288
+ const vaultBytes = vaultAddress ? hexToBytes(vaultAddress) : new Uint8Array();
1289
+ const expiresMarker = expiresAfter !== void 0 ? new Uint8Array([0]) : new Uint8Array();
1290
+ const expiresBytes = expiresAfter !== void 0 ? toUint64Bytes(expiresAfter) : new Uint8Array();
1291
+ const bytes = concatBytes(actionBytes, nonceBytes, vaultMarker, vaultBytes, expiresMarker, expiresBytes);
1292
+ return keccak256(bytes);
1293
+ }
1294
+ function buildHyperliquidAgentTypedData(args) {
1295
+ const connectionId = createHyperliquidL1ActionHash(args);
1296
+ const source = args.isTestnet ? "b" : "a";
1297
+ return {
1298
+ domain: EXCHANGE_DOMAIN,
1299
+ types: AGENT_TYPES,
1300
+ primaryType: "Agent",
1301
+ message: {
1302
+ source,
1303
+ connectionId
1304
+ },
1305
+ connectionId,
1306
+ nonce: args.nonce,
1307
+ action: args.action
1308
+ };
1309
+ }
1310
+ function buildHyperliquidUpdateLeverageAction(args) {
1311
+ const leverage = Math.trunc(args.leverage);
1312
+ if (!Number.isFinite(leverage) || leverage < 1) {
1313
+ throw new Error("leverage must be a positive integer");
1314
+ }
1315
+ return {
1316
+ type: "updateLeverage",
1317
+ asset: args.asset,
1318
+ isCross: args.isCross !== false,
1319
+ leverage
1320
+ };
1321
+ }
1322
+ function hyperliquidFloatToWire(value) {
1323
+ const n = typeof value === "number" ? value : Number.parseFloat(String(value).trim());
1324
+ if (!Number.isFinite(n)) throw new Error("Invalid Hyperliquid wire number.");
1325
+ const rounded = n.toFixed(8);
1326
+ if (Math.abs(Number.parseFloat(rounded) - n) >= 1e-12) {
1327
+ throw new Error(`Hyperliquid wire value ${value} has too many decimal places.`);
1328
+ }
1329
+ const normalized = Number(rounded === "-0" ? "0" : rounded);
1330
+ return String(normalized);
1331
+ }
1332
+ function hyperliquidL1TifFromKey(tif) {
1333
+ const key = String(tif ?? "gtc").trim().toLowerCase();
1334
+ if (key === "alo") return "Alo";
1335
+ if (key === "ioc") return "Ioc";
1336
+ if (key === "gtc") return "Gtc";
1337
+ throw new Error(`Unknown time-in-force: ${tif}. Use alo, gtc, or ioc.`);
1338
+ }
1339
+ function buildHyperliquidLimitOrderWire(args) {
1340
+ return {
1341
+ a: args.asset,
1342
+ b: args.isBuy,
1343
+ p: hyperliquidFloatToWire(args.limitPxHuman),
1344
+ s: hyperliquidFloatToWire(args.szHuman),
1345
+ r: Boolean(args.reduceOnly),
1346
+ t: { limit: { tif: hyperliquidL1TifFromKey(args.tif) } }
1347
+ };
1348
+ }
1349
+ function buildHyperliquidTriggerOrderWire(args) {
1350
+ const mode = args.tpslExecMode ?? "limit_at_trigger";
1351
+ const triggerPx = hyperliquidFloatToWire(args.triggerPxHuman);
1352
+ const limitPx = mode === "market" ? triggerPx : hyperliquidFloatToWire(args.limitPxHuman ?? args.triggerPxHuman);
1353
+ return {
1354
+ a: args.asset,
1355
+ b: args.isBuy,
1356
+ p: limitPx,
1357
+ s: hyperliquidFloatToWire(args.szHuman),
1358
+ r: true,
1359
+ t: {
1360
+ trigger: {
1361
+ isMarket: mode === "market",
1362
+ triggerPx,
1363
+ tpsl: args.tpsl
1364
+ }
1365
+ }
1366
+ };
1367
+ }
1368
+ function validateHyperliquidTpslGeometry(args) {
1369
+ const entry = Number.parseFloat(String(args.entryPxHuman).trim());
1370
+ const tp = args.takeProfitTriggerPxHuman?.trim() != null && args.takeProfitTriggerPxHuman.trim() !== "" ? Number.parseFloat(args.takeProfitTriggerPxHuman.trim()) : null;
1371
+ const sl = args.stopLossTriggerPxHuman?.trim() != null && args.stopLossTriggerPxHuman.trim() !== "" ? Number.parseFloat(args.stopLossTriggerPxHuman.trim()) : null;
1372
+ if (!Number.isFinite(entry)) throw new Error("Invalid entry limit price for TP/SL validation.");
1373
+ if (tp != null && !Number.isFinite(tp)) throw new Error("Invalid take-profit trigger price.");
1374
+ if (sl != null && !Number.isFinite(sl)) throw new Error("Invalid stop-loss trigger price.");
1375
+ if (args.isBuy) {
1376
+ if (sl != null && sl >= entry) {
1377
+ throw new Error("Long stop-loss must be below entry price.");
1378
+ }
1379
+ if (tp != null && tp <= entry) {
1380
+ throw new Error("Long take-profit must be above entry price.");
1381
+ }
1382
+ } else {
1383
+ if (sl != null && sl <= entry) {
1384
+ throw new Error("Short stop-loss must be above entry price.");
1385
+ }
1386
+ if (tp != null && tp >= entry) {
1387
+ throw new Error("Short take-profit must be below entry price.");
1388
+ }
1389
+ }
1390
+ }
1391
+ function buildHyperliquidNormalTpslOrderWires(args) {
1392
+ validateHyperliquidTpslGeometry({
1393
+ isBuy: args.isBuy,
1394
+ entryPxHuman: args.limitPxHuman,
1395
+ takeProfitTriggerPxHuman: args.takeProfitTriggerPxHuman,
1396
+ stopLossTriggerPxHuman: args.stopLossTriggerPxHuman
1397
+ });
1398
+ const orders = [
1399
+ buildHyperliquidLimitOrderWire({
1400
+ asset: args.asset,
1401
+ isBuy: args.isBuy,
1402
+ limitPxHuman: args.limitPxHuman,
1403
+ szHuman: args.szHuman,
1404
+ tif: args.tif
1405
+ })
1406
+ ];
1407
+ const closeIsBuy = !args.isBuy;
1408
+ const tp = args.takeProfitTriggerPxHuman?.trim();
1409
+ const sl = args.stopLossTriggerPxHuman?.trim();
1410
+ if (tp) {
1411
+ orders.push(
1412
+ buildHyperliquidTriggerOrderWire({
1413
+ asset: args.asset,
1414
+ isBuy: closeIsBuy,
1415
+ szHuman: args.szHuman,
1416
+ triggerPxHuman: tp,
1417
+ tpsl: "tp",
1418
+ tpslExecMode: args.tpslExecMode
1419
+ })
1420
+ );
1421
+ }
1422
+ if (sl) {
1423
+ orders.push(
1424
+ buildHyperliquidTriggerOrderWire({
1425
+ asset: args.asset,
1426
+ isBuy: closeIsBuy,
1427
+ szHuman: args.szHuman,
1428
+ triggerPxHuman: sl,
1429
+ tpsl: "sl",
1430
+ tpslExecMode: args.tpslExecMode
1431
+ })
1432
+ );
1433
+ }
1434
+ return orders;
1435
+ }
1436
+ function buildHyperliquidOrderAction(args) {
1437
+ return {
1438
+ type: "order",
1439
+ orders: args.orders,
1440
+ grouping: args.grouping ?? "na"
1441
+ };
1442
+ }
1443
+
1444
+ // src/protocols/evm/hyperliquid/exchangeMultisign.ts
1445
+ var ZERO_ADDRESS = "0x0000000000000000000000000000000000000000";
1446
+ async function buildHyperliquidLimitOrderWithTpslMultisign(args) {
1447
+ const marketKind = args.marketKind ?? "perp";
1448
+ const { asset } = await hyperliquidResolveAsset({
1449
+ chainId: args.chainId,
1450
+ coin: args.coin,
1451
+ marketKind,
1452
+ dex: args.dex
1453
+ });
1454
+ const tp = args.takeProfitTriggerPxHuman?.trim();
1455
+ const sl = args.stopLossTriggerPxHuman?.trim();
1456
+ if (!tp && !sl) {
1457
+ throw new Error("At least one of takeProfitTriggerPxHuman or stopLossTriggerPxHuman is required for bracket orders.");
1458
+ }
1459
+ const orderWires = buildHyperliquidNormalTpslOrderWires({
1460
+ asset,
1461
+ isBuy: args.isBuy,
1462
+ limitPxHuman: args.limitPxHuman,
1463
+ szHuman: args.szHuman,
1464
+ tif: args.tif,
1465
+ takeProfitTriggerPxHuman: tp || void 0,
1466
+ stopLossTriggerPxHuman: sl || void 0,
1467
+ tpslExecMode: args.tpslExecMode
1468
+ });
1469
+ const action = buildHyperliquidOrderAction({
1470
+ orders: orderWires,
1471
+ grouping: "normalTpsl"
1472
+ });
1473
+ const nonce = args.nonce ?? Date.now();
1474
+ const isTestnet = args.chainId === 998;
1475
+ const typed = buildHyperliquidAgentTypedData({ action, nonce, isTestnet });
1476
+ return buildEip712MultisignBody({
1477
+ keyGen: args.keyGen,
1478
+ purposeText: args.purposeText,
1479
+ destinationChainID: String(args.chainId),
1480
+ destinationAddress: ZERO_ADDRESS,
1481
+ typedData: {
1482
+ domain: typed.domain,
1483
+ types: typed.types,
1484
+ primaryType: typed.primaryType,
1485
+ message: typed.message
1486
+ },
1487
+ delivery: {
1488
+ kind: "hyperliquid_exchange",
1489
+ chainId: args.chainId,
1490
+ isTestnet,
1491
+ action,
1492
+ nonce
1493
+ },
1494
+ audit: {
1495
+ protocol: "hyperliquid",
1496
+ action: "limitOrderWithTpsl",
1497
+ coin: args.coin,
1498
+ marketKind,
1499
+ asset,
1500
+ isBuy: args.isBuy,
1501
+ limitPxHuman: args.limitPxHuman,
1502
+ szHuman: args.szHuman,
1503
+ takeProfitTriggerPxHuman: tp ?? null,
1504
+ stopLossTriggerPxHuman: sl ?? null,
1505
+ tpslExecMode: args.tpslExecMode ?? "limit_at_trigger",
1506
+ grouping: "normalTpsl",
1507
+ nonce,
1508
+ connectionId: typed.connectionId
1509
+ }
1510
+ });
1511
+ }
1512
+ async function buildHyperliquidUpdateLeverageMultisign(args) {
1513
+ const marketKind = args.marketKind ?? "perp";
1514
+ const { asset } = await hyperliquidResolveAsset({
1515
+ chainId: args.chainId,
1516
+ coin: args.coin,
1517
+ marketKind,
1518
+ dex: args.dex
1519
+ });
1520
+ const action = buildHyperliquidUpdateLeverageAction({
1521
+ asset,
1522
+ leverage: args.leverage,
1523
+ isCross: args.isCross
1524
+ });
1525
+ const nonce = args.nonce ?? Date.now();
1526
+ const isTestnet = args.chainId === 998;
1527
+ const typed = buildHyperliquidAgentTypedData({ action, nonce, isTestnet });
1528
+ return buildEip712MultisignBody({
1529
+ keyGen: args.keyGen,
1530
+ purposeText: args.purposeText,
1531
+ destinationChainID: String(args.chainId),
1532
+ destinationAddress: ZERO_ADDRESS,
1533
+ typedData: {
1534
+ domain: typed.domain,
1535
+ types: typed.types,
1536
+ primaryType: typed.primaryType,
1537
+ message: typed.message
1538
+ },
1539
+ delivery: {
1540
+ kind: "hyperliquid_exchange",
1541
+ chainId: args.chainId,
1542
+ isTestnet,
1543
+ action,
1544
+ nonce
1545
+ },
1546
+ audit: {
1547
+ protocol: "hyperliquid",
1548
+ action: "updateLeverage",
1549
+ coin: args.coin,
1550
+ marketKind,
1551
+ asset,
1552
+ leverage: action.leverage,
1553
+ isCross: action.isCross,
1554
+ nonce,
1555
+ connectionId: typed.connectionId
1556
+ }
1557
+ });
1558
+ }
1160
1559
 
1161
1560
  // src/protocols/evm/hyperliquid/multisign.ts
1561
+ function hasHyperliquidBracketTpsl(args) {
1562
+ return Boolean(args.takeProfitTriggerPxHuman?.trim() || args.stopLossTriggerPxHuman?.trim());
1563
+ }
1162
1564
  async function buildCoreWriterMultisign(common, data, signatureMeta) {
1163
1565
  const step = coreWriterStep(data);
1164
1566
  return buildEvmMultisignBatch({
@@ -1183,6 +1585,26 @@ async function buildCoreWriterMultisign(common, data, signatureMeta) {
1183
1585
  });
1184
1586
  }
1185
1587
  async function buildEvmMultisignBodyHyperliquidLimitOrderBatch(args) {
1588
+ if (hasHyperliquidBracketTpsl(args)) {
1589
+ if (args.reduceOnly) {
1590
+ throw new Error("reduceOnly cannot be combined with takeProfitTriggerPxHuman or stopLossTriggerPxHuman.");
1591
+ }
1592
+ return buildHyperliquidLimitOrderWithTpslMultisign({
1593
+ keyGen: args.keyGen,
1594
+ chainId: args.chainId,
1595
+ purposeText: args.purposeText,
1596
+ coin: args.coin,
1597
+ marketKind: args.marketKind,
1598
+ dex: args.dex,
1599
+ isBuy: args.isBuy,
1600
+ limitPxHuman: args.limitPxHuman,
1601
+ szHuman: args.szHuman,
1602
+ tif: args.tif,
1603
+ takeProfitTriggerPxHuman: args.takeProfitTriggerPxHuman,
1604
+ stopLossTriggerPxHuman: args.stopLossTriggerPxHuman,
1605
+ tpslExecMode: args.tpslExecMode
1606
+ });
1607
+ }
1186
1608
  const marketKind = args.marketKind ?? "perp";
1187
1609
  const { asset } = await hyperliquidResolveAsset({
1188
1610
  chainId: args.chainId,
@@ -1332,212 +1754,6 @@ async function buildEvmMultisignBodyHyperliquidDelegateOnlyBatch(args) {
1332
1754
  async function buildEvmMultisignBodyHyperliquidUndelegateBatch(args) {
1333
1755
  return buildEvmMultisignBodyHyperliquidDelegateBatch({ ...args, isUndelegate: true });
1334
1756
  }
1335
- var EXCHANGE_DOMAIN = {
1336
- name: "Exchange",
1337
- version: "1",
1338
- chainId: 1337,
1339
- verifyingContract: "0x0000000000000000000000000000000000000000"
1340
- };
1341
- var AGENT_TYPES = {
1342
- Agent: [
1343
- { name: "source", type: "string" },
1344
- { name: "connectionId", type: "bytes32" }
1345
- ]
1346
- };
1347
- function adjustMsgpackValue(value) {
1348
- if (Array.isArray(value)) return value.map(adjustMsgpackValue);
1349
- if (typeof value === "object" && value !== null) {
1350
- const result = {};
1351
- for (const key of Object.keys(value)) {
1352
- const entry = value[key];
1353
- if (entry !== void 0) result[key] = adjustMsgpackValue(entry);
1354
- }
1355
- return result;
1356
- }
1357
- if (typeof value === "number" && Number.isInteger(value) && (value >= 4294967296 || value < -2147483648)) {
1358
- return BigInt(value);
1359
- }
1360
- return value;
1361
- }
1362
- function toUint64Bytes(n) {
1363
- const bytes = new Uint8Array(8);
1364
- new DataView(bytes.buffer).setBigUint64(0, BigInt(n));
1365
- return bytes;
1366
- }
1367
- function concatBytes(...parts) {
1368
- const total = parts.reduce((sum, p) => sum + p.length, 0);
1369
- const out = new Uint8Array(total);
1370
- let offset = 0;
1371
- for (const p of parts) {
1372
- out.set(p, offset);
1373
- offset += p.length;
1374
- }
1375
- return out;
1376
- }
1377
- function hexToBytes(hex) {
1378
- const h = hex.startsWith("0x") ? hex.slice(2) : hex;
1379
- const bytes = new Uint8Array(h.length / 2);
1380
- for (let i = 0; i < bytes.length; i++) {
1381
- bytes[i] = parseInt(h.slice(i * 2, i * 2 + 2), 16);
1382
- }
1383
- return bytes;
1384
- }
1385
- function createHyperliquidL1ActionHash(args) {
1386
- const { action, nonce, vaultAddress, expiresAfter } = args;
1387
- const actionBytes = encode(adjustMsgpackValue(action));
1388
- const nonceBytes = toUint64Bytes(nonce);
1389
- const vaultMarker = vaultAddress ? new Uint8Array([1]) : new Uint8Array([0]);
1390
- const vaultBytes = vaultAddress ? hexToBytes(vaultAddress) : new Uint8Array();
1391
- const expiresMarker = expiresAfter !== void 0 ? new Uint8Array([0]) : new Uint8Array();
1392
- const expiresBytes = expiresAfter !== void 0 ? toUint64Bytes(expiresAfter) : new Uint8Array();
1393
- const bytes = concatBytes(actionBytes, nonceBytes, vaultMarker, vaultBytes, expiresMarker, expiresBytes);
1394
- return keccak256(bytes);
1395
- }
1396
- function buildHyperliquidAgentTypedData(args) {
1397
- const connectionId = createHyperliquidL1ActionHash(args);
1398
- const source = args.isTestnet ? "b" : "a";
1399
- return {
1400
- domain: EXCHANGE_DOMAIN,
1401
- types: AGENT_TYPES,
1402
- primaryType: "Agent",
1403
- message: {
1404
- source,
1405
- connectionId
1406
- },
1407
- connectionId,
1408
- nonce: args.nonce,
1409
- action: args.action
1410
- };
1411
- }
1412
- function buildHyperliquidUpdateLeverageAction(args) {
1413
- const leverage = Math.trunc(args.leverage);
1414
- if (!Number.isFinite(leverage) || leverage < 1) {
1415
- throw new Error("leverage must be a positive integer");
1416
- }
1417
- return {
1418
- type: "updateLeverage",
1419
- asset: args.asset,
1420
- isCross: args.isCross !== false,
1421
- leverage
1422
- };
1423
- }
1424
- var EIP712_SIGN_REQUEST_KIND = "eip712";
1425
- function msgHashNo0x(digest) {
1426
- return digest.startsWith("0x") ? digest.slice(2) : digest;
1427
- }
1428
- function eip712SignatureText(domain, primaryType) {
1429
- return JSON.stringify({
1430
- kind: "EIP-712",
1431
- ...typeof domain.name === "string" ? { name: domain.name } : {},
1432
- primaryType
1433
- });
1434
- }
1435
- function jsonStringifyForAudit(value) {
1436
- return JSON.stringify(value, (_, v) => typeof v === "bigint" ? v.toString() : v);
1437
- }
1438
- function eip712MsgRawHex(typedData, delivery) {
1439
- const envelope = {
1440
- version: 1,
1441
- ...typedData,
1442
- delivery
1443
- };
1444
- return stringToHex(jsonStringifyForAudit(envelope));
1445
- }
1446
- function buildEip712MultisignBody(args) {
1447
- const { typedData, delivery } = args;
1448
- const digest = hashTypedData({
1449
- domain: typedData.domain,
1450
- types: typedData.types,
1451
- primaryType: typedData.primaryType,
1452
- message: typedData.message
1453
- });
1454
- const extraJSON = {
1455
- signRequestKind: EIP712_SIGN_REQUEST_KIND,
1456
- eip712: {
1457
- version: 1,
1458
- digest,
1459
- domain: typedData.domain,
1460
- types: typedData.types,
1461
- primaryType: typedData.primaryType,
1462
- message: typedData.message
1463
- },
1464
- delivery
1465
- };
1466
- return finalizeMultisign({
1467
- keyGen: args.keyGen,
1468
- purposeText: args.purposeText,
1469
- purposeSuffix: args.purposeSuffix,
1470
- destinationChainID: args.destinationChainID,
1471
- destinationAddress: args.destinationAddress,
1472
- extraJSON,
1473
- expiryDate: args.expiryDate,
1474
- legs: [
1475
- {
1476
- msgHash: msgHashNo0x(digest),
1477
- msgRaw: eip712MsgRawHex(typedData, delivery),
1478
- destinationAddress: args.destinationAddress,
1479
- signatureText: eip712SignatureText(typedData.domain, typedData.primaryType),
1480
- audit: {
1481
- kind: "EIP712",
1482
- primaryType: typedData.primaryType,
1483
- deliveryKind: delivery.kind,
1484
- ...args.audit ?? {}
1485
- },
1486
- feeSnapshot: {}
1487
- }
1488
- ]
1489
- });
1490
- }
1491
-
1492
- // src/protocols/evm/hyperliquid/exchangeMultisign.ts
1493
- var ZERO_ADDRESS = "0x0000000000000000000000000000000000000000";
1494
- async function buildHyperliquidUpdateLeverageMultisign(args) {
1495
- const marketKind = args.marketKind ?? "perp";
1496
- const { asset } = await hyperliquidResolveAsset({
1497
- chainId: args.chainId,
1498
- coin: args.coin,
1499
- marketKind,
1500
- dex: args.dex
1501
- });
1502
- const action = buildHyperliquidUpdateLeverageAction({
1503
- asset,
1504
- leverage: args.leverage,
1505
- isCross: args.isCross
1506
- });
1507
- const nonce = args.nonce ?? Date.now();
1508
- const isTestnet = args.chainId === 998;
1509
- const typed = buildHyperliquidAgentTypedData({ action, nonce, isTestnet });
1510
- return buildEip712MultisignBody({
1511
- keyGen: args.keyGen,
1512
- purposeText: args.purposeText,
1513
- destinationChainID: String(args.chainId),
1514
- destinationAddress: ZERO_ADDRESS,
1515
- typedData: {
1516
- domain: typed.domain,
1517
- types: typed.types,
1518
- primaryType: typed.primaryType,
1519
- message: typed.message
1520
- },
1521
- delivery: {
1522
- kind: "hyperliquid_exchange",
1523
- chainId: args.chainId,
1524
- isTestnet,
1525
- action,
1526
- nonce
1527
- },
1528
- audit: {
1529
- protocol: "hyperliquid",
1530
- action: "updateLeverage",
1531
- coin: args.coin,
1532
- marketKind,
1533
- asset,
1534
- leverage: action.leverage,
1535
- isCross: action.isCross,
1536
- nonce,
1537
- connectionId: typed.connectionId
1538
- }
1539
- });
1540
- }
1541
1757
  var HYPERLIQUID_BRIDGE_MIN_DEPOSIT_USDC = 5;
1542
1758
  var HYPERLIQUID_BRIDGE_ARBITRUM_MAINNET_CHAIN_ID = 42161;
1543
1759
  var HYPERLIQUID_BRIDGE_ARBITRUM_TESTNET_CHAIN_ID = 421614;
@@ -1734,6 +1950,44 @@ async function buildHyperliquidBridgeWithdrawMultisign(args) {
1734
1950
  });
1735
1951
  }
1736
1952
 
1953
+ // src/protocols/evm/hyperliquid/pendingClose.ts
1954
+ function parsePositiveSize(value) {
1955
+ if (value == null || !String(value).trim()) return null;
1956
+ const n = Number.parseFloat(String(value).trim());
1957
+ if (!Number.isFinite(n) || n <= 0) return null;
1958
+ return n;
1959
+ }
1960
+ function hyperliquidOrderClosesPosition(position, orderSide) {
1961
+ const side = String(orderSide).trim().toUpperCase();
1962
+ return position.isLong ? side === "A" : side === "B";
1963
+ }
1964
+ function hyperliquidOrderCountsAsPendingClose(order) {
1965
+ return Boolean(order.reduceOnly) || Boolean(order.isTrigger);
1966
+ }
1967
+ function hyperliquidPendingCloseForPosition(args) {
1968
+ const positionSize = parsePositiveSize(args.position.size);
1969
+ if (positionSize == null) {
1970
+ return { pendingCloseSz: 0, pendingClosePct: 0 };
1971
+ }
1972
+ let pendingCloseSz = 0;
1973
+ for (const order of args.orders) {
1974
+ if (order.coin !== args.position.coin) continue;
1975
+ if (!hyperliquidOrderClosesPosition(args.position, order.side)) continue;
1976
+ if (!hyperliquidOrderCountsAsPendingClose(order)) continue;
1977
+ const sz = parsePositiveSize(order.sz);
1978
+ if (sz != null) pendingCloseSz += sz;
1979
+ }
1980
+ const pendingClosePct = Math.min(100, pendingCloseSz / positionSize * 100);
1981
+ return { pendingCloseSz, pendingClosePct };
1982
+ }
1983
+ function hyperliquidPendingCloseByCoin(args) {
1984
+ const out = /* @__PURE__ */ new Map();
1985
+ for (const position of args.positions) {
1986
+ out.set(position.key, hyperliquidPendingCloseForPosition({ position, orders: args.orders }));
1987
+ }
1988
+ return out;
1989
+ }
1990
+
1737
1991
  // src/protocols/evm/hyperliquid/index.ts
1738
1992
  var HYPERLIQUID_PROTOCOL_ID = "hyperliquid";
1739
1993
  var hyperliquidProtocolModule = {
@@ -1753,7 +2007,7 @@ var hyperliquidProtocolModule = {
1753
2007
  id: "hyperliquid.limitOrder",
1754
2008
  protocolId: HYPERLIQUID_PROTOCOL_ID,
1755
2009
  chainCategory: "evm",
1756
- description: "Place a Hyperliquid limit/IoC order via HyperEVM CoreWriter",
2010
+ description: "Place a Hyperliquid limit/IoC order via CoreWriter, or L1 normalTpsl bracket when TP/SL triggers are set",
1757
2011
  commonParams: ["keyGen", "purposeText", "useCustomGas"],
1758
2012
  params: {
1759
2013
  coin: { type: "string", required: true, description: "Market coin e.g. BTC" },
@@ -1762,7 +2016,10 @@ var hyperliquidProtocolModule = {
1762
2016
  szHuman: { type: "string", required: true, description: "Order size in coin units" },
1763
2017
  marketKind: { type: "string", required: false, description: "perp (default) or spot" },
1764
2018
  tif: { type: "string", required: false, description: "gtc, ioc, or alo" },
1765
- dex: { type: "string", required: false, description: "HIP-3 dex name when applicable" }
2019
+ dex: { type: "string", required: false, description: "HIP-3 dex name when applicable" },
2020
+ takeProfitTriggerPxHuman: { type: "string", required: false, description: "TP trigger \u2014 enables L1 bracket with SL" },
2021
+ stopLossTriggerPxHuman: { type: "string", required: false, description: "SL trigger \u2014 enables L1 bracket with TP" },
2022
+ tpslExecMode: { type: "string", required: false, description: "limit_at_trigger (default) or market" }
1766
2023
  }
1767
2024
  },
1768
2025
  {
@@ -1902,6 +2159,6 @@ var hyperliquidProtocolModule = {
1902
2159
  };
1903
2160
  registerProtocolModule(hyperliquidProtocolModule);
1904
2161
 
1905
- export { HYPERLIQUID_BRIDGE_ARBITRUM_MAINNET_CHAIN_ID, HYPERLIQUID_BRIDGE_ARBITRUM_TESTNET_CHAIN_ID, HYPERLIQUID_BRIDGE_ERC20_TRANSFER_FALLBACK_GAS, HYPERLIQUID_BRIDGE_MIN_DEPOSIT_USDC, HYPERLIQUID_CORE_WRITER_ADDRESS, HYPERLIQUID_CORE_WRITER_GAS_FALLBACK, HYPERLIQUID_DEFAULT_CANDLE_LIMIT, HYPERLIQUID_DEFAULT_LOOKBACK_DAYS, HYPERLIQUID_DEFAULT_OHLCV_INTERVAL, HYPERLIQUID_HLP_VAULT_ADDRESS, HYPERLIQUID_HYPEREVM_USDC_MAINNET, HYPERLIQUID_HYPEREVM_USDC_TESTNET, HYPERLIQUID_INTERVAL_MS, HYPERLIQUID_MAX_CANDLE_LIMIT, HYPERLIQUID_MAX_LOOKBACK_DAYS, HYPERLIQUID_MAX_OHLCV_BARS, HYPERLIQUID_PROTOCOL_ID, HYPERLIQUID_SPOT_ASSET_OFFSET, HYPERLIQUID_SUPPORTED_CHAIN_IDS, HYPERLIQUID_TIF, HYPERLIQUID_USER_SIGNED_DOMAIN, HYPERLIQUID_USER_SIGNED_SIGNATURE_CHAIN_ID, HYPERLIQUID_WITHDRAW_SIGN_TYPES, buildCoreWriterCancelByCloidCalldata, buildCoreWriterCancelByOidCalldata, buildCoreWriterLimitOrderCalldata, buildCoreWriterStakingDepositCalldata, buildCoreWriterStakingWithdrawCalldata, buildCoreWriterTokenDelegateCalldata, buildCoreWriterUsdClassTransferCalldata, buildCoreWriterVaultTransferCalldata, buildEvmMultisignBodyHyperliquidBridgeDepositBatch, buildEvmMultisignBodyHyperliquidCancelBatch, buildEvmMultisignBodyHyperliquidCloseBatch, buildEvmMultisignBodyHyperliquidDelegateBatch, buildEvmMultisignBodyHyperliquidDelegateOnlyBatch, buildEvmMultisignBodyHyperliquidLimitOrderBatch, buildEvmMultisignBodyHyperliquidStakeDepositBatch, buildEvmMultisignBodyHyperliquidStakeWithdrawBatch, buildEvmMultisignBodyHyperliquidUndelegateBatch, buildEvmMultisignBodyHyperliquidUsdClassTransferBatch, buildEvmMultisignBodyHyperliquidVaultDepositBatch, buildEvmMultisignBodyHyperliquidVaultWithdrawBatch, buildHyperliquidAgentTypedData, buildHyperliquidBridgeWithdrawMultisign, buildHyperliquidUpdateLeverageAction, buildHyperliquidUpdateLeverageMultisign, buildHyperliquidWithdraw3Action, buildHyperliquidWithdraw3TypedData, coreWriterStep, createHyperliquidL1ActionHash, hyperliquidApiBaseUrl, hyperliquidBridgeArbitrumChainId, hyperliquidBridgeConfig, hyperliquidCollectAllPerpMarkets, hyperliquidEncodePx8, hyperliquidEncodeUsd6, hyperliquidEncodeWei8, hyperliquidFetchActiveAssetData, hyperliquidFetchAllMids, hyperliquidFetchCandles, hyperliquidFetchClearinghouseState, hyperliquidFetchDelegations, hyperliquidFetchDelegationsForExecutor, hyperliquidFetchDexList, hyperliquidFetchMarketSnapshot, hyperliquidFetchMarketSnapshotSummary, hyperliquidFetchMarketsSummary, hyperliquidFetchOhlcvRange, hyperliquidFetchOhlcvSummary, hyperliquidFetchOpenContextSummary, hyperliquidFetchOpenMarketContext, hyperliquidFetchOpenOrders, hyperliquidFetchOpenOrdersSummary, hyperliquidFetchOrdersForExecutor, hyperliquidFetchPerpAssetContext, hyperliquidFetchPerpConciseAnnotations, hyperliquidFetchPerpMeta, hyperliquidFetchPositionDisplayRows, hyperliquidFetchPositionsForExecutor, hyperliquidFetchSpotClearinghouseState, hyperliquidFetchSpotMeta, hyperliquidFetchStakingSummary, hyperliquidFetchStakingSummaryForExecutor, hyperliquidFetchUsdClassBalances, hyperliquidFetchUsdClassBalancesSummary, hyperliquidFetchUserVaultEquities, hyperliquidFetchUserVaultEquitiesSummary, hyperliquidFetchVaultCatalogSummary, hyperliquidFetchVaultSummaries, hyperliquidInferDexFromCoin, hyperliquidIsSpotAssetId, hyperliquidMarketSymbol, hyperliquidProtocolModule, hyperliquidResolveAsset, hyperliquidResolveOhlcvWindow, hyperliquidResolvePerpAsset, hyperliquidResolvePerpMarket, hyperliquidResolveSpotAsset, hyperliquidResolveTif, hyperliquidSearchMarkets, hyperliquidSearchMarketsSummary, hyperliquidVaultStatsUrl, isHyperliquidBridgeArbitrumChainSupported, isHyperliquidBridgeArbitrumUsdcRow, isHyperliquidChainSupported, isHyperliquidHyperEvmUsdcRow };
2162
+ export { HYPERLIQUID_BRIDGE_ARBITRUM_MAINNET_CHAIN_ID, HYPERLIQUID_BRIDGE_ARBITRUM_TESTNET_CHAIN_ID, HYPERLIQUID_BRIDGE_ERC20_TRANSFER_FALLBACK_GAS, HYPERLIQUID_BRIDGE_MIN_DEPOSIT_USDC, HYPERLIQUID_CORE_WRITER_ADDRESS, HYPERLIQUID_CORE_WRITER_GAS_FALLBACK, HYPERLIQUID_DEFAULT_CANDLE_LIMIT, HYPERLIQUID_DEFAULT_LOOKBACK_DAYS, HYPERLIQUID_DEFAULT_OHLCV_INTERVAL, HYPERLIQUID_HLP_VAULT_ADDRESS, HYPERLIQUID_HYPEREVM_USDC_MAINNET, HYPERLIQUID_HYPEREVM_USDC_TESTNET, HYPERLIQUID_INTERVAL_MS, HYPERLIQUID_MAX_CANDLE_LIMIT, HYPERLIQUID_MAX_LOOKBACK_DAYS, HYPERLIQUID_MAX_OHLCV_BARS, HYPERLIQUID_PROTOCOL_ID, HYPERLIQUID_SPOT_ASSET_OFFSET, HYPERLIQUID_SUPPORTED_CHAIN_IDS, HYPERLIQUID_TIF, HYPERLIQUID_USER_SIGNED_DOMAIN, HYPERLIQUID_USER_SIGNED_SIGNATURE_CHAIN_ID, HYPERLIQUID_WITHDRAW_SIGN_TYPES, buildCoreWriterCancelByCloidCalldata, buildCoreWriterCancelByOidCalldata, buildCoreWriterLimitOrderCalldata, buildCoreWriterStakingDepositCalldata, buildCoreWriterStakingWithdrawCalldata, buildCoreWriterTokenDelegateCalldata, buildCoreWriterUsdClassTransferCalldata, buildCoreWriterVaultTransferCalldata, buildEvmMultisignBodyHyperliquidBridgeDepositBatch, buildEvmMultisignBodyHyperliquidCancelBatch, buildEvmMultisignBodyHyperliquidCloseBatch, buildEvmMultisignBodyHyperliquidDelegateBatch, buildEvmMultisignBodyHyperliquidDelegateOnlyBatch, buildEvmMultisignBodyHyperliquidLimitOrderBatch, buildEvmMultisignBodyHyperliquidStakeDepositBatch, buildEvmMultisignBodyHyperliquidStakeWithdrawBatch, buildEvmMultisignBodyHyperliquidUndelegateBatch, buildEvmMultisignBodyHyperliquidUsdClassTransferBatch, buildEvmMultisignBodyHyperliquidVaultDepositBatch, buildEvmMultisignBodyHyperliquidVaultWithdrawBatch, buildHyperliquidAgentTypedData, buildHyperliquidBridgeWithdrawMultisign, buildHyperliquidLimitOrderWire, buildHyperliquidLimitOrderWithTpslMultisign, buildHyperliquidNormalTpslOrderWires, buildHyperliquidOrderAction, buildHyperliquidTriggerOrderWire, buildHyperliquidUpdateLeverageAction, buildHyperliquidUpdateLeverageMultisign, buildHyperliquidWithdraw3Action, buildHyperliquidWithdraw3TypedData, coreWriterStep, createHyperliquidL1ActionHash, hyperliquidApiBaseUrl, hyperliquidBridgeArbitrumChainId, hyperliquidBridgeConfig, hyperliquidCollectAllPerpMarkets, hyperliquidEncodePx8, hyperliquidEncodeUsd6, hyperliquidEncodeWei8, hyperliquidFetchActiveAssetData, hyperliquidFetchAllMids, hyperliquidFetchCandles, hyperliquidFetchClearinghouseState, hyperliquidFetchDelegations, hyperliquidFetchDelegationsForExecutor, hyperliquidFetchDexList, hyperliquidFetchFrontendOpenOrders, hyperliquidFetchMarketSnapshot, hyperliquidFetchMarketSnapshotSummary, hyperliquidFetchMarketsSummary, hyperliquidFetchOhlcvRange, hyperliquidFetchOhlcvSummary, hyperliquidFetchOpenContextSummary, hyperliquidFetchOpenMarketContext, hyperliquidFetchOpenOrders, hyperliquidFetchOpenOrdersSummary, hyperliquidFetchOrdersForExecutor, hyperliquidFetchPerpAssetContext, hyperliquidFetchPerpConciseAnnotations, hyperliquidFetchPerpMeta, hyperliquidFetchPositionDisplayRows, hyperliquidFetchPositionsForExecutor, hyperliquidFetchSpotClearinghouseState, hyperliquidFetchSpotMeta, hyperliquidFetchStakingSummary, hyperliquidFetchStakingSummaryForExecutor, hyperliquidFetchUsdClassBalances, hyperliquidFetchUsdClassBalancesSummary, hyperliquidFetchUserVaultEquities, hyperliquidFetchUserVaultEquitiesSummary, hyperliquidFetchVaultCatalogSummary, hyperliquidFetchVaultSummaries, hyperliquidFloatToWire, hyperliquidInferDexFromCoin, hyperliquidIsSpotAssetId, hyperliquidL1TifFromKey, hyperliquidMarketSymbol, hyperliquidOrderClosesPosition, hyperliquidOrderCountsAsPendingClose, hyperliquidPendingCloseByCoin, hyperliquidPendingCloseForPosition, hyperliquidProtocolModule, hyperliquidResolveAsset, hyperliquidResolveOhlcvWindow, hyperliquidResolvePerpAsset, hyperliquidResolvePerpMarket, hyperliquidResolveSpotAsset, hyperliquidResolveTif, hyperliquidSearchMarkets, hyperliquidSearchMarketsSummary, hyperliquidVaultStatsUrl, isHyperliquidBridgeArbitrumChainSupported, isHyperliquidBridgeArbitrumUsdcRow, isHyperliquidChainSupported, isHyperliquidHyperEvmUsdcRow, validateHyperliquidTpslGeometry };
1906
2163
  //# sourceMappingURL=index.js.map
1907
2164
  //# sourceMappingURL=index.js.map