@zyfai/sdk 0.2.56 → 0.3.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/README.md +426 -33
- package/dist/index.d.mts +367 -65
- package/dist/index.d.ts +367 -65
- package/dist/index.js +900 -260
- package/dist/index.mjs +885 -260
- package/package.json +13 -4
package/dist/index.js
CHANGED
|
@@ -31,22 +31,37 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
|
|
|
31
31
|
var index_exports = {};
|
|
32
32
|
__export(index_exports, {
|
|
33
33
|
ALLOWED_HISTORY_DAYS: () => ALLOWED_HISTORY_DAYS,
|
|
34
|
+
API_ENDPOINT: () => API_ENDPOINT,
|
|
35
|
+
DATA_API_BASE_URLS: () => DATA_API_BASE_URLS,
|
|
36
|
+
DATA_API_ENDPOINT: () => DATA_API_ENDPOINT,
|
|
34
37
|
DEFAULT_TOKEN_ADDRESSES: () => DEFAULT_TOKEN_ADDRESSES,
|
|
35
38
|
ERC7579_LAUNCHPAD_ADDRESS: () => ERC7579_LAUNCHPAD_ADDRESS,
|
|
39
|
+
EXECUTION_API_BASE_URLS: () => EXECUTION_API_BASE_URLS,
|
|
36
40
|
INTENT_EXECUTOR: () => INTENT_EXECUTOR,
|
|
37
41
|
INTENT_SMART_SESSIONS: () => INTENT_SMART_SESSIONS,
|
|
42
|
+
LOCAL_DATA_API_BASE_URL: () => LOCAL_DATA_API_BASE_URL,
|
|
43
|
+
LOCAL_EXECUTION_API_BASE_URL: () => LOCAL_EXECUTION_API_BASE_URL,
|
|
44
|
+
LOCAL_WS_URL: () => LOCAL_WS_URL,
|
|
38
45
|
OWNABLE_VALIDATOR: () => OWNABLE_VALIDATOR,
|
|
39
46
|
POOL_MODULE_ADDRESSES: () => POOL_MODULE_ADDRESSES,
|
|
40
47
|
PROXY_EXECUTOR: () => PROXY_EXECUTOR,
|
|
41
48
|
SAFE_7579_ADDRESS: () => SAFE_7579_ADDRESS,
|
|
42
49
|
SMART_SESSIONS_FALLBACK: () => SMART_SESSIONS_FALLBACK,
|
|
43
50
|
SMART_SESSIONS_VALIDATOR: () => SMART_SESSIONS_VALIDATOR,
|
|
51
|
+
STAGING_DATA_API_BASE_URL: () => STAGING_DATA_API_BASE_URL,
|
|
52
|
+
STAGING_EXECUTION_API_BASE_URL: () => STAGING_EXECUTION_API_BASE_URL,
|
|
53
|
+
STAGING_WS_URL: () => STAGING_WS_URL,
|
|
44
54
|
VAULT_ADDRESS: () => VAULT_ADDRESS,
|
|
55
|
+
WS_ENDPOINT: () => WS_ENDPOINT,
|
|
56
|
+
WS_URLS: () => WS_URLS,
|
|
45
57
|
ZyfaiSDK: () => ZyfaiSDK,
|
|
46
58
|
createBankrProvider: () => createBankrProvider,
|
|
47
59
|
getChainConfig: () => getChainConfig,
|
|
60
|
+
getDataApiBaseUrl: () => getDataApiBaseUrl,
|
|
48
61
|
getDefaultTokenAddress: () => getDefaultTokenAddress,
|
|
62
|
+
getExecutionApiBaseUrl: () => getExecutionApiBaseUrl,
|
|
49
63
|
getSupportedChainIds: () => getSupportedChainIds,
|
|
64
|
+
getWsUrl: () => getWsUrl,
|
|
50
65
|
isSupportedChain: () => isSupportedChain
|
|
51
66
|
});
|
|
52
67
|
module.exports = __toCommonJS(index_exports);
|
|
@@ -55,9 +70,40 @@ module.exports = __toCommonJS(index_exports);
|
|
|
55
70
|
var import_axios = __toESM(require("axios"));
|
|
56
71
|
|
|
57
72
|
// src/config/endpoints.ts
|
|
58
|
-
var
|
|
59
|
-
|
|
60
|
-
|
|
73
|
+
var EXECUTION_API_BASE_URLS = {
|
|
74
|
+
production: "https://api.zyf.ai",
|
|
75
|
+
staging: "https://staging-api.zyf.ai",
|
|
76
|
+
local: "http://localhost:3000"
|
|
77
|
+
};
|
|
78
|
+
var DATA_API_BASE_URLS = {
|
|
79
|
+
production: "https://defiapi.zyf.ai",
|
|
80
|
+
staging: "https://staging-defiapi.zyf.ai",
|
|
81
|
+
/** Both backends default to port 3000 locally; run one at a time or override PORT. */
|
|
82
|
+
local: "http://localhost:3000"
|
|
83
|
+
};
|
|
84
|
+
var WS_URLS = {
|
|
85
|
+
production: "wss://defiapi.zyf.ai/ws/events",
|
|
86
|
+
staging: "wss://staging-defiapi.zyf.ai/ws/events",
|
|
87
|
+
local: "ws://localhost:3000/ws/events"
|
|
88
|
+
};
|
|
89
|
+
var API_ENDPOINT = EXECUTION_API_BASE_URLS.production;
|
|
90
|
+
var DATA_API_ENDPOINT = DATA_API_BASE_URLS.production;
|
|
91
|
+
var WS_ENDPOINT = WS_URLS.production;
|
|
92
|
+
var STAGING_EXECUTION_API_BASE_URL = EXECUTION_API_BASE_URLS.staging;
|
|
93
|
+
var STAGING_DATA_API_BASE_URL = DATA_API_BASE_URLS.staging;
|
|
94
|
+
var STAGING_WS_URL = WS_URLS.staging;
|
|
95
|
+
var LOCAL_EXECUTION_API_BASE_URL = EXECUTION_API_BASE_URLS.local;
|
|
96
|
+
var LOCAL_DATA_API_BASE_URL = DATA_API_BASE_URLS.local;
|
|
97
|
+
var LOCAL_WS_URL = WS_URLS.local;
|
|
98
|
+
function getExecutionApiBaseUrl(environment = "production") {
|
|
99
|
+
return EXECUTION_API_BASE_URLS[environment];
|
|
100
|
+
}
|
|
101
|
+
function getDataApiBaseUrl(environment = "production") {
|
|
102
|
+
return DATA_API_BASE_URLS[environment];
|
|
103
|
+
}
|
|
104
|
+
function getWsUrl(environment = "production") {
|
|
105
|
+
return WS_URLS[environment];
|
|
106
|
+
}
|
|
61
107
|
var API_VERSION = "/api/v1";
|
|
62
108
|
var DATA_API_VERSION = "/api/v2";
|
|
63
109
|
var ENDPOINTS = {
|
|
@@ -68,7 +114,8 @@ var ENDPOINTS = {
|
|
|
68
114
|
USER_ME: "/users/me",
|
|
69
115
|
USER_WITHDRAW: "/users/withdraw",
|
|
70
116
|
PARTIAL_WITHDRAW: "/users/partial-withdraw",
|
|
71
|
-
LOG_DEPOSIT: "/users/log_deposit",
|
|
117
|
+
LOG_DEPOSIT: "/users/log_deposit/v2",
|
|
118
|
+
DEPOSIT_STATUS: (depositId) => `/users/deposits/${depositId}`,
|
|
72
119
|
// Safe Deployment (single endpoint)
|
|
73
120
|
SAFE_DEPLOY: "/users/safe-deploy",
|
|
74
121
|
// Multichain deploy for predeployed (pool) wallets — deploys + rotates the
|
|
@@ -103,11 +150,17 @@ var ENDPOINTS = {
|
|
|
103
150
|
`networks=${networks}`,
|
|
104
151
|
`strategy=${params.strategy}`
|
|
105
152
|
];
|
|
106
|
-
if (params.minSplit !== void 0)
|
|
107
|
-
|
|
153
|
+
if (params.minSplit !== void 0)
|
|
154
|
+
query.push(`minSplit=${params.minSplit}`);
|
|
155
|
+
if (params.protocols?.length)
|
|
156
|
+
query.push(`protocols=${params.protocols.join(",")}`);
|
|
108
157
|
if (params.pools?.length) query.push(`pools=${params.pools.join(",")}`);
|
|
109
|
-
if (params.userPositions?.length)
|
|
110
|
-
|
|
158
|
+
if (params.userPositions?.length)
|
|
159
|
+
query.push(
|
|
160
|
+
`userPositions=${encodeURIComponent(JSON.stringify(params.userPositions))}`
|
|
161
|
+
);
|
|
162
|
+
if (params.partOfZyfiTvl !== void 0)
|
|
163
|
+
query.push(`partOfZyfiTvl=${params.partOfZyfiTvl}`);
|
|
111
164
|
return `/simulate/best-positions?${query.join("&")}`;
|
|
112
165
|
},
|
|
113
166
|
// Customization
|
|
@@ -142,12 +195,20 @@ var DATA_ENDPOINTS = {
|
|
|
142
195
|
if (status) params.push(`status=${status}`);
|
|
143
196
|
return params.length > 0 ? `/opportunities/degen-strategies?${params.join("&")}` : "/opportunities/degen-strategies";
|
|
144
197
|
},
|
|
198
|
+
OPPORTUNITIES_ASYNC: (chainId, asset, status) => {
|
|
199
|
+
const params = [];
|
|
200
|
+
if (chainId !== void 0) params.push(`chainId=${chainId}`);
|
|
201
|
+
if (asset) params.push(`asset=${asset}`);
|
|
202
|
+
if (status) params.push(`status=${status}`);
|
|
203
|
+
return params.length > 0 ? `/opportunities/async?${params.join("&")}` : "/opportunities/async";
|
|
204
|
+
},
|
|
145
205
|
// APY History
|
|
146
206
|
DAILY_APY_HISTORY_WEIGHTED: (walletAddress, days) => `/daily-apy-history/weighted-multi-asset/${walletAddress}${days ? `?days=${days}` : ""}`,
|
|
147
207
|
// Rebalance
|
|
148
208
|
REBALANCE_INFO: (options) => {
|
|
149
209
|
const params = [];
|
|
150
|
-
if (options?.isCrossChain !== void 0)
|
|
210
|
+
if (options?.isCrossChain !== void 0)
|
|
211
|
+
params.push(`isCrossChain=${options.isCrossChain}`);
|
|
151
212
|
if (options?.tokenSymbol) params.push(`tokenSymbol=${options.tokenSymbol}`);
|
|
152
213
|
return params.length > 0 ? `/rebalance/rebalance-info?${params.join("&")}` : "/rebalance/rebalance-info";
|
|
153
214
|
},
|
|
@@ -156,10 +217,12 @@ var DATA_ENDPOINTS = {
|
|
|
156
217
|
// APY Per Strategy
|
|
157
218
|
APY_PER_STRATEGY: (options = {}) => {
|
|
158
219
|
const params = [];
|
|
159
|
-
if (options.isCrossChain !== void 0)
|
|
220
|
+
if (options.isCrossChain !== void 0)
|
|
221
|
+
params.push(`isCrossChain=${options.isCrossChain}`);
|
|
160
222
|
if (options.days !== void 0) params.push(`days=${options.days}`);
|
|
161
223
|
if (options.strategy) params.push(`strategy=${options.strategy}`);
|
|
162
|
-
if (options.chainId !== void 0)
|
|
224
|
+
if (options.chainId !== void 0)
|
|
225
|
+
params.push(`chainId=${options.chainId}`);
|
|
163
226
|
if (options.tokenSymbol) params.push(`tokenSymbol=${options.tokenSymbol}`);
|
|
164
227
|
return params.length > 0 ? `/rebalance/rebalance-info?${params.join("&")}` : "/rebalance/rebalance-info";
|
|
165
228
|
}
|
|
@@ -172,14 +235,16 @@ var HttpClient = class {
|
|
|
172
235
|
*
|
|
173
236
|
* @param apiKey - API key for both Execution API and Data API
|
|
174
237
|
*/
|
|
175
|
-
constructor(apiKey) {
|
|
238
|
+
constructor(apiKey, config = {}) {
|
|
176
239
|
this.authToken = null;
|
|
177
240
|
this.apiKey = apiKey;
|
|
178
|
-
const
|
|
241
|
+
const executionApiUrl = config.executionApiUrl ?? API_ENDPOINT;
|
|
242
|
+
this.dataApiBaseUrl = config.dataApiUrl ?? DATA_API_ENDPOINT;
|
|
243
|
+
const parsedUrl = new URL(executionApiUrl);
|
|
179
244
|
this.origin = parsedUrl.origin;
|
|
180
245
|
this.host = parsedUrl.host;
|
|
181
246
|
this.client = import_axios.default.create({
|
|
182
|
-
baseURL: `${
|
|
247
|
+
baseURL: `${executionApiUrl}${API_VERSION}`,
|
|
183
248
|
headers: {
|
|
184
249
|
"Content-Type": "application/json",
|
|
185
250
|
"X-API-Key": this.apiKey
|
|
@@ -187,7 +252,7 @@ var HttpClient = class {
|
|
|
187
252
|
timeout: 3e4
|
|
188
253
|
});
|
|
189
254
|
this.dataClient = import_axios.default.create({
|
|
190
|
-
baseURL: `${
|
|
255
|
+
baseURL: `${this.dataApiBaseUrl}${DATA_API_VERSION}`,
|
|
191
256
|
headers: {
|
|
192
257
|
"Content-Type": "application/json",
|
|
193
258
|
"X-API-Key": this.apiKey
|
|
@@ -230,7 +295,9 @@ var HttpClient = class {
|
|
|
230
295
|
const data = error.response.data;
|
|
231
296
|
switch (status) {
|
|
232
297
|
case 401:
|
|
233
|
-
throw new Error(
|
|
298
|
+
throw new Error(
|
|
299
|
+
this.authToken ? "Unauthorized: Invalid or expired user session. Call connectAccount() to sign in again." : "Unauthorized: Missing user session. Call connectAccount() before this endpoint \u2014 the SDK API key alone is not sufficient."
|
|
300
|
+
);
|
|
234
301
|
case 403:
|
|
235
302
|
throw new Error("Forbidden: Access denied");
|
|
236
303
|
case 404:
|
|
@@ -240,7 +307,9 @@ var HttpClient = class {
|
|
|
240
307
|
case 429:
|
|
241
308
|
throw new Error("Rate limit exceeded. Please try again later.");
|
|
242
309
|
case 500:
|
|
243
|
-
throw new Error(
|
|
310
|
+
throw new Error(
|
|
311
|
+
data?.message || data?.error || "Internal server error. Please try again later."
|
|
312
|
+
);
|
|
244
313
|
default:
|
|
245
314
|
throw new Error(data.message || "An error occurred");
|
|
246
315
|
}
|
|
@@ -286,7 +355,7 @@ var HttpClient = class {
|
|
|
286
355
|
* @param config - Additional axios config
|
|
287
356
|
*/
|
|
288
357
|
async dataPostCustom(path, data, config) {
|
|
289
|
-
const fullUrl = `${
|
|
358
|
+
const fullUrl = `${this.dataApiBaseUrl}${path}`;
|
|
290
359
|
const headers = {
|
|
291
360
|
"Content-Type": "application/json",
|
|
292
361
|
"X-API-Key": this.apiKey,
|
|
@@ -321,7 +390,9 @@ var HttpClient = class {
|
|
|
321
390
|
const data = error.response.data;
|
|
322
391
|
switch (status) {
|
|
323
392
|
case 401:
|
|
324
|
-
throw new Error(
|
|
393
|
+
throw new Error(
|
|
394
|
+
this.authToken ? "Unauthorized: Invalid or expired user session. Call connectAccount() to sign in again." : "Unauthorized: Missing user session. Call connectAccount() before this endpoint \u2014 the SDK API key alone is not sufficient."
|
|
395
|
+
);
|
|
325
396
|
case 403:
|
|
326
397
|
throw new Error("Forbidden: Access denied to data API");
|
|
327
398
|
case 404:
|
|
@@ -349,26 +420,30 @@ var HttpClient = class {
|
|
|
349
420
|
}
|
|
350
421
|
};
|
|
351
422
|
|
|
352
|
-
// src/utils/
|
|
423
|
+
// src/utils/poll.ts
|
|
424
|
+
function sleep(ms) {
|
|
425
|
+
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
426
|
+
}
|
|
427
|
+
|
|
428
|
+
// src/utils/token-price.ts
|
|
353
429
|
var PRICE_SCALE = 8;
|
|
354
|
-
var
|
|
430
|
+
var parseTokenUsdPrice = (response) => {
|
|
355
431
|
const priceUsd = response?.data?.price_usd;
|
|
356
432
|
if (typeof priceUsd !== "number" || !Number.isFinite(priceUsd) || priceUsd <= 0) {
|
|
357
|
-
throw new Error("
|
|
433
|
+
throw new Error("Token USD price must be a positive number");
|
|
358
434
|
}
|
|
359
435
|
return priceUsd;
|
|
360
436
|
};
|
|
361
|
-
var
|
|
362
|
-
if (!Number.isFinite(
|
|
363
|
-
throw new Error("
|
|
437
|
+
var usdToTokenUnits = (usdAmount, priceUsd, decimals) => {
|
|
438
|
+
if (!Number.isFinite(priceUsd) || priceUsd <= 0) {
|
|
439
|
+
throw new Error("Token USD price must be positive");
|
|
364
440
|
}
|
|
365
|
-
const scaledPrice = BigInt(Math.round(
|
|
441
|
+
const scaledPrice = BigInt(Math.round(priceUsd * 10 ** PRICE_SCALE));
|
|
366
442
|
if (scaledPrice <= 0n) {
|
|
367
|
-
throw new Error("
|
|
443
|
+
throw new Error("Token USD price must be positive");
|
|
368
444
|
}
|
|
369
|
-
return usdAmount * 10n **
|
|
445
|
+
return usdAmount * 10n ** BigInt(decimals) * 10n ** BigInt(PRICE_SCALE) / scaledPrice;
|
|
370
446
|
};
|
|
371
|
-
var minWethWeiForUsd = (ethUsd, usdAmount) => usdToWethWei(usdAmount, ethUsd);
|
|
372
447
|
|
|
373
448
|
// src/config/abis.ts
|
|
374
449
|
var import_viem = require("viem");
|
|
@@ -561,11 +636,26 @@ var MIN_PORTFOLIO_BALANCE = {
|
|
|
561
636
|
// 100 EURC (6 decimals)
|
|
562
637
|
}
|
|
563
638
|
};
|
|
564
|
-
var
|
|
565
|
-
1: 10000n,
|
|
566
|
-
8453: 100n,
|
|
567
|
-
42161: 100n
|
|
639
|
+
var MIN_PORTFOLIO_USD = {
|
|
640
|
+
1: { WETH: 10000n },
|
|
641
|
+
8453: { WETH: 100n, NVDAc: 100n },
|
|
642
|
+
42161: { WETH: 100n }
|
|
643
|
+
};
|
|
644
|
+
var DEPOSIT_CREDIT_INTERVAL_MS = {
|
|
645
|
+
1: 2e3,
|
|
646
|
+
8453: 500,
|
|
647
|
+
42161: 250
|
|
568
648
|
};
|
|
649
|
+
var DEPOSIT_CREDIT_TIMEOUT_MS = {
|
|
650
|
+
1: 6e4,
|
|
651
|
+
// 1 minute
|
|
652
|
+
8453: 2e4,
|
|
653
|
+
// ~10 Base blocks
|
|
654
|
+
42161: 2e4
|
|
655
|
+
// ~10 Arbitrum blocks
|
|
656
|
+
};
|
|
657
|
+
var getDepositCreditIntervalMs = (chainId) => DEPOSIT_CREDIT_INTERVAL_MS[chainId];
|
|
658
|
+
var getDepositCreditTimeoutMs = (chainId) => DEPOSIT_CREDIT_TIMEOUT_MS[chainId];
|
|
569
659
|
var formatMinPortfolioLabel = (raw, decimals, symbol) => {
|
|
570
660
|
const base2 = 10n ** BigInt(decimals);
|
|
571
661
|
const whole = raw / base2;
|
|
@@ -577,6 +667,25 @@ var formatMinPortfolioLabel = (raw, decimals, symbol) => {
|
|
|
577
667
|
return `${whole.toString()}.${fractionStr} ${symbol}`;
|
|
578
668
|
};
|
|
579
669
|
|
|
670
|
+
// src/config/local-dev.ts
|
|
671
|
+
function isLocalExecutionApiUrl(executionApiUrl) {
|
|
672
|
+
if (executionApiUrl === EXECUTION_API_BASE_URLS.local) {
|
|
673
|
+
return true;
|
|
674
|
+
}
|
|
675
|
+
try {
|
|
676
|
+
const { hostname } = new URL(executionApiUrl);
|
|
677
|
+
return hostname === "localhost" || hostname === "127.0.0.1";
|
|
678
|
+
} catch {
|
|
679
|
+
return false;
|
|
680
|
+
}
|
|
681
|
+
}
|
|
682
|
+
function shouldBypassMinPortfolioCheck(executionApiUrl) {
|
|
683
|
+
if (process.env.NODE_ENV === "production") {
|
|
684
|
+
return false;
|
|
685
|
+
}
|
|
686
|
+
return isLocalExecutionApiUrl(executionApiUrl);
|
|
687
|
+
}
|
|
688
|
+
|
|
580
689
|
// src/core/ZyfaiSDK.ts
|
|
581
690
|
var import_accounts2 = require("viem/accounts");
|
|
582
691
|
var import_viem4 = require("viem");
|
|
@@ -627,6 +736,8 @@ var ASSET_CONFIGS = {
|
|
|
627
736
|
displayName: "WETH",
|
|
628
737
|
icon: "/ai-dashboard/eth-token.png",
|
|
629
738
|
decimals: 18,
|
|
739
|
+
// Data API `/price?token=` identifier, used for USD-denominated minimums.
|
|
740
|
+
priceTokenSymbol: "eth",
|
|
630
741
|
tokenSymbols: ["WETH", "ETH"],
|
|
631
742
|
tokenSymbolsByChainId: {
|
|
632
743
|
1: "WETH",
|
|
@@ -667,8 +778,39 @@ var ASSET_CONFIGS = {
|
|
|
667
778
|
// Base
|
|
668
779
|
},
|
|
669
780
|
enabled: true
|
|
781
|
+
},
|
|
782
|
+
// Coinbase B20 tokenized NVIDIA equity. Base only, and only reachable through
|
|
783
|
+
// protocols with delayed withdrawals — see the `yieldmaxxing` strategy.
|
|
784
|
+
NVDAc: {
|
|
785
|
+
symbol: "NVDAc",
|
|
786
|
+
assetType: "nvdac",
|
|
787
|
+
displayName: "NVIDIA",
|
|
788
|
+
icon: "https://metadata.coinbase.com/equity_icons/1fee9b7a44e800d438dd9d96c3283e05784c925c2c871a48ff735950740b551a.png",
|
|
789
|
+
decimals: 8,
|
|
790
|
+
priceTokenSymbol: "nvdac",
|
|
791
|
+
tokenSymbols: ["NVDAc"],
|
|
792
|
+
tokenSymbolsByChainId: {
|
|
793
|
+
8453: "NVDAc"
|
|
794
|
+
},
|
|
795
|
+
addresses: {
|
|
796
|
+
8453: "0xb20000000000000000000078ee7ce2fE4908108C"
|
|
797
|
+
// Base
|
|
798
|
+
},
|
|
799
|
+
enabled: true
|
|
670
800
|
}
|
|
671
801
|
};
|
|
802
|
+
var resolveAssetSymbol = (asset) => {
|
|
803
|
+
const match = Object.keys(ASSET_CONFIGS).find(
|
|
804
|
+
(key) => key.toLowerCase() === asset.toLowerCase()
|
|
805
|
+
);
|
|
806
|
+
if (!match) {
|
|
807
|
+
throw new Error(
|
|
808
|
+
`Unsupported asset: ${asset}. Supported: ${Object.keys(ASSET_CONFIGS).join(", ")}.`
|
|
809
|
+
);
|
|
810
|
+
}
|
|
811
|
+
return match;
|
|
812
|
+
};
|
|
813
|
+
var getAssetChainIds = (asset) => Object.keys(ASSET_CONFIGS[asset]?.addresses ?? {}).map(Number).filter((chainId) => chainId in CHAINS);
|
|
672
814
|
var getDefaultTokenAddress = (chainId, asset) => {
|
|
673
815
|
const address = ASSET_CONFIGS[asset || "USDC"]?.addresses[chainId];
|
|
674
816
|
if (!address || address === "0x0000000000000000000000000000000000000000") {
|
|
@@ -943,15 +1085,19 @@ var signSessionKey = async (config, sessions, allPublicClients, signingParams) =
|
|
|
943
1085
|
};
|
|
944
1086
|
|
|
945
1087
|
// src/utils/strategy.ts
|
|
1088
|
+
var PUBLIC_STRATEGIES = `"conservative", "aggressive" or "yieldmaxxing"`;
|
|
1089
|
+
var SUPPORTED_ASSETS = `"USDC", "WETH", "EURC" or "NVDAc"`;
|
|
946
1090
|
function toInternalStrategy(publicStrategy) {
|
|
947
1091
|
switch (publicStrategy) {
|
|
948
1092
|
case "conservative":
|
|
949
1093
|
return "safe_strategy";
|
|
950
1094
|
case "aggressive":
|
|
951
1095
|
return "degen_strategy";
|
|
1096
|
+
case "yieldmaxxing":
|
|
1097
|
+
return "async_strategy";
|
|
952
1098
|
default:
|
|
953
1099
|
throw new Error(
|
|
954
|
-
`Invalid public strategy: ${publicStrategy}. Must be
|
|
1100
|
+
`Invalid public strategy: ${publicStrategy}. Must be ${PUBLIC_STRATEGIES}.`
|
|
955
1101
|
);
|
|
956
1102
|
}
|
|
957
1103
|
}
|
|
@@ -962,12 +1108,25 @@ function toPublicStrategy(internalStrategy) {
|
|
|
962
1108
|
if (internalStrategy === "degen_strategy" || internalStrategy === "degen") {
|
|
963
1109
|
return "aggressive";
|
|
964
1110
|
}
|
|
1111
|
+
if (internalStrategy === "async_strategy" || internalStrategy === "async") {
|
|
1112
|
+
return "yieldmaxxing";
|
|
1113
|
+
}
|
|
965
1114
|
throw new Error(
|
|
966
|
-
`Invalid internal strategy: ${internalStrategy}. Must be "safe_strategy" or "
|
|
1115
|
+
`Invalid internal strategy: ${internalStrategy}. Must be "safe_strategy", "degen_strategy" or "async_strategy".`
|
|
967
1116
|
);
|
|
968
1117
|
}
|
|
1118
|
+
function toPublicStrategyOrUndefined(internalStrategy) {
|
|
1119
|
+
if (!internalStrategy) {
|
|
1120
|
+
return void 0;
|
|
1121
|
+
}
|
|
1122
|
+
try {
|
|
1123
|
+
return toPublicStrategy(internalStrategy);
|
|
1124
|
+
} catch {
|
|
1125
|
+
return void 0;
|
|
1126
|
+
}
|
|
1127
|
+
}
|
|
969
1128
|
function isValidPublicStrategy(strategy) {
|
|
970
|
-
return strategy === "conservative" || strategy === "aggressive";
|
|
1129
|
+
return strategy === "conservative" || strategy === "aggressive" || strategy === "yieldmaxxing";
|
|
971
1130
|
}
|
|
972
1131
|
function convertStrategyToPublic(obj) {
|
|
973
1132
|
if (!obj.strategy) {
|
|
@@ -1016,8 +1175,11 @@ function convertAssetInternally(asset) {
|
|
|
1016
1175
|
if (asset === "EURC") {
|
|
1017
1176
|
return "eurc";
|
|
1018
1177
|
}
|
|
1178
|
+
if (asset === "NVDAc") {
|
|
1179
|
+
return "nvdac";
|
|
1180
|
+
}
|
|
1019
1181
|
throw new Error(
|
|
1020
|
-
`Invalid asset: ${asset}. Must be
|
|
1182
|
+
`Invalid asset: ${asset}. Must be ${SUPPORTED_ASSETS}.`
|
|
1021
1183
|
);
|
|
1022
1184
|
}
|
|
1023
1185
|
function convertStrategiesToPublic(array) {
|
|
@@ -1062,16 +1224,19 @@ var hasAssetOnSelectedChains = (protocol, chains, asset) => {
|
|
|
1062
1224
|
(a) => chains.includes(a.chainId) && validSymbols.includes(a.symbol)
|
|
1063
1225
|
);
|
|
1064
1226
|
};
|
|
1227
|
+
var ELIGIBLE_PROTOCOL_STRATEGIES = {
|
|
1228
|
+
safe_strategy: ["safe_strategy"],
|
|
1229
|
+
degen_strategy: ["safe_strategy", "degen_strategy"],
|
|
1230
|
+
async_strategy: ["safe_strategy", "degen_strategy", "async_strategy"]
|
|
1231
|
+
};
|
|
1065
1232
|
var getMatchingProtocolIds = (protocols, internalStrategy, chains, asset) => {
|
|
1066
1233
|
if (chains.length === 0) return [];
|
|
1234
|
+
const eligible = ELIGIBLE_PROTOCOL_STRATEGIES[internalStrategy] ?? ELIGIBLE_PROTOCOL_STRATEGIES.safe_strategy;
|
|
1067
1235
|
return protocols.filter((protocol) => {
|
|
1068
1236
|
if (!protocol || !protocol.strategies) return false;
|
|
1069
1237
|
if (!protocol.chains?.some((c) => chains.includes(c))) return false;
|
|
1070
1238
|
if (!hasAssetOnSelectedChains(protocol, chains, asset)) return false;
|
|
1071
|
-
|
|
1072
|
-
return protocol.strategies.includes("degen_strategy") || protocol.strategies.includes("safe_strategy");
|
|
1073
|
-
}
|
|
1074
|
-
return protocol.strategies.includes("safe_strategy");
|
|
1239
|
+
return protocol.strategies.some((s) => eligible.includes(s));
|
|
1075
1240
|
}).map((protocol) => protocol.id);
|
|
1076
1241
|
};
|
|
1077
1242
|
var hasMatchingPool = (data, chains, asset) => {
|
|
@@ -1437,8 +1602,34 @@ function enrichOnchainEarningsTotals(apiData) {
|
|
|
1437
1602
|
};
|
|
1438
1603
|
}
|
|
1439
1604
|
|
|
1605
|
+
// src/utils/async-withdrawals.ts
|
|
1606
|
+
var findBlockingAsyncRedemption = (portfolio, chainId, tokenSymbol) => {
|
|
1607
|
+
const matchesToken = (symbol) => !tokenSymbol || symbol?.toLowerCase() === tokenSymbol.toLowerCase();
|
|
1608
|
+
const blocked = (portfolio.pendingAsyncWithdrawals ?? []).filter(
|
|
1609
|
+
(w) => w.chainId === chainId && (w.status === "REQUESTED" || w.status === "CLAIMABLE") && matchesToken(w.token?.symbol)
|
|
1610
|
+
);
|
|
1611
|
+
if (blocked.length === 0) return void 0;
|
|
1612
|
+
const blockedPools = new Set(
|
|
1613
|
+
blocked.map((w) => w.pool?.toLowerCase()).filter(Boolean)
|
|
1614
|
+
);
|
|
1615
|
+
const hasFreePosition = (portfolio.positions ?? []).some(
|
|
1616
|
+
(p) => matchesToken(p.token_symbol) && Number(chainNameToId(p.chain ?? "")) === chainId && !blockedPools.has(p.pool?.toLowerCase() ?? "")
|
|
1617
|
+
);
|
|
1618
|
+
const hasIdleBalance = (portfolio.staleBalances ?? []).some(
|
|
1619
|
+
(b) => b.chainId === chainId && matchesToken(b.tokenSymbol) && BigInt(b.balance ?? "0") > 0n
|
|
1620
|
+
);
|
|
1621
|
+
return hasFreePosition || hasIdleBalance ? void 0 : blocked[0];
|
|
1622
|
+
};
|
|
1623
|
+
|
|
1440
1624
|
// src/core/ZyfaiSDK.ts
|
|
1441
1625
|
var import_siwe = require("siwe");
|
|
1626
|
+
var DepositCreditTimeoutError = class extends Error {
|
|
1627
|
+
constructor(depositId) {
|
|
1628
|
+
super(`Timed out waiting for deposit ${depositId} to be credited`);
|
|
1629
|
+
this.name = "DepositCreditTimeoutError";
|
|
1630
|
+
}
|
|
1631
|
+
};
|
|
1632
|
+
var MANAGED_ASSETS = ["USDC", "WETH", "EURC", "NVDAc"];
|
|
1442
1633
|
var _ZyfaiSDK = class _ZyfaiSDK {
|
|
1443
1634
|
constructor(config) {
|
|
1444
1635
|
this.signer = null;
|
|
@@ -1450,21 +1641,33 @@ var _ZyfaiSDK = class _ZyfaiSDK {
|
|
|
1450
1641
|
this.currentProvider = null;
|
|
1451
1642
|
this.currentChainId = null;
|
|
1452
1643
|
const sdkConfig = typeof config === "string" ? { apiKey: config } : config;
|
|
1453
|
-
const {
|
|
1644
|
+
const {
|
|
1645
|
+
apiKey,
|
|
1646
|
+
rpcUrls,
|
|
1647
|
+
referralSource,
|
|
1648
|
+
executionApiUrl,
|
|
1649
|
+
dataApiUrl,
|
|
1650
|
+
bypassMinPortfolio
|
|
1651
|
+
} = sdkConfig;
|
|
1454
1652
|
if (!apiKey) {
|
|
1455
1653
|
throw new Error("API key is required");
|
|
1456
1654
|
}
|
|
1457
|
-
this.
|
|
1655
|
+
this.executionApiUrl = executionApiUrl ?? API_ENDPOINT;
|
|
1656
|
+
this.bypassMinPortfolio = bypassMinPortfolio ?? shouldBypassMinPortfolioCheck(this.executionApiUrl);
|
|
1657
|
+
this.httpClient = new HttpClient(apiKey, {
|
|
1658
|
+
executionApiUrl: this.executionApiUrl,
|
|
1659
|
+
dataApiUrl
|
|
1660
|
+
});
|
|
1458
1661
|
this.rpcUrls = rpcUrls;
|
|
1459
1662
|
this.referralSource = referralSource;
|
|
1460
1663
|
}
|
|
1461
1664
|
/**
|
|
1462
|
-
* Warn that a legacy method is deprecated in favor of
|
|
1665
|
+
* Warn that a legacy method is deprecated in favor of sendDeposit.
|
|
1463
1666
|
* Predeployed wallets no longer require deploySafe / createSessionKey.
|
|
1464
1667
|
*/
|
|
1465
1668
|
warnDeprecatedOnboardingMethod(methodName) {
|
|
1466
1669
|
console.warn(
|
|
1467
|
-
`[ZyfaiSDK] ${methodName}() is deprecated for partner integrations. Prefer
|
|
1670
|
+
`[ZyfaiSDK] ${methodName}() is deprecated for partner integrations. Prefer sendDeposit() \u2014 predeployed Safes and session keys are handled automatically on first deposit.`
|
|
1468
1671
|
);
|
|
1469
1672
|
}
|
|
1470
1673
|
/**
|
|
@@ -1491,8 +1694,8 @@ var _ZyfaiSDK = class _ZyfaiSDK {
|
|
|
1491
1694
|
uri = globalWindow.location.origin;
|
|
1492
1695
|
domain = globalWindow.location.host;
|
|
1493
1696
|
} else {
|
|
1494
|
-
uri =
|
|
1495
|
-
domain =
|
|
1697
|
+
uri = this.executionApiUrl;
|
|
1698
|
+
domain = new URL(this.executionApiUrl).host;
|
|
1496
1699
|
}
|
|
1497
1700
|
const messageObj = new import_siwe.SiweMessage({
|
|
1498
1701
|
address: userAddress,
|
|
@@ -1562,33 +1765,37 @@ var _ZyfaiSDK = class _ZyfaiSDK {
|
|
|
1562
1765
|
if (request.strategy) {
|
|
1563
1766
|
if (!isValidPublicStrategy(request.strategy)) {
|
|
1564
1767
|
throw new Error(
|
|
1565
|
-
`Invalid strategy: ${request.strategy}. Must be "conservative" or "
|
|
1768
|
+
`Invalid strategy: ${request.strategy}. Must be "conservative", "aggressive" or "yieldmaxxing".`
|
|
1566
1769
|
);
|
|
1567
1770
|
}
|
|
1568
|
-
rebalanceStrategy = toInternalStrategy(
|
|
1569
|
-
request.strategy
|
|
1570
|
-
);
|
|
1771
|
+
rebalanceStrategy = toInternalStrategy(request.strategy);
|
|
1571
1772
|
}
|
|
1572
1773
|
const assetSettings = {};
|
|
1573
|
-
if (rebalanceStrategy !== void 0)
|
|
1574
|
-
|
|
1575
|
-
if (request.
|
|
1576
|
-
|
|
1577
|
-
if (request.
|
|
1774
|
+
if (rebalanceStrategy !== void 0)
|
|
1775
|
+
assetSettings.rebalanceStrategy = rebalanceStrategy;
|
|
1776
|
+
if (request.autocompounding !== void 0)
|
|
1777
|
+
assetSettings.autocompounding = request.autocompounding;
|
|
1778
|
+
if (request.crosschainStrategy !== void 0)
|
|
1779
|
+
assetSettings.crosschainStrategy = request.crosschainStrategy;
|
|
1780
|
+
if (request.splitting !== void 0)
|
|
1781
|
+
assetSettings.splitting = request.splitting;
|
|
1782
|
+
if (request.minSplits !== void 0)
|
|
1783
|
+
assetSettings.minSplits = request.minSplits;
|
|
1578
1784
|
if (request.chains !== void 0) assetSettings.chains = request.chains;
|
|
1579
|
-
if (request.autoSelectProtocols !== void 0)
|
|
1580
|
-
|
|
1785
|
+
if (request.autoSelectProtocols !== void 0)
|
|
1786
|
+
assetSettings.autoSelectProtocols = request.autoSelectProtocols;
|
|
1787
|
+
if (request.protocols !== void 0)
|
|
1788
|
+
assetSettings.protocols = request.protocols;
|
|
1581
1789
|
const payload = {
|
|
1582
1790
|
assetTypeSettings: {
|
|
1583
1791
|
[internalAsset]: assetSettings
|
|
1584
1792
|
}
|
|
1585
1793
|
};
|
|
1586
|
-
if (request.omniAccount !== void 0)
|
|
1587
|
-
|
|
1588
|
-
|
|
1589
|
-
|
|
1590
|
-
|
|
1591
|
-
);
|
|
1794
|
+
if (request.omniAccount !== void 0)
|
|
1795
|
+
payload.omniAccount = request.omniAccount;
|
|
1796
|
+
if (request.agentName !== void 0)
|
|
1797
|
+
payload.agentName = request.agentName;
|
|
1798
|
+
await this.httpClient.patch(ENDPOINTS.USER_ME, payload);
|
|
1592
1799
|
return await this.getUserDetails(asset);
|
|
1593
1800
|
} catch (error) {
|
|
1594
1801
|
throw new Error(
|
|
@@ -1616,19 +1823,14 @@ var _ZyfaiSDK = class _ZyfaiSDK {
|
|
|
1616
1823
|
*/
|
|
1617
1824
|
async pauseAgent() {
|
|
1618
1825
|
try {
|
|
1619
|
-
|
|
1620
|
-
|
|
1621
|
-
protocols: []
|
|
1622
|
-
}
|
|
1623
|
-
|
|
1624
|
-
|
|
1625
|
-
|
|
1626
|
-
|
|
1627
|
-
const response = await this.updateUserProfile({
|
|
1628
|
-
asset: "EURC",
|
|
1629
|
-
protocols: []
|
|
1630
|
-
});
|
|
1631
|
-
return response;
|
|
1826
|
+
let latest;
|
|
1827
|
+
for (const asset of MANAGED_ASSETS) {
|
|
1828
|
+
latest = await this.updateUserProfile({ asset, protocols: [] });
|
|
1829
|
+
}
|
|
1830
|
+
if (!latest) {
|
|
1831
|
+
throw new Error("No supported assets to pause");
|
|
1832
|
+
}
|
|
1833
|
+
return latest;
|
|
1632
1834
|
} catch (error) {
|
|
1633
1835
|
throw new Error(`Failed to pause agent: ${error.message}`);
|
|
1634
1836
|
}
|
|
@@ -1653,46 +1855,22 @@ var _ZyfaiSDK = class _ZyfaiSDK {
|
|
|
1653
1855
|
*/
|
|
1654
1856
|
async resumeAgent() {
|
|
1655
1857
|
try {
|
|
1656
|
-
const userDetailsUSDC = await this.getUserDetails("USDC");
|
|
1657
|
-
const userDetailsETH = await this.getUserDetails("WETH");
|
|
1658
|
-
const userDetailsEURC = await this.getUserDetails("EURC");
|
|
1659
|
-
const chains = userDetailsUSDC.chains && userDetailsUSDC.chains.length > 0 ? userDetailsUSDC.chains : [8453, 42161];
|
|
1660
|
-
const eurcChains = userDetailsEURC.chains && userDetailsEURC.chains.length > 0 ? userDetailsEURC.chains.filter((c) => c === 1 || c === 8453) : [1, 8453];
|
|
1661
1858
|
const allProtocols = await this.httpClient.get(
|
|
1662
1859
|
ENDPOINTS.PROTOCOLS()
|
|
1663
1860
|
);
|
|
1664
|
-
|
|
1665
|
-
const
|
|
1666
|
-
|
|
1667
|
-
|
|
1668
|
-
|
|
1669
|
-
|
|
1670
|
-
|
|
1671
|
-
|
|
1672
|
-
|
|
1673
|
-
|
|
1674
|
-
|
|
1675
|
-
|
|
1676
|
-
|
|
1677
|
-
}
|
|
1678
|
-
return protocol.strategies?.includes("safe_strategy");
|
|
1679
|
-
}).map((protocol) => protocol.id);
|
|
1680
|
-
};
|
|
1681
|
-
const usdcProtocols = filterProtocolsByStrategy(usdcStrategy, chains);
|
|
1682
|
-
const ethProtocols = filterProtocolsByStrategy(ethStrategy, chains);
|
|
1683
|
-
const eurcProtocols = filterProtocolsByStrategy(eurcStrategy, eurcChains);
|
|
1684
|
-
await this.updateUserProfile({
|
|
1685
|
-
asset: "USDC",
|
|
1686
|
-
protocols: usdcProtocols
|
|
1687
|
-
});
|
|
1688
|
-
await this.updateUserProfile({
|
|
1689
|
-
asset: "WETH",
|
|
1690
|
-
protocols: ethProtocols
|
|
1691
|
-
});
|
|
1692
|
-
return await this.updateUserProfile({
|
|
1693
|
-
asset: "EURC",
|
|
1694
|
-
protocols: eurcProtocols
|
|
1695
|
-
});
|
|
1861
|
+
let latest;
|
|
1862
|
+
for (const asset of MANAGED_ASSETS) {
|
|
1863
|
+
latest = await this.updateUserProtocolsForAsset(
|
|
1864
|
+
asset,
|
|
1865
|
+
getAssetChainIds(asset),
|
|
1866
|
+
void 0,
|
|
1867
|
+
allProtocols
|
|
1868
|
+
);
|
|
1869
|
+
}
|
|
1870
|
+
if (!latest) {
|
|
1871
|
+
throw new Error("No supported assets to resume");
|
|
1872
|
+
}
|
|
1873
|
+
return latest;
|
|
1696
1874
|
} catch (error) {
|
|
1697
1875
|
throw new Error(`Failed to resume agent: ${error.message}`);
|
|
1698
1876
|
}
|
|
@@ -1727,7 +1905,9 @@ var _ZyfaiSDK = class _ZyfaiSDK {
|
|
|
1727
1905
|
});
|
|
1728
1906
|
return response;
|
|
1729
1907
|
} catch (error) {
|
|
1730
|
-
throw new Error(
|
|
1908
|
+
throw new Error(
|
|
1909
|
+
`Failed to enable splitting: ${error.message}`
|
|
1910
|
+
);
|
|
1731
1911
|
}
|
|
1732
1912
|
}
|
|
1733
1913
|
/**
|
|
@@ -1755,7 +1935,9 @@ var _ZyfaiSDK = class _ZyfaiSDK {
|
|
|
1755
1935
|
});
|
|
1756
1936
|
return response;
|
|
1757
1937
|
} catch (error) {
|
|
1758
|
-
throw new Error(
|
|
1938
|
+
throw new Error(
|
|
1939
|
+
`Failed to disable splitting: ${error.message}`
|
|
1940
|
+
);
|
|
1759
1941
|
}
|
|
1760
1942
|
}
|
|
1761
1943
|
/**
|
|
@@ -1787,7 +1969,9 @@ var _ZyfaiSDK = class _ZyfaiSDK {
|
|
|
1787
1969
|
});
|
|
1788
1970
|
return response;
|
|
1789
1971
|
} catch (error) {
|
|
1790
|
-
throw new Error(
|
|
1972
|
+
throw new Error(
|
|
1973
|
+
`Failed to update min splits: ${error.message}`
|
|
1974
|
+
);
|
|
1791
1975
|
}
|
|
1792
1976
|
}
|
|
1793
1977
|
/**
|
|
@@ -2085,20 +2269,21 @@ var _ZyfaiSDK = class _ZyfaiSDK {
|
|
|
2085
2269
|
/**
|
|
2086
2270
|
* Deploy Safe Smart Wallet for a user
|
|
2087
2271
|
*
|
|
2088
|
-
* @deprecated Prefer `
|
|
2272
|
+
* @deprecated Prefer `sendDeposit()`. Predeployed Safes and session keys are
|
|
2089
2273
|
* managed automatically on first deposit. This method remains available for
|
|
2090
2274
|
* legacy flows.
|
|
2091
2275
|
*
|
|
2092
2276
|
* @param userAddress - User's EOA address (the connected EOA, not the smart wallet address)
|
|
2093
2277
|
* @param chainId - Target chain ID
|
|
2094
|
-
* @param strategy - Optional strategy selection: "conservative" (default) or "
|
|
2278
|
+
* @param strategy - Optional strategy selection: "conservative" (default), "aggressive" or "yieldmaxxing"
|
|
2095
2279
|
* @param createSessionKey - If true, automatically creates a session key after deployment (default: false)
|
|
2096
2280
|
* @returns Deployment response with Safe address and transaction hash
|
|
2097
2281
|
*
|
|
2098
2282
|
* @example
|
|
2099
2283
|
* ```typescript
|
|
2100
|
-
* // Preferred:
|
|
2101
|
-
* await sdk.
|
|
2284
|
+
* // Preferred: sendDeposit handles predeployed wallet onboarding
|
|
2285
|
+
* const sent = await sdk.sendDeposit(userAddress, 8453, amount, "USDC");
|
|
2286
|
+
* await sdk.waitForDepositCredit(sent.registration.id, 8453);
|
|
2102
2287
|
*
|
|
2103
2288
|
* // Legacy: deploy with default conservative strategy
|
|
2104
2289
|
* await sdk.deploySafe(userAddress, 8453);
|
|
@@ -2216,7 +2401,7 @@ var _ZyfaiSDK = class _ZyfaiSDK {
|
|
|
2216
2401
|
} catch (error) {
|
|
2217
2402
|
console.error("Safe deployment failed:", error);
|
|
2218
2403
|
throw new Error(
|
|
2219
|
-
`Safe deployment failed: ${error.message}. deploySafe() is deprecated \u2014 prefer
|
|
2404
|
+
`Safe deployment failed: ${error.message}. deploySafe() is deprecated \u2014 prefer sendDeposit() for predeployed wallet onboarding.`
|
|
2220
2405
|
);
|
|
2221
2406
|
}
|
|
2222
2407
|
}
|
|
@@ -2224,7 +2409,7 @@ var _ZyfaiSDK = class _ZyfaiSDK {
|
|
|
2224
2409
|
* Create session key with auto-fetched configuration from Zyfai API
|
|
2225
2410
|
* This is the simplified method that automatically fetches session configuration
|
|
2226
2411
|
*
|
|
2227
|
-
* @deprecated Prefer `
|
|
2412
|
+
* @deprecated Prefer `sendDeposit()`. Predeployed wallets already have the
|
|
2228
2413
|
* agent session enabled; session activation is handled after first deposit.
|
|
2229
2414
|
* This method remains available for legacy flows.
|
|
2230
2415
|
*
|
|
@@ -2234,8 +2419,9 @@ var _ZyfaiSDK = class _ZyfaiSDK {
|
|
|
2234
2419
|
*
|
|
2235
2420
|
* @example
|
|
2236
2421
|
* ```typescript
|
|
2237
|
-
* // Preferred:
|
|
2238
|
-
* await sdk.
|
|
2422
|
+
* // Preferred: sendDeposit handles session onboarding for predeployed wallets
|
|
2423
|
+
* const sent = await sdk.sendDeposit(userAddress, 8453, amount, "USDC");
|
|
2424
|
+
* await sdk.waitForDepositCredit(sent.registration.id, 8453);
|
|
2239
2425
|
*
|
|
2240
2426
|
* // Legacy:
|
|
2241
2427
|
* const result = await sdk.createSessionKey(userAddress, 8453);
|
|
@@ -2316,7 +2502,7 @@ var _ZyfaiSDK = class _ZyfaiSDK {
|
|
|
2316
2502
|
};
|
|
2317
2503
|
} catch (error) {
|
|
2318
2504
|
throw new Error(
|
|
2319
|
-
`Failed to create session key: ${error.message}. createSessionKey() is deprecated \u2014 prefer
|
|
2505
|
+
`Failed to create session key: ${error.message}. createSessionKey() is deprecated \u2014 prefer sendDeposit() for predeployed wallet onboarding.`
|
|
2320
2506
|
);
|
|
2321
2507
|
}
|
|
2322
2508
|
}
|
|
@@ -2383,34 +2569,46 @@ var _ZyfaiSDK = class _ZyfaiSDK {
|
|
|
2383
2569
|
* asset/chain/strategy combo.
|
|
2384
2570
|
* 4. Persist via `updateUserProfile` (writes `assetTypeSettings`).
|
|
2385
2571
|
*
|
|
2386
|
-
* Called from `deploySafe` after every path, and from `
|
|
2572
|
+
* Called from `deploySafe` after every path, and from `sendDeposit` on
|
|
2387
2573
|
* the account's first deposit (when USDC chains are still empty).
|
|
2388
2574
|
*
|
|
2389
2575
|
* @internal
|
|
2390
2576
|
*/
|
|
2391
|
-
async updateUserProtocols(strategy) {
|
|
2577
|
+
async updateUserProtocols(strategy, options) {
|
|
2578
|
+
const strict = options?.strict ?? false;
|
|
2579
|
+
const assetErrors = [];
|
|
2392
2580
|
try {
|
|
2393
2581
|
const allProtocols = await this.httpClient.get(
|
|
2394
2582
|
ENDPOINTS.PROTOCOLS()
|
|
2395
2583
|
);
|
|
2396
|
-
const
|
|
2397
|
-
const assets = ["USDC", "WETH", "EURC"];
|
|
2398
|
-
for (const asset of assets) {
|
|
2584
|
+
for (const asset of MANAGED_ASSETS) {
|
|
2399
2585
|
try {
|
|
2400
|
-
const chainsForAsset = asset === "EURC" ? [1, 8453] : allChains;
|
|
2401
2586
|
await this.updateUserProtocolsForAsset(
|
|
2402
2587
|
asset,
|
|
2403
|
-
|
|
2588
|
+
getAssetChainIds(asset),
|
|
2404
2589
|
strategy,
|
|
2405
2590
|
allProtocols
|
|
2406
2591
|
);
|
|
2407
2592
|
} catch (assetError) {
|
|
2408
|
-
|
|
2409
|
-
|
|
2410
|
-
|
|
2593
|
+
const message = assetError.message;
|
|
2594
|
+
if (strict) {
|
|
2595
|
+
assetErrors.push(`${asset}: ${message}`);
|
|
2596
|
+
} else {
|
|
2597
|
+
console.warn(`Failed to update ${asset} protocols: ${message}`);
|
|
2598
|
+
}
|
|
2411
2599
|
}
|
|
2412
2600
|
}
|
|
2601
|
+
if (strict && assetErrors.length > 0) {
|
|
2602
|
+
throw new Error(
|
|
2603
|
+
`Failed to configure user protocols for first deposit: ${assetErrors.join(
|
|
2604
|
+
"; "
|
|
2605
|
+
)}`
|
|
2606
|
+
);
|
|
2607
|
+
}
|
|
2413
2608
|
} catch (error) {
|
|
2609
|
+
if (strict) {
|
|
2610
|
+
throw error;
|
|
2611
|
+
}
|
|
2414
2612
|
console.warn(
|
|
2415
2613
|
`Failed to update user protocols: ${error.message}`
|
|
2416
2614
|
);
|
|
@@ -2437,27 +2635,100 @@ var _ZyfaiSDK = class _ZyfaiSDK {
|
|
|
2437
2635
|
const withPools = await this.filterProtocolIdsWithPools(
|
|
2438
2636
|
matching,
|
|
2439
2637
|
effectiveChains,
|
|
2440
|
-
asset
|
|
2638
|
+
asset,
|
|
2639
|
+
internalStrategy
|
|
2441
2640
|
);
|
|
2442
|
-
await this.updateUserProfile({
|
|
2641
|
+
return await this.updateUserProfile({
|
|
2443
2642
|
asset,
|
|
2444
2643
|
protocols: withPools,
|
|
2445
|
-
chains: effectiveChains
|
|
2644
|
+
chains: effectiveChains,
|
|
2645
|
+
...strategy !== void 0 && { strategy }
|
|
2446
2646
|
});
|
|
2447
2647
|
}
|
|
2648
|
+
/**
|
|
2649
|
+
* Switch one asset to a strategy and select the protocols that go with it.
|
|
2650
|
+
*
|
|
2651
|
+
* `updateUserProfile` stores a strategy but does not compute a protocol
|
|
2652
|
+
* list, so on its own it leaves the asset with nothing to deploy into. This
|
|
2653
|
+
* method does both in one call: it resolves the protocols that support the
|
|
2654
|
+
* asset on the requested chains under the requested strategy, drops those
|
|
2655
|
+
* with no pool available, and persists strategy, chains and protocols
|
|
2656
|
+
* together.
|
|
2657
|
+
*
|
|
2658
|
+
* Mostly needed for assets that are not set up by the account's first
|
|
2659
|
+
* deposit, or to change an existing account's strategy — `sendDeposit`
|
|
2660
|
+
* ignores its `strategy` argument after the first deposit.
|
|
2661
|
+
*
|
|
2662
|
+
* @param params.asset - Asset to configure
|
|
2663
|
+
* @param params.strategy - Strategy to apply; defaults to the one already
|
|
2664
|
+
* stored for this asset (`"conservative"` on a fresh account), which lets
|
|
2665
|
+
* you recompute a protocol list without changing the strategy
|
|
2666
|
+
* @param params.chains - Chains to enable. Defaults to every chain the asset
|
|
2667
|
+
* exists on. **Additive**: chains already enabled are kept, so this cannot
|
|
2668
|
+
* be used to disable one.
|
|
2669
|
+
* @returns The updated profile for that asset
|
|
2670
|
+
*
|
|
2671
|
+
* @example
|
|
2672
|
+
* ```typescript
|
|
2673
|
+
* // NVDAc only lives in async protocols, so it needs "yieldmaxxing".
|
|
2674
|
+
* // Chains default to Base, the only chain it exists on.
|
|
2675
|
+
* const profile = await sdk.setAssetStrategy({
|
|
2676
|
+
* asset: "NVDAc",
|
|
2677
|
+
* strategy: "yieldmaxxing",
|
|
2678
|
+
* });
|
|
2679
|
+
* console.log(profile.protocols); // Ipor + Superform
|
|
2680
|
+
* ```
|
|
2681
|
+
*/
|
|
2682
|
+
async setAssetStrategy(params) {
|
|
2683
|
+
const { asset, strategy, chains } = params;
|
|
2684
|
+
try {
|
|
2685
|
+
if (strategy !== void 0 && !isValidPublicStrategy(strategy)) {
|
|
2686
|
+
throw new Error(
|
|
2687
|
+
`Invalid strategy: ${strategy}. Must be "conservative", "aggressive" or "yieldmaxxing".`
|
|
2688
|
+
);
|
|
2689
|
+
}
|
|
2690
|
+
const supported = getAssetChainIds(asset);
|
|
2691
|
+
if (supported.length === 0) {
|
|
2692
|
+
throw new Error(`Unsupported asset: ${asset}.`);
|
|
2693
|
+
}
|
|
2694
|
+
const targetChains = chains ?? supported;
|
|
2695
|
+
const unsupported = targetChains.filter((c) => !supported.includes(c));
|
|
2696
|
+
if (unsupported.length > 0) {
|
|
2697
|
+
throw new Error(
|
|
2698
|
+
`${asset} is not available on chain ${unsupported.join(
|
|
2699
|
+
", "
|
|
2700
|
+
)}. Supported chains: ${supported.join(", ")}.`
|
|
2701
|
+
);
|
|
2702
|
+
}
|
|
2703
|
+
const allProtocols = await this.httpClient.get(
|
|
2704
|
+
ENDPOINTS.PROTOCOLS()
|
|
2705
|
+
);
|
|
2706
|
+
return await this.updateUserProtocolsForAsset(
|
|
2707
|
+
asset,
|
|
2708
|
+
targetChains,
|
|
2709
|
+
strategy,
|
|
2710
|
+
allProtocols
|
|
2711
|
+
);
|
|
2712
|
+
} catch (error) {
|
|
2713
|
+
throw new Error(
|
|
2714
|
+
`Failed to set ${asset} strategy: ${error.message}`
|
|
2715
|
+
);
|
|
2716
|
+
}
|
|
2717
|
+
}
|
|
2448
2718
|
/**
|
|
2449
2719
|
* Drop protocols that have no pools on any of the selected chains for the
|
|
2450
|
-
* requested asset.
|
|
2451
|
-
*
|
|
2452
|
-
*
|
|
2720
|
+
* requested asset. The /customization/pools endpoint filters server-side on
|
|
2721
|
+
* the strategy, and each tier is a superset of the previous one, so the
|
|
2722
|
+
* caller's strategy must be passed through — asking for `degen_strategy`
|
|
2723
|
+
* returns an empty pool set for async-only assets.
|
|
2453
2724
|
* @internal
|
|
2454
2725
|
*/
|
|
2455
|
-
async filterProtocolIdsWithPools(protocolIds, chains, asset) {
|
|
2726
|
+
async filterProtocolIdsWithPools(protocolIds, chains, asset, internalStrategy = "degen_strategy") {
|
|
2456
2727
|
if (protocolIds.length === 0) return [];
|
|
2457
2728
|
const results = await Promise.allSettled(
|
|
2458
2729
|
protocolIds.map(async (id) => {
|
|
2459
2730
|
const poolsData = await this.httpClient.get(
|
|
2460
|
-
ENDPOINTS.CUSTOMIZATION_POOLS(id,
|
|
2731
|
+
ENDPOINTS.CUSTOMIZATION_POOLS(id, internalStrategy)
|
|
2461
2732
|
);
|
|
2462
2733
|
return { id, hasPool: hasMatchingPool(poolsData, chains, asset) };
|
|
2463
2734
|
})
|
|
@@ -2498,47 +2769,6 @@ var _ZyfaiSDK = class _ZyfaiSDK {
|
|
|
2498
2769
|
return value;
|
|
2499
2770
|
});
|
|
2500
2771
|
}
|
|
2501
|
-
/**
|
|
2502
|
-
* Deposit funds from EOA to Safe smart wallet
|
|
2503
|
-
* Transfers tokens from the connected wallet to the user's Safe and logs the deposit
|
|
2504
|
-
*
|
|
2505
|
-
* Token address is selected from `asset` for the given chain:
|
|
2506
|
-
* - Ethereum Mainnet (1), Base (8453), Arbitrum (42161): USDC or WETH
|
|
2507
|
-
* - Ethereum Mainnet (1), Base (8453): EURC
|
|
2508
|
-
*
|
|
2509
|
-
* On the account's first deposit (USDC profile has no chains yet), patches
|
|
2510
|
-
* protocol selection for USDC, WETH, and EURC across all supported chains
|
|
2511
|
-
* (EURC on Mainnet/Base only) before the transfer and log_deposit.
|
|
2512
|
-
* Pass `strategy` to select protocols for that first-deposit setup
|
|
2513
|
-
* (same role as the former `deploySafe` strategy argument).
|
|
2514
|
-
*
|
|
2515
|
-
* Minimum portfolio balance enforced (Safe balance + deposit amount):
|
|
2516
|
-
* - Stablecoins: `MIN_PORTFOLIO_BALANCE` (Mainnet 10,000 USDC/EURC; Base/Arbitrum 100)
|
|
2517
|
-
* - WETH: about $10,000 on Mainnet, $100 on Base/Arbitrum, from Data API `/price?token=eth`
|
|
2518
|
-
*
|
|
2519
|
-
* @param userAddress - User's address (owner of the Safe)
|
|
2520
|
-
* @param chainId - Target chain ID
|
|
2521
|
-
* @param amount - Amount in least decimal units (e.g., "100000000" for 100 USDC with 6 decimals)
|
|
2522
|
-
* @param asset - Asset symbol: "USDC", "WETH", or "EURC".
|
|
2523
|
-
* EURC is supported on Ethereum Mainnet and Base only.
|
|
2524
|
-
* @param strategy - Optional strategy for first-deposit protocol patching:
|
|
2525
|
-
* "conservative" (default) or "aggressive"
|
|
2526
|
-
* @returns Deposit response with transaction hash
|
|
2527
|
-
*
|
|
2528
|
-
* @example
|
|
2529
|
-
* ```typescript
|
|
2530
|
-
* // Deposit 10,000 USDC (6 decimals) to Safe on Base
|
|
2531
|
-
* const result = await sdk.depositFunds(
|
|
2532
|
-
* "0xUser...",
|
|
2533
|
-
* 8453,
|
|
2534
|
-
* "10000000000",
|
|
2535
|
-
* "USDC"
|
|
2536
|
-
* );
|
|
2537
|
-
*
|
|
2538
|
-
* // First deposit with aggressive strategy
|
|
2539
|
-
* await sdk.depositFunds(userAddress, 8453, "10000000000", "USDC", "aggressive");
|
|
2540
|
-
* ```
|
|
2541
|
-
*/
|
|
2542
2772
|
/**
|
|
2543
2773
|
* Deploy the connected predeployed (pool) wallet on one or more chains.
|
|
2544
2774
|
*
|
|
@@ -2549,7 +2779,7 @@ var _ZyfaiSDK = class _ZyfaiSDK {
|
|
|
2549
2779
|
* resolves once all requested chains have landed on-chain. Idempotent — chains
|
|
2550
2780
|
* already deployed are a no-op.
|
|
2551
2781
|
*
|
|
2552
|
-
* Optional for deposits: `
|
|
2782
|
+
* Optional for deposits: `sendDeposit` no longer pre-deploys the target chain — the ERC20
|
|
2553
2783
|
* transfer lands on the counterfactual address and the backend deploys + hands over on first
|
|
2554
2784
|
* deposit (report-deposit). Use this only to pre-provision chains ahead of time.
|
|
2555
2785
|
*
|
|
@@ -2565,7 +2795,13 @@ var _ZyfaiSDK = class _ZyfaiSDK {
|
|
|
2565
2795
|
await this.authenticateUser();
|
|
2566
2796
|
return this.httpClient.post(ENDPOINTS.DEPLOY_CHAINS, { chainIds });
|
|
2567
2797
|
}
|
|
2568
|
-
|
|
2798
|
+
/**
|
|
2799
|
+
* Send a deposit from an EOA to its Safe smart wallet.
|
|
2800
|
+
*
|
|
2801
|
+
* Confirms the ERC-20 transfer and starts the custody-credit lifecycle. Use
|
|
2802
|
+
* `waitForDepositCredit(result.registration.id, chainId)` to await credit.
|
|
2803
|
+
*/
|
|
2804
|
+
async sendDeposit(userAddress, chainId, amount, asset, strategy) {
|
|
2569
2805
|
try {
|
|
2570
2806
|
if (!userAddress) {
|
|
2571
2807
|
throw new Error("User address is required");
|
|
@@ -2581,37 +2817,54 @@ var _ZyfaiSDK = class _ZyfaiSDK {
|
|
|
2581
2817
|
}
|
|
2582
2818
|
if (strategy !== void 0 && !isValidPublicStrategy(strategy)) {
|
|
2583
2819
|
throw new Error(
|
|
2584
|
-
`Invalid strategy: ${strategy}. Must be "conservative" or "
|
|
2820
|
+
`Invalid strategy: ${strategy}. Must be "conservative", "aggressive" or "yieldmaxxing".`
|
|
2585
2821
|
);
|
|
2586
2822
|
}
|
|
2587
|
-
const assetSymbol = asset
|
|
2823
|
+
const assetSymbol = resolveAssetSymbol(asset);
|
|
2588
2824
|
const assetConfig = ASSET_CONFIGS[assetSymbol];
|
|
2589
|
-
|
|
2825
|
+
const assetChains = getAssetChainIds(assetSymbol);
|
|
2826
|
+
if (!assetChains.includes(chainId)) {
|
|
2590
2827
|
throw new Error(
|
|
2591
|
-
|
|
2592
|
-
|
|
2593
|
-
|
|
2594
|
-
let minRequired = MIN_PORTFOLIO_BALANCE[chainId]?.[assetSymbol];
|
|
2595
|
-
if (assetSymbol === "WETH") {
|
|
2596
|
-
const priceResponse = await this.httpClient.dataGet(
|
|
2597
|
-
DATA_ENDPOINTS.TOKEN_PRICE("eth")
|
|
2598
|
-
);
|
|
2599
|
-
minRequired = minWethWeiForUsd(
|
|
2600
|
-
parseEthUsdPrice(priceResponse),
|
|
2601
|
-
MIN_WETH_USD[chainId]
|
|
2828
|
+
`${assetSymbol} is not available on chain ${chainId}. Supported chains: ${assetChains.join(
|
|
2829
|
+
", "
|
|
2830
|
+
)}.`
|
|
2602
2831
|
);
|
|
2603
2832
|
}
|
|
2833
|
+
let minRequired = this.bypassMinPortfolio ? void 0 : MIN_PORTFOLIO_BALANCE[chainId]?.[assetSymbol];
|
|
2834
|
+
const minUsd = this.bypassMinPortfolio ? void 0 : MIN_PORTFOLIO_USD[chainId]?.[assetSymbol];
|
|
2604
2835
|
const token = getDefaultTokenAddress(chainId, assetSymbol);
|
|
2605
2836
|
const walletClient = this.getWalletClient();
|
|
2606
2837
|
const chainConfig = getChainConfig(chainId, this.rpcUrls);
|
|
2838
|
+
if (minUsd !== void 0) {
|
|
2839
|
+
const [, priceResponse] = await Promise.all([
|
|
2840
|
+
this.authenticateUser(),
|
|
2841
|
+
this.httpClient.dataGet(
|
|
2842
|
+
DATA_ENDPOINTS.TOKEN_PRICE(assetConfig.priceTokenSymbol)
|
|
2843
|
+
)
|
|
2844
|
+
]);
|
|
2845
|
+
minRequired = usdToTokenUnits(
|
|
2846
|
+
minUsd,
|
|
2847
|
+
parseTokenUsdPrice(priceResponse),
|
|
2848
|
+
assetConfig.decimals
|
|
2849
|
+
);
|
|
2850
|
+
} else {
|
|
2851
|
+
await this.authenticateUser();
|
|
2852
|
+
}
|
|
2607
2853
|
const safeAddress = await this.getSafeAddressFor(userAddress, chainId);
|
|
2608
2854
|
if (!safeAddress) {
|
|
2609
2855
|
throw new Error("Smart wallet address is not available");
|
|
2610
2856
|
}
|
|
2611
|
-
const
|
|
2612
|
-
|
|
2613
|
-
chainConfig.publicClient
|
|
2614
|
-
|
|
2857
|
+
const amountBigInt = BigInt(amount);
|
|
2858
|
+
const [isDeployed, currentSafeBalance] = await Promise.all([
|
|
2859
|
+
isSafeDeployed(safeAddress, chainConfig.publicClient),
|
|
2860
|
+
minRequired !== void 0 ? chainConfig.publicClient.readContract({
|
|
2861
|
+
address: token,
|
|
2862
|
+
abi: ERC20_ABI,
|
|
2863
|
+
functionName: "balanceOf",
|
|
2864
|
+
args: [safeAddress]
|
|
2865
|
+
}) : Promise.resolve(void 0),
|
|
2866
|
+
this.prepareFirstDeposit(strategy)
|
|
2867
|
+
]).then(([deployed, balance]) => [deployed, balance]);
|
|
2615
2868
|
if (!isDeployed) {
|
|
2616
2869
|
if (!(this.isPredeployed && this.isConnectedUser(userAddress))) {
|
|
2617
2870
|
throw new Error(
|
|
@@ -2619,26 +2872,9 @@ var _ZyfaiSDK = class _ZyfaiSDK {
|
|
|
2619
2872
|
);
|
|
2620
2873
|
}
|
|
2621
2874
|
}
|
|
2622
|
-
try {
|
|
2623
|
-
const usdcDetails = await this.getUserDetails("USDC");
|
|
2624
|
-
if ((usdcDetails.chains?.length ?? 0) === 0) {
|
|
2625
|
-
await this.updateUserProtocols(strategy);
|
|
2626
|
-
}
|
|
2627
|
-
} catch (protocolError) {
|
|
2628
|
-
console.warn(
|
|
2629
|
-
"Failed to update user protocols before deposit:",
|
|
2630
|
-
protocolError.message
|
|
2631
|
-
);
|
|
2632
|
-
}
|
|
2633
|
-
const amountBigInt = BigInt(amount);
|
|
2634
2875
|
if (minRequired !== void 0) {
|
|
2635
|
-
const
|
|
2636
|
-
|
|
2637
|
-
abi: ERC20_ABI,
|
|
2638
|
-
functionName: "balanceOf",
|
|
2639
|
-
args: [safeAddress]
|
|
2640
|
-
});
|
|
2641
|
-
const totalAfterDeposit = currentSafeBalance + amountBigInt;
|
|
2876
|
+
const safeBalance = currentSafeBalance;
|
|
2877
|
+
const totalAfterDeposit = safeBalance + amountBigInt;
|
|
2642
2878
|
if (totalAfterDeposit < minRequired) {
|
|
2643
2879
|
const minLabel = formatMinPortfolioLabel(
|
|
2644
2880
|
minRequired,
|
|
@@ -2646,7 +2882,7 @@ var _ZyfaiSDK = class _ZyfaiSDK {
|
|
|
2646
2882
|
assetSymbol
|
|
2647
2883
|
);
|
|
2648
2884
|
throw new Error(
|
|
2649
|
-
`Minimum portfolio balance not met on chain ${chainId}. Total portfolio must be at least ${minLabel}. Current Safe balance: ${
|
|
2885
|
+
`Minimum portfolio balance not met on chain ${chainId}. Total portfolio must be at least ${minLabel}. Current Safe balance: ${safeBalance.toString()}, deposit amount: ${amountBigInt.toString()}, total after deposit: ${totalAfterDeposit.toString()} (raw units, ${assetConfig.decimals} decimals).`
|
|
2650
2886
|
);
|
|
2651
2887
|
}
|
|
2652
2888
|
}
|
|
@@ -2661,38 +2897,220 @@ var _ZyfaiSDK = class _ZyfaiSDK {
|
|
|
2661
2897
|
const receipt = await chainConfig.publicClient.waitForTransactionReceipt({
|
|
2662
2898
|
hash: txHash
|
|
2663
2899
|
});
|
|
2664
|
-
try {
|
|
2665
|
-
await this.httpClient.post(ENDPOINTS.LOG_DEPOSIT, {
|
|
2666
|
-
chainId,
|
|
2667
|
-
transaction: txHash,
|
|
2668
|
-
token,
|
|
2669
|
-
amount
|
|
2670
|
-
});
|
|
2671
|
-
} catch (logError) {
|
|
2672
|
-
console.warn("Failed to log deposit:", logError.message);
|
|
2673
|
-
}
|
|
2674
2900
|
if (receipt.status !== "success") {
|
|
2675
2901
|
throw new Error("Deposit transaction failed");
|
|
2676
2902
|
}
|
|
2903
|
+
const registration = await this.registerDeposit(
|
|
2904
|
+
chainId,
|
|
2905
|
+
txHash,
|
|
2906
|
+
amount,
|
|
2907
|
+
token
|
|
2908
|
+
);
|
|
2677
2909
|
return {
|
|
2678
2910
|
success: true,
|
|
2679
2911
|
txHash,
|
|
2680
2912
|
smartWallet: safeAddress,
|
|
2681
|
-
amount: amountBigInt.toString()
|
|
2913
|
+
amount: amountBigInt.toString(),
|
|
2914
|
+
registration
|
|
2682
2915
|
};
|
|
2683
2916
|
} catch (error) {
|
|
2684
2917
|
throw new Error(`Deposit failed: ${error.message}`);
|
|
2685
2918
|
}
|
|
2686
2919
|
}
|
|
2920
|
+
/**
|
|
2921
|
+
* @deprecated Compatibility convenience method. Prefer `sendDeposit()` followed by
|
|
2922
|
+
* `waitForDepositCredit()` when the caller owns the completion UX.
|
|
2923
|
+
*/
|
|
2924
|
+
async depositFunds(userAddress, chainId, amount, asset, strategy) {
|
|
2925
|
+
this.warnDeprecatedOnboardingMethod("depositFunds");
|
|
2926
|
+
const sent = await this.sendDeposit(
|
|
2927
|
+
userAddress,
|
|
2928
|
+
chainId,
|
|
2929
|
+
amount,
|
|
2930
|
+
asset,
|
|
2931
|
+
strategy
|
|
2932
|
+
);
|
|
2933
|
+
return {
|
|
2934
|
+
...sent,
|
|
2935
|
+
registration: await this.waitForDepositCredit(
|
|
2936
|
+
sent.registration.id,
|
|
2937
|
+
chainId
|
|
2938
|
+
)
|
|
2939
|
+
};
|
|
2940
|
+
}
|
|
2941
|
+
/**
|
|
2942
|
+
* Prepare ERC-20 transfer calldata for builders using a custom signer,
|
|
2943
|
+
* sponsored transaction provider, or mobile wallet. Most custom-wallet
|
|
2944
|
+
* integrations can compose this with `ensureFirstDepositSetup()` and
|
|
2945
|
+
* `logDeposit()` instead.
|
|
2946
|
+
*/
|
|
2947
|
+
async buildDepositTransfer(params) {
|
|
2948
|
+
const { userAddress, chainId, amount, asset } = params;
|
|
2949
|
+
if (!userAddress || !amount || BigInt(amount) <= 0n) {
|
|
2950
|
+
throw new Error("A user address and positive amount are required");
|
|
2951
|
+
}
|
|
2952
|
+
if (!isSupportedChain(chainId)) {
|
|
2953
|
+
throw new Error(`Unsupported chain ID: ${chainId}`);
|
|
2954
|
+
}
|
|
2955
|
+
const assetSymbol = resolveAssetSymbol(asset);
|
|
2956
|
+
const assetChains = getAssetChainIds(assetSymbol);
|
|
2957
|
+
if (!assetChains.includes(chainId)) {
|
|
2958
|
+
throw new Error(
|
|
2959
|
+
`${assetSymbol} is not available on chain ${chainId}. Supported chains: ${assetChains.join(
|
|
2960
|
+
", "
|
|
2961
|
+
)}.`
|
|
2962
|
+
);
|
|
2963
|
+
}
|
|
2964
|
+
const safeAddress = await this.getSafeAddressFor(userAddress, chainId);
|
|
2965
|
+
if (!safeAddress) {
|
|
2966
|
+
throw new Error("Smart wallet address is not available");
|
|
2967
|
+
}
|
|
2968
|
+
const chainConfig = getChainConfig(chainId, this.rpcUrls);
|
|
2969
|
+
const isDeployed = await isSafeDeployed(
|
|
2970
|
+
safeAddress,
|
|
2971
|
+
chainConfig.publicClient
|
|
2972
|
+
);
|
|
2973
|
+
if (!(isDeployed || this.isPredeployed && this.isConnectedUser(userAddress))) {
|
|
2974
|
+
throw new Error(
|
|
2975
|
+
`Safe not available for ${userAddress} on chain ${chainId}.`
|
|
2976
|
+
);
|
|
2977
|
+
}
|
|
2978
|
+
const amountBigInt = BigInt(amount);
|
|
2979
|
+
await this.enforceMinimumPortfolioBalance(
|
|
2980
|
+
chainId,
|
|
2981
|
+
asset,
|
|
2982
|
+
amountBigInt,
|
|
2983
|
+
safeAddress
|
|
2984
|
+
);
|
|
2985
|
+
const tokenAddress = getDefaultTokenAddress(
|
|
2986
|
+
chainId,
|
|
2987
|
+
assetSymbol
|
|
2988
|
+
);
|
|
2989
|
+
return {
|
|
2990
|
+
safeAddress,
|
|
2991
|
+
tokenAddress,
|
|
2992
|
+
to: tokenAddress,
|
|
2993
|
+
data: (0, import_viem4.encodeFunctionData)({
|
|
2994
|
+
abi: ERC20_ABI,
|
|
2995
|
+
functionName: "transfer",
|
|
2996
|
+
args: [safeAddress, amountBigInt]
|
|
2997
|
+
}),
|
|
2998
|
+
value: "0"
|
|
2999
|
+
};
|
|
3000
|
+
}
|
|
3001
|
+
/** Apply the same per-asset minimum portfolio rule as sendDeposit. */
|
|
3002
|
+
async enforceMinimumPortfolioBalance(chainId, asset, amount, safeAddress) {
|
|
3003
|
+
if (this.bypassMinPortfolio) {
|
|
3004
|
+
return;
|
|
3005
|
+
}
|
|
3006
|
+
const assetSymbol = resolveAssetSymbol(asset);
|
|
3007
|
+
const assetConfig = ASSET_CONFIGS[assetSymbol];
|
|
3008
|
+
let minRequired = MIN_PORTFOLIO_BALANCE[chainId]?.[assetSymbol];
|
|
3009
|
+
const minUsd = MIN_PORTFOLIO_USD[chainId]?.[assetSymbol];
|
|
3010
|
+
if (minUsd !== void 0) {
|
|
3011
|
+
const [, priceResponse] = await Promise.all([
|
|
3012
|
+
this.authenticateUser(),
|
|
3013
|
+
this.httpClient.dataGet(
|
|
3014
|
+
DATA_ENDPOINTS.TOKEN_PRICE(assetConfig.priceTokenSymbol)
|
|
3015
|
+
)
|
|
3016
|
+
]);
|
|
3017
|
+
minRequired = usdToTokenUnits(
|
|
3018
|
+
minUsd,
|
|
3019
|
+
parseTokenUsdPrice(priceResponse),
|
|
3020
|
+
assetConfig.decimals
|
|
3021
|
+
);
|
|
3022
|
+
}
|
|
3023
|
+
if (minRequired === void 0) return;
|
|
3024
|
+
const chainConfig = getChainConfig(chainId, this.rpcUrls);
|
|
3025
|
+
const token = getDefaultTokenAddress(chainId, assetSymbol);
|
|
3026
|
+
const currentSafeBalance = await chainConfig.publicClient.readContract({
|
|
3027
|
+
address: token,
|
|
3028
|
+
abi: ERC20_ABI,
|
|
3029
|
+
functionName: "balanceOf",
|
|
3030
|
+
args: [safeAddress]
|
|
3031
|
+
});
|
|
3032
|
+
const totalAfterDeposit = currentSafeBalance + amount;
|
|
3033
|
+
if (totalAfterDeposit < minRequired) {
|
|
3034
|
+
const minLabel = formatMinPortfolioLabel(
|
|
3035
|
+
minRequired,
|
|
3036
|
+
assetConfig.decimals,
|
|
3037
|
+
assetSymbol
|
|
3038
|
+
);
|
|
3039
|
+
throw new Error(
|
|
3040
|
+
`Minimum portfolio balance not met on chain ${chainId}. Total portfolio must be at least ${minLabel}. Current Safe balance: ${currentSafeBalance.toString()}, deposit amount: ${amount.toString()}, total after deposit: ${totalAfterDeposit.toString()} (raw units, ${assetConfig.decimals} decimals).`
|
|
3041
|
+
);
|
|
3042
|
+
}
|
|
3043
|
+
}
|
|
3044
|
+
/**
|
|
3045
|
+
* Idempotently apply the first-deposit profile configuration for builders
|
|
3046
|
+
* composing an advanced custom transfer flow. Most custom-wallet
|
|
3047
|
+
* integrations can use this with `buildDepositTransfer()` and `logDeposit()`.
|
|
3048
|
+
*
|
|
3049
|
+
* When setup runs (`applied: true`), protocol configuration is persisted
|
|
3050
|
+
* before returning. Failures throw so callers can abort before submitting a
|
|
3051
|
+
* transfer. High-level deposit methods still treat setup as best-effort.
|
|
3052
|
+
*/
|
|
3053
|
+
async ensureFirstDepositSetup(strategy) {
|
|
3054
|
+
if (strategy !== void 0 && !isValidPublicStrategy(strategy)) {
|
|
3055
|
+
throw new Error(
|
|
3056
|
+
`Invalid strategy: ${strategy}. Must be "conservative", "aggressive" or "yieldmaxxing".`
|
|
3057
|
+
);
|
|
3058
|
+
}
|
|
3059
|
+
await this.authenticateUser();
|
|
3060
|
+
const usdcDetails = await this.getUserDetails("USDC");
|
|
3061
|
+
if ((usdcDetails.chains?.length ?? 0) > 0) {
|
|
3062
|
+
return { applied: false };
|
|
3063
|
+
}
|
|
3064
|
+
await this.updateUserProtocols(strategy, { strict: true });
|
|
3065
|
+
const usdcAfterSetup = await this.getUserDetails("USDC");
|
|
3066
|
+
if ((usdcAfterSetup.chains?.length ?? 0) === 0) {
|
|
3067
|
+
throw new Error(
|
|
3068
|
+
"First-deposit setup did not persist USDC chain configuration."
|
|
3069
|
+
);
|
|
3070
|
+
}
|
|
3071
|
+
return { applied: true };
|
|
3072
|
+
}
|
|
3073
|
+
/** Best-effort first-deposit setup shared by both high-level deposit flows. */
|
|
3074
|
+
async prepareFirstDeposit(strategy) {
|
|
3075
|
+
try {
|
|
3076
|
+
await this.ensureFirstDepositSetup(strategy);
|
|
3077
|
+
} catch (protocolError) {
|
|
3078
|
+
console.warn(
|
|
3079
|
+
"Failed to update user protocols before deposit:",
|
|
3080
|
+
protocolError.message
|
|
3081
|
+
);
|
|
3082
|
+
}
|
|
3083
|
+
}
|
|
3084
|
+
/** Shared post-transfer registration path for every deposit flow. */
|
|
3085
|
+
async registerDeposit(chainId, txHash, amount, tokenAddress) {
|
|
3086
|
+
let registration;
|
|
3087
|
+
try {
|
|
3088
|
+
registration = await this.logDeposit(
|
|
3089
|
+
chainId,
|
|
3090
|
+
txHash,
|
|
3091
|
+
amount,
|
|
3092
|
+
tokenAddress
|
|
3093
|
+
);
|
|
3094
|
+
} catch (logError) {
|
|
3095
|
+
throw new Error(
|
|
3096
|
+
`On-chain deposit succeeded (tx=${txHash}) but backend registration failed: ${logError.message}. Call connectAccount() then logDeposit(${chainId}, "${txHash}", "${amount}") to retry.`
|
|
3097
|
+
);
|
|
3098
|
+
}
|
|
3099
|
+
return registration.deposit;
|
|
3100
|
+
}
|
|
2687
3101
|
/**
|
|
2688
3102
|
* Log a deposit that was executed client-side.
|
|
2689
3103
|
*
|
|
2690
|
-
* `
|
|
3104
|
+
* `sendDeposit()` already calls this after the ERC20 transfer. If you send the
|
|
2691
3105
|
* transfer yourself (front, Privy, Biconomy, custom wallet) you **must** call
|
|
2692
3106
|
* `logDeposit` — otherwise the backend never sees the deposit: a reserved pool
|
|
2693
3107
|
* wallet stays reserved (no ownership rotation), and yield/agent tracking does
|
|
2694
3108
|
* not start.
|
|
2695
3109
|
*
|
|
3110
|
+
* Requires `connectAccount()` on the same SDK instance first (SIWE user JWT).
|
|
3111
|
+
* The SDK API key alone is not enough — `log_deposit` returns 401 without a
|
|
3112
|
+
* Bearer token.
|
|
3113
|
+
*
|
|
2696
3114
|
* Use this method when you execute the deposit transaction yourself and need to
|
|
2697
3115
|
* register it with the Zyfai backend.
|
|
2698
3116
|
*
|
|
@@ -2739,26 +3157,110 @@ var _ZyfaiSDK = class _ZyfaiSDK {
|
|
|
2739
3157
|
throw new Error("Valid amount is required");
|
|
2740
3158
|
}
|
|
2741
3159
|
const token = tokenAddress || getDefaultTokenAddress(chainId);
|
|
2742
|
-
await this.
|
|
2743
|
-
|
|
2744
|
-
|
|
2745
|
-
|
|
2746
|
-
|
|
2747
|
-
|
|
3160
|
+
await this.authenticateUser();
|
|
3161
|
+
const deposit = await this.httpClient.post(
|
|
3162
|
+
ENDPOINTS.LOG_DEPOSIT,
|
|
3163
|
+
{
|
|
3164
|
+
chainId,
|
|
3165
|
+
transaction: txHash,
|
|
3166
|
+
token,
|
|
3167
|
+
amount
|
|
3168
|
+
}
|
|
3169
|
+
);
|
|
2748
3170
|
return {
|
|
2749
3171
|
success: true,
|
|
2750
|
-
message: "Deposit
|
|
3172
|
+
message: deposit.status === "credited" ? "Deposit credited successfully" : "Deposit accepted; custody handover is pending",
|
|
3173
|
+
deposit
|
|
2751
3174
|
};
|
|
2752
3175
|
} catch (error) {
|
|
2753
3176
|
throw new Error(`Log deposit failed: ${error.message}`);
|
|
2754
3177
|
}
|
|
2755
3178
|
}
|
|
3179
|
+
/**
|
|
3180
|
+
* Fetch the custody handover and balance-credit lifecycle for a registered
|
|
3181
|
+
* deposit. A status of `credited` is required before funds are investable.
|
|
3182
|
+
*/
|
|
3183
|
+
async getDepositStatus(depositId) {
|
|
3184
|
+
if (!depositId) {
|
|
3185
|
+
throw new Error("Deposit ID is required");
|
|
3186
|
+
}
|
|
3187
|
+
await this.authenticateUser();
|
|
3188
|
+
return this.httpClient.get(
|
|
3189
|
+
ENDPOINTS.DEPOSIT_STATUS(depositId)
|
|
3190
|
+
);
|
|
3191
|
+
}
|
|
3192
|
+
/**
|
|
3193
|
+
* Await deposit credit after `logDeposit` returns `handover_pending`.
|
|
3194
|
+
*
|
|
3195
|
+
* Polls `getDepositStatus` until `status === "credited"` and
|
|
3196
|
+
* `balanceCredited === true`. Rejects on recovery, timeout, or poll errors.
|
|
3197
|
+
*
|
|
3198
|
+
* Poll interval and timeout are chain-specific. Mainnet defaults to a 2s
|
|
3199
|
+
* interval and 1 minute ceiling; Base/Arbitrum use tighter polling (~500ms /
|
|
3200
|
+
* ~250ms) with a ~20 second completion window. Override `timeoutMs` when a
|
|
3201
|
+
* caller intentionally wants to wait longer than the normal UX window.
|
|
3202
|
+
*
|
|
3203
|
+
* Requires `connectAccount()` on the same SDK instance first.
|
|
3204
|
+
*/
|
|
3205
|
+
async waitForDepositCredit(depositId, chainId, options) {
|
|
3206
|
+
if (!depositId) {
|
|
3207
|
+
throw new Error("Deposit ID is required");
|
|
3208
|
+
}
|
|
3209
|
+
if (!isSupportedChain(chainId)) {
|
|
3210
|
+
throw new Error(`Unsupported chain ID: ${chainId}`);
|
|
3211
|
+
}
|
|
3212
|
+
const intervalMs = options?.intervalMs ?? getDepositCreditIntervalMs(chainId);
|
|
3213
|
+
const timeoutMs = options?.timeoutMs ?? getDepositCreditTimeoutMs(chainId);
|
|
3214
|
+
const started = Date.now();
|
|
3215
|
+
while (Date.now() - started < timeoutMs) {
|
|
3216
|
+
const status = await this.getDepositStatus(depositId);
|
|
3217
|
+
if (status.status === "credited" && status.balanceCredited) {
|
|
3218
|
+
return status;
|
|
3219
|
+
}
|
|
3220
|
+
if (status.status === "recovered_to_eoa") {
|
|
3221
|
+
throw new Error(
|
|
3222
|
+
`Deposit ${depositId} recovered to EOA (status=${status.status}); balance was not credited`
|
|
3223
|
+
);
|
|
3224
|
+
}
|
|
3225
|
+
if (Date.now() - started >= timeoutMs) {
|
|
3226
|
+
break;
|
|
3227
|
+
}
|
|
3228
|
+
await sleep(intervalMs);
|
|
3229
|
+
}
|
|
3230
|
+
throw new DepositCreditTimeoutError(depositId);
|
|
3231
|
+
}
|
|
2756
3232
|
/**
|
|
2757
3233
|
* Withdraw funds from Safe smart wallet
|
|
2758
3234
|
* Initiates a withdrawal request to the Zyfai API
|
|
2759
3235
|
* Note: The withdrawal is processed asynchronously, so txHash may not be immediately available
|
|
2760
3236
|
* Funds are always withdrawn to the Safe owner's address (userAddress)
|
|
2761
3237
|
*
|
|
3238
|
+
* **Delayed withdrawals.** Positions held under the `"yieldmaxxing"`
|
|
3239
|
+
* strategy sit in protocols that cannot be exited on demand. For those the
|
|
3240
|
+
* backend transfers the immediately available portion, then queues a
|
|
3241
|
+
* redemption for the rest and forwards the funds to the EOA once the
|
|
3242
|
+
* protocol releases them — about a day on Ipor, three on Superform. No
|
|
3243
|
+
* further call is needed, but the returned `txHash` only covers the
|
|
3244
|
+
* immediate portion. Track the remainder through
|
|
3245
|
+
* `getPortfolio().portfolio.pendingAsyncWithdrawals`, whose entries carry a
|
|
3246
|
+
* `status` and an `estimatedClaimAt`.
|
|
3247
|
+
*
|
|
3248
|
+
* When every source is an async pool nothing settles on-chain at that point,
|
|
3249
|
+
* so `txHash` is `undefined` on a successful call.
|
|
3250
|
+
*
|
|
3251
|
+
* **One redemption per pool at a time.** While an entry for a pool is
|
|
3252
|
+
* `REQUESTED` or `CLAIMABLE`, the backend drops a further withdrawal aimed at
|
|
3253
|
+
* that same pool — the protocols behind it (ERC-7540) hold a single request
|
|
3254
|
+
* slot per user. This method throws rather than reporting that no-op as a
|
|
3255
|
+
* success. It only throws when nothing the call could reach is withdrawable:
|
|
3256
|
+
* another pool, another asset or an idle Safe balance still goes through.
|
|
3257
|
+
*
|
|
3258
|
+
* Once requested, that amount can no longer be withdrawn: it is gone from
|
|
3259
|
+
* both the position snapshot and the Safe balance, so a second call silently
|
|
3260
|
+
* returns only what is left. Validate user-entered amounts against
|
|
3261
|
+
* `portfolioByAssetType`, not against the total that includes in-flight
|
|
3262
|
+
* funds — see `getPortfolio`.
|
|
3263
|
+
*
|
|
2762
3264
|
* @param userAddress - User's address (owner of the Safe)
|
|
2763
3265
|
* @param chainId - Target chain ID
|
|
2764
3266
|
* @param amount - Optional: Amount in least decimal units to withdraw (partial withdrawal). If not specified, withdraws all funds
|
|
@@ -2801,6 +3303,11 @@ var _ZyfaiSDK = class _ZyfaiSDK {
|
|
|
2801
3303
|
);
|
|
2802
3304
|
}
|
|
2803
3305
|
await this.authenticateUser();
|
|
3306
|
+
await this.assertAsyncRedemptionSlotFree(
|
|
3307
|
+
userAddress,
|
|
3308
|
+
chainId,
|
|
3309
|
+
tokenSymbol
|
|
3310
|
+
);
|
|
2804
3311
|
let response = {};
|
|
2805
3312
|
if (amount) {
|
|
2806
3313
|
response = await this.httpClient.post(ENDPOINTS.PARTIAL_WITHDRAW, {
|
|
@@ -2828,6 +3335,31 @@ var _ZyfaiSDK = class _ZyfaiSDK {
|
|
|
2828
3335
|
throw new Error(`Withdrawal failed: ${error.message}`);
|
|
2829
3336
|
}
|
|
2830
3337
|
}
|
|
3338
|
+
/**
|
|
3339
|
+
* Turn a withdrawal the backend would silently drop — one aimed only at
|
|
3340
|
+
* async pools that already hold an in-flight redemption — into an error, so
|
|
3341
|
+
* the caller gets an answer rather than a `success: true` no-op.
|
|
3342
|
+
*
|
|
3343
|
+
* @internal
|
|
3344
|
+
*/
|
|
3345
|
+
async assertAsyncRedemptionSlotFree(userAddress, chainId, tokenSymbol) {
|
|
3346
|
+
let portfolio;
|
|
3347
|
+
try {
|
|
3348
|
+
({ portfolio } = await this.getPortfolio(userAddress));
|
|
3349
|
+
} catch {
|
|
3350
|
+
return;
|
|
3351
|
+
}
|
|
3352
|
+
const blocking = findBlockingAsyncRedemption(
|
|
3353
|
+
portfolio,
|
|
3354
|
+
chainId,
|
|
3355
|
+
tokenSymbol
|
|
3356
|
+
);
|
|
3357
|
+
if (!blocking) return;
|
|
3358
|
+
const eta = blocking.estimatedClaimAt ? ` Estimated settlement: ${blocking.estimatedClaimAt}.` : "";
|
|
3359
|
+
throw new Error(
|
|
3360
|
+
`A redemption is already in flight for ${blocking.token?.symbol ?? "this asset"} on ${blocking.pool ?? "the pool"} (status ${blocking.status}), and async pools allow only one at a time. Wait for it to reach CLAIMED before withdrawing the rest.${eta}`
|
|
3361
|
+
);
|
|
3362
|
+
}
|
|
2831
3363
|
/**
|
|
2832
3364
|
* Get available DeFi protocols and pools for a specific chain
|
|
2833
3365
|
*
|
|
@@ -2923,6 +3455,29 @@ var _ZyfaiSDK = class _ZyfaiSDK {
|
|
|
2923
3455
|
* Note: portfolio balances are live; earnings used for the fee may be from
|
|
2924
3456
|
* a snapshot, so net values can differ slightly from a fully live calc.
|
|
2925
3457
|
*
|
|
3458
|
+
* **Total balance.** `portfolioByAssetType` sums deployed positions and idle
|
|
3459
|
+
* Safe balances, and nothing else. Under the `"yieldmaxxing"` strategy a
|
|
3460
|
+
* redemption in flight has already left its position and has not landed in
|
|
3461
|
+
* the Safe yet, so its funds appear in no balance field at all. That makes
|
|
3462
|
+
* two distinct numbers:
|
|
3463
|
+
*
|
|
3464
|
+
* ```
|
|
3465
|
+
* total = portfolioByAssetType[assetType].balance
|
|
3466
|
+
* + sum(pendingAsyncWithdrawals where REQUESTED or CLAIMABLE)
|
|
3467
|
+
*
|
|
3468
|
+
* requestable = portfolioByAssetType[assetType].balance
|
|
3469
|
+
* ```
|
|
3470
|
+
*
|
|
3471
|
+
* An in-flight amount is no longer withdrawable: `withdrawFunds` only reaches
|
|
3472
|
+
* the current positions and idle balances, so calling it again neither speeds
|
|
3473
|
+
* those funds up nor errors. They reach the EOA on their own. Cap any
|
|
3474
|
+
* user-entered withdrawal amount at `requestable`, never at `total`.
|
|
3475
|
+
*
|
|
3476
|
+
* Do not add `staleBalances` on top — those are the same idle balances
|
|
3477
|
+
* `portfolioByAssetType` already counts, exposed as a per-chain view.
|
|
3478
|
+
* Do not add `CLAIMED` withdrawals either (the array keeps them for 24
|
|
3479
|
+
* hours); their funds are back in the Safe and already counted.
|
|
3480
|
+
*
|
|
2926
3481
|
* @param userAddress - User's EOA address
|
|
2927
3482
|
* @returns Portfolio with optional fee-adjusted balance fields
|
|
2928
3483
|
*
|
|
@@ -2930,6 +3485,11 @@ var _ZyfaiSDK = class _ZyfaiSDK {
|
|
|
2930
3485
|
* ```typescript
|
|
2931
3486
|
* const { portfolio } = await sdk.getPortfolio(userAddress);
|
|
2932
3487
|
* console.log(portfolio.portfolioByAssetType?.usdc?.balanceWithFee);
|
|
3488
|
+
*
|
|
3489
|
+
* // Funds still locked in an async redemption
|
|
3490
|
+
* const inFlight = (portfolio.pendingAsyncWithdrawals ?? []).filter(
|
|
3491
|
+
* (w) => w.status === "REQUESTED" || w.status === "CLAIMABLE"
|
|
3492
|
+
* );
|
|
2933
3493
|
* ```
|
|
2934
3494
|
*/
|
|
2935
3495
|
async getPortfolio(userAddress) {
|
|
@@ -3003,7 +3563,11 @@ var _ZyfaiSDK = class _ZyfaiSDK {
|
|
|
3003
3563
|
omniAccount: convertedResponse.omniAccount,
|
|
3004
3564
|
asset,
|
|
3005
3565
|
autoSelectProtocols: convertedResponse.assetTypeSettings?.[internalAsset]?.autoSelectProtocols,
|
|
3006
|
-
strategy
|
|
3566
|
+
// `convertStrategyToPublic` only touches the root `strategy` field;
|
|
3567
|
+
// the per-asset one is nested and has to be converted here.
|
|
3568
|
+
strategy: toPublicStrategyOrUndefined(
|
|
3569
|
+
convertedResponse.assetTypeSettings?.[internalAsset]?.rebalanceStrategy
|
|
3570
|
+
),
|
|
3007
3571
|
autocompounding: convertedResponse.assetTypeSettings?.[internalAsset]?.autocompounding,
|
|
3008
3572
|
crosschainStrategy: convertedResponse.assetTypeSettings?.[internalAsset]?.crosschainStrategy,
|
|
3009
3573
|
splitting: convertedResponse.assetTypeSettings?.[internalAsset]?.splitting,
|
|
@@ -3050,7 +3614,7 @@ var _ZyfaiSDK = class _ZyfaiSDK {
|
|
|
3050
3614
|
*
|
|
3051
3615
|
* @param crossChain - Whether to get cross-chain APY (true = omni account, false = simple account)
|
|
3052
3616
|
* @param days - Time period: 7, 14, or 30
|
|
3053
|
-
* @param strategy - Strategy type: "conservative" (default) or "
|
|
3617
|
+
* @param strategy - Strategy type: "conservative" (default), "aggressive" or "yieldmaxxing"
|
|
3054
3618
|
* @param chainId - Optional chain ID filter
|
|
3055
3619
|
* @param tokenSymbol - Optional token symbol filter (e.g. "USDC", "WETH", "WBTC")
|
|
3056
3620
|
* @returns APY per strategy for a specific chain
|
|
@@ -3101,7 +3665,9 @@ var _ZyfaiSDK = class _ZyfaiSDK {
|
|
|
3101
3665
|
*/
|
|
3102
3666
|
async getVolume(assetType = "usdc") {
|
|
3103
3667
|
try {
|
|
3104
|
-
const response = await this.httpClient.get(
|
|
3668
|
+
const response = await this.httpClient.get(
|
|
3669
|
+
ENDPOINTS.DATA_VOLUME(assetType)
|
|
3670
|
+
);
|
|
3105
3671
|
return {
|
|
3106
3672
|
success: true,
|
|
3107
3673
|
volumeInUSD: response.volumeInUSD || "0"
|
|
@@ -3517,6 +4083,53 @@ var _ZyfaiSDK = class _ZyfaiSDK {
|
|
|
3517
4083
|
);
|
|
3518
4084
|
}
|
|
3519
4085
|
}
|
|
4086
|
+
/**
|
|
4087
|
+
* Get yieldmaxxing opportunities — pools reachable only with the
|
|
4088
|
+
* `"yieldmaxxing"` strategy, including protocols whose withdrawals are
|
|
4089
|
+
* asynchronous (Ipor, Superform). Exiting these pools takes about a day
|
|
4090
|
+
* on Ipor and three on Superform; track the redemption through
|
|
4091
|
+
* `getPortfolio().portfolio.pendingAsyncWithdrawals`.
|
|
4092
|
+
*
|
|
4093
|
+
* @param chainId - Optional chain ID filter
|
|
4094
|
+
* @param asset - Optional asset filter (e.g. "USDC", "WETH")
|
|
4095
|
+
* @returns List of yieldmaxxing opportunities
|
|
4096
|
+
*
|
|
4097
|
+
* @example
|
|
4098
|
+
* ```typescript
|
|
4099
|
+
* const opportunities = await sdk.getAsyncOpportunities(8453);
|
|
4100
|
+
* opportunities.data.forEach(o => console.log(o.protocolName, o.apy));
|
|
4101
|
+
* ```
|
|
4102
|
+
*/
|
|
4103
|
+
async getAsyncOpportunities(chainId, asset, status) {
|
|
4104
|
+
try {
|
|
4105
|
+
const response = await this.httpClient.dataGet(
|
|
4106
|
+
DATA_ENDPOINTS.OPPORTUNITIES_ASYNC(chainId, asset, status)
|
|
4107
|
+
);
|
|
4108
|
+
const data = response.data || response || [];
|
|
4109
|
+
return {
|
|
4110
|
+
success: true,
|
|
4111
|
+
chainId,
|
|
4112
|
+
strategyType: "yieldmaxxing",
|
|
4113
|
+
data: Array.isArray(data) ? data.map((o) => ({
|
|
4114
|
+
id: o.id,
|
|
4115
|
+
protocolId: o.protocol_id || o.protocolId,
|
|
4116
|
+
protocolName: o.protocol_name || o.protocolName,
|
|
4117
|
+
poolName: o.pool_name || o.poolName,
|
|
4118
|
+
chainId: o.chain_id || o.chainId,
|
|
4119
|
+
apy: o.combined_apy || 0,
|
|
4120
|
+
tvl: o.tvl || o.zyfiTvl,
|
|
4121
|
+
asset: o.asset || o.underlying_token,
|
|
4122
|
+
risk: o.risk,
|
|
4123
|
+
strategyType: "yieldmaxxing",
|
|
4124
|
+
status: o.status
|
|
4125
|
+
})) : []
|
|
4126
|
+
};
|
|
4127
|
+
} catch (error) {
|
|
4128
|
+
throw new Error(
|
|
4129
|
+
`Failed to get yieldmaxxing opportunities: ${error.message}`
|
|
4130
|
+
);
|
|
4131
|
+
}
|
|
4132
|
+
}
|
|
3520
4133
|
/**
|
|
3521
4134
|
* Get active conservative opportunities (status = "live") with risk and utilization data
|
|
3522
4135
|
* Returns pool info, liquidity depth (true if > 1M), utilization rate, stability metrics, avg APY, and collateral
|
|
@@ -3831,9 +4444,7 @@ var _ZyfaiSDK = class _ZyfaiSDK {
|
|
|
3831
4444
|
}
|
|
3832
4445
|
};
|
|
3833
4446
|
} catch (error) {
|
|
3834
|
-
throw new Error(
|
|
3835
|
-
`Failed to get SDK key TVL: ${error.message}`
|
|
3836
|
-
);
|
|
4447
|
+
throw new Error(`Failed to get SDK key TVL: ${error.message}`);
|
|
3837
4448
|
}
|
|
3838
4449
|
}
|
|
3839
4450
|
// ============================================================================
|
|
@@ -3893,7 +4504,7 @@ var _ZyfaiSDK = class _ZyfaiSDK {
|
|
|
3893
4504
|
* Returns the list of pools available for a given protocol, optionally filtered by strategy.
|
|
3894
4505
|
*
|
|
3895
4506
|
* @param protocolId - The protocol UUID
|
|
3896
|
-
* @param strategy - Optional strategy filter ("conservative" or "
|
|
4507
|
+
* @param strategy - Optional strategy filter ("conservative", "aggressive" or "yieldmaxxing")
|
|
3897
4508
|
* @returns List of available pool names
|
|
3898
4509
|
*
|
|
3899
4510
|
* @example
|
|
@@ -3915,7 +4526,7 @@ var _ZyfaiSDK = class _ZyfaiSDK {
|
|
|
3915
4526
|
if (strategy) {
|
|
3916
4527
|
if (!isValidPublicStrategy(strategy)) {
|
|
3917
4528
|
throw new Error(
|
|
3918
|
-
`Invalid strategy: ${strategy}. Must be "conservative" or "
|
|
4529
|
+
`Invalid strategy: ${strategy}. Must be "conservative", "aggressive" or "yieldmaxxing".`
|
|
3919
4530
|
);
|
|
3920
4531
|
}
|
|
3921
4532
|
internalStrategy = toInternalStrategy(strategy);
|
|
@@ -3961,7 +4572,7 @@ var _ZyfaiSDK = class _ZyfaiSDK {
|
|
|
3961
4572
|
try {
|
|
3962
4573
|
if (!isValidPublicStrategy(params.strategy)) {
|
|
3963
4574
|
throw new Error(
|
|
3964
|
-
`Invalid strategy: ${params.strategy}. Must be "conservative" or "
|
|
4575
|
+
`Invalid strategy: ${params.strategy}. Must be "conservative", "aggressive" or "yieldmaxxing".`
|
|
3965
4576
|
);
|
|
3966
4577
|
}
|
|
3967
4578
|
const internalStrategy = toInternalStrategy(params.strategy);
|
|
@@ -4016,7 +4627,9 @@ var _ZyfaiSDK = class _ZyfaiSDK {
|
|
|
4016
4627
|
* Check if a chain ID supports the Identity Registry
|
|
4017
4628
|
*/
|
|
4018
4629
|
isSupportedIdentityRegistryChain(chainId) {
|
|
4019
|
-
return _ZyfaiSDK.IDENTITY_REGISTRY_CHAIN_IDS.includes(
|
|
4630
|
+
return _ZyfaiSDK.IDENTITY_REGISTRY_CHAIN_IDS.includes(
|
|
4631
|
+
chainId
|
|
4632
|
+
);
|
|
4020
4633
|
}
|
|
4021
4634
|
/**
|
|
4022
4635
|
* Register an agent on the Identity Registry (ERC-8004)
|
|
@@ -4113,7 +4726,9 @@ var _ZyfaiSDK = class _ZyfaiSDK {
|
|
|
4113
4726
|
const chainConfig = getChainConfig(chainId, this.rpcUrls);
|
|
4114
4727
|
const tokenAddress = getDefaultTokenAddress(chainId, asset);
|
|
4115
4728
|
const decimals = 6;
|
|
4116
|
-
const parsedAmount = BigInt(
|
|
4729
|
+
const parsedAmount = BigInt(
|
|
4730
|
+
Math.floor(parseFloat(amount) * 10 ** decimals)
|
|
4731
|
+
);
|
|
4117
4732
|
try {
|
|
4118
4733
|
const allowance = await chainConfig.publicClient.readContract({
|
|
4119
4734
|
address: tokenAddress,
|
|
@@ -4191,7 +4806,9 @@ var _ZyfaiSDK = class _ZyfaiSDK {
|
|
|
4191
4806
|
args: [userAddress]
|
|
4192
4807
|
});
|
|
4193
4808
|
if (maxShares === 0n) {
|
|
4194
|
-
throw new Error(
|
|
4809
|
+
throw new Error(
|
|
4810
|
+
"No shares available to redeem or withdrawals are paused"
|
|
4811
|
+
);
|
|
4195
4812
|
}
|
|
4196
4813
|
sharesToRedeem = maxShares;
|
|
4197
4814
|
}
|
|
@@ -4235,7 +4852,9 @@ var _ZyfaiSDK = class _ZyfaiSDK {
|
|
|
4235
4852
|
status: isClaimable ? "claimable" : "pending"
|
|
4236
4853
|
};
|
|
4237
4854
|
} catch (error) {
|
|
4238
|
-
throw new Error(
|
|
4855
|
+
throw new Error(
|
|
4856
|
+
`Vault withdraw request failed: ${error.message}`
|
|
4857
|
+
);
|
|
4239
4858
|
}
|
|
4240
4859
|
}
|
|
4241
4860
|
/**
|
|
@@ -4315,7 +4934,9 @@ var _ZyfaiSDK = class _ZyfaiSDK {
|
|
|
4315
4934
|
nonce
|
|
4316
4935
|
};
|
|
4317
4936
|
} catch (error) {
|
|
4318
|
-
throw new Error(
|
|
4937
|
+
throw new Error(
|
|
4938
|
+
`Failed to get withdraw status: ${error.message}`
|
|
4939
|
+
);
|
|
4319
4940
|
}
|
|
4320
4941
|
}
|
|
4321
4942
|
/**
|
|
@@ -4358,7 +4979,9 @@ var _ZyfaiSDK = class _ZyfaiSDK {
|
|
|
4358
4979
|
if (isClaimed) {
|
|
4359
4980
|
throw new Error("This withdrawal has already been claimed");
|
|
4360
4981
|
}
|
|
4361
|
-
throw new Error(
|
|
4982
|
+
throw new Error(
|
|
4983
|
+
"Withdrawal is not yet claimable. Please wait for processing."
|
|
4984
|
+
);
|
|
4362
4985
|
}
|
|
4363
4986
|
const claimTx = await this.walletClient.writeContract({
|
|
4364
4987
|
address: VAULT_ADDRESS,
|
|
@@ -4398,7 +5021,9 @@ var _ZyfaiSDK = class _ZyfaiSDK {
|
|
|
4398
5021
|
async getVaultShares(userAddress, chainId = 8453) {
|
|
4399
5022
|
const address = userAddress || this.walletClient?.account?.address;
|
|
4400
5023
|
if (!address) {
|
|
4401
|
-
throw new Error(
|
|
5024
|
+
throw new Error(
|
|
5025
|
+
"User address required. Provide address or connect wallet first."
|
|
5026
|
+
);
|
|
4402
5027
|
}
|
|
4403
5028
|
const chainConfig = getChainConfig(chainId, this.rpcUrls);
|
|
4404
5029
|
const [shareBalance, tokenSymbol] = await Promise.all([
|
|
@@ -4670,21 +5295,36 @@ function createBankrProvider(config) {
|
|
|
4670
5295
|
// Annotate the CommonJS export names for ESM import in node:
|
|
4671
5296
|
0 && (module.exports = {
|
|
4672
5297
|
ALLOWED_HISTORY_DAYS,
|
|
5298
|
+
API_ENDPOINT,
|
|
5299
|
+
DATA_API_BASE_URLS,
|
|
5300
|
+
DATA_API_ENDPOINT,
|
|
4673
5301
|
DEFAULT_TOKEN_ADDRESSES,
|
|
4674
5302
|
ERC7579_LAUNCHPAD_ADDRESS,
|
|
5303
|
+
EXECUTION_API_BASE_URLS,
|
|
4675
5304
|
INTENT_EXECUTOR,
|
|
4676
5305
|
INTENT_SMART_SESSIONS,
|
|
5306
|
+
LOCAL_DATA_API_BASE_URL,
|
|
5307
|
+
LOCAL_EXECUTION_API_BASE_URL,
|
|
5308
|
+
LOCAL_WS_URL,
|
|
4677
5309
|
OWNABLE_VALIDATOR,
|
|
4678
5310
|
POOL_MODULE_ADDRESSES,
|
|
4679
5311
|
PROXY_EXECUTOR,
|
|
4680
5312
|
SAFE_7579_ADDRESS,
|
|
4681
5313
|
SMART_SESSIONS_FALLBACK,
|
|
4682
5314
|
SMART_SESSIONS_VALIDATOR,
|
|
5315
|
+
STAGING_DATA_API_BASE_URL,
|
|
5316
|
+
STAGING_EXECUTION_API_BASE_URL,
|
|
5317
|
+
STAGING_WS_URL,
|
|
4683
5318
|
VAULT_ADDRESS,
|
|
5319
|
+
WS_ENDPOINT,
|
|
5320
|
+
WS_URLS,
|
|
4684
5321
|
ZyfaiSDK,
|
|
4685
5322
|
createBankrProvider,
|
|
4686
5323
|
getChainConfig,
|
|
5324
|
+
getDataApiBaseUrl,
|
|
4687
5325
|
getDefaultTokenAddress,
|
|
5326
|
+
getExecutionApiBaseUrl,
|
|
4688
5327
|
getSupportedChainIds,
|
|
5328
|
+
getWsUrl,
|
|
4689
5329
|
isSupportedChain
|
|
4690
5330
|
});
|