@zyfai/sdk 0.13.0 → 0.15.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -54,6 +54,9 @@ var ENDPOINTS = {
54
54
  USER_WITHDRAW: "/users/withdraw/v2",
55
55
  PARTIAL_WITHDRAW: "/users/partial-withdraw/v2",
56
56
  LOG_DEPOSIT: "/users/log_deposit/v2",
57
+ FIRST_PERMIT_DEPOSIT: "/users/me/permit-deposit",
58
+ FIRST_PERMIT_DEPOSIT_PREPARE: "/users/me/permit-deposit/prepare",
59
+ FIRST_PERMIT_DEPOSIT_SUBMIT: (id) => `/users/me/permit-deposit/${encodeURIComponent(id)}/submit`,
57
60
  FUNDING_ORDERS: "/users/me/funding-orders",
58
61
  FUNDING_ORDER: (orderId) => `/users/me/funding-orders/${encodeURIComponent(orderId)}`,
59
62
  FUNDING_ORDER_QUOTE: (orderId) => `/users/me/funding-orders/${encodeURIComponent(orderId)}/quote`,
@@ -261,8 +264,9 @@ var HttpClient = class {
261
264
  case 403:
262
265
  throw new Error("Forbidden: Access denied");
263
266
  case 404:
264
- throw new Error(
265
- `Not found: ${data.message || "Resource not found"}`
267
+ throw Object.assign(
268
+ new Error(`Not found: ${data.message || "Resource not found"}`),
269
+ { status }
266
270
  );
267
271
  case 429:
268
272
  throw new Error("Rate limit exceeded. Please try again later.");
@@ -385,6 +389,20 @@ var HttpClient = class {
385
389
  };
386
390
 
387
391
  // src/utils/poll.ts
392
+ async function pollUntil(fn, predicate, options) {
393
+ const intervalMs = options?.intervalMs ?? 5e3;
394
+ const timeoutMs = options?.timeoutMs ?? 12e4;
395
+ const label = options?.label ?? "condition";
396
+ const started = Date.now();
397
+ while (Date.now() - started < timeoutMs) {
398
+ const value = await fn();
399
+ if (predicate(value)) {
400
+ return { value, elapsedMs: Date.now() - started };
401
+ }
402
+ await new Promise((resolve) => setTimeout(resolve, intervalMs));
403
+ }
404
+ throw new Error(`Timed out waiting for ${label} after ${timeoutMs}ms`);
405
+ }
388
406
  function sleep(ms) {
389
407
  return new Promise((resolve) => setTimeout(resolve, ms));
390
408
  }
@@ -818,6 +836,7 @@ import {
818
836
  custom,
819
837
  http as http2,
820
838
  getAddress as getAddress2,
839
+ isAddressEqual as isAddressEqual2,
821
840
  encodeFunctionData as encodeFunctionData2,
822
841
  defineChain
823
842
  } from "viem";
@@ -1136,6 +1155,29 @@ var positiveUnits = (value) => {
1136
1155
  };
1137
1156
  var resolveCollateralMinimum = (storedMinimum, quote) => positiveUnits(storedMinimum) ?? positiveUnits(quote.details?.currencyOut?.minimumAmount) ?? positiveUnits(quote.details?.currencyOut?.amount) ?? "0";
1138
1157
 
1158
+ // src/deposits/first-permit-deposit.ts
1159
+ import { isAddressEqual } from "viem";
1160
+ var firstPermitTypes = {
1161
+ Permit: [
1162
+ { name: "owner", type: "address" },
1163
+ { name: "spender", type: "address" },
1164
+ { name: "value", type: "uint256" },
1165
+ { name: "nonce", type: "uint256" },
1166
+ { name: "deadline", type: "uint256" }
1167
+ ]
1168
+ };
1169
+ function matchesFirstPermitDeposit(intent, request) {
1170
+ return intent.chainId === request.chainId && isAddressEqual(intent.token, request.token) && intent.amount === request.amount.toString();
1171
+ }
1172
+ function validateFirstPermit({ domain, message }, request) {
1173
+ const value = BigInt(message.value);
1174
+ const nonce = BigInt(message.nonce);
1175
+ if (domain.chainId !== request.chainId || !isAddressEqual(domain.verifyingContract, request.token) || !isAddressEqual(message.owner, request.owner) || !isAddressEqual(message.spender, request.safe) || value !== request.amount || nonce < 0n || !Number.isSafeInteger(message.deadline) || message.deadline <= Math.floor(Date.now() / 1e3)) {
1176
+ throw new Error("Prepared permit does not match this deposit");
1177
+ }
1178
+ return { ...message, value, nonce, deadline: BigInt(message.deadline) };
1179
+ }
1180
+
1139
1181
  // src/deposits/relay-slippage.ts
1140
1182
  var DEFAULT_RELAY_SLIPPAGE_BPS = 200;
1141
1183
  var MAX_RELAY_SLIPPAGE_BPS = 500;
@@ -3545,14 +3587,16 @@ var _ZyfaiSDK = class _ZyfaiSDK {
3545
3587
  return this.httpClient.post(ENDPOINTS.DEPLOY_CHAINS, { chainIds });
3546
3588
  }
3547
3589
  /**
3548
- * Transfer a collateral token the wallet already holds into the Safe.
3590
+ * Deposit a collateral token the wallet already holds into the Safe.
3549
3591
  *
3550
3592
  * @remarks
3551
3593
  * Use this when the connected wallet holds the strategy collateral on the
3552
3594
  * deposit chain. {@link ZyfaiSDK.sendDeposit} calls this automatically in
3553
3595
  * that case. A different token uses {@link ZyfaiSDK.sendSwapDeposit}.
3554
3596
  *
3555
- * Confirms the ERC-20 `transfer`, then calls {@link ZyfaiSDK.logDeposit}.
3597
+ * Eligible first deposits sign an ERC-2612 permit and the backend sponsors and
3598
+ * registers the pull. Other direct deposits confirm an ERC-20 transfer and
3599
+ * call {@link ZyfaiSDK.logDeposit}.
3556
3600
  * Requires {@link ZyfaiSDK.connectAccount}. Pass the **EOA** as `userAddress`.
3557
3601
  *
3558
3602
  * @group Deposits and withdrawals
@@ -3576,6 +3620,9 @@ var _ZyfaiSDK = class _ZyfaiSDK {
3576
3620
  * ```
3577
3621
  */
3578
3622
  async sendDirectDeposit(userAddress, chainId, amount, asset, strategy) {
3623
+ return this.sendCollateralDeposit(userAddress, chainId, amount, asset, strategy, true);
3624
+ }
3625
+ async sendCollateralDeposit(userAddress, chainId, amount, asset, strategy, allowPermit) {
3579
3626
  try {
3580
3627
  if (!userAddress) {
3581
3628
  throw new Error("User address is required");
@@ -3667,6 +3714,16 @@ var _ZyfaiSDK = class _ZyfaiSDK {
3667
3714
  );
3668
3715
  }
3669
3716
  }
3717
+ if (allowPermit && this.isPredeployed && this.isConnectedUser(userAddress)) {
3718
+ const sponsored = await this.sendFirstPermitDeposit({
3719
+ owner: getAddress2(userAddress),
3720
+ safe: safeAddress,
3721
+ chainId,
3722
+ token: getAddress2(token),
3723
+ amount: amountBigInt
3724
+ });
3725
+ if (sponsored) return sponsored;
3726
+ }
3670
3727
  const txHash = await walletClient.writeContract({
3671
3728
  address: token,
3672
3729
  abi: erc20TransferWriteAbi(assetSymbol),
@@ -3699,6 +3756,115 @@ var _ZyfaiSDK = class _ZyfaiSDK {
3699
3756
  throw new Error(`Deposit failed: ${error.message}`);
3700
3757
  }
3701
3758
  }
3759
+ /**
3760
+ * Read the current first-deposit permit intent after a pending or interrupted deposit.
3761
+ *
3762
+ * @remarks
3763
+ * Uses the execution API and the SIWE session from {@link ZyfaiSDK.connectAccount}.
3764
+ * A registered intent provides the deposit id for {@link ZyfaiSDK.getDepositStatus}.
3765
+ *
3766
+ * @group Deposits and withdrawals
3767
+ *
3768
+ * @param userAddress - Authenticated EOA
3769
+ * @returns The latest permit intent, or null when no intent exists
3770
+ * @throws If the address differs from the authenticated EOA or the request fails
3771
+ *
3772
+ * @example
3773
+ * ```typescript
3774
+ * const intent = await sdk.getFirstPermitDepositStatus(eoa);
3775
+ * if (intent?.depositId) await sdk.waitForDepositCredit(intent.depositId, intent.chainId);
3776
+ * ```
3777
+ */
3778
+ async getFirstPermitDepositStatus(userAddress) {
3779
+ if (!this.sessionEoa || !isAddressEqual2(getAddress2(userAddress), this.sessionEoa)) {
3780
+ throw new Error("userAddress does not match authenticated session EOA");
3781
+ }
3782
+ return (await this.getFirstPermitDepositAvailability()).intent;
3783
+ }
3784
+ async getFirstPermitDepositAvailability(chainId) {
3785
+ try {
3786
+ return await this.httpClient.get(
3787
+ ENDPOINTS.FIRST_PERMIT_DEPOSIT,
3788
+ chainId != null ? { params: { chainId } } : void 0
3789
+ );
3790
+ } catch (error) {
3791
+ if (error instanceof Error && "status" in error && error.status === 404) {
3792
+ return { enabledTokens: [], intent: null };
3793
+ }
3794
+ throw error;
3795
+ }
3796
+ }
3797
+ async sendFirstPermitDeposit(request) {
3798
+ const { enabledTokens, intent, permitPreferred } = await this.getFirstPermitDepositAvailability(request.chainId);
3799
+ let id;
3800
+ let accepted;
3801
+ if (intent?.status === "queued" || intent?.status === "submitted") {
3802
+ if (!matchesFirstPermitDeposit(intent, request)) {
3803
+ throw new Error(`First permit deposit ${intent.id} is already pending for a different deposit`);
3804
+ }
3805
+ id = intent.id;
3806
+ accepted = intent;
3807
+ } else {
3808
+ const { owner, chainId, token, amount } = request;
3809
+ if (permitPreferred === false) return null;
3810
+ if (!enabledTokens.includes(`${chainId}:${token.toLowerCase()}`)) return null;
3811
+ const prepared = await this.httpClient.post(
3812
+ ENDPOINTS.FIRST_PERMIT_DEPOSIT_PREPARE,
3813
+ { owner, chainId, token, amount: amount.toString() }
3814
+ );
3815
+ if (!prepared) return null;
3816
+ const message = validateFirstPermit(prepared, request);
3817
+ const currentWallet = this.getWalletClient();
3818
+ const wallet = currentWallet.chain?.id === chainId ? currentWallet : await this.walletClientForOrigin(chainId);
3819
+ const signature = await wallet.signTypedData({
3820
+ account: wallet.account,
3821
+ domain: prepared.domain,
3822
+ types: firstPermitTypes,
3823
+ primaryType: "Permit",
3824
+ message
3825
+ });
3826
+ id = prepared.id;
3827
+ try {
3828
+ accepted = await this.httpClient.post(
3829
+ ENDPOINTS.FIRST_PERMIT_DEPOSIT_SUBMIT(id),
3830
+ { signature }
3831
+ );
3832
+ } catch (error) {
3833
+ accepted = await this.getFirstPermitDepositStatus(owner).catch(() => null);
3834
+ if (accepted?.id !== id || accepted.status === "prepared") {
3835
+ throw new Error(
3836
+ `Could not confirm first permit deposit ${id}. Check getFirstPermitDepositStatus before retrying: ${thrownMessage(error)}`
3837
+ );
3838
+ }
3839
+ }
3840
+ }
3841
+ let status = accepted;
3842
+ const { value: registered } = await pollUntil(async () => {
3843
+ const current = status ?? await this.getFirstPermitDepositStatus(request.owner);
3844
+ status = null;
3845
+ if (current?.id !== id || !matchesFirstPermitDeposit(current, request)) {
3846
+ throw new Error(`Unable to resolve first permit deposit ${id}. Check getFirstPermitDepositStatus before retrying.`);
3847
+ }
3848
+ if (current.status === "failed") {
3849
+ throw new Error(`First permit deposit ${id} failed`);
3850
+ }
3851
+ return current;
3852
+ }, (current) => current.status === "registered", {
3853
+ intervalMs: 3e3,
3854
+ label: `first permit deposit ${id} registration. Check getFirstPermitDepositStatus before retrying`
3855
+ });
3856
+ if (!registered.txHash || !registered.depositId) {
3857
+ throw new Error(`First permit deposit ${id} is missing its registration. Check getFirstPermitDepositStatus before retrying.`);
3858
+ }
3859
+ return {
3860
+ success: true,
3861
+ txHash: registered.txHash,
3862
+ smartWallet: request.safe,
3863
+ amount: registered.amount,
3864
+ route: "direct",
3865
+ registration: await this.getDepositStatus(registered.depositId)
3866
+ };
3867
+ }
3702
3868
  async sendDeposit(userAddressOrParams, chainId, amount, asset, strategy) {
3703
3869
  if (typeof userAddressOrParams !== "string") {
3704
3870
  return this.sendRoutedDeposit(userAddressOrParams);
@@ -3987,12 +4153,13 @@ var _ZyfaiSDK = class _ZyfaiSDK {
3987
4153
  BigInt(params.amount)
3988
4154
  );
3989
4155
  await this.wrapNativeEth(params.chainId, params.amount);
3990
- const sent = await this.sendDirectDeposit(
4156
+ const sent = await this.sendCollateralDeposit(
3991
4157
  params.userAddress,
3992
4158
  params.chainId,
3993
4159
  params.amount,
3994
4160
  "WETH",
3995
- params.strategy
4161
+ params.strategy,
4162
+ false
3996
4163
  );
3997
4164
  return { ...sent, route: "wrap" };
3998
4165
  }
@@ -5812,19 +5979,19 @@ var _ZyfaiSDK = class _ZyfaiSDK {
5812
5979
  }
5813
5980
  }
5814
5981
  /**
5815
- * Get aggressive (high-risk, high-reward) yield opportunities
5982
+ * Get balanced (high-risk, high-reward) yield opportunities.
5816
5983
  *
5817
5984
  * @param chainId - Optional chain ID filter
5818
5985
  * @param asset - Optional asset filter (e.g. "USDC", "WETH", "WBTC")
5819
- * @returns List of aggressive opportunities
5986
+ * @returns List of balanced opportunities
5820
5987
  *
5821
5988
  * @example
5822
5989
  * ```typescript
5823
- * const opportunities = await sdk.getAggressiveOpportunities(8453, "WETH");
5990
+ * const opportunities = await sdk.getBalancedOpportunities(8453, "WETH");
5824
5991
  * opportunities.data.forEach(o => console.log(o.protocolName, o.apy));
5825
5992
  * ```
5826
5993
  */
5827
- async getAggressiveOpportunities(chainId, asset, status) {
5994
+ async getBalancedOpportunities(chainId, asset, status) {
5828
5995
  try {
5829
5996
  const response = await this.httpClient.dataGet(
5830
5997
  DATA_ENDPOINTS.OPPORTUNITIES_DEGEN(chainId, asset, status)
@@ -5833,7 +6000,7 @@ var _ZyfaiSDK = class _ZyfaiSDK {
5833
6000
  return {
5834
6001
  success: true,
5835
6002
  chainId,
5836
- strategyType: "aggressive",
6003
+ strategyType: "balanced",
5837
6004
  data: Array.isArray(data) ? data.map((o) => ({
5838
6005
  id: o.id,
5839
6006
  protocolId: o.protocol_id || o.protocolId,
@@ -5844,34 +6011,47 @@ var _ZyfaiSDK = class _ZyfaiSDK {
5844
6011
  tvl: o.tvl || o.zyfiTvl,
5845
6012
  asset: o.asset || o.underlying_token,
5846
6013
  risk: o.risk,
5847
- strategyType: "aggressive",
6014
+ strategyType: "balanced",
5848
6015
  status: o.status
5849
6016
  })) : []
5850
6017
  };
5851
6018
  } catch (error) {
5852
6019
  throw new Error(
5853
- `Failed to get aggressive opportunities: ${error.message}`
6020
+ `Failed to get balanced opportunities: ${error.message}`
5854
6021
  );
5855
6022
  }
5856
6023
  }
5857
6024
  /**
5858
- * Get yieldmaxxing opportunities — pools reachable only with the
5859
- * `"yieldmaxxing"` strategy, including protocols whose withdrawals are
6025
+ * @deprecated Use {@link getBalancedOpportunities} instead. Retains the
6026
+ * pre-rename `getAggressiveOpportunities` entry point; same HTTP request as
6027
+ * balanced, with legacy `strategyType: "aggressive"` on the response and rows.
6028
+ */
6029
+ async getAggressiveOpportunities(chainId, asset, status) {
6030
+ const result = await this.getBalancedOpportunities(chainId, asset, status);
6031
+ return {
6032
+ ...result,
6033
+ strategyType: "aggressive",
6034
+ data: result.data.map((o) => ({ ...o, strategyType: "aggressive" }))
6035
+ };
6036
+ }
6037
+ /**
6038
+ * Get advanced yield opportunities — pools reachable only with the
6039
+ * `"advanced"` strategy, including protocols whose withdrawals are
5860
6040
  * asynchronous (Ipor, Superform). Exiting these pools takes about a day
5861
6041
  * on Ipor and three on Superform; track the redemption through
5862
6042
  * `getPortfolio().portfolio.pendingAsyncWithdrawals`.
5863
6043
  *
5864
6044
  * @param chainId - Optional chain ID filter
5865
6045
  * @param asset - Optional asset filter (e.g. "USDC", "WETH")
5866
- * @returns List of yieldmaxxing opportunities
6046
+ * @returns List of advanced opportunities
5867
6047
  *
5868
6048
  * @example
5869
6049
  * ```typescript
5870
- * const opportunities = await sdk.getAsyncOpportunities(8453);
6050
+ * const opportunities = await sdk.getAdvancedOpportunities(8453);
5871
6051
  * opportunities.data.forEach(o => console.log(o.protocolName, o.apy));
5872
6052
  * ```
5873
6053
  */
5874
- async getAsyncOpportunities(chainId, asset, status) {
6054
+ async getAdvancedOpportunities(chainId, asset, status) {
5875
6055
  try {
5876
6056
  const response = await this.httpClient.dataGet(
5877
6057
  DATA_ENDPOINTS.OPPORTUNITIES_ASYNC(chainId, asset, status)
@@ -5880,7 +6060,7 @@ var _ZyfaiSDK = class _ZyfaiSDK {
5880
6060
  return {
5881
6061
  success: true,
5882
6062
  chainId,
5883
- strategyType: "yieldmaxxing",
6063
+ strategyType: "advanced",
5884
6064
  data: Array.isArray(data) ? data.map((o) => ({
5885
6065
  id: o.id,
5886
6066
  protocolId: o.protocol_id || o.protocolId,
@@ -5891,16 +6071,29 @@ var _ZyfaiSDK = class _ZyfaiSDK {
5891
6071
  tvl: o.tvl || o.zyfiTvl,
5892
6072
  asset: o.asset || o.underlying_token,
5893
6073
  risk: o.risk,
5894
- strategyType: "yieldmaxxing",
6074
+ strategyType: "advanced",
5895
6075
  status: o.status
5896
6076
  })) : []
5897
6077
  };
5898
6078
  } catch (error) {
5899
6079
  throw new Error(
5900
- `Failed to get yieldmaxxing opportunities: ${error.message}`
6080
+ `Failed to get advanced opportunities: ${error.message}`
5901
6081
  );
5902
6082
  }
5903
6083
  }
6084
+ /**
6085
+ * @deprecated Use {@link getAdvancedOpportunities} instead. Retains the
6086
+ * pre-rename `getAsyncOpportunities` entry point; same HTTP request as
6087
+ * advanced, with legacy `strategyType: "yieldmaxxing"` on the response and rows.
6088
+ */
6089
+ async getAsyncOpportunities(chainId, asset, status) {
6090
+ const result = await this.getAdvancedOpportunities(chainId, asset, status);
6091
+ return {
6092
+ ...result,
6093
+ strategyType: "yieldmaxxing",
6094
+ data: result.data.map((o) => ({ ...o, strategyType: "yieldmaxxing" }))
6095
+ };
6096
+ }
5904
6097
  /**
5905
6098
  * Get active conservative opportunities (status = "live") with risk and utilization data
5906
6099
  * Returns pool info, liquidity depth (true if > 1M), utilization rate, stability metrics, avg APY, and collateral
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@zyfai/sdk",
3
- "version": "0.13.0",
3
+ "version": "0.15.0",
4
4
  "description": "TypeScript SDK for self-custodial Zyfai yield agents: discover DeFi opportunities and manage deposits, withdrawals, positions, and strategies across Ethereum, Base, and Arbitrum",
5
5
  "main": "dist/index.js",
6
6
  "module": "dist/index.mjs",