@zyfai/sdk 0.12.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.js CHANGED
@@ -128,6 +128,9 @@ var ENDPOINTS = {
128
128
  USER_WITHDRAW: "/users/withdraw/v2",
129
129
  PARTIAL_WITHDRAW: "/users/partial-withdraw/v2",
130
130
  LOG_DEPOSIT: "/users/log_deposit/v2",
131
+ FIRST_PERMIT_DEPOSIT: "/users/me/permit-deposit",
132
+ FIRST_PERMIT_DEPOSIT_PREPARE: "/users/me/permit-deposit/prepare",
133
+ FIRST_PERMIT_DEPOSIT_SUBMIT: (id) => `/users/me/permit-deposit/${encodeURIComponent(id)}/submit`,
131
134
  FUNDING_ORDERS: "/users/me/funding-orders",
132
135
  FUNDING_ORDER: (orderId) => `/users/me/funding-orders/${encodeURIComponent(orderId)}`,
133
136
  FUNDING_ORDER_QUOTE: (orderId) => `/users/me/funding-orders/${encodeURIComponent(orderId)}/quote`,
@@ -335,8 +338,9 @@ var HttpClient = class {
335
338
  case 403:
336
339
  throw new Error("Forbidden: Access denied");
337
340
  case 404:
338
- throw new Error(
339
- `Not found: ${data.message || "Resource not found"}`
341
+ throw Object.assign(
342
+ new Error(`Not found: ${data.message || "Resource not found"}`),
343
+ { status }
340
344
  );
341
345
  case 429:
342
346
  throw new Error("Rate limit exceeded. Please try again later.");
@@ -459,6 +463,20 @@ var HttpClient = class {
459
463
  };
460
464
 
461
465
  // src/utils/poll.ts
466
+ async function pollUntil(fn, predicate, options) {
467
+ const intervalMs = options?.intervalMs ?? 5e3;
468
+ const timeoutMs = options?.timeoutMs ?? 12e4;
469
+ const label = options?.label ?? "condition";
470
+ const started = Date.now();
471
+ while (Date.now() - started < timeoutMs) {
472
+ const value = await fn();
473
+ if (predicate(value)) {
474
+ return { value, elapsedMs: Date.now() - started };
475
+ }
476
+ await new Promise((resolve) => setTimeout(resolve, intervalMs));
477
+ }
478
+ throw new Error(`Timed out waiting for ${label} after ${timeoutMs}ms`);
479
+ }
462
480
  function sleep(ms) {
463
481
  return new Promise((resolve) => setTimeout(resolve, ms));
464
482
  }
@@ -691,6 +709,63 @@ var VAULT_ABI = [
691
709
  }
692
710
  ];
693
711
  var VAULT_ADDRESS = "0xD580071c47d4a667858B5FafAb85BC9C609beC5D";
712
+ var MERKL_DISTRIBUTOR_ADDRESS = "0x3Ef3D8bA38EBe18DB133cEc108f4D14CE00Dd9Ae";
713
+ var RZFI_TOKEN_ADDRESS = "0x1c08C7df416062b472F553DCC1ed3045489520C5";
714
+ var MERKL_DISTRIBUTOR_ABI = (0, import_viem.parseAbi)([
715
+ "function claim(address[] users, address[] tokens, uint256[] amounts, bytes32[][] proofs)",
716
+ "function claimed(address user, address token) view returns (uint208 amount, uint48 timestamp, bytes32 merkleRoot)",
717
+ "function getMerkleRoot() view returns (bytes32)"
718
+ ]);
719
+ var SAFE_ABI = (0, import_viem.parseAbi)([
720
+ "function execTransaction(address to, uint256 value, bytes data, uint8 operation, uint256 safeTxGas, uint256 baseGas, uint256 gasPrice, address gasToken, address refundReceiver, bytes signatures) payable returns (bool success)",
721
+ "function getOwners() view returns (address[])",
722
+ "function getThreshold() view returns (uint256)"
723
+ ]);
724
+
725
+ // src/utils/rzfi-claim.ts
726
+ var import_viem2 = require("viem");
727
+ var MERKL_API_URL = "https://api.merkl.xyz/v4";
728
+ async function fetchMerklRzfiReward(safe) {
729
+ const response = await fetch(
730
+ `${MERKL_API_URL}/users/${safe}/rewards?chainId=8453`
731
+ );
732
+ if (!response.ok) {
733
+ throw new Error(`Merkl API error: ${response.status}`);
734
+ }
735
+ const body = await response.json();
736
+ const reward = body[0]?.rewards?.find(
737
+ (r) => r.token.address.toLowerCase() === RZFI_TOKEN_ADDRESS.toLowerCase()
738
+ );
739
+ return reward ? { amount: BigInt(reward.amount), root: reward.root, proofs: reward.proofs } : null;
740
+ }
741
+ function encodeRzfiClaimExecTransaction(params) {
742
+ const { safe, owner, amount, proofs } = params;
743
+ const claimData = (0, import_viem2.encodeFunctionData)({
744
+ abi: MERKL_DISTRIBUTOR_ABI,
745
+ functionName: "claim",
746
+ args: [[safe], [RZFI_TOKEN_ADDRESS], [amount], [proofs]]
747
+ });
748
+ const signature = (0, import_viem2.encodePacked)(
749
+ ["bytes32", "bytes32", "uint8"],
750
+ [(0, import_viem2.pad)(owner), (0, import_viem2.pad)("0x00"), 1]
751
+ );
752
+ return (0, import_viem2.encodeFunctionData)({
753
+ abi: SAFE_ABI,
754
+ functionName: "execTransaction",
755
+ args: [
756
+ MERKL_DISTRIBUTOR_ADDRESS,
757
+ 0n,
758
+ claimData,
759
+ 0,
760
+ 0n,
761
+ 0n,
762
+ 0n,
763
+ import_viem2.zeroAddress,
764
+ import_viem2.zeroAddress,
765
+ signature
766
+ ]
767
+ });
768
+ }
694
769
 
695
770
  // src/config/constants.ts
696
771
  var ZYFI_FEE_RATE = 0.1;
@@ -825,11 +900,11 @@ function isMainnetMinPortfolioExempt(chainId, ...addresses) {
825
900
 
826
901
  // src/core/ZyfaiSDK.ts
827
902
  var import_accounts2 = require("viem/accounts");
828
- var import_viem4 = require("viem");
903
+ var import_viem6 = require("viem");
829
904
  var import_relay_sdk2 = require("@relayprotocol/relay-sdk");
830
905
 
831
906
  // src/config/chains.ts
832
- var import_viem2 = require("viem");
907
+ var import_viem3 = require("viem");
833
908
  var import_chains = require("viem/chains");
834
909
  var DEFAULT_TOKEN_ADDRESSES = {
835
910
  1: "0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48",
@@ -1004,9 +1079,9 @@ var getChainConfig = (chainId, rpcUrls) => {
1004
1079
  throw new Error(`Unsupported chain ID: ${chainId}`);
1005
1080
  }
1006
1081
  const rpcUrl = rpcUrls && rpcUrls[chainId] || DEFAULT_RPC_URLS[chainId];
1007
- const publicClient = (0, import_viem2.createPublicClient)({
1082
+ const publicClient = (0, import_viem3.createPublicClient)({
1008
1083
  chain,
1009
- transport: (0, import_viem2.http)(rpcUrl)
1084
+ transport: (0, import_viem3.http)(rpcUrl)
1010
1085
  });
1011
1086
  return {
1012
1087
  chain,
@@ -1141,6 +1216,29 @@ var positiveUnits = (value) => {
1141
1216
  };
1142
1217
  var resolveCollateralMinimum = (storedMinimum, quote) => positiveUnits(storedMinimum) ?? positiveUnits(quote.details?.currencyOut?.minimumAmount) ?? positiveUnits(quote.details?.currencyOut?.amount) ?? "0";
1143
1218
 
1219
+ // src/deposits/first-permit-deposit.ts
1220
+ var import_viem4 = require("viem");
1221
+ var firstPermitTypes = {
1222
+ Permit: [
1223
+ { name: "owner", type: "address" },
1224
+ { name: "spender", type: "address" },
1225
+ { name: "value", type: "uint256" },
1226
+ { name: "nonce", type: "uint256" },
1227
+ { name: "deadline", type: "uint256" }
1228
+ ]
1229
+ };
1230
+ function matchesFirstPermitDeposit(intent, request) {
1231
+ return intent.chainId === request.chainId && (0, import_viem4.isAddressEqual)(intent.token, request.token) && intent.amount === request.amount.toString();
1232
+ }
1233
+ function validateFirstPermit({ domain, message }, request) {
1234
+ const value = BigInt(message.value);
1235
+ const nonce = BigInt(message.nonce);
1236
+ if (domain.chainId !== request.chainId || !(0, import_viem4.isAddressEqual)(domain.verifyingContract, request.token) || !(0, import_viem4.isAddressEqual)(message.owner, request.owner) || !(0, import_viem4.isAddressEqual)(message.spender, request.safe) || value !== request.amount || nonce < 0n || !Number.isSafeInteger(message.deadline) || message.deadline <= Math.floor(Date.now() / 1e3)) {
1237
+ throw new Error("Prepared permit does not match this deposit");
1238
+ }
1239
+ return { ...message, value, nonce, deadline: BigInt(message.deadline) };
1240
+ }
1241
+
1144
1242
  // src/deposits/relay-slippage.ts
1145
1243
  var DEFAULT_RELAY_SLIPPAGE_BPS = 200;
1146
1244
  var MAX_RELAY_SLIPPAGE_BPS = 500;
@@ -1264,7 +1362,7 @@ function getManagedAssets() {
1264
1362
  // src/utils/safe-account.ts
1265
1363
  var import_module_sdk = require("@rhinestone/module-sdk");
1266
1364
  var import_accounts = require("permissionless/accounts");
1267
- var import_viem3 = require("viem");
1365
+ var import_viem5 = require("viem");
1268
1366
  var import_account_abstraction = require("viem/account-abstraction");
1269
1367
 
1270
1368
  // src/config/modules.ts
@@ -1294,12 +1392,12 @@ var getSafeAccount = async (config) => {
1294
1392
  if (!safeOwnerAddress) {
1295
1393
  throw new Error("Safe owner address is required");
1296
1394
  }
1297
- const formattedOwnerAddress = (0, import_viem3.getAddress)(safeOwnerAddress);
1395
+ const formattedOwnerAddress = (0, import_viem5.getAddress)(safeOwnerAddress);
1298
1396
  const ownableValidator = (0, import_module_sdk.getOwnableValidator)({
1299
1397
  owners: [formattedOwnerAddress],
1300
1398
  threshold: 1
1301
1399
  });
1302
- const saltHex = (0, import_viem3.fromHex)((0, import_viem3.toHex)(ACCOUNT_SALT), "bigint");
1400
+ const saltHex = (0, import_viem5.fromHex)((0, import_viem5.toHex)(ACCOUNT_SALT), "bigint");
1303
1401
  const tempOwner = {
1304
1402
  address: formattedOwnerAddress,
1305
1403
  type: "json-rpc"
@@ -1346,12 +1444,12 @@ var isSafeDeployed = async (address, publicClient) => {
1346
1444
  }
1347
1445
  };
1348
1446
  var isOwnableValidatorOwner = async (safeAddress, userAddress, publicClient) => {
1349
- const normalizedUser = (0, import_viem3.getAddress)(userAddress);
1350
- const normalizedSafe = (0, import_viem3.getAddress)(safeAddress);
1447
+ const normalizedUser = (0, import_viem5.getAddress)(userAddress);
1448
+ const normalizedSafe = (0, import_viem5.getAddress)(safeAddress);
1351
1449
  const validatorAddresses = Array.from(
1352
1450
  /* @__PURE__ */ new Set([
1353
- (0, import_viem3.getAddress)(OWNABLE_VALIDATOR),
1354
- (0, import_viem3.getAddress)(import_module_sdk.OWNABLE_VALIDATOR_ADDRESS)
1451
+ (0, import_viem5.getAddress)(OWNABLE_VALIDATOR),
1452
+ (0, import_viem5.getAddress)(import_module_sdk.OWNABLE_VALIDATOR_ADDRESS)
1355
1453
  ])
1356
1454
  );
1357
1455
  for (const validatorAddress of validatorAddresses) {
@@ -1362,7 +1460,7 @@ var isOwnableValidatorOwner = async (safeAddress, userAddress, publicClient) =>
1362
1460
  functionName: "getOwners",
1363
1461
  args: [normalizedSafe]
1364
1462
  });
1365
- if (owners.some((owner) => (0, import_viem3.getAddress)(owner) === normalizedUser)) {
1463
+ if (owners.some((owner) => (0, import_viem5.getAddress)(owner) === normalizedUser)) {
1366
1464
  return true;
1367
1465
  }
1368
1466
  } catch {
@@ -2140,7 +2238,7 @@ var _ZyfaiSDK = class _ZyfaiSDK {
2140
2238
  }
2141
2239
  this.httpClient.setAuthToken(session.accessToken);
2142
2240
  this.authenticatedUserId = session.userId ?? "bearer-session";
2143
- this.sessionEoa = session.eoa ? (0, import_viem4.getAddress)(session.eoa) : null;
2241
+ this.sessionEoa = session.eoa ? (0, import_viem6.getAddress)(session.eoa) : null;
2144
2242
  this.sessionChannel = session.channel;
2145
2243
  this.isPredeployed = false;
2146
2244
  this.predeployedResolved = false;
@@ -2189,7 +2287,7 @@ var _ZyfaiSDK = class _ZyfaiSDK {
2189
2287
  this.isPredeployed = loginResponse.predeployed || false;
2190
2288
  this.predeployedResolved = true;
2191
2289
  this.connectedSmartWallet = loginResponse.smartWallet || null;
2192
- this.sessionEoa = (0, import_viem4.getAddress)(params.message.address);
2290
+ this.sessionEoa = (0, import_viem6.getAddress)(params.message.address);
2193
2291
  this.sessionChannel = void 0;
2194
2292
  return loginResponse;
2195
2293
  }
@@ -2218,7 +2316,7 @@ var _ZyfaiSDK = class _ZyfaiSDK {
2218
2316
  return;
2219
2317
  }
2220
2318
  const walletClient = this.getWalletClient();
2221
- const userAddress = (0, import_viem4.getAddress)(walletClient.account.address);
2319
+ const userAddress = (0, import_viem6.getAddress)(walletClient.account.address);
2222
2320
  const chainId = this.currentChainId || walletClient.chain?.id || 8453;
2223
2321
  const challengeResponse = await this.httpClient.post(ENDPOINTS.AUTH_CHALLENGE, {});
2224
2322
  let uri;
@@ -2596,10 +2694,10 @@ var _ZyfaiSDK = class _ZyfaiSDK {
2596
2694
  this.walletClient.chain?.id || 8453,
2597
2695
  this.rpcUrls
2598
2696
  );
2599
- this.walletClient = (0, import_viem4.createWalletClient)({
2697
+ this.walletClient = (0, import_viem6.createWalletClient)({
2600
2698
  account: newAddress,
2601
2699
  chain: chainConfig.chain,
2602
- transport: (0, import_viem4.custom)(this.currentProvider)
2700
+ transport: (0, import_viem6.custom)(this.currentProvider)
2603
2701
  });
2604
2702
  this.currentChainId = this.walletClient.chain?.id || null;
2605
2703
  try {
@@ -2664,10 +2762,10 @@ var _ZyfaiSDK = class _ZyfaiSDK {
2664
2762
  }
2665
2763
  this.signer = (0, import_accounts2.privateKeyToAccount)(privateKey);
2666
2764
  this.currentChainId = chainId;
2667
- this.walletClient = (0, import_viem4.createWalletClient)({
2765
+ this.walletClient = (0, import_viem6.createWalletClient)({
2668
2766
  account: this.signer,
2669
2767
  chain: chainConfig.chain,
2670
- transport: (0, import_viem4.http)(chainConfig.rpcUrl)
2768
+ transport: (0, import_viem6.http)(chainConfig.rpcUrl)
2671
2769
  });
2672
2770
  connectedAddress = this.signer.address;
2673
2771
  this.currentProvider = null;
@@ -2685,10 +2783,10 @@ var _ZyfaiSDK = class _ZyfaiSDK {
2685
2783
  if (!accounts || accounts.length === 0) {
2686
2784
  throw new Error("No accounts found in wallet provider");
2687
2785
  }
2688
- this.walletClient = (0, import_viem4.createWalletClient)({
2786
+ this.walletClient = (0, import_viem6.createWalletClient)({
2689
2787
  account: accounts[0],
2690
2788
  chain: chainConfig.chain,
2691
- transport: (0, import_viem4.custom)(provider)
2789
+ transport: (0, import_viem6.custom)(provider)
2692
2790
  });
2693
2791
  connectedAddress = accounts[0];
2694
2792
  this.currentProvider = provider;
@@ -2697,7 +2795,7 @@ var _ZyfaiSDK = class _ZyfaiSDK {
2697
2795
  provider.on("accountsChanged", this.handleAccountsChanged.bind(this));
2698
2796
  }
2699
2797
  } else if (provider.account && provider.transport) {
2700
- this.walletClient = (0, import_viem4.createWalletClient)({
2798
+ this.walletClient = (0, import_viem6.createWalletClient)({
2701
2799
  account: provider.account,
2702
2800
  chain: chainConfig.chain,
2703
2801
  transport: provider.transport
@@ -2758,10 +2856,10 @@ var _ZyfaiSDK = class _ZyfaiSDK {
2758
2856
  targetChainId,
2759
2857
  this.rpcUrls
2760
2858
  );
2761
- return (0, import_viem4.createWalletClient)({
2859
+ return (0, import_viem6.createWalletClient)({
2762
2860
  account: this.signer,
2763
2861
  chain: targetChainConfig.chain,
2764
- transport: (0, import_viem4.http)(targetChainConfig.rpcUrl)
2862
+ transport: (0, import_viem6.http)(targetChainConfig.rpcUrl)
2765
2863
  });
2766
2864
  } else {
2767
2865
  if (!this.walletClient) {
@@ -3531,14 +3629,16 @@ var _ZyfaiSDK = class _ZyfaiSDK {
3531
3629
  return this.httpClient.post(ENDPOINTS.DEPLOY_CHAINS, { chainIds });
3532
3630
  }
3533
3631
  /**
3534
- * Transfer a collateral token the wallet already holds into the Safe.
3632
+ * Deposit a collateral token the wallet already holds into the Safe.
3535
3633
  *
3536
3634
  * @remarks
3537
3635
  * Use this when the connected wallet holds the strategy collateral on the
3538
3636
  * deposit chain. {@link ZyfaiSDK.sendDeposit} calls this automatically in
3539
3637
  * that case. A different token uses {@link ZyfaiSDK.sendSwapDeposit}.
3540
3638
  *
3541
- * Confirms the ERC-20 `transfer`, then calls {@link ZyfaiSDK.logDeposit}.
3639
+ * Eligible first deposits sign an ERC-2612 permit and the backend sponsors and
3640
+ * registers the pull. Other direct deposits confirm an ERC-20 transfer and
3641
+ * call {@link ZyfaiSDK.logDeposit}.
3542
3642
  * Requires {@link ZyfaiSDK.connectAccount}. Pass the **EOA** as `userAddress`.
3543
3643
  *
3544
3644
  * @group Deposits and withdrawals
@@ -3562,6 +3662,9 @@ var _ZyfaiSDK = class _ZyfaiSDK {
3562
3662
  * ```
3563
3663
  */
3564
3664
  async sendDirectDeposit(userAddress, chainId, amount, asset, strategy) {
3665
+ return this.sendCollateralDeposit(userAddress, chainId, amount, asset, strategy, true);
3666
+ }
3667
+ async sendCollateralDeposit(userAddress, chainId, amount, asset, strategy, allowPermit) {
3565
3668
  try {
3566
3669
  if (!userAddress) {
3567
3670
  throw new Error("User address is required");
@@ -3653,6 +3756,16 @@ var _ZyfaiSDK = class _ZyfaiSDK {
3653
3756
  );
3654
3757
  }
3655
3758
  }
3759
+ if (allowPermit && this.isPredeployed && this.isConnectedUser(userAddress)) {
3760
+ const sponsored = await this.sendFirstPermitDeposit({
3761
+ owner: (0, import_viem6.getAddress)(userAddress),
3762
+ safe: safeAddress,
3763
+ chainId,
3764
+ token: (0, import_viem6.getAddress)(token),
3765
+ amount: amountBigInt
3766
+ });
3767
+ if (sponsored) return sponsored;
3768
+ }
3656
3769
  const txHash = await walletClient.writeContract({
3657
3770
  address: token,
3658
3771
  abi: erc20TransferWriteAbi(assetSymbol),
@@ -3685,6 +3798,115 @@ var _ZyfaiSDK = class _ZyfaiSDK {
3685
3798
  throw new Error(`Deposit failed: ${error.message}`);
3686
3799
  }
3687
3800
  }
3801
+ /**
3802
+ * Read the current first-deposit permit intent after a pending or interrupted deposit.
3803
+ *
3804
+ * @remarks
3805
+ * Uses the execution API and the SIWE session from {@link ZyfaiSDK.connectAccount}.
3806
+ * A registered intent provides the deposit id for {@link ZyfaiSDK.getDepositStatus}.
3807
+ *
3808
+ * @group Deposits and withdrawals
3809
+ *
3810
+ * @param userAddress - Authenticated EOA
3811
+ * @returns The latest permit intent, or null when no intent exists
3812
+ * @throws If the address differs from the authenticated EOA or the request fails
3813
+ *
3814
+ * @example
3815
+ * ```typescript
3816
+ * const intent = await sdk.getFirstPermitDepositStatus(eoa);
3817
+ * if (intent?.depositId) await sdk.waitForDepositCredit(intent.depositId, intent.chainId);
3818
+ * ```
3819
+ */
3820
+ async getFirstPermitDepositStatus(userAddress) {
3821
+ if (!this.sessionEoa || !(0, import_viem6.isAddressEqual)((0, import_viem6.getAddress)(userAddress), this.sessionEoa)) {
3822
+ throw new Error("userAddress does not match authenticated session EOA");
3823
+ }
3824
+ return (await this.getFirstPermitDepositAvailability()).intent;
3825
+ }
3826
+ async getFirstPermitDepositAvailability(chainId) {
3827
+ try {
3828
+ return await this.httpClient.get(
3829
+ ENDPOINTS.FIRST_PERMIT_DEPOSIT,
3830
+ chainId != null ? { params: { chainId } } : void 0
3831
+ );
3832
+ } catch (error) {
3833
+ if (error instanceof Error && "status" in error && error.status === 404) {
3834
+ return { enabledTokens: [], intent: null };
3835
+ }
3836
+ throw error;
3837
+ }
3838
+ }
3839
+ async sendFirstPermitDeposit(request) {
3840
+ const { enabledTokens, intent, permitPreferred } = await this.getFirstPermitDepositAvailability(request.chainId);
3841
+ let id;
3842
+ let accepted;
3843
+ if (intent?.status === "queued" || intent?.status === "submitted") {
3844
+ if (!matchesFirstPermitDeposit(intent, request)) {
3845
+ throw new Error(`First permit deposit ${intent.id} is already pending for a different deposit`);
3846
+ }
3847
+ id = intent.id;
3848
+ accepted = intent;
3849
+ } else {
3850
+ const { owner, chainId, token, amount } = request;
3851
+ if (permitPreferred === false) return null;
3852
+ if (!enabledTokens.includes(`${chainId}:${token.toLowerCase()}`)) return null;
3853
+ const prepared = await this.httpClient.post(
3854
+ ENDPOINTS.FIRST_PERMIT_DEPOSIT_PREPARE,
3855
+ { owner, chainId, token, amount: amount.toString() }
3856
+ );
3857
+ if (!prepared) return null;
3858
+ const message = validateFirstPermit(prepared, request);
3859
+ const currentWallet = this.getWalletClient();
3860
+ const wallet = currentWallet.chain?.id === chainId ? currentWallet : await this.walletClientForOrigin(chainId);
3861
+ const signature = await wallet.signTypedData({
3862
+ account: wallet.account,
3863
+ domain: prepared.domain,
3864
+ types: firstPermitTypes,
3865
+ primaryType: "Permit",
3866
+ message
3867
+ });
3868
+ id = prepared.id;
3869
+ try {
3870
+ accepted = await this.httpClient.post(
3871
+ ENDPOINTS.FIRST_PERMIT_DEPOSIT_SUBMIT(id),
3872
+ { signature }
3873
+ );
3874
+ } catch (error) {
3875
+ accepted = await this.getFirstPermitDepositStatus(owner).catch(() => null);
3876
+ if (accepted?.id !== id || accepted.status === "prepared") {
3877
+ throw new Error(
3878
+ `Could not confirm first permit deposit ${id}. Check getFirstPermitDepositStatus before retrying: ${thrownMessage(error)}`
3879
+ );
3880
+ }
3881
+ }
3882
+ }
3883
+ let status = accepted;
3884
+ const { value: registered } = await pollUntil(async () => {
3885
+ const current = status ?? await this.getFirstPermitDepositStatus(request.owner);
3886
+ status = null;
3887
+ if (current?.id !== id || !matchesFirstPermitDeposit(current, request)) {
3888
+ throw new Error(`Unable to resolve first permit deposit ${id}. Check getFirstPermitDepositStatus before retrying.`);
3889
+ }
3890
+ if (current.status === "failed") {
3891
+ throw new Error(`First permit deposit ${id} failed`);
3892
+ }
3893
+ return current;
3894
+ }, (current) => current.status === "registered", {
3895
+ intervalMs: 3e3,
3896
+ label: `first permit deposit ${id} registration. Check getFirstPermitDepositStatus before retrying`
3897
+ });
3898
+ if (!registered.txHash || !registered.depositId) {
3899
+ throw new Error(`First permit deposit ${id} is missing its registration. Check getFirstPermitDepositStatus before retrying.`);
3900
+ }
3901
+ return {
3902
+ success: true,
3903
+ txHash: registered.txHash,
3904
+ smartWallet: request.safe,
3905
+ amount: registered.amount,
3906
+ route: "direct",
3907
+ registration: await this.getDepositStatus(registered.depositId)
3908
+ };
3909
+ }
3688
3910
  async sendDeposit(userAddressOrParams, chainId, amount, asset, strategy) {
3689
3911
  if (typeof userAddressOrParams !== "string") {
3690
3912
  return this.sendRoutedDeposit(userAddressOrParams);
@@ -3973,12 +4195,13 @@ var _ZyfaiSDK = class _ZyfaiSDK {
3973
4195
  BigInt(params.amount)
3974
4196
  );
3975
4197
  await this.wrapNativeEth(params.chainId, params.amount);
3976
- const sent = await this.sendDirectDeposit(
4198
+ const sent = await this.sendCollateralDeposit(
3977
4199
  params.userAddress,
3978
4200
  params.chainId,
3979
4201
  params.amount,
3980
4202
  "WETH",
3981
- params.strategy
4203
+ params.strategy,
4204
+ false
3982
4205
  );
3983
4206
  return { ...sent, route: "wrap" };
3984
4207
  }
@@ -4066,16 +4289,16 @@ var _ZyfaiSDK = class _ZyfaiSDK {
4066
4289
  method: "wallet_switchEthereumChain",
4067
4290
  params: [{ chainId: `0x${originChainId.toString(16)}` }]
4068
4291
  });
4069
- const chain = isSupportedChain(originChainId) ? getChainConfig(originChainId, this.rpcUrls).chain : (0, import_viem4.defineChain)({
4292
+ const chain = isSupportedChain(originChainId) ? getChainConfig(originChainId, this.rpcUrls).chain : (0, import_viem6.defineChain)({
4070
4293
  id: originChainId,
4071
4294
  name: `Chain ${originChainId}`,
4072
4295
  nativeCurrency: { name: "Ether", symbol: "ETH", decimals: 18 },
4073
4296
  rpcUrls: { default: { http: ["http://127.0.0.1"] } }
4074
4297
  });
4075
- this.walletClient = (0, import_viem4.createWalletClient)({
4298
+ this.walletClient = (0, import_viem6.createWalletClient)({
4076
4299
  account: this.walletClient.account,
4077
4300
  chain,
4078
- transport: (0, import_viem4.custom)(this.currentProvider)
4301
+ transport: (0, import_viem6.custom)(this.currentProvider)
4079
4302
  });
4080
4303
  if (isSupportedChain(originChainId)) {
4081
4304
  this.currentChainId = originChainId;
@@ -4251,7 +4474,7 @@ var _ZyfaiSDK = class _ZyfaiSDK {
4251
4474
  safeAddress,
4252
4475
  tokenAddress,
4253
4476
  to: tokenAddress,
4254
- data: (0, import_viem4.encodeFunctionData)({
4477
+ data: (0, import_viem6.encodeFunctionData)({
4255
4478
  abi: ERC20_ABI,
4256
4479
  functionName: "transfer",
4257
4480
  args: [safeAddress, amountBigInt]
@@ -4259,6 +4482,91 @@ var _ZyfaiSDK = class _ZyfaiSDK {
4259
4482
  value: "0"
4260
4483
  };
4261
4484
  }
4485
+ /**
4486
+ * Build the rZFI claim as an unsigned transaction for your own signer.
4487
+ *
4488
+ * @remarks
4489
+ * Same pattern as {@link ZyfaiSDK.buildDepositTransfer}: sign and send
4490
+ * `{ to, data, value }` from `userAddress` on Base (chain 8453). It must be
4491
+ * sent by `userAddress` itself; any other sender reverts. The sender pays the
4492
+ * gas. Claims all unclaimed rZFI into the user's Safe.
4493
+ *
4494
+ * @group Rewards
4495
+ *
4496
+ * @param userAddress - Owner EOA, which must send the transaction
4497
+ * @returns Safe address, claimable amount, and the transaction to send
4498
+ *
4499
+ * @throws If there is no rZFI to claim, the reward tree is updating (retry
4500
+ * later), or `userAddress` cannot execute the Safe alone (not an owner, or threshold above 1)
4501
+ */
4502
+ async buildRzfiClaimTransaction(userAddress) {
4503
+ if (!userAddress) {
4504
+ throw new Error("A user address is required");
4505
+ }
4506
+ const owner = (0, import_viem6.getAddress)(userAddress);
4507
+ const chainId = 8453;
4508
+ await this.hydrateSessionWallet();
4509
+ const safe = await this.getSafeAddressFor(owner, chainId);
4510
+ if (!safe) {
4511
+ throw new Error("Smart wallet address is not available");
4512
+ }
4513
+ const { publicClient } = getChainConfig(chainId, this.rpcUrls);
4514
+ const [owners, threshold] = await Promise.all([
4515
+ publicClient.readContract({
4516
+ address: safe,
4517
+ abi: SAFE_ABI,
4518
+ functionName: "getOwners"
4519
+ }),
4520
+ publicClient.readContract({
4521
+ address: safe,
4522
+ abi: SAFE_ABI,
4523
+ functionName: "getThreshold"
4524
+ })
4525
+ ]).catch(() => {
4526
+ throw new Error(`Safe ${safe} is not deployed on Base`);
4527
+ });
4528
+ if (threshold !== 1n || !owners.some((o) => (0, import_viem6.getAddress)(o) === owner)) {
4529
+ throw new Error(
4530
+ `${owner} cannot execute Safe ${safe} alone (not an owner, or threshold above 1)`
4531
+ );
4532
+ }
4533
+ const [reward, [claimed], liveRoot] = await Promise.all([
4534
+ fetchMerklRzfiReward(safe),
4535
+ publicClient.readContract({
4536
+ address: MERKL_DISTRIBUTOR_ADDRESS,
4537
+ abi: MERKL_DISTRIBUTOR_ABI,
4538
+ functionName: "claimed",
4539
+ args: [safe, RZFI_TOKEN_ADDRESS]
4540
+ }),
4541
+ publicClient.readContract({
4542
+ address: MERKL_DISTRIBUTOR_ADDRESS,
4543
+ abi: MERKL_DISTRIBUTOR_ABI,
4544
+ functionName: "getMerkleRoot"
4545
+ })
4546
+ ]);
4547
+ const claimable = reward ? reward.amount - claimed : 0n;
4548
+ if (!reward || claimable <= 0n) {
4549
+ throw new Error("No rZFI available to claim");
4550
+ }
4551
+ if (reward.root.toLowerCase() !== liveRoot.toLowerCase()) {
4552
+ throw new Error(
4553
+ "rZFI rewards are being updated on-chain. Retry in a few minutes."
4554
+ );
4555
+ }
4556
+ return {
4557
+ safeAddress: safe,
4558
+ chainId: 8453,
4559
+ claimableAmount: claimable.toString(),
4560
+ to: safe,
4561
+ data: encodeRzfiClaimExecTransaction({
4562
+ safe,
4563
+ owner,
4564
+ amount: reward.amount,
4565
+ proofs: reward.proofs
4566
+ }),
4567
+ value: "0"
4568
+ };
4569
+ }
4262
4570
  /**
4263
4571
  * Prepare a gas-sponsored rZFI claim into the user's Safe on Base.
4264
4572
  *
@@ -4306,7 +4614,7 @@ var _ZyfaiSDK = class _ZyfaiSDK {
4306
4614
  if (!userAddress) {
4307
4615
  throw new Error("A user address is required");
4308
4616
  }
4309
- if (this.sessionEoa && (0, import_viem4.getAddress)(userAddress) !== this.sessionEoa) {
4617
+ if (this.sessionEoa && (0, import_viem6.getAddress)(userAddress) !== this.sessionEoa) {
4310
4618
  throw new Error("userAddress does not match authenticated session EOA");
4311
4619
  }
4312
4620
  }
@@ -4452,7 +4760,7 @@ var _ZyfaiSDK = class _ZyfaiSDK {
4452
4760
  */
4453
4761
  async prepareDeposit(params) {
4454
4762
  const { userAddress, chainId, amount, asset } = params;
4455
- if (this.sessionEoa && (0, import_viem4.getAddress)(userAddress) !== this.sessionEoa) {
4763
+ if (this.sessionEoa && (0, import_viem6.getAddress)(userAddress) !== this.sessionEoa) {
4456
4764
  throw new Error("userAddress does not match authenticated session EOA");
4457
4765
  }
4458
4766
  const setup = await this.ensureDepositProfileForPrepare({
@@ -5713,19 +6021,19 @@ var _ZyfaiSDK = class _ZyfaiSDK {
5713
6021
  }
5714
6022
  }
5715
6023
  /**
5716
- * Get aggressive (high-risk, high-reward) yield opportunities
6024
+ * Get balanced (high-risk, high-reward) yield opportunities.
5717
6025
  *
5718
6026
  * @param chainId - Optional chain ID filter
5719
6027
  * @param asset - Optional asset filter (e.g. "USDC", "WETH", "WBTC")
5720
- * @returns List of aggressive opportunities
6028
+ * @returns List of balanced opportunities
5721
6029
  *
5722
6030
  * @example
5723
6031
  * ```typescript
5724
- * const opportunities = await sdk.getAggressiveOpportunities(8453, "WETH");
6032
+ * const opportunities = await sdk.getBalancedOpportunities(8453, "WETH");
5725
6033
  * opportunities.data.forEach(o => console.log(o.protocolName, o.apy));
5726
6034
  * ```
5727
6035
  */
5728
- async getAggressiveOpportunities(chainId, asset, status) {
6036
+ async getBalancedOpportunities(chainId, asset, status) {
5729
6037
  try {
5730
6038
  const response = await this.httpClient.dataGet(
5731
6039
  DATA_ENDPOINTS.OPPORTUNITIES_DEGEN(chainId, asset, status)
@@ -5734,7 +6042,7 @@ var _ZyfaiSDK = class _ZyfaiSDK {
5734
6042
  return {
5735
6043
  success: true,
5736
6044
  chainId,
5737
- strategyType: "aggressive",
6045
+ strategyType: "balanced",
5738
6046
  data: Array.isArray(data) ? data.map((o) => ({
5739
6047
  id: o.id,
5740
6048
  protocolId: o.protocol_id || o.protocolId,
@@ -5745,34 +6053,47 @@ var _ZyfaiSDK = class _ZyfaiSDK {
5745
6053
  tvl: o.tvl || o.zyfiTvl,
5746
6054
  asset: o.asset || o.underlying_token,
5747
6055
  risk: o.risk,
5748
- strategyType: "aggressive",
6056
+ strategyType: "balanced",
5749
6057
  status: o.status
5750
6058
  })) : []
5751
6059
  };
5752
6060
  } catch (error) {
5753
6061
  throw new Error(
5754
- `Failed to get aggressive opportunities: ${error.message}`
6062
+ `Failed to get balanced opportunities: ${error.message}`
5755
6063
  );
5756
6064
  }
5757
6065
  }
5758
6066
  /**
5759
- * Get yieldmaxxing opportunities — pools reachable only with the
5760
- * `"yieldmaxxing"` strategy, including protocols whose withdrawals are
6067
+ * @deprecated Use {@link getBalancedOpportunities} instead. Retains the
6068
+ * pre-rename `getAggressiveOpportunities` entry point; same HTTP request as
6069
+ * balanced, with legacy `strategyType: "aggressive"` on the response and rows.
6070
+ */
6071
+ async getAggressiveOpportunities(chainId, asset, status) {
6072
+ const result = await this.getBalancedOpportunities(chainId, asset, status);
6073
+ return {
6074
+ ...result,
6075
+ strategyType: "aggressive",
6076
+ data: result.data.map((o) => ({ ...o, strategyType: "aggressive" }))
6077
+ };
6078
+ }
6079
+ /**
6080
+ * Get advanced yield opportunities — pools reachable only with the
6081
+ * `"advanced"` strategy, including protocols whose withdrawals are
5761
6082
  * asynchronous (Ipor, Superform). Exiting these pools takes about a day
5762
6083
  * on Ipor and three on Superform; track the redemption through
5763
6084
  * `getPortfolio().portfolio.pendingAsyncWithdrawals`.
5764
6085
  *
5765
6086
  * @param chainId - Optional chain ID filter
5766
6087
  * @param asset - Optional asset filter (e.g. "USDC", "WETH")
5767
- * @returns List of yieldmaxxing opportunities
6088
+ * @returns List of advanced opportunities
5768
6089
  *
5769
6090
  * @example
5770
6091
  * ```typescript
5771
- * const opportunities = await sdk.getAsyncOpportunities(8453);
6092
+ * const opportunities = await sdk.getAdvancedOpportunities(8453);
5772
6093
  * opportunities.data.forEach(o => console.log(o.protocolName, o.apy));
5773
6094
  * ```
5774
6095
  */
5775
- async getAsyncOpportunities(chainId, asset, status) {
6096
+ async getAdvancedOpportunities(chainId, asset, status) {
5776
6097
  try {
5777
6098
  const response = await this.httpClient.dataGet(
5778
6099
  DATA_ENDPOINTS.OPPORTUNITIES_ASYNC(chainId, asset, status)
@@ -5781,7 +6102,7 @@ var _ZyfaiSDK = class _ZyfaiSDK {
5781
6102
  return {
5782
6103
  success: true,
5783
6104
  chainId,
5784
- strategyType: "yieldmaxxing",
6105
+ strategyType: "advanced",
5785
6106
  data: Array.isArray(data) ? data.map((o) => ({
5786
6107
  id: o.id,
5787
6108
  protocolId: o.protocol_id || o.protocolId,
@@ -5792,16 +6113,29 @@ var _ZyfaiSDK = class _ZyfaiSDK {
5792
6113
  tvl: o.tvl || o.zyfiTvl,
5793
6114
  asset: o.asset || o.underlying_token,
5794
6115
  risk: o.risk,
5795
- strategyType: "yieldmaxxing",
6116
+ strategyType: "advanced",
5796
6117
  status: o.status
5797
6118
  })) : []
5798
6119
  };
5799
6120
  } catch (error) {
5800
6121
  throw new Error(
5801
- `Failed to get yieldmaxxing opportunities: ${error.message}`
6122
+ `Failed to get advanced opportunities: ${error.message}`
5802
6123
  );
5803
6124
  }
5804
6125
  }
6126
+ /**
6127
+ * @deprecated Use {@link getAdvancedOpportunities} instead. Retains the
6128
+ * pre-rename `getAsyncOpportunities` entry point; same HTTP request as
6129
+ * advanced, with legacy `strategyType: "yieldmaxxing"` on the response and rows.
6130
+ */
6131
+ async getAsyncOpportunities(chainId, asset, status) {
6132
+ const result = await this.getAdvancedOpportunities(chainId, asset, status);
6133
+ return {
6134
+ ...result,
6135
+ strategyType: "yieldmaxxing",
6136
+ data: result.data.map((o) => ({ ...o, strategyType: "yieldmaxxing" }))
6137
+ };
6138
+ }
5805
6139
  /**
5806
6140
  * Get active conservative opportunities (status = "live") with risk and utilization data
5807
6141
  * Returns pool info, liquidity depth (true if > 1M), utilization rate, stability metrics, avg APY, and collateral
@@ -6472,7 +6806,7 @@ var _ZyfaiSDK = class _ZyfaiSDK {
6472
6806
  if (!tokenUriResponse.tokenUri) {
6473
6807
  throw new Error("API did not return a tokenUri");
6474
6808
  }
6475
- const callData = (0, import_viem4.encodeFunctionData)({
6809
+ const callData = (0, import_viem6.encodeFunctionData)({
6476
6810
  abi: IDENTITY_REGISTRY_ABI,
6477
6811
  functionName: "register",
6478
6812
  args: [tokenUriResponse.tokenUri]