@zyfai/sdk 0.10.0 → 0.11.2

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,10 @@ 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
+ FUNDING_ORDERS: "/users/me/funding-orders",
58
+ FUNDING_ORDER: (orderId) => `/users/me/funding-orders/${encodeURIComponent(orderId)}`,
59
+ FUNDING_ORDER_QUOTE: (orderId) => `/users/me/funding-orders/${encodeURIComponent(orderId)}/quote`,
60
+ FUNDING_ORDER_EXECUTION: (orderId) => `/users/me/funding-orders/${encodeURIComponent(orderId)}/execution`,
57
61
  DEPOSIT_STATUS: (depositId) => `/users/deposits/${depositId}/v2`,
58
62
  WITHDRAW_STATUS: (withdrawalId) => `/users/withdrawals/${withdrawalId}`,
59
63
  // Safe Deployment (single endpoint)
@@ -485,6 +489,15 @@ var ERC20_ABI = [
485
489
  outputs: [{ name: "", type: "uint256" }]
486
490
  }
487
491
  ];
492
+ var WETH_DEPOSIT_ABI = [
493
+ {
494
+ name: "deposit",
495
+ type: "function",
496
+ stateMutability: "payable",
497
+ inputs: [],
498
+ outputs: []
499
+ }
500
+ ];
488
501
  var ERC20_TRANSFER_LEGACY_ABI = [
489
502
  {
490
503
  name: "transfer",
@@ -679,9 +692,9 @@ function nextWithdrawCompleteDeadline(startedAt, previousDeadline, estimatedClai
679
692
  var AGENT_DEPOSIT_INTENT_INTERVAL_MS = 1500;
680
693
  var AGENT_DEPOSIT_INTENT_TIMEOUT_MS = 30 * 60 * 1e3;
681
694
  var formatMinPortfolioLabel = (raw, decimals, symbol) => {
682
- const base2 = 10n ** BigInt(decimals);
683
- const whole = raw / base2;
684
- const fraction = raw % base2;
695
+ const base3 = 10n ** BigInt(decimals);
696
+ const whole = raw / base3;
697
+ const fraction = raw % base3;
685
698
  if (fraction === 0n) {
686
699
  return `${whole.toString()} ${symbol}`;
687
700
  }
@@ -740,8 +753,10 @@ import {
740
753
  custom,
741
754
  http as http2,
742
755
  getAddress as getAddress2,
743
- encodeFunctionData
756
+ encodeFunctionData,
757
+ defineChain
744
758
  } from "viem";
759
+ import { execute } from "@relayprotocol/relay-sdk";
745
760
 
746
761
  // src/config/chains.ts
747
762
  import { createPublicClient, http } from "viem";
@@ -936,6 +951,233 @@ var getSupportedChainIds = () => {
936
951
  return Object.keys(CHAINS).map(Number);
937
952
  };
938
953
 
954
+ // src/deposits/deposit-route.ts
955
+ var NATIVE_CURRENCY = "0x0000000000000000000000000000000000000000";
956
+ var RELAY_DESTINATION_ASSETS = [
957
+ "USDC",
958
+ "WETH",
959
+ "CBBTC",
960
+ "WBTC",
961
+ "EURC",
962
+ "USDT",
963
+ "PYUSD",
964
+ "NVDAC",
965
+ "GOOGLC",
966
+ "AAPLC",
967
+ "METAC"
968
+ ];
969
+ var lookupCollateral = (asset) => Object.keys(ASSET_CONFIGS).find(
970
+ (key) => key.toLowerCase() === asset.toLowerCase()
971
+ ) ?? null;
972
+ var toRelayDestinationAsset = (asset) => asset.trim().toUpperCase();
973
+ var isNativeSpendToken = (token) => {
974
+ const value = token.trim().toLowerCase();
975
+ return value === "eth" || value === "native" || value === NATIVE_CURRENCY;
976
+ };
977
+ var isSameCollateralToken = (spend, collateral, chainId) => {
978
+ if (spend.toLowerCase() === collateral.toLowerCase()) return true;
979
+ const address = ASSET_CONFIGS[collateral]?.addresses?.[chainId];
980
+ return !!address && spend.toLowerCase() === address.toLowerCase();
981
+ };
982
+ var originCurrencyForSpend = (spend, chainId) => {
983
+ if (isNativeSpendToken(spend)) return NATIVE_CURRENCY;
984
+ if (/^0x[0-9a-fA-F]{40}$/.test(spend)) return spend;
985
+ const collateral = lookupCollateral(spend);
986
+ if (!collateral) {
987
+ throw new Error(
988
+ `spendToken must be a collateral symbol or a token contract address. Received "${spend}".`
989
+ );
990
+ }
991
+ const address = ASSET_CONFIGS[collateral]?.addresses?.[chainId];
992
+ if (!address) {
993
+ throw new Error(`${collateral} is not available on chain ${chainId}.`);
994
+ }
995
+ return address;
996
+ };
997
+ var resolveDepositRoute = (input) => {
998
+ const asset = input.asset?.trim();
999
+ if (!asset) throw new Error("Asset is required");
1000
+ const spendChainId = input.spendChainId ?? input.chainId;
1001
+ const collateral = lookupCollateral(asset);
1002
+ const spend = input.spendToken?.trim();
1003
+ const holdsDestinationCollateral = !spend || spendChainId === input.chainId && !!collateral && isSameCollateralToken(spend, collateral, input.chainId);
1004
+ if (holdsDestinationCollateral) {
1005
+ if (!collateral) {
1006
+ throw new Error(
1007
+ `${asset} cannot be transferred directly. Pass spendToken to swap another token into it.`
1008
+ );
1009
+ }
1010
+ const chains = getAssetChainIds(collateral);
1011
+ if (!chains.includes(input.chainId)) {
1012
+ throw new Error(
1013
+ `${collateral} is not available on chain ${input.chainId}. Supported chains: ${chains.join(", ")}.`
1014
+ );
1015
+ }
1016
+ return { kind: "direct", asset: collateral };
1017
+ }
1018
+ if (collateral === "WETH" && spendChainId === input.chainId && spend && isNativeSpendToken(spend)) {
1019
+ return { kind: "wrap", asset: "WETH" };
1020
+ }
1021
+ const destinationAsset = toRelayDestinationAsset(asset);
1022
+ if (!RELAY_DESTINATION_ASSETS.includes(
1023
+ destinationAsset
1024
+ )) {
1025
+ throw new Error(
1026
+ `${asset} is not a collateral Relay can deliver. Supported: ${RELAY_DESTINATION_ASSETS.join(", ")}.`
1027
+ );
1028
+ }
1029
+ return {
1030
+ kind: "swap",
1031
+ originChainId: spendChainId,
1032
+ originCurrency: originCurrencyForSpend(spend, spendChainId),
1033
+ destinationAsset
1034
+ };
1035
+ };
1036
+
1037
+ // src/deposits/funding-order-route.ts
1038
+ var sameText = (left, right) => typeof left === "string" && left.trim().toLowerCase() === right.trim().toLowerCase();
1039
+ var assertStoredFundingOrderRoute = (order, requested) => {
1040
+ const mismatches = [];
1041
+ if (order.originChainId !== requested.originChainId) {
1042
+ mismatches.push(
1043
+ `originChainId caller ${requested.originChainId}, stored ${order.originChainId}`
1044
+ );
1045
+ }
1046
+ if (!sameText(order.originCurrency, requested.originCurrency)) {
1047
+ mismatches.push(
1048
+ `originCurrency caller ${requested.originCurrency}, stored ${order.originCurrency}`
1049
+ );
1050
+ }
1051
+ if (order.destinationChainId !== requested.destinationChainId) {
1052
+ mismatches.push(
1053
+ `destinationChainId caller ${requested.destinationChainId}, stored ${order.destinationChainId}`
1054
+ );
1055
+ }
1056
+ if (!sameText(order.destinationAsset, requested.destinationAsset)) {
1057
+ mismatches.push(
1058
+ `destinationAsset caller ${requested.destinationAsset}, stored ${order.destinationAsset}`
1059
+ );
1060
+ }
1061
+ if (mismatches.length === 0) return;
1062
+ throw new Error(
1063
+ `Funding order ${order.id} does not match this swap: ${mismatches.join("; ")}`
1064
+ );
1065
+ };
1066
+
1067
+ // src/deposits/collateral-minimum.ts
1068
+ var positiveUnits = (value) => {
1069
+ if (!value || value === "0") return null;
1070
+ return value;
1071
+ };
1072
+ var resolveCollateralMinimum = (storedMinimum, quote) => positiveUnits(storedMinimum) ?? positiveUnits(quote.details?.currencyOut?.minimumAmount) ?? positiveUnits(quote.details?.currencyOut?.amount) ?? "0";
1073
+
1074
+ // src/deposits/relay-slippage.ts
1075
+ var DEFAULT_RELAY_SLIPPAGE_BPS = 200;
1076
+ var MAX_RELAY_SLIPPAGE_BPS = 500;
1077
+ var RELAY_SLIPPAGE_PRESETS_BPS = [50, 200, 500];
1078
+ var resolveRelaySlippageBps = (clientBps) => {
1079
+ if (clientBps == null || !Number.isFinite(clientBps)) {
1080
+ return DEFAULT_RELAY_SLIPPAGE_BPS;
1081
+ }
1082
+ return Math.min(
1083
+ Math.max(1, Math.trunc(clientBps)),
1084
+ MAX_RELAY_SLIPPAGE_BPS
1085
+ );
1086
+ };
1087
+
1088
+ // src/deposits/relay-client.ts
1089
+ import {
1090
+ MAINNET_RELAY_API,
1091
+ convertViemChainToRelayChain,
1092
+ createClient,
1093
+ getClient
1094
+ } from "@relayprotocol/relay-sdk";
1095
+ import { arbitrum as arbitrum2, base as base2, mainnet as mainnet2 } from "viem/chains";
1096
+ var RELAY_FUNDING_CHAIN_IDS = [mainnet2.id, base2.id, arbitrum2.id];
1097
+ var clientHasFundingChains = () => {
1098
+ const client = getClient();
1099
+ if (!client?.baseApiUrl) return false;
1100
+ return RELAY_FUNDING_CHAIN_IDS.every(
1101
+ (chainId) => client.chains.some((chain) => chain.id === chainId)
1102
+ );
1103
+ };
1104
+ var ensureRelaySdkClient = () => {
1105
+ if (clientHasFundingChains()) return;
1106
+ createClient({
1107
+ baseApiUrl: MAINNET_RELAY_API,
1108
+ source: "zyf.ai",
1109
+ chains: [mainnet2, base2, arbitrum2].map(convertViemChainToRelayChain)
1110
+ });
1111
+ };
1112
+
1113
+ // src/deposits/relay-fill.ts
1114
+ var TRANSFER_TOPIC = "0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef";
1115
+ var collectTxHashes = (execution) => {
1116
+ const out = [];
1117
+ for (const step of execution.steps ?? []) {
1118
+ for (const item of step.items ?? []) {
1119
+ for (const row of item.txHashes ?? []) {
1120
+ if (row.txHash) out.push(row);
1121
+ }
1122
+ for (const row of item.internalTxHashes ?? []) {
1123
+ if (row.txHash) out.push(row);
1124
+ }
1125
+ }
1126
+ }
1127
+ return out;
1128
+ };
1129
+ var collectRelaySourceTxHashes = (execution, originChainId) => {
1130
+ const hashes = /* @__PURE__ */ new Set();
1131
+ for (const row of collectTxHashes(execution)) {
1132
+ if (row.chainId === originChainId) hashes.add(row.txHash);
1133
+ }
1134
+ return [...hashes];
1135
+ };
1136
+ var collectRelayDestinationTxHashes = (execution, destinationChainId) => {
1137
+ const hashes = /* @__PURE__ */ new Set();
1138
+ for (const row of collectTxHashes(execution)) {
1139
+ if (row.chainId === destinationChainId && row.txHash) {
1140
+ hashes.add(row.txHash);
1141
+ }
1142
+ }
1143
+ return [...hashes];
1144
+ };
1145
+ var transferAmountTo = (logs, token, recipient) => {
1146
+ const tokenAddr = token.toLowerCase();
1147
+ const recipientAddr = recipient.toLowerCase();
1148
+ let total = 0n;
1149
+ for (const log of logs) {
1150
+ if (log.address.toLowerCase() !== tokenAddr) continue;
1151
+ if (log.topics[0]?.toLowerCase() !== TRANSFER_TOPIC) continue;
1152
+ const toTopic = log.topics[2];
1153
+ if (!toTopic) continue;
1154
+ const to = `0x${toTopic.slice(-40)}`.toLowerCase();
1155
+ if (to !== recipientAddr) continue;
1156
+ try {
1157
+ const value = BigInt(log.data);
1158
+ if (value > 0n) total += value;
1159
+ } catch {
1160
+ }
1161
+ }
1162
+ return total;
1163
+ };
1164
+ var receiptTransfersTokenTo = (logs, token, recipient) => transferAmountTo(logs, token, recipient) > 0n;
1165
+ var selectRelayCreditTxHash = (params) => {
1166
+ const seen = /* @__PURE__ */ new Set();
1167
+ for (const hash of params.candidates) {
1168
+ if (!hash) continue;
1169
+ const key = hash.toLowerCase();
1170
+ if (seen.has(key)) continue;
1171
+ seen.add(key);
1172
+ const receipt = params.receipts.get(key);
1173
+ if (!receipt || receipt.status !== "success") continue;
1174
+ if (receiptTransfersTokenTo(receipt.logs, params.token, params.recipient)) {
1175
+ return hash;
1176
+ }
1177
+ }
1178
+ return null;
1179
+ };
1180
+
939
1181
  // src/config/managed-assets.ts
940
1182
  var MANAGED_ASSET_ORDER = [
941
1183
  "USDC",
@@ -1764,6 +2006,13 @@ var AgentDepositIntentTimeoutError = class extends Error {
1764
2006
  this.name = "AgentDepositIntentTimeoutError";
1765
2007
  }
1766
2008
  };
2009
+ var thrownMessage = (error) => {
2010
+ if (error instanceof Error) return error.message;
2011
+ if (error && typeof error === "object" && "message" in error && typeof error.message === "string") {
2012
+ return error.message;
2013
+ }
2014
+ return String(error);
2015
+ };
1767
2016
  var _ZyfaiSDK = class _ZyfaiSDK {
1768
2017
  /**
1769
2018
  * Create an SDK instance bound to a partner API key.
@@ -2950,14 +3199,15 @@ var _ZyfaiSDK = class _ZyfaiSDK {
2950
3199
  effectiveChains,
2951
3200
  withPools,
2952
3201
  strategy,
2953
- mandateChainId
3202
+ mandateChainId,
3203
+ existingChains
2954
3204
  );
2955
3205
  }
2956
3206
  /**
2957
3207
  * Persist protocol discovery for one asset (user PATCH or agent deposit-setup).
2958
3208
  * @internal
2959
3209
  */
2960
- async persistDiscoveredAssetProfile(asset, effectiveChains, withPools, strategy, agentDepositChainId) {
3210
+ async persistDiscoveredAssetProfile(asset, effectiveChains, withPools, strategy, agentDepositChainId, existingChains = []) {
2961
3211
  const internalAsset = convertAssetInternally(asset);
2962
3212
  const assetSettings = {
2963
3213
  chains: effectiveChains,
@@ -2966,9 +3216,18 @@ var _ZyfaiSDK = class _ZyfaiSDK {
2966
3216
  if (strategy !== void 0) {
2967
3217
  assetSettings.rebalanceStrategy = toInternalStrategy(strategy);
2968
3218
  }
3219
+ const configureProfile = () => this.updateUserProfile({
3220
+ asset,
3221
+ protocols: withPools,
3222
+ chains: effectiveChains,
3223
+ ...strategy !== void 0 && { strategy }
3224
+ });
2969
3225
  if (this.sessionChannel === "agent") {
2970
3226
  const chainId = agentDepositChainId ?? effectiveChains[effectiveChains.length - 1] ?? effectiveChains[0];
2971
- await this.httpClient.post(
3227
+ if (existingChains.includes(chainId)) {
3228
+ return await configureProfile();
3229
+ }
3230
+ const setupResult = await this.httpClient.post(
2972
3231
  ENDPOINTS.AGENT_DEPOSIT_SETUP,
2973
3232
  {
2974
3233
  asset,
@@ -2979,14 +3238,14 @@ var _ZyfaiSDK = class _ZyfaiSDK {
2979
3238
  }
2980
3239
  }
2981
3240
  );
3241
+ if (!setupResult.applied) {
3242
+ throw new Error(
3243
+ `Agent deposit setup did not apply for ${asset} on chain ${chainId}.`
3244
+ );
3245
+ }
2982
3246
  return await this.getUserDetails(asset);
2983
3247
  }
2984
- return await this.updateUserProfile({
2985
- asset,
2986
- protocols: withPools,
2987
- chains: effectiveChains,
2988
- ...strategy !== void 0 && { strategy }
2989
- });
3248
+ return await configureProfile();
2990
3249
  }
2991
3250
  /**
2992
3251
  * Switch one asset to a strategy and select the protocols that go with it.
@@ -3221,14 +3480,14 @@ var _ZyfaiSDK = class _ZyfaiSDK {
3221
3480
  return this.httpClient.post(ENDPOINTS.DEPLOY_CHAINS, { chainIds });
3222
3481
  }
3223
3482
  /**
3224
- * Transfer funds from the connected EOA to the user's Safe and register the deposit.
3483
+ * Transfer a collateral token the wallet already holds into the Safe.
3225
3484
  *
3226
3485
  * @remarks
3227
- * Execution API + on-chain ERC-20 `transfer`. Confirms the transaction, then calls
3228
- * {@link ZyfaiSDK.logDeposit}. Pair with {@link ZyfaiSDK.waitForDepositCredit} for
3229
- * investable balance. Custom-wallet flows: {@link ZyfaiSDK.buildDepositTransfer},
3230
- * {@link ZyfaiSDK.logDeposit}, {@link ZyfaiSDK.getDepositStatus}.
3486
+ * Use this when the connected wallet holds the strategy collateral on the
3487
+ * deposit chain. {@link ZyfaiSDK.sendDeposit} calls this automatically in
3488
+ * that case. A different token uses {@link ZyfaiSDK.sendSwapDeposit}.
3231
3489
  *
3490
+ * Confirms the ERC-20 `transfer`, then calls {@link ZyfaiSDK.logDeposit}.
3232
3491
  * Requires {@link ZyfaiSDK.connectAccount}. Pass the **EOA** as `userAddress`.
3233
3492
  *
3234
3493
  * @group Deposits and withdrawals
@@ -3236,20 +3495,22 @@ var _ZyfaiSDK = class _ZyfaiSDK {
3236
3495
  * @param userAddress - Owner EOA (not the Safe)
3237
3496
  * @param chainId - Chain for the transfer
3238
3497
  * @param amount - Amount in least units (string integer)
3239
- * @param asset - Asset symbol (`USDC`, `WETH`, `EURC`, `NVDAc`)
3498
+ * @param asset - Collateral symbol (`USDC`, `WETH`, `EURC`, `NVDAc`)
3240
3499
  * @param strategy - Optional first-deposit {@link Strategy}
3241
- * @returns Transfer receipt and deposit registration (not yet credited until polled)
3500
+ * @returns Transfer receipt and deposit registration
3242
3501
  *
3243
- * @throws If validation fails, minimum portfolio is not met, Safe is unavailable, or transfer/register fails
3502
+ * @throws If validation fails, the minimum portfolio is not met, the Safe is unavailable, or transfer/register fails
3503
+ *
3504
+ * @see {@link ZyfaiSDK.sendDeposit}
3244
3505
  *
3245
3506
  * @example
3246
3507
  * ```typescript
3247
3508
  * await sdk.connectAccount(provider);
3248
- * const sent = await sdk.sendDeposit(eoa, 8453, "10000000", "USDC", "conservative");
3249
- * await sdk.waitForDepositCredit(sent.registration.id, 8453);
3509
+ * const sent = await sdk.sendDirectDeposit(eoa, 8453, "10000000", "USDC", "conservative");
3510
+ * await sdk.waitForDepositPosition(sent.registration.id, 8453);
3250
3511
  * ```
3251
3512
  */
3252
- async sendDeposit(userAddress, chainId, amount, asset, strategy) {
3513
+ async sendDirectDeposit(userAddress, chainId, amount, asset, strategy) {
3253
3514
  try {
3254
3515
  if (!userAddress) {
3255
3516
  throw new Error("User address is required");
@@ -3366,12 +3627,489 @@ var _ZyfaiSDK = class _ZyfaiSDK {
3366
3627
  txHash,
3367
3628
  smartWallet: safeAddress,
3368
3629
  amount: amountBigInt.toString(),
3630
+ route: "direct",
3369
3631
  registration
3370
3632
  };
3371
3633
  } catch (error) {
3372
3634
  throw new Error(`Deposit failed: ${error.message}`);
3373
3635
  }
3374
3636
  }
3637
+ async sendDeposit(userAddressOrParams, chainId, amount, asset, strategy) {
3638
+ if (typeof userAddressOrParams !== "string") {
3639
+ return this.sendRoutedDeposit(userAddressOrParams);
3640
+ }
3641
+ if (chainId === void 0 || amount === void 0 || asset === void 0) {
3642
+ throw new Error(
3643
+ "Deposit failed: chainId, amount, and asset are required"
3644
+ );
3645
+ }
3646
+ return this.sendDirectDeposit(
3647
+ userAddressOrParams,
3648
+ chainId,
3649
+ amount,
3650
+ asset,
3651
+ strategy
3652
+ );
3653
+ }
3654
+ /**
3655
+ * Resolve a deposit without signing.
3656
+ *
3657
+ * @remarks
3658
+ * A collateral the wallet already holds on `chainId` returns `route: "direct"`.
3659
+ * Same-chain native ETH into WETH returns `route: "wrap"`. Any other spend
3660
+ * token returns a Relay review quote (`route: "swap"`). Nothing is signed.
3661
+ * Optional `slippageBps` (default 200, max 500) is stored on that funding
3662
+ * order and reused when the quote is refreshed for signing.
3663
+ *
3664
+ * @group Deposits and withdrawals
3665
+ *
3666
+ * @param params - Destination collateral and optional spend token
3667
+ * @returns The route, and a review quote when a swap is required
3668
+ *
3669
+ * @throws If the spend token or destination collateral is not supported
3670
+ */
3671
+ async quoteDeposit(params) {
3672
+ if (!params.userAddress) throw new Error("User address is required");
3673
+ if (!isSupportedChain(params.chainId)) {
3674
+ throw new Error(`Unsupported chain ID: ${params.chainId}`);
3675
+ }
3676
+ if (!params.amount || BigInt(params.amount) <= 0n) {
3677
+ throw new Error("Valid amount is required");
3678
+ }
3679
+ const route = resolveDepositRoute(params);
3680
+ if (route.kind === "direct" || route.kind === "wrap") {
3681
+ return {
3682
+ route: route.kind,
3683
+ asset: route.asset,
3684
+ chainId: params.chainId,
3685
+ amount: params.amount
3686
+ };
3687
+ }
3688
+ const quote = await this.quoteSwapDeposit({
3689
+ userAddress: params.userAddress,
3690
+ originChainId: route.originChainId,
3691
+ originCurrency: route.originCurrency,
3692
+ originAmount: params.amount,
3693
+ destinationChainId: params.chainId,
3694
+ destinationAsset: route.destinationAsset,
3695
+ strategy: params.strategy,
3696
+ slippageBps: params.slippageBps
3697
+ });
3698
+ return { route: "swap", ...quote };
3699
+ }
3700
+ /**
3701
+ * Quote a Relay swap that delivers a collateral token to the Safe.
3702
+ *
3703
+ * @remarks
3704
+ * Creates a funding order on the execution API. The connected wallet does
3705
+ * not sign. Pass `orderId` to {@link ZyfaiSDK.sendSwapDeposit} to sign the
3706
+ * refreshed quote, or call {@link ZyfaiSDK.sendDeposit} to quote and sign
3707
+ * in one step.
3708
+ *
3709
+ * Same-chain native ETH into WETH is rejected here. Use {@link ZyfaiSDK.sendDeposit}
3710
+ * with `spendToken: "ETH"`, which wraps in the wallet.
3711
+ *
3712
+ * Optional `slippageBps` defaults to 200 (max 500) and is fixed when this
3713
+ * funding order is created. Sign-time refresh reuses the stored value.
3714
+ *
3715
+ * @group Deposits and withdrawals
3716
+ *
3717
+ * @param params - Origin token, destination collateral, and funding wallet
3718
+ * @returns Review quote. Not yet signed.
3719
+ *
3720
+ * @throws If the server rejects the pair, the amount, or the quote
3721
+ */
3722
+ async quoteSwapDeposit(params) {
3723
+ this.assertSwapDepositParams(params);
3724
+ await this.authenticateUser();
3725
+ const created = await this.httpClient.post(
3726
+ ENDPOINTS.FUNDING_ORDERS,
3727
+ {
3728
+ originChainId: params.originChainId,
3729
+ destinationChainId: params.destinationChainId,
3730
+ originCurrency: params.originCurrency,
3731
+ originAmount: params.originAmount,
3732
+ destinationAsset: params.destinationAsset.toUpperCase(),
3733
+ fundingWallet: params.userAddress,
3734
+ ...params.slippageBps != null ? { slippageBps: resolveRelaySlippageBps(params.slippageBps) } : {}
3735
+ }
3736
+ );
3737
+ return {
3738
+ orderId: created.orderId,
3739
+ status: created.status,
3740
+ spend: created.spend,
3741
+ expectedOutput: created.expectedOutput,
3742
+ minimumOutput: created.minimumOutput,
3743
+ destinationChainId: created.destinationChainId,
3744
+ destinationCurrency: created.destinationCurrency,
3745
+ destinationAsset: params.destinationAsset.toUpperCase(),
3746
+ fees: created.fees ?? [],
3747
+ investEligible: created.investEligible,
3748
+ expiresAt: created.expiresAt ?? null,
3749
+ timeEstimate: created.timeEstimate ?? null
3750
+ };
3751
+ }
3752
+ /**
3753
+ * Read a Relay funding order, including a linked deposit once credit starts.
3754
+ *
3755
+ * @group Deposits and withdrawals
3756
+ *
3757
+ * @param orderId - Id from {@link ZyfaiSDK.quoteSwapDeposit}
3758
+ * @returns Stored order
3759
+ *
3760
+ * @throws If `orderId` is missing
3761
+ */
3762
+ async getSwapDeposit(orderId) {
3763
+ if (!orderId) throw new Error("Funding order id is required");
3764
+ await this.authenticateUser();
3765
+ return this.httpClient.get(ENDPOINTS.FUNDING_ORDER(orderId));
3766
+ }
3767
+ /**
3768
+ * Swap or bridge a token into a Zyfai collateral, then register the deposit.
3769
+ *
3770
+ * @remarks
3771
+ * The execution API quotes Relay with the Safe as recipient. This method
3772
+ * refreshes that quote, signs the steps with the connected wallet, waits
3773
+ * for the collateral transfer into the Safe, and calls {@link ZyfaiSDK.logDeposit}.
3774
+ * Credit still requires that verified transfer. A refund or failed fill does
3775
+ * not register a deposit.
3776
+ *
3777
+ * Requires {@link ZyfaiSDK.connectAccount}. Origin chains other than
3778
+ * Ethereum, Base, and Arbitrum need an EIP-1193 wallet that can sign there.
3779
+ *
3780
+ * Optional `slippageBps` defaults to 200 (max 500) and is fixed when the
3781
+ * funding order is created. A later call that passes `orderId` ignores
3782
+ * `slippageBps` and signs the stored order.
3783
+ *
3784
+ * @group Deposits and withdrawals
3785
+ *
3786
+ * @param params - Origin token and destination collateral
3787
+ * @returns Destination transfer and deposit registration
3788
+ *
3789
+ * @throws If the quote, signature, fill, or registration fails, or if
3790
+ * `orderId` names a funding order whose origin or destination differs from
3791
+ * this call
3792
+ *
3793
+ * @see {@link ZyfaiSDK.sendDeposit}
3794
+ *
3795
+ * @example
3796
+ * ```typescript
3797
+ * await sdk.connectAccount(provider);
3798
+ * const sent = await sdk.sendSwapDeposit({
3799
+ * userAddress: eoa,
3800
+ * originChainId: 42161,
3801
+ * originCurrency: "0xaf88d065e77c8cC2239327C5EDb3A432268e5831",
3802
+ * originAmount: "10000000",
3803
+ * destinationChainId: 8453,
3804
+ * destinationAsset: "WETH",
3805
+ * });
3806
+ * ```
3807
+ */
3808
+ async sendSwapDeposit(params) {
3809
+ try {
3810
+ this.assertSwapDepositParams(params);
3811
+ await this.authenticateUser();
3812
+ await this.prepareFirstDeposit(params.strategy);
3813
+ let orderId;
3814
+ let destinationCurrency;
3815
+ let storedMinimum;
3816
+ if (params.orderId) {
3817
+ const existing = await this.getSwapDeposit(params.orderId);
3818
+ assertStoredFundingOrderRoute(existing, params);
3819
+ orderId = existing.id;
3820
+ destinationCurrency = existing.destinationCurrency;
3821
+ storedMinimum = existing.minimumOutput;
3822
+ } else {
3823
+ const created = await this.quoteSwapDeposit(params);
3824
+ orderId = created.orderId;
3825
+ destinationCurrency = created.destinationCurrency;
3826
+ storedMinimum = created.minimumOutput;
3827
+ }
3828
+ const signQuote = await this.httpClient.post(ENDPOINTS.FUNDING_ORDER_QUOTE(orderId));
3829
+ if (!signQuote.quote) {
3830
+ throw new Error("Relay funding quote is missing from the server response");
3831
+ }
3832
+ const minimumOutput = resolveCollateralMinimum(
3833
+ storedMinimum,
3834
+ signQuote.quote
3835
+ );
3836
+ await this.assertCollateralMinimum(
3837
+ params.userAddress,
3838
+ params.destinationChainId,
3839
+ params.destinationAsset,
3840
+ BigInt(minimumOutput)
3841
+ );
3842
+ ensureRelaySdkClient();
3843
+ const walletClient = await this.walletClientForOrigin(params.originChainId);
3844
+ const { data: execution } = await execute({
3845
+ quote: signQuote.quote,
3846
+ wallet: walletClient
3847
+ });
3848
+ const sourceTxHashes = collectRelaySourceTxHashes(
3849
+ execution,
3850
+ params.originChainId
3851
+ );
3852
+ const destinationFromExecution = collectRelayDestinationTxHashes(
3853
+ execution,
3854
+ params.destinationChainId
3855
+ );
3856
+ await this.httpClient.post(ENDPOINTS.FUNDING_ORDER_EXECUTION(orderId), {
3857
+ sourceTxHashes: sourceTxHashes.length ? sourceTxHashes : void 0,
3858
+ stepStatus: "submitted"
3859
+ });
3860
+ await this.hydrateSessionWallet();
3861
+ const safeAddress = await this.getSafeAddressFor(
3862
+ params.userAddress,
3863
+ params.destinationChainId
3864
+ );
3865
+ if (!safeAddress) {
3866
+ throw new Error("Smart wallet address is not available");
3867
+ }
3868
+ const filled = await this.waitForRelayCreditTx({
3869
+ orderId,
3870
+ destinationChainId: params.destinationChainId,
3871
+ destinationToken: destinationCurrency,
3872
+ recipientSafe: safeAddress,
3873
+ initialCandidates: destinationFromExecution
3874
+ });
3875
+ const creditAmount = filled.amount.toString();
3876
+ const registration = await this.registerDeposit(
3877
+ params.destinationChainId,
3878
+ filled.hash,
3879
+ creditAmount,
3880
+ destinationCurrency
3881
+ );
3882
+ return {
3883
+ success: true,
3884
+ txHash: filled.hash,
3885
+ smartWallet: safeAddress,
3886
+ amount: creditAmount,
3887
+ route: "swap",
3888
+ orderId,
3889
+ registration
3890
+ };
3891
+ } catch (error) {
3892
+ const message = thrownMessage(error);
3893
+ throw new Error(
3894
+ message.startsWith("Deposit failed:") ? message : `Deposit failed: ${message}`
3895
+ );
3896
+ }
3897
+ }
3898
+ async sendRoutedDeposit(params) {
3899
+ try {
3900
+ if (!params.userAddress) throw new Error("User address is required");
3901
+ if (!isSupportedChain(params.chainId)) {
3902
+ throw new Error(`Unsupported chain ID: ${params.chainId}`);
3903
+ }
3904
+ if (!params.amount || BigInt(params.amount) <= 0n) {
3905
+ throw new Error("Valid amount is required");
3906
+ }
3907
+ const route = resolveDepositRoute(params);
3908
+ if (route.kind === "direct") {
3909
+ return this.sendDirectDeposit(
3910
+ params.userAddress,
3911
+ params.chainId,
3912
+ params.amount,
3913
+ route.asset,
3914
+ params.strategy
3915
+ );
3916
+ }
3917
+ if (route.kind === "wrap") {
3918
+ await this.assertCollateralMinimum(
3919
+ params.userAddress,
3920
+ params.chainId,
3921
+ "WETH",
3922
+ BigInt(params.amount)
3923
+ );
3924
+ await this.wrapNativeEth(params.chainId, params.amount);
3925
+ const sent = await this.sendDirectDeposit(
3926
+ params.userAddress,
3927
+ params.chainId,
3928
+ params.amount,
3929
+ "WETH",
3930
+ params.strategy
3931
+ );
3932
+ return { ...sent, route: "wrap" };
3933
+ }
3934
+ return this.sendSwapDeposit({
3935
+ userAddress: params.userAddress,
3936
+ originChainId: route.originChainId,
3937
+ originCurrency: route.originCurrency,
3938
+ originAmount: params.amount,
3939
+ destinationChainId: params.chainId,
3940
+ destinationAsset: route.destinationAsset,
3941
+ strategy: params.strategy,
3942
+ slippageBps: params.slippageBps
3943
+ });
3944
+ } catch (error) {
3945
+ const message = thrownMessage(error);
3946
+ throw new Error(
3947
+ message.startsWith("Deposit failed:") ? message : `Deposit failed: ${message}`
3948
+ );
3949
+ }
3950
+ }
3951
+ /** Portfolio floor used by a direct deposit, applied before a wrap or swap spends. */
3952
+ async assertCollateralMinimum(userAddress, chainId, asset, amount) {
3953
+ const symbol = Object.keys(ASSET_CONFIGS).find(
3954
+ (key) => key.toLowerCase() === asset.toLowerCase()
3955
+ );
3956
+ if (!symbol || !getAssetChainIds(symbol).includes(chainId)) return;
3957
+ await this.hydrateSessionWallet();
3958
+ const safeAddress = await this.getSafeAddressFor(userAddress, chainId);
3959
+ if (!safeAddress) {
3960
+ throw new Error("Smart wallet address is not available");
3961
+ }
3962
+ await this.enforceMinimumPortfolioBalance(
3963
+ chainId,
3964
+ symbol,
3965
+ amount,
3966
+ safeAddress,
3967
+ userAddress
3968
+ );
3969
+ }
3970
+ assertSwapDepositParams(params) {
3971
+ if (!params.userAddress) throw new Error("User address is required");
3972
+ if (!params.originAmount || BigInt(params.originAmount) <= 0n) {
3973
+ throw new Error("Valid origin amount is required");
3974
+ }
3975
+ if (!Number.isInteger(params.originChainId) || params.originChainId <= 0) {
3976
+ throw new Error("Valid origin chain is required");
3977
+ }
3978
+ if (!isSupportedChain(params.destinationChainId)) {
3979
+ throw new Error(`Unsupported chain ID: ${params.destinationChainId}`);
3980
+ }
3981
+ if (!params.originCurrency) throw new Error("Origin token is required");
3982
+ if (!params.destinationAsset) throw new Error("Destination asset is required");
3983
+ if (params.slippageBps != null) {
3984
+ if (!Number.isInteger(params.slippageBps) || params.slippageBps < 1 || params.slippageBps > MAX_RELAY_SLIPPAGE_BPS) {
3985
+ throw new Error(
3986
+ `slippageBps must be an integer from 1 to ${MAX_RELAY_SLIPPAGE_BPS}. Received ${params.slippageBps}.`
3987
+ );
3988
+ }
3989
+ }
3990
+ if (params.destinationAsset.toUpperCase() === "WETH" && params.originChainId === params.destinationChainId && isNativeSpendToken(params.originCurrency)) {
3991
+ throw new Error(
3992
+ 'Same-chain ETH to WETH is a wrap, not a Relay swap. Call sendDeposit with spendToken "ETH".'
3993
+ );
3994
+ }
3995
+ }
3996
+ async walletClientForOrigin(originChainId) {
3997
+ if (this.signer) {
3998
+ if (!isSupportedChain(originChainId)) {
3999
+ throw new Error(
4000
+ `Cannot sign a swap from chain ${originChainId} with a private key. Connect an EIP-1193 wallet, or spend from Ethereum, Base, or Arbitrum.`
4001
+ );
4002
+ }
4003
+ return this.getWalletClient(originChainId);
4004
+ }
4005
+ if (!this.walletClient?.account) {
4006
+ throw new Error("No account connected. Call connectAccount() first");
4007
+ }
4008
+ if (!this.currentProvider?.request) {
4009
+ if (this.walletClient.chain?.id === originChainId) return this.walletClient;
4010
+ throw new Error(
4011
+ `Wallet is on chain ${this.walletClient.chain?.id ?? "unknown"}. Switch it to chain ${originChainId} before this swap.`
4012
+ );
4013
+ }
4014
+ await this.currentProvider.request({
4015
+ method: "wallet_switchEthereumChain",
4016
+ params: [{ chainId: `0x${originChainId.toString(16)}` }]
4017
+ });
4018
+ const chain = isSupportedChain(originChainId) ? getChainConfig(originChainId, this.rpcUrls).chain : defineChain({
4019
+ id: originChainId,
4020
+ name: `Chain ${originChainId}`,
4021
+ nativeCurrency: { name: "Ether", symbol: "ETH", decimals: 18 },
4022
+ rpcUrls: { default: { http: ["http://127.0.0.1"] } }
4023
+ });
4024
+ this.walletClient = createWalletClient({
4025
+ account: this.walletClient.account,
4026
+ chain,
4027
+ transport: custom(this.currentProvider)
4028
+ });
4029
+ if (isSupportedChain(originChainId)) {
4030
+ this.currentChainId = originChainId;
4031
+ }
4032
+ return this.walletClient;
4033
+ }
4034
+ async wrapNativeEth(chainId, amount) {
4035
+ const token = getDefaultTokenAddress(chainId, "WETH");
4036
+ const walletClient = this.getWalletClient(chainId);
4037
+ const chainConfig = getChainConfig(chainId, this.rpcUrls);
4038
+ const hash = await walletClient.writeContract({
4039
+ address: token,
4040
+ abi: WETH_DEPOSIT_ABI,
4041
+ functionName: "deposit",
4042
+ value: BigInt(amount),
4043
+ chain: chainConfig.chain,
4044
+ account: walletClient.account
4045
+ });
4046
+ const receipt = await chainConfig.publicClient.waitForTransactionReceipt({
4047
+ hash
4048
+ });
4049
+ if (receipt.status !== "success") {
4050
+ throw new Error("ETH wrap failed");
4051
+ }
4052
+ }
4053
+ async waitForRelayCreditTx(params) {
4054
+ const chainConfig = getChainConfig(params.destinationChainId, this.rpcUrls);
4055
+ const receipts = /* @__PURE__ */ new Map();
4056
+ const maxAttempts = 120;
4057
+ const intervalMs = 5e3;
4058
+ const loadReceipt = async (hash) => {
4059
+ const key = hash.toLowerCase();
4060
+ if (receipts.has(key)) return;
4061
+ try {
4062
+ const receipt = await chainConfig.publicClient.getTransactionReceipt({
4063
+ hash
4064
+ });
4065
+ receipts.set(key, {
4066
+ status: receipt.status,
4067
+ logs: receipt.logs.map((log) => ({
4068
+ address: log.address,
4069
+ topics: log.topics,
4070
+ data: log.data
4071
+ }))
4072
+ });
4073
+ } catch {
4074
+ }
4075
+ };
4076
+ const pick = async (candidates) => {
4077
+ for (const hash2 of candidates) {
4078
+ if (hash2) await loadReceipt(hash2);
4079
+ }
4080
+ const hash = selectRelayCreditTxHash({
4081
+ candidates,
4082
+ receipts,
4083
+ token: params.destinationToken,
4084
+ recipient: params.recipientSafe
4085
+ });
4086
+ if (!hash) return null;
4087
+ const receipt = receipts.get(hash.toLowerCase());
4088
+ return {
4089
+ hash,
4090
+ amount: receipt ? transferAmountTo(
4091
+ receipt.logs,
4092
+ params.destinationToken,
4093
+ params.recipientSafe
4094
+ ) : 0n
4095
+ };
4096
+ };
4097
+ const immediate = await pick(params.initialCandidates);
4098
+ if (immediate) return immediate;
4099
+ for (let attempt = 0; attempt < maxAttempts; attempt += 1) {
4100
+ const order = await this.getSwapDeposit(params.orderId);
4101
+ if (order.status === "refunded" || order.status === "failed") {
4102
+ throw new Error(`Relay funding ${order.status}`);
4103
+ }
4104
+ const match = await pick([
4105
+ ...params.initialCandidates,
4106
+ ...order.destinationTxHashes ?? []
4107
+ ]);
4108
+ if (match) return match;
4109
+ await sleep(intervalMs);
4110
+ }
4111
+ throw new Error("Relay funding is still converting");
4112
+ }
3375
4113
  /**
3376
4114
  * @deprecated Compatibility convenience method. Prefer {@link ZyfaiSDK.sendDeposit} followed by
3377
4115
  * {@link ZyfaiSDK.waitForDepositCredit} when the caller owns the completion UX.
@@ -3537,7 +4275,9 @@ var _ZyfaiSDK = class _ZyfaiSDK {
3537
4275
  }
3538
4276
  await this.authenticateUser();
3539
4277
  const usdcDetails = await this.getUserDetails("USDC");
3540
- if ((usdcDetails.chains?.length ?? 0) > 0) {
4278
+ const usdcChainsConfigured = (usdcDetails.chains?.length ?? 0) > 0;
4279
+ const usdcProtocolsConfigured = (usdcDetails.protocols?.length ?? 0) > 0;
4280
+ if (usdcChainsConfigured && usdcProtocolsConfigured) {
3541
4281
  return { applied: false };
3542
4282
  }
3543
4283
  await this.updateUserProtocols(strategy, { strict: true });
@@ -3547,6 +4287,11 @@ var _ZyfaiSDK = class _ZyfaiSDK {
3547
4287
  "First-deposit setup did not persist USDC chain configuration."
3548
4288
  );
3549
4289
  }
4290
+ if ((usdcAfterSetup.protocols?.length ?? 0) === 0) {
4291
+ throw new Error(
4292
+ "First-deposit setup did not persist USDC protocol configuration."
4293
+ );
4294
+ }
3550
4295
  return { applied: true };
3551
4296
  }
3552
4297
  /**
@@ -3563,7 +4308,9 @@ var _ZyfaiSDK = class _ZyfaiSDK {
3563
4308
  }
3564
4309
  await this.authenticateUser();
3565
4310
  const details = await this.getUserDetails(asset);
3566
- if (details.chains?.includes(chainId)) {
4311
+ const chainConfigured = details.chains?.includes(chainId) ?? false;
4312
+ const protocolsConfigured = (details.protocols?.length ?? 0) > 0;
4313
+ if (chainConfigured && protocolsConfigured) {
3567
4314
  return { applied: false };
3568
4315
  }
3569
4316
  const allProtocols = await this.httpClient.get(
@@ -3581,8 +4328,20 @@ var _ZyfaiSDK = class _ZyfaiSDK {
3581
4328
  `First-deposit setup did not persist ${asset} chain ${chainId} configuration.`
3582
4329
  );
3583
4330
  }
4331
+ if ((afterSetup.protocols?.length ?? 0) === 0) {
4332
+ throw new Error(
4333
+ `First-deposit setup did not persist ${asset} protocol configuration.`
4334
+ );
4335
+ }
3584
4336
  return { applied: true };
3585
4337
  }
4338
+ /**
4339
+ * Persist the deposit asset on one chain before a signing page runs the transfer or swap.
4340
+ * Does not build calldata and does not check the portfolio minimum.
4341
+ */
4342
+ async ensureDepositAssetOnChain(params) {
4343
+ return this.ensureDepositProfileForPrepare(params);
4344
+ }
3586
4345
  /**
3587
4346
  * Prepare a deposit: persist first-deposit profile when needed and return
3588
4347
  * ERC-20 transfer calldata for the user to sign (does not broadcast).
@@ -6204,6 +6963,7 @@ export {
6204
6963
  API_ENDPOINT,
6205
6964
  DATA_API_BASE_URLS,
6206
6965
  DATA_API_ENDPOINT,
6966
+ DEFAULT_RELAY_SLIPPAGE_BPS,
6207
6967
  DEFAULT_TOKEN_ADDRESSES,
6208
6968
  ERC7579_LAUNCHPAD_ADDRESS,
6209
6969
  EXECUTION_API_BASE_URLS,
@@ -6212,9 +6972,11 @@ export {
6212
6972
  LOCAL_DATA_API_BASE_URL,
6213
6973
  LOCAL_EXECUTION_API_BASE_URL,
6214
6974
  LOCAL_WS_URL,
6975
+ MAX_RELAY_SLIPPAGE_BPS,
6215
6976
  OWNABLE_VALIDATOR,
6216
6977
  POOL_MODULE_ADDRESSES,
6217
6978
  PROXY_EXECUTOR,
6979
+ RELAY_SLIPPAGE_PRESETS_BPS,
6218
6980
  SAFE_7579_ADDRESS,
6219
6981
  SMART_SESSIONS_FALLBACK,
6220
6982
  SMART_SESSIONS_VALIDATOR,
@@ -6233,5 +6995,7 @@ export {
6233
6995
  getManagedAssets,
6234
6996
  getSupportedChainIds,
6235
6997
  getWsUrl,
6236
- isSupportedChain
6998
+ isSupportedChain,
6999
+ resolveDepositRoute,
7000
+ resolveRelaySlippageBps
6237
7001
  };