@continuumdao/ctm-mpc-defi 0.2.1 → 0.2.3

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 (57) hide show
  1. package/dist/agent/catalog.cjs +96 -25
  2. package/dist/agent/catalog.cjs.map +1 -1
  3. package/dist/agent/catalog.d.ts +27 -1
  4. package/dist/agent/catalog.js +95 -26
  5. package/dist/agent/catalog.js.map +1 -1
  6. package/dist/agent/skills/curve-dao/SKILL.md +2 -1
  7. package/dist/chains/evm/index.cjs +54 -0
  8. package/dist/chains/evm/index.cjs.map +1 -1
  9. package/dist/chains/evm/index.d.ts +13 -1
  10. package/dist/chains/evm/index.js +52 -2
  11. package/dist/chains/evm/index.js.map +1 -1
  12. package/dist/core/index.cjs +64 -0
  13. package/dist/core/index.cjs.map +1 -1
  14. package/dist/core/index.d.ts +20 -1
  15. package/dist/core/index.js +56 -1
  16. package/dist/core/index.js.map +1 -1
  17. package/dist/index.cjs +165 -14
  18. package/dist/index.cjs.map +1 -1
  19. package/dist/index.d.ts +2 -2
  20. package/dist/index.js +154 -16
  21. package/dist/index.js.map +1 -1
  22. package/dist/protocols/evm/aave-v4/index.cjs +766 -6
  23. package/dist/protocols/evm/aave-v4/index.cjs.map +1 -1
  24. package/dist/protocols/evm/aave-v4/index.d.ts +417 -1
  25. package/dist/protocols/evm/aave-v4/index.js +741 -8
  26. package/dist/protocols/evm/aave-v4/index.js.map +1 -1
  27. package/dist/protocols/evm/curve-dao/index.cjs +268 -21
  28. package/dist/protocols/evm/curve-dao/index.cjs.map +1 -1
  29. package/dist/protocols/evm/curve-dao/index.d.ts +74 -9
  30. package/dist/protocols/evm/curve-dao/index.js +262 -23
  31. package/dist/protocols/evm/curve-dao/index.js.map +1 -1
  32. package/dist/protocols/evm/ethena/index.cjs +104 -0
  33. package/dist/protocols/evm/ethena/index.cjs.map +1 -1
  34. package/dist/protocols/evm/ethena/index.d.ts +46 -1
  35. package/dist/protocols/evm/ethena/index.js +99 -1
  36. package/dist/protocols/evm/ethena/index.js.map +1 -1
  37. package/dist/protocols/evm/euler-v2/index.cjs +2334 -37
  38. package/dist/protocols/evm/euler-v2/index.cjs.map +1 -1
  39. package/dist/protocols/evm/euler-v2/index.d.ts +464 -1
  40. package/dist/protocols/evm/euler-v2/index.js +2286 -39
  41. package/dist/protocols/evm/euler-v2/index.js.map +1 -1
  42. package/dist/protocols/evm/lido/index.cjs +110 -0
  43. package/dist/protocols/evm/lido/index.cjs.map +1 -1
  44. package/dist/protocols/evm/lido/index.d.ts +33 -2
  45. package/dist/protocols/evm/lido/index.js +107 -2
  46. package/dist/protocols/evm/lido/index.js.map +1 -1
  47. package/dist/protocols/evm/maple/index.cjs +83 -0
  48. package/dist/protocols/evm/maple/index.cjs.map +1 -1
  49. package/dist/protocols/evm/maple/index.d.ts +22 -1
  50. package/dist/protocols/evm/maple/index.js +82 -1
  51. package/dist/protocols/evm/maple/index.js.map +1 -1
  52. package/dist/protocols/evm/sky/index.cjs +217 -0
  53. package/dist/protocols/evm/sky/index.cjs.map +1 -1
  54. package/dist/protocols/evm/sky/index.d.ts +56 -1
  55. package/dist/protocols/evm/sky/index.js +210 -2
  56. package/dist/protocols/evm/sky/index.js.map +1 -1
  57. package/package.json +3 -3
@@ -1,4 +1,4 @@
1
- import { isAddress, getAddress, parseUnits, formatUnits, defineChain, createPublicClient, http, parseAbi, encodeFunctionData, parseGwei, serializeTransaction, keccak256 } from 'viem';
1
+ import { parseAbi, isAddress, getAddress, defineChain, createPublicClient, http, parseUnits, encodeFunctionData, formatUnits, parseGwei, serializeTransaction, keccak256, zeroAddress } from 'viem';
2
2
  import { fetchChainFeeParams, gasLimitFromEstimateAndChainConfig, gweiToDecimalString, proposalTxParamsToFeeSnapshot, alignEip1559FeesWithLatestBase, getClientIdFromKeyGenResult } from '@continuumdao/continuum-node-sdk';
3
3
 
4
4
  // src/core/registry.ts
@@ -63,6 +63,17 @@ function isCurveApiChainSupported(chainId) {
63
63
  if (Number.isNaN(n) || n < 0) return false;
64
64
  return CURVE_FULL_NETWORK_CONSTANTS_CHAIN_IDS.has(n);
65
65
  }
66
+ function normalizeHumanDecimalAmount(raw, tokenDecimals) {
67
+ const t = raw.trim().replace(/,/g, "");
68
+ if (!t) return "";
69
+ if (!Number.isInteger(tokenDecimals) || tokenDecimals < 0 || tokenDecimals > 18) {
70
+ throw new Error("Invalid token decimals for amount normalization.");
71
+ }
72
+ const wei = parseUnits(t, tokenDecimals);
73
+ return formatUnits(wei, tokenDecimals);
74
+ }
75
+
76
+ // src/protocols/evm/curve-dao/swapDestinations.ts
66
77
  var CURVE_NATIVE_PLACEHOLDER = "0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee";
67
78
  var ETH_PLACEHOLDER = CURVE_NATIVE_PLACEHOLDER;
68
79
  function normalizeAddr(a) {
@@ -95,13 +106,7 @@ function toCurveRouterTokenId(tokenAddress, wrappedNative) {
95
106
  }
96
107
  }
97
108
  function normalizeCurveRouterAmountString(raw, tokenInDecimals) {
98
- const t = raw.trim().replace(/,/g, "");
99
- if (!t) return "";
100
- if (!Number.isInteger(tokenInDecimals) || tokenInDecimals < 0 || tokenInDecimals > 18) {
101
- throw new Error("Invalid token-in decimals for amount normalization.");
102
- }
103
- const wei = parseUnits(t, tokenInDecimals);
104
- return formatUnits(wei, tokenInDecimals);
109
+ return normalizeHumanDecimalAmount(raw, tokenInDecimals);
105
110
  }
106
111
  function addEdge(adj, a, b) {
107
112
  if (a === b) return;
@@ -167,46 +172,97 @@ function bfsCurveSwapDestinations(adj, start) {
167
172
  }
168
173
 
169
174
  // src/protocols/evm/curve-dao/apiSession.ts
175
+ var CURVE_SESSION_CACHE_TTL_MS = 5 * 60 * 1e3;
176
+ var curveSessionCache = /* @__PURE__ */ new Map();
170
177
  async function fetchAllCurvePools(curve) {
171
178
  const run = (p) => p.catch(() => void 0);
172
- await Promise.all([
173
- run(curve.factory.fetchPools()),
174
- run(curve.crvUSDFactory.fetchPools()),
175
- run(curve.EYWAFactory.fetchPools()),
176
- run(curve.cryptoFactory.fetchPools()),
177
- run(curve.twocryptoFactory.fetchPools()),
178
- run(curve.tricryptoFactory.fetchPools()),
179
- run(curve.stableNgFactory.fetchPools())
180
- ]);
179
+ const tasks = [];
180
+ for (const key of [
181
+ "factory",
182
+ "crvUSDFactory",
183
+ "EYWAFactory",
184
+ "cryptoFactory",
185
+ "twocryptoFactory",
186
+ "tricryptoFactory",
187
+ "stableNgFactory"
188
+ ]) {
189
+ const f = curve[key];
190
+ if (f?.fetchPools) {
191
+ tasks.push(run(f.fetchPools()));
192
+ }
193
+ }
194
+ await Promise.all(tasks);
181
195
  }
182
196
  async function loadFullCurveSessionForRpc(rpcUrl) {
183
197
  const url = (rpcUrl ?? "").trim();
184
- if (!url) return null;
198
+ if (!url) {
199
+ throw new Error("rpcUrl is required.");
200
+ }
201
+ const cached = curveSessionCache.get(url);
202
+ if (cached && cached.expiresAt > Date.now()) {
203
+ return cached.session;
204
+ }
185
205
  try {
186
206
  const { default: curve } = await import('@curvefi/api');
187
207
  await curve.init("JsonRpc", { url }, {});
188
208
  const wrapped = curve.getNetworkConstants().NATIVE_COIN?.wrappedAddress;
189
209
  if (!curve.hasRouter || !curve.hasRouter()) {
190
- return {
210
+ const session2 = {
191
211
  curve,
192
212
  adj: /* @__PURE__ */ new Map(),
193
213
  swappableNodeKeys: /* @__PURE__ */ new Set(),
194
214
  wrappedNative: wrapped
195
215
  };
216
+ curveSessionCache.set(url, { session: session2, expiresAt: Date.now() + CURVE_SESSION_CACHE_TTL_MS });
217
+ return session2;
196
218
  }
197
219
  await fetchAllCurvePools(curve);
198
220
  const adj = buildCurveLiquidityGraphFromApi(curve);
199
221
  addNativeWethBridge(adj, wrapped);
200
- return {
222
+ const session = {
201
223
  curve,
202
224
  adj,
203
225
  swappableNodeKeys: swappableCurveGraphNodeKeys(adj),
204
226
  wrappedNative: wrapped
205
227
  };
206
- } catch {
207
- return null;
228
+ curveSessionCache.set(url, { session, expiresAt: Date.now() + CURVE_SESSION_CACHE_TTL_MS });
229
+ return session;
230
+ } catch (e) {
231
+ const msg = e instanceof Error ? e.message : String(e);
232
+ throw new Error(`Curve session init failed for RPC: ${msg}`);
208
233
  }
209
234
  }
235
+ async function loadCurveSessionSnapshotForRpc(rpcUrl) {
236
+ const session = await loadFullCurveSessionForRpc(rpcUrl);
237
+ const adj = {};
238
+ for (const [key, neighbors] of session.adj) {
239
+ adj[key] = [...neighbors];
240
+ }
241
+ return {
242
+ wrappedNative: session.wrappedNative,
243
+ swappableNodeKeys: [...session.swappableNodeKeys],
244
+ routerReady: Boolean(session.curve?.hasRouter?.() && session.curve.hasRouter()),
245
+ adj
246
+ };
247
+ }
248
+ async function fetchCurveCoinsDataForRpc(rpcUrl, addresses) {
249
+ const session = await loadFullCurveSessionForRpc(rpcUrl);
250
+ if (!session.curve?.getCoinsData) {
251
+ throw new Error("Curve getCoinsData is not available for this RPC session.");
252
+ }
253
+ const coins = await session.curve.getCoinsData(addresses);
254
+ return addresses.map((addr, i) => {
255
+ const c = coins[i];
256
+ const dec = c?.decimals;
257
+ const decimals = typeof dec === "number" && Number.isInteger(dec) && dec >= 0 && dec <= 18 ? dec : null;
258
+ return {
259
+ address: addr,
260
+ name: c?.name && String(c.name).trim() || "\u2014",
261
+ symbol: c?.symbol && String(c.symbol).trim() || addr.slice(0, 6),
262
+ decimals
263
+ };
264
+ });
265
+ }
210
266
 
211
267
  // src/protocols/evm/curve-dao/purpose.ts
212
268
  function buildCurveDaoPurposePrefill(args) {
@@ -704,6 +760,176 @@ async function buildEvmMultisignBodyCurveDaoBatch(args) {
704
760
  }
705
761
  });
706
762
  }
763
+ var erc20DecimalsAbi = parseAbi(["function decimals() view returns (uint8)"]);
764
+ function normalizeNativeTokenIn(tokenIn) {
765
+ const trimmed = tokenIn.trim();
766
+ if (!trimmed) return tokenIn;
767
+ const lower = trimmed.toLowerCase();
768
+ if (lower === "eth" || lower === "native" || lower === "native_eth" || lower === zeroAddress.toLowerCase() || lower === CURVE_NATIVE_PLACEHOLDER.toLowerCase()) {
769
+ return CURVE_NATIVE_PLACEHOLDER;
770
+ }
771
+ return trimmed;
772
+ }
773
+ async function resolveTokenInDecimals(args) {
774
+ if (args.tokenInDecimals != null && Number.isInteger(args.tokenInDecimals) && args.tokenInDecimals >= 0 && args.tokenInDecimals <= 18) {
775
+ return args.tokenInDecimals;
776
+ }
777
+ const normalized = normalizeNativeTokenIn(args.tokenIn);
778
+ if (normalized.toLowerCase() === CURVE_NATIVE_PLACEHOLDER.toLowerCase()) {
779
+ return 18;
780
+ }
781
+ const addr = getAddress(
782
+ normalized.startsWith("0x") ? normalized : `0x${normalized}`
783
+ );
784
+ const ch = defineChain({
785
+ id: args.chainId,
786
+ name: "CurveQuote",
787
+ nativeCurrency: { decimals: 18, name: "Ether", symbol: "ETH" },
788
+ rpcUrls: { default: { http: [args.rpcUrl] } }
789
+ });
790
+ const publicClient = createPublicClient({ chain: ch, transport: http(args.rpcUrl) });
791
+ const decimalsN = await publicClient.readContract({
792
+ address: addr,
793
+ abi: erc20DecimalsAbi,
794
+ functionName: "decimals"
795
+ });
796
+ return Number(decimalsN);
797
+ }
798
+ async function curveDaoQuote(args) {
799
+ const rpcUrl = (args.rpcUrl ?? "").trim();
800
+ if (!rpcUrl) {
801
+ throw new Error("rpcUrl is required.");
802
+ }
803
+ if (!Number.isFinite(args.chainId) || args.chainId <= 0) {
804
+ throw new Error("chainId must be a positive integer.");
805
+ }
806
+ if (!isCurveApiChainSupported(args.chainId)) {
807
+ throw new Error(`Chain ${args.chainId} is not supported by Curve Router NG.`);
808
+ }
809
+ const tokenInDecimals = await resolveTokenInDecimals({
810
+ rpcUrl,
811
+ chainId: args.chainId,
812
+ tokenIn: args.tokenIn,
813
+ tokenInDecimals: args.tokenInDecimals
814
+ });
815
+ const amountForRouter = normalizeCurveRouterAmountString(
816
+ args.amountHuman,
817
+ tokenInDecimals
818
+ );
819
+ if (!amountForRouter) {
820
+ throw new Error("amountHuman must be a positive decimal string.");
821
+ }
822
+ const session = await loadFullCurveSessionForRpc(rpcUrl);
823
+ if (!session.curve?.router?.getBestRouteAndOutput) {
824
+ throw new Error("Curve router is not available (session load failed or chain has no router).");
825
+ }
826
+ const { curve, wrappedNative: wn } = session;
827
+ const tokenInRouterId = toCurveRouterTokenId(normalizeNativeTokenIn(args.tokenIn), wn);
828
+ const tokenOutTrim = (args.tokenOut ?? "").trim();
829
+ const tokenOutRouterId = toCurveRouterTokenId(
830
+ tokenOutTrim.toLowerCase() === CURVE_NATIVE_PLACEHOLDER.toLowerCase() ? CURVE_NATIVE_PLACEHOLDER : getAddress(
831
+ tokenOutTrim.startsWith("0x") ? tokenOutTrim : `0x${tokenOutTrim}`
832
+ ),
833
+ wn
834
+ );
835
+ const res = await curve.router.getBestRouteAndOutput(
836
+ tokenInRouterId,
837
+ tokenOutRouterId,
838
+ amountForRouter
839
+ );
840
+ const route = res?.route;
841
+ if (!route || Array.isArray(route) && route.length === 0) {
842
+ throw new Error(
843
+ "Curve router could not find a pool route for this pair and size."
844
+ );
845
+ }
846
+ const outStr = String(res?.output ?? "0");
847
+ let priceImpactPercent = null;
848
+ try {
849
+ const pi = await curve.router.swapPriceImpact(
850
+ tokenInRouterId,
851
+ tokenOutRouterId,
852
+ amountForRouter
853
+ );
854
+ if (typeof pi === "number" && Number.isFinite(pi)) {
855
+ priceImpactPercent = pi;
856
+ }
857
+ } catch {
858
+ }
859
+ return {
860
+ inputAmount: amountForRouter,
861
+ output: outStr,
862
+ route,
863
+ priceImpactPercent,
864
+ tokenInRouterId,
865
+ tokenOutRouterId
866
+ };
867
+ }
868
+ function curveProbeInAmountString(fullNormalizedHuman, tokenInDecimals) {
869
+ const t = (fullNormalizedHuman ?? "").trim();
870
+ if (!t) return null;
871
+ if (!Number.isInteger(tokenInDecimals) || tokenInDecimals < 0 || tokenInDecimals > 18) return null;
872
+ let wei;
873
+ try {
874
+ wei = parseUnits(t, tokenInDecimals);
875
+ } catch {
876
+ return null;
877
+ }
878
+ if (wei <= 1n) return null;
879
+ let p = wei / 10000n;
880
+ if (p < 1n) p = 1n;
881
+ if (p >= wei) p = wei - 1n;
882
+ return formatUnits(p, tokenInDecimals);
883
+ }
884
+ function computeCurveExecutionSlippagePercent(args) {
885
+ const aIn = parseFloat((args.fullInHuman ?? "").replace(/,/g, "").trim());
886
+ const aOut = parseFloat((args.fullOutHuman ?? "").replace(/,/g, "").trim());
887
+ const pIn = parseFloat((args.probeInHuman ?? "").replace(/,/g, "").trim());
888
+ const pOut = parseFloat((args.probeOutHuman ?? "").replace(/,/g, "").trim());
889
+ if (!(aIn > 0) || !(aOut >= 0) || !(pIn > 0) || !Number.isFinite(pOut) || pOut < 0) return null;
890
+ const marginal = pOut / pIn;
891
+ const avg = aOut / aIn;
892
+ if (!Number.isFinite(marginal) || marginal <= 0 || !Number.isFinite(avg)) return null;
893
+ const pct = (1 - avg / marginal) * 100;
894
+ if (!Number.isFinite(pct)) return null;
895
+ return Math.max(0, pct);
896
+ }
897
+ function formatCurveExchangeLine(amountIn, amountOut, tokenInSymbol, tokenOutSymbol) {
898
+ const a = parseFloat((amountIn ?? "").replace(/,/g, "").trim());
899
+ const b = parseFloat((amountOut ?? "").replace(/,/g, "").trim());
900
+ const sIn = (tokenInSymbol || "").trim() || "in";
901
+ const sOut = (tokenOutSymbol || "").trim() || "out";
902
+ if (!(a > 0) || !Number.isFinite(b)) return "\u2014";
903
+ const r = b / a;
904
+ let rate;
905
+ if (r >= 1e-4) {
906
+ rate = r.toFixed(8).replace(/0+$/, "").replace(/\.$/, "");
907
+ } else if (r > 0) {
908
+ rate = r.toPrecision(6);
909
+ } else {
910
+ rate = "0";
911
+ }
912
+ if (!rate) rate = "0";
913
+ return `1 ${sIn} \u2248 ${rate} ${sOut}`;
914
+ }
915
+ function formatCurvePriceImpact(percent0to100) {
916
+ if (percent0to100 == null || !Number.isFinite(percent0to100) || percent0to100 < 0) return "\u2014";
917
+ if (percent0to100 === 0) return "0%";
918
+ if (percent0to100 < 1e-4) return "<0.0001%";
919
+ const t = percent0to100 < 0.01 ? percent0to100.toFixed(4) : percent0to100 < 1 ? percent0to100.toFixed(3) : percent0to100 < 10 ? percent0to100.toFixed(2) : percent0to100.toFixed(1);
920
+ return `${t.replace(/(\.\d*?[1-9])0+$/g, "$1").replace(/\.0$/, "")}%`;
921
+ }
922
+ function formatMinOutAtUserSlippage(quoteOutDecimal, userSlippagePercentInput, tokenOutSymbol) {
923
+ const q = parseFloat((quoteOutDecimal ?? "").replace(/,/g, "").trim());
924
+ const rawS = (userSlippagePercentInput ?? "0.5").trim().replace(/,/g, "");
925
+ const slip = Number.parseFloat(rawS);
926
+ const s = Number.isFinite(slip) && slip >= 0 && slip < 100 ? slip : 0.5;
927
+ if (!Number.isFinite(q) || q < 0) return "\u2014";
928
+ const min = q * ((100 - s) / 100);
929
+ const sOut = (tokenOutSymbol || "").trim() || "out";
930
+ const t = min.toFixed(8).replace(/\.?0+$/, "").replace(/(\.\d*?[1-9])0+$/, "$1");
931
+ return `${t} ${sOut}`.trim();
932
+ }
707
933
 
708
934
  // src/protocols/evm/curve-dao/index.ts
709
935
  var CURVE_DAO_PROTOCOL_ID = "curve-dao";
@@ -719,6 +945,19 @@ var curveDaoProtocolModule = {
719
945
  return token.kind === "native" || token.kind === "erc20";
720
946
  },
721
947
  actions: [
948
+ {
949
+ id: "curve-dao.quote",
950
+ protocolId: CURVE_DAO_PROTOCOL_ID,
951
+ chainCategory: "evm",
952
+ description: "Quote swap via Curve Router NG (getBestRouteAndOutput)",
953
+ commonParams: [],
954
+ params: {
955
+ chainId: { type: "number", required: true, description: "EVM chain id" },
956
+ tokenIn: { type: "address", required: true, description: "Token in or native placeholder" },
957
+ tokenOut: { type: "address", required: true, description: "Token out or native placeholder" },
958
+ amountHuman: { type: "string", required: true, description: "Human-readable input amount" }
959
+ }
960
+ },
722
961
  {
723
962
  id: "curve-dao.swap",
724
963
  protocolId: CURVE_DAO_PROTOCOL_ID,
@@ -741,6 +980,6 @@ var curveDao = {
741
980
  loadSession: loadFullCurveSessionForRpc
742
981
  };
743
982
 
744
- export { CURVE_DAO_PROTOCOL_ID, CURVE_NATIVE_PLACEHOLDER, CURVE_ROUTER_EXCHANGE_DEFAULT_GAS_UNITS, addNativeWethBridge, bfsCurveSwapDestinations, buildCurveDaoPurposePrefill, buildCurveLiquidityGraphFromApi, buildEvmMultisignBodyCurveDaoBatch, curveDao, curveDaoProtocolModule, fetchAllCurvePools, isCurveApiChainSupported, isCurveApiChainSupported as isCurveDaoChainSupported, isCurveDaoErc20ApproveEvmSignRequest, isCurveDaoSwapEvmSignRequest, isCurveTokenKeySwappable, loadFullCurveSessionForRpc, normalizeCurveRouterAmountString, resolveCurveDaoRouterGasUnitsFromSignRequest, swappableCurveGraphNodeKeys, toCurveRouterTokenId, toCurveTokenKey };
983
+ export { CURVE_DAO_PROTOCOL_ID, CURVE_NATIVE_PLACEHOLDER, CURVE_ROUTER_EXCHANGE_DEFAULT_GAS_UNITS, addNativeWethBridge, bfsCurveSwapDestinations, buildCurveDaoPurposePrefill, buildCurveLiquidityGraphFromApi, buildEvmMultisignBodyCurveDaoBatch, computeCurveExecutionSlippagePercent, curveDao, curveDaoProtocolModule, curveDaoQuote, curveProbeInAmountString, fetchAllCurvePools, fetchCurveCoinsDataForRpc, formatCurveExchangeLine, formatCurvePriceImpact, formatMinOutAtUserSlippage, isCurveApiChainSupported, isCurveApiChainSupported as isCurveDaoChainSupported, isCurveDaoErc20ApproveEvmSignRequest, isCurveDaoSwapEvmSignRequest, isCurveTokenKeySwappable, loadCurveSessionSnapshotForRpc, loadFullCurveSessionForRpc, normalizeCurveRouterAmountString, resolveCurveDaoRouterGasUnitsFromSignRequest, swappableCurveGraphNodeKeys, toCurveRouterTokenId, toCurveTokenKey };
745
984
  //# sourceMappingURL=index.js.map
746
985
  //# sourceMappingURL=index.js.map