@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.mjs
CHANGED
|
@@ -2,9 +2,40 @@
|
|
|
2
2
|
import axios from "axios";
|
|
3
3
|
|
|
4
4
|
// src/config/endpoints.ts
|
|
5
|
-
var
|
|
6
|
-
|
|
7
|
-
|
|
5
|
+
var EXECUTION_API_BASE_URLS = {
|
|
6
|
+
production: "https://api.zyf.ai",
|
|
7
|
+
staging: "https://staging-api.zyf.ai",
|
|
8
|
+
local: "http://localhost:3000"
|
|
9
|
+
};
|
|
10
|
+
var DATA_API_BASE_URLS = {
|
|
11
|
+
production: "https://defiapi.zyf.ai",
|
|
12
|
+
staging: "https://staging-defiapi.zyf.ai",
|
|
13
|
+
/** Both backends default to port 3000 locally; run one at a time or override PORT. */
|
|
14
|
+
local: "http://localhost:3000"
|
|
15
|
+
};
|
|
16
|
+
var WS_URLS = {
|
|
17
|
+
production: "wss://defiapi.zyf.ai/ws/events",
|
|
18
|
+
staging: "wss://staging-defiapi.zyf.ai/ws/events",
|
|
19
|
+
local: "ws://localhost:3000/ws/events"
|
|
20
|
+
};
|
|
21
|
+
var API_ENDPOINT = EXECUTION_API_BASE_URLS.production;
|
|
22
|
+
var DATA_API_ENDPOINT = DATA_API_BASE_URLS.production;
|
|
23
|
+
var WS_ENDPOINT = WS_URLS.production;
|
|
24
|
+
var STAGING_EXECUTION_API_BASE_URL = EXECUTION_API_BASE_URLS.staging;
|
|
25
|
+
var STAGING_DATA_API_BASE_URL = DATA_API_BASE_URLS.staging;
|
|
26
|
+
var STAGING_WS_URL = WS_URLS.staging;
|
|
27
|
+
var LOCAL_EXECUTION_API_BASE_URL = EXECUTION_API_BASE_URLS.local;
|
|
28
|
+
var LOCAL_DATA_API_BASE_URL = DATA_API_BASE_URLS.local;
|
|
29
|
+
var LOCAL_WS_URL = WS_URLS.local;
|
|
30
|
+
function getExecutionApiBaseUrl(environment = "production") {
|
|
31
|
+
return EXECUTION_API_BASE_URLS[environment];
|
|
32
|
+
}
|
|
33
|
+
function getDataApiBaseUrl(environment = "production") {
|
|
34
|
+
return DATA_API_BASE_URLS[environment];
|
|
35
|
+
}
|
|
36
|
+
function getWsUrl(environment = "production") {
|
|
37
|
+
return WS_URLS[environment];
|
|
38
|
+
}
|
|
8
39
|
var API_VERSION = "/api/v1";
|
|
9
40
|
var DATA_API_VERSION = "/api/v2";
|
|
10
41
|
var ENDPOINTS = {
|
|
@@ -15,7 +46,8 @@ var ENDPOINTS = {
|
|
|
15
46
|
USER_ME: "/users/me",
|
|
16
47
|
USER_WITHDRAW: "/users/withdraw",
|
|
17
48
|
PARTIAL_WITHDRAW: "/users/partial-withdraw",
|
|
18
|
-
LOG_DEPOSIT: "/users/log_deposit",
|
|
49
|
+
LOG_DEPOSIT: "/users/log_deposit/v2",
|
|
50
|
+
DEPOSIT_STATUS: (depositId) => `/users/deposits/${depositId}`,
|
|
19
51
|
// Safe Deployment (single endpoint)
|
|
20
52
|
SAFE_DEPLOY: "/users/safe-deploy",
|
|
21
53
|
// Multichain deploy for predeployed (pool) wallets — deploys + rotates the
|
|
@@ -50,11 +82,17 @@ var ENDPOINTS = {
|
|
|
50
82
|
`networks=${networks}`,
|
|
51
83
|
`strategy=${params.strategy}`
|
|
52
84
|
];
|
|
53
|
-
if (params.minSplit !== void 0)
|
|
54
|
-
|
|
85
|
+
if (params.minSplit !== void 0)
|
|
86
|
+
query.push(`minSplit=${params.minSplit}`);
|
|
87
|
+
if (params.protocols?.length)
|
|
88
|
+
query.push(`protocols=${params.protocols.join(",")}`);
|
|
55
89
|
if (params.pools?.length) query.push(`pools=${params.pools.join(",")}`);
|
|
56
|
-
if (params.userPositions?.length)
|
|
57
|
-
|
|
90
|
+
if (params.userPositions?.length)
|
|
91
|
+
query.push(
|
|
92
|
+
`userPositions=${encodeURIComponent(JSON.stringify(params.userPositions))}`
|
|
93
|
+
);
|
|
94
|
+
if (params.partOfZyfiTvl !== void 0)
|
|
95
|
+
query.push(`partOfZyfiTvl=${params.partOfZyfiTvl}`);
|
|
58
96
|
return `/simulate/best-positions?${query.join("&")}`;
|
|
59
97
|
},
|
|
60
98
|
// Customization
|
|
@@ -89,12 +127,20 @@ var DATA_ENDPOINTS = {
|
|
|
89
127
|
if (status) params.push(`status=${status}`);
|
|
90
128
|
return params.length > 0 ? `/opportunities/degen-strategies?${params.join("&")}` : "/opportunities/degen-strategies";
|
|
91
129
|
},
|
|
130
|
+
OPPORTUNITIES_ASYNC: (chainId, asset, status) => {
|
|
131
|
+
const params = [];
|
|
132
|
+
if (chainId !== void 0) params.push(`chainId=${chainId}`);
|
|
133
|
+
if (asset) params.push(`asset=${asset}`);
|
|
134
|
+
if (status) params.push(`status=${status}`);
|
|
135
|
+
return params.length > 0 ? `/opportunities/async?${params.join("&")}` : "/opportunities/async";
|
|
136
|
+
},
|
|
92
137
|
// APY History
|
|
93
138
|
DAILY_APY_HISTORY_WEIGHTED: (walletAddress, days) => `/daily-apy-history/weighted-multi-asset/${walletAddress}${days ? `?days=${days}` : ""}`,
|
|
94
139
|
// Rebalance
|
|
95
140
|
REBALANCE_INFO: (options) => {
|
|
96
141
|
const params = [];
|
|
97
|
-
if (options?.isCrossChain !== void 0)
|
|
142
|
+
if (options?.isCrossChain !== void 0)
|
|
143
|
+
params.push(`isCrossChain=${options.isCrossChain}`);
|
|
98
144
|
if (options?.tokenSymbol) params.push(`tokenSymbol=${options.tokenSymbol}`);
|
|
99
145
|
return params.length > 0 ? `/rebalance/rebalance-info?${params.join("&")}` : "/rebalance/rebalance-info";
|
|
100
146
|
},
|
|
@@ -103,10 +149,12 @@ var DATA_ENDPOINTS = {
|
|
|
103
149
|
// APY Per Strategy
|
|
104
150
|
APY_PER_STRATEGY: (options = {}) => {
|
|
105
151
|
const params = [];
|
|
106
|
-
if (options.isCrossChain !== void 0)
|
|
152
|
+
if (options.isCrossChain !== void 0)
|
|
153
|
+
params.push(`isCrossChain=${options.isCrossChain}`);
|
|
107
154
|
if (options.days !== void 0) params.push(`days=${options.days}`);
|
|
108
155
|
if (options.strategy) params.push(`strategy=${options.strategy}`);
|
|
109
|
-
if (options.chainId !== void 0)
|
|
156
|
+
if (options.chainId !== void 0)
|
|
157
|
+
params.push(`chainId=${options.chainId}`);
|
|
110
158
|
if (options.tokenSymbol) params.push(`tokenSymbol=${options.tokenSymbol}`);
|
|
111
159
|
return params.length > 0 ? `/rebalance/rebalance-info?${params.join("&")}` : "/rebalance/rebalance-info";
|
|
112
160
|
}
|
|
@@ -119,14 +167,16 @@ var HttpClient = class {
|
|
|
119
167
|
*
|
|
120
168
|
* @param apiKey - API key for both Execution API and Data API
|
|
121
169
|
*/
|
|
122
|
-
constructor(apiKey) {
|
|
170
|
+
constructor(apiKey, config = {}) {
|
|
123
171
|
this.authToken = null;
|
|
124
172
|
this.apiKey = apiKey;
|
|
125
|
-
const
|
|
173
|
+
const executionApiUrl = config.executionApiUrl ?? API_ENDPOINT;
|
|
174
|
+
this.dataApiBaseUrl = config.dataApiUrl ?? DATA_API_ENDPOINT;
|
|
175
|
+
const parsedUrl = new URL(executionApiUrl);
|
|
126
176
|
this.origin = parsedUrl.origin;
|
|
127
177
|
this.host = parsedUrl.host;
|
|
128
178
|
this.client = axios.create({
|
|
129
|
-
baseURL: `${
|
|
179
|
+
baseURL: `${executionApiUrl}${API_VERSION}`,
|
|
130
180
|
headers: {
|
|
131
181
|
"Content-Type": "application/json",
|
|
132
182
|
"X-API-Key": this.apiKey
|
|
@@ -134,7 +184,7 @@ var HttpClient = class {
|
|
|
134
184
|
timeout: 3e4
|
|
135
185
|
});
|
|
136
186
|
this.dataClient = axios.create({
|
|
137
|
-
baseURL: `${
|
|
187
|
+
baseURL: `${this.dataApiBaseUrl}${DATA_API_VERSION}`,
|
|
138
188
|
headers: {
|
|
139
189
|
"Content-Type": "application/json",
|
|
140
190
|
"X-API-Key": this.apiKey
|
|
@@ -177,7 +227,9 @@ var HttpClient = class {
|
|
|
177
227
|
const data = error.response.data;
|
|
178
228
|
switch (status) {
|
|
179
229
|
case 401:
|
|
180
|
-
throw new Error(
|
|
230
|
+
throw new Error(
|
|
231
|
+
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."
|
|
232
|
+
);
|
|
181
233
|
case 403:
|
|
182
234
|
throw new Error("Forbidden: Access denied");
|
|
183
235
|
case 404:
|
|
@@ -187,7 +239,9 @@ var HttpClient = class {
|
|
|
187
239
|
case 429:
|
|
188
240
|
throw new Error("Rate limit exceeded. Please try again later.");
|
|
189
241
|
case 500:
|
|
190
|
-
throw new Error(
|
|
242
|
+
throw new Error(
|
|
243
|
+
data?.message || data?.error || "Internal server error. Please try again later."
|
|
244
|
+
);
|
|
191
245
|
default:
|
|
192
246
|
throw new Error(data.message || "An error occurred");
|
|
193
247
|
}
|
|
@@ -233,7 +287,7 @@ var HttpClient = class {
|
|
|
233
287
|
* @param config - Additional axios config
|
|
234
288
|
*/
|
|
235
289
|
async dataPostCustom(path, data, config) {
|
|
236
|
-
const fullUrl = `${
|
|
290
|
+
const fullUrl = `${this.dataApiBaseUrl}${path}`;
|
|
237
291
|
const headers = {
|
|
238
292
|
"Content-Type": "application/json",
|
|
239
293
|
"X-API-Key": this.apiKey,
|
|
@@ -268,7 +322,9 @@ var HttpClient = class {
|
|
|
268
322
|
const data = error.response.data;
|
|
269
323
|
switch (status) {
|
|
270
324
|
case 401:
|
|
271
|
-
throw new Error(
|
|
325
|
+
throw new Error(
|
|
326
|
+
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."
|
|
327
|
+
);
|
|
272
328
|
case 403:
|
|
273
329
|
throw new Error("Forbidden: Access denied to data API");
|
|
274
330
|
case 404:
|
|
@@ -296,26 +352,30 @@ var HttpClient = class {
|
|
|
296
352
|
}
|
|
297
353
|
};
|
|
298
354
|
|
|
299
|
-
// src/utils/
|
|
355
|
+
// src/utils/poll.ts
|
|
356
|
+
function sleep(ms) {
|
|
357
|
+
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
358
|
+
}
|
|
359
|
+
|
|
360
|
+
// src/utils/token-price.ts
|
|
300
361
|
var PRICE_SCALE = 8;
|
|
301
|
-
var
|
|
362
|
+
var parseTokenUsdPrice = (response) => {
|
|
302
363
|
const priceUsd = response?.data?.price_usd;
|
|
303
364
|
if (typeof priceUsd !== "number" || !Number.isFinite(priceUsd) || priceUsd <= 0) {
|
|
304
|
-
throw new Error("
|
|
365
|
+
throw new Error("Token USD price must be a positive number");
|
|
305
366
|
}
|
|
306
367
|
return priceUsd;
|
|
307
368
|
};
|
|
308
|
-
var
|
|
309
|
-
if (!Number.isFinite(
|
|
310
|
-
throw new Error("
|
|
369
|
+
var usdToTokenUnits = (usdAmount, priceUsd, decimals) => {
|
|
370
|
+
if (!Number.isFinite(priceUsd) || priceUsd <= 0) {
|
|
371
|
+
throw new Error("Token USD price must be positive");
|
|
311
372
|
}
|
|
312
|
-
const scaledPrice = BigInt(Math.round(
|
|
373
|
+
const scaledPrice = BigInt(Math.round(priceUsd * 10 ** PRICE_SCALE));
|
|
313
374
|
if (scaledPrice <= 0n) {
|
|
314
|
-
throw new Error("
|
|
375
|
+
throw new Error("Token USD price must be positive");
|
|
315
376
|
}
|
|
316
|
-
return usdAmount * 10n **
|
|
377
|
+
return usdAmount * 10n ** BigInt(decimals) * 10n ** BigInt(PRICE_SCALE) / scaledPrice;
|
|
317
378
|
};
|
|
318
|
-
var minWethWeiForUsd = (ethUsd, usdAmount) => usdToWethWei(usdAmount, ethUsd);
|
|
319
379
|
|
|
320
380
|
// src/config/abis.ts
|
|
321
381
|
import { parseAbi } from "viem";
|
|
@@ -508,11 +568,26 @@ var MIN_PORTFOLIO_BALANCE = {
|
|
|
508
568
|
// 100 EURC (6 decimals)
|
|
509
569
|
}
|
|
510
570
|
};
|
|
511
|
-
var
|
|
512
|
-
1: 10000n,
|
|
513
|
-
8453: 100n,
|
|
514
|
-
42161: 100n
|
|
571
|
+
var MIN_PORTFOLIO_USD = {
|
|
572
|
+
1: { WETH: 10000n },
|
|
573
|
+
8453: { WETH: 100n, NVDAc: 100n },
|
|
574
|
+
42161: { WETH: 100n }
|
|
575
|
+
};
|
|
576
|
+
var DEPOSIT_CREDIT_INTERVAL_MS = {
|
|
577
|
+
1: 2e3,
|
|
578
|
+
8453: 500,
|
|
579
|
+
42161: 250
|
|
515
580
|
};
|
|
581
|
+
var DEPOSIT_CREDIT_TIMEOUT_MS = {
|
|
582
|
+
1: 6e4,
|
|
583
|
+
// 1 minute
|
|
584
|
+
8453: 2e4,
|
|
585
|
+
// ~10 Base blocks
|
|
586
|
+
42161: 2e4
|
|
587
|
+
// ~10 Arbitrum blocks
|
|
588
|
+
};
|
|
589
|
+
var getDepositCreditIntervalMs = (chainId) => DEPOSIT_CREDIT_INTERVAL_MS[chainId];
|
|
590
|
+
var getDepositCreditTimeoutMs = (chainId) => DEPOSIT_CREDIT_TIMEOUT_MS[chainId];
|
|
516
591
|
var formatMinPortfolioLabel = (raw, decimals, symbol) => {
|
|
517
592
|
const base2 = 10n ** BigInt(decimals);
|
|
518
593
|
const whole = raw / base2;
|
|
@@ -524,6 +599,25 @@ var formatMinPortfolioLabel = (raw, decimals, symbol) => {
|
|
|
524
599
|
return `${whole.toString()}.${fractionStr} ${symbol}`;
|
|
525
600
|
};
|
|
526
601
|
|
|
602
|
+
// src/config/local-dev.ts
|
|
603
|
+
function isLocalExecutionApiUrl(executionApiUrl) {
|
|
604
|
+
if (executionApiUrl === EXECUTION_API_BASE_URLS.local) {
|
|
605
|
+
return true;
|
|
606
|
+
}
|
|
607
|
+
try {
|
|
608
|
+
const { hostname } = new URL(executionApiUrl);
|
|
609
|
+
return hostname === "localhost" || hostname === "127.0.0.1";
|
|
610
|
+
} catch {
|
|
611
|
+
return false;
|
|
612
|
+
}
|
|
613
|
+
}
|
|
614
|
+
function shouldBypassMinPortfolioCheck(executionApiUrl) {
|
|
615
|
+
if (process.env.NODE_ENV === "production") {
|
|
616
|
+
return false;
|
|
617
|
+
}
|
|
618
|
+
return isLocalExecutionApiUrl(executionApiUrl);
|
|
619
|
+
}
|
|
620
|
+
|
|
527
621
|
// src/core/ZyfaiSDK.ts
|
|
528
622
|
import { privateKeyToAccount } from "viem/accounts";
|
|
529
623
|
import {
|
|
@@ -580,6 +674,8 @@ var ASSET_CONFIGS = {
|
|
|
580
674
|
displayName: "WETH",
|
|
581
675
|
icon: "/ai-dashboard/eth-token.png",
|
|
582
676
|
decimals: 18,
|
|
677
|
+
// Data API `/price?token=` identifier, used for USD-denominated minimums.
|
|
678
|
+
priceTokenSymbol: "eth",
|
|
583
679
|
tokenSymbols: ["WETH", "ETH"],
|
|
584
680
|
tokenSymbolsByChainId: {
|
|
585
681
|
1: "WETH",
|
|
@@ -620,8 +716,39 @@ var ASSET_CONFIGS = {
|
|
|
620
716
|
// Base
|
|
621
717
|
},
|
|
622
718
|
enabled: true
|
|
719
|
+
},
|
|
720
|
+
// Coinbase B20 tokenized NVIDIA equity. Base only, and only reachable through
|
|
721
|
+
// protocols with delayed withdrawals — see the `yieldmaxxing` strategy.
|
|
722
|
+
NVDAc: {
|
|
723
|
+
symbol: "NVDAc",
|
|
724
|
+
assetType: "nvdac",
|
|
725
|
+
displayName: "NVIDIA",
|
|
726
|
+
icon: "https://metadata.coinbase.com/equity_icons/1fee9b7a44e800d438dd9d96c3283e05784c925c2c871a48ff735950740b551a.png",
|
|
727
|
+
decimals: 8,
|
|
728
|
+
priceTokenSymbol: "nvdac",
|
|
729
|
+
tokenSymbols: ["NVDAc"],
|
|
730
|
+
tokenSymbolsByChainId: {
|
|
731
|
+
8453: "NVDAc"
|
|
732
|
+
},
|
|
733
|
+
addresses: {
|
|
734
|
+
8453: "0xb20000000000000000000078ee7ce2fE4908108C"
|
|
735
|
+
// Base
|
|
736
|
+
},
|
|
737
|
+
enabled: true
|
|
623
738
|
}
|
|
624
739
|
};
|
|
740
|
+
var resolveAssetSymbol = (asset) => {
|
|
741
|
+
const match = Object.keys(ASSET_CONFIGS).find(
|
|
742
|
+
(key) => key.toLowerCase() === asset.toLowerCase()
|
|
743
|
+
);
|
|
744
|
+
if (!match) {
|
|
745
|
+
throw new Error(
|
|
746
|
+
`Unsupported asset: ${asset}. Supported: ${Object.keys(ASSET_CONFIGS).join(", ")}.`
|
|
747
|
+
);
|
|
748
|
+
}
|
|
749
|
+
return match;
|
|
750
|
+
};
|
|
751
|
+
var getAssetChainIds = (asset) => Object.keys(ASSET_CONFIGS[asset]?.addresses ?? {}).map(Number).filter((chainId) => chainId in CHAINS);
|
|
625
752
|
var getDefaultTokenAddress = (chainId, asset) => {
|
|
626
753
|
const address = ASSET_CONFIGS[asset || "USDC"]?.addresses[chainId];
|
|
627
754
|
if (!address || address === "0x0000000000000000000000000000000000000000") {
|
|
@@ -910,15 +1037,19 @@ var signSessionKey = async (config, sessions, allPublicClients, signingParams) =
|
|
|
910
1037
|
};
|
|
911
1038
|
|
|
912
1039
|
// src/utils/strategy.ts
|
|
1040
|
+
var PUBLIC_STRATEGIES = `"conservative", "aggressive" or "yieldmaxxing"`;
|
|
1041
|
+
var SUPPORTED_ASSETS = `"USDC", "WETH", "EURC" or "NVDAc"`;
|
|
913
1042
|
function toInternalStrategy(publicStrategy) {
|
|
914
1043
|
switch (publicStrategy) {
|
|
915
1044
|
case "conservative":
|
|
916
1045
|
return "safe_strategy";
|
|
917
1046
|
case "aggressive":
|
|
918
1047
|
return "degen_strategy";
|
|
1048
|
+
case "yieldmaxxing":
|
|
1049
|
+
return "async_strategy";
|
|
919
1050
|
default:
|
|
920
1051
|
throw new Error(
|
|
921
|
-
`Invalid public strategy: ${publicStrategy}. Must be
|
|
1052
|
+
`Invalid public strategy: ${publicStrategy}. Must be ${PUBLIC_STRATEGIES}.`
|
|
922
1053
|
);
|
|
923
1054
|
}
|
|
924
1055
|
}
|
|
@@ -929,12 +1060,25 @@ function toPublicStrategy(internalStrategy) {
|
|
|
929
1060
|
if (internalStrategy === "degen_strategy" || internalStrategy === "degen") {
|
|
930
1061
|
return "aggressive";
|
|
931
1062
|
}
|
|
1063
|
+
if (internalStrategy === "async_strategy" || internalStrategy === "async") {
|
|
1064
|
+
return "yieldmaxxing";
|
|
1065
|
+
}
|
|
932
1066
|
throw new Error(
|
|
933
|
-
`Invalid internal strategy: ${internalStrategy}. Must be "safe_strategy" or "
|
|
1067
|
+
`Invalid internal strategy: ${internalStrategy}. Must be "safe_strategy", "degen_strategy" or "async_strategy".`
|
|
934
1068
|
);
|
|
935
1069
|
}
|
|
1070
|
+
function toPublicStrategyOrUndefined(internalStrategy) {
|
|
1071
|
+
if (!internalStrategy) {
|
|
1072
|
+
return void 0;
|
|
1073
|
+
}
|
|
1074
|
+
try {
|
|
1075
|
+
return toPublicStrategy(internalStrategy);
|
|
1076
|
+
} catch {
|
|
1077
|
+
return void 0;
|
|
1078
|
+
}
|
|
1079
|
+
}
|
|
936
1080
|
function isValidPublicStrategy(strategy) {
|
|
937
|
-
return strategy === "conservative" || strategy === "aggressive";
|
|
1081
|
+
return strategy === "conservative" || strategy === "aggressive" || strategy === "yieldmaxxing";
|
|
938
1082
|
}
|
|
939
1083
|
function convertStrategyToPublic(obj) {
|
|
940
1084
|
if (!obj.strategy) {
|
|
@@ -983,8 +1127,11 @@ function convertAssetInternally(asset) {
|
|
|
983
1127
|
if (asset === "EURC") {
|
|
984
1128
|
return "eurc";
|
|
985
1129
|
}
|
|
1130
|
+
if (asset === "NVDAc") {
|
|
1131
|
+
return "nvdac";
|
|
1132
|
+
}
|
|
986
1133
|
throw new Error(
|
|
987
|
-
`Invalid asset: ${asset}. Must be
|
|
1134
|
+
`Invalid asset: ${asset}. Must be ${SUPPORTED_ASSETS}.`
|
|
988
1135
|
);
|
|
989
1136
|
}
|
|
990
1137
|
function convertStrategiesToPublic(array) {
|
|
@@ -1029,16 +1176,19 @@ var hasAssetOnSelectedChains = (protocol, chains, asset) => {
|
|
|
1029
1176
|
(a) => chains.includes(a.chainId) && validSymbols.includes(a.symbol)
|
|
1030
1177
|
);
|
|
1031
1178
|
};
|
|
1179
|
+
var ELIGIBLE_PROTOCOL_STRATEGIES = {
|
|
1180
|
+
safe_strategy: ["safe_strategy"],
|
|
1181
|
+
degen_strategy: ["safe_strategy", "degen_strategy"],
|
|
1182
|
+
async_strategy: ["safe_strategy", "degen_strategy", "async_strategy"]
|
|
1183
|
+
};
|
|
1032
1184
|
var getMatchingProtocolIds = (protocols, internalStrategy, chains, asset) => {
|
|
1033
1185
|
if (chains.length === 0) return [];
|
|
1186
|
+
const eligible = ELIGIBLE_PROTOCOL_STRATEGIES[internalStrategy] ?? ELIGIBLE_PROTOCOL_STRATEGIES.safe_strategy;
|
|
1034
1187
|
return protocols.filter((protocol) => {
|
|
1035
1188
|
if (!protocol || !protocol.strategies) return false;
|
|
1036
1189
|
if (!protocol.chains?.some((c) => chains.includes(c))) return false;
|
|
1037
1190
|
if (!hasAssetOnSelectedChains(protocol, chains, asset)) return false;
|
|
1038
|
-
|
|
1039
|
-
return protocol.strategies.includes("degen_strategy") || protocol.strategies.includes("safe_strategy");
|
|
1040
|
-
}
|
|
1041
|
-
return protocol.strategies.includes("safe_strategy");
|
|
1191
|
+
return protocol.strategies.some((s) => eligible.includes(s));
|
|
1042
1192
|
}).map((protocol) => protocol.id);
|
|
1043
1193
|
};
|
|
1044
1194
|
var hasMatchingPool = (data, chains, asset) => {
|
|
@@ -1404,8 +1554,34 @@ function enrichOnchainEarningsTotals(apiData) {
|
|
|
1404
1554
|
};
|
|
1405
1555
|
}
|
|
1406
1556
|
|
|
1557
|
+
// src/utils/async-withdrawals.ts
|
|
1558
|
+
var findBlockingAsyncRedemption = (portfolio, chainId, tokenSymbol) => {
|
|
1559
|
+
const matchesToken = (symbol) => !tokenSymbol || symbol?.toLowerCase() === tokenSymbol.toLowerCase();
|
|
1560
|
+
const blocked = (portfolio.pendingAsyncWithdrawals ?? []).filter(
|
|
1561
|
+
(w) => w.chainId === chainId && (w.status === "REQUESTED" || w.status === "CLAIMABLE") && matchesToken(w.token?.symbol)
|
|
1562
|
+
);
|
|
1563
|
+
if (blocked.length === 0) return void 0;
|
|
1564
|
+
const blockedPools = new Set(
|
|
1565
|
+
blocked.map((w) => w.pool?.toLowerCase()).filter(Boolean)
|
|
1566
|
+
);
|
|
1567
|
+
const hasFreePosition = (portfolio.positions ?? []).some(
|
|
1568
|
+
(p) => matchesToken(p.token_symbol) && Number(chainNameToId(p.chain ?? "")) === chainId && !blockedPools.has(p.pool?.toLowerCase() ?? "")
|
|
1569
|
+
);
|
|
1570
|
+
const hasIdleBalance = (portfolio.staleBalances ?? []).some(
|
|
1571
|
+
(b) => b.chainId === chainId && matchesToken(b.tokenSymbol) && BigInt(b.balance ?? "0") > 0n
|
|
1572
|
+
);
|
|
1573
|
+
return hasFreePosition || hasIdleBalance ? void 0 : blocked[0];
|
|
1574
|
+
};
|
|
1575
|
+
|
|
1407
1576
|
// src/core/ZyfaiSDK.ts
|
|
1408
1577
|
import { SiweMessage } from "siwe";
|
|
1578
|
+
var DepositCreditTimeoutError = class extends Error {
|
|
1579
|
+
constructor(depositId) {
|
|
1580
|
+
super(`Timed out waiting for deposit ${depositId} to be credited`);
|
|
1581
|
+
this.name = "DepositCreditTimeoutError";
|
|
1582
|
+
}
|
|
1583
|
+
};
|
|
1584
|
+
var MANAGED_ASSETS = ["USDC", "WETH", "EURC", "NVDAc"];
|
|
1409
1585
|
var _ZyfaiSDK = class _ZyfaiSDK {
|
|
1410
1586
|
constructor(config) {
|
|
1411
1587
|
this.signer = null;
|
|
@@ -1417,21 +1593,33 @@ var _ZyfaiSDK = class _ZyfaiSDK {
|
|
|
1417
1593
|
this.currentProvider = null;
|
|
1418
1594
|
this.currentChainId = null;
|
|
1419
1595
|
const sdkConfig = typeof config === "string" ? { apiKey: config } : config;
|
|
1420
|
-
const {
|
|
1596
|
+
const {
|
|
1597
|
+
apiKey,
|
|
1598
|
+
rpcUrls,
|
|
1599
|
+
referralSource,
|
|
1600
|
+
executionApiUrl,
|
|
1601
|
+
dataApiUrl,
|
|
1602
|
+
bypassMinPortfolio
|
|
1603
|
+
} = sdkConfig;
|
|
1421
1604
|
if (!apiKey) {
|
|
1422
1605
|
throw new Error("API key is required");
|
|
1423
1606
|
}
|
|
1424
|
-
this.
|
|
1607
|
+
this.executionApiUrl = executionApiUrl ?? API_ENDPOINT;
|
|
1608
|
+
this.bypassMinPortfolio = bypassMinPortfolio ?? shouldBypassMinPortfolioCheck(this.executionApiUrl);
|
|
1609
|
+
this.httpClient = new HttpClient(apiKey, {
|
|
1610
|
+
executionApiUrl: this.executionApiUrl,
|
|
1611
|
+
dataApiUrl
|
|
1612
|
+
});
|
|
1425
1613
|
this.rpcUrls = rpcUrls;
|
|
1426
1614
|
this.referralSource = referralSource;
|
|
1427
1615
|
}
|
|
1428
1616
|
/**
|
|
1429
|
-
* Warn that a legacy method is deprecated in favor of
|
|
1617
|
+
* Warn that a legacy method is deprecated in favor of sendDeposit.
|
|
1430
1618
|
* Predeployed wallets no longer require deploySafe / createSessionKey.
|
|
1431
1619
|
*/
|
|
1432
1620
|
warnDeprecatedOnboardingMethod(methodName) {
|
|
1433
1621
|
console.warn(
|
|
1434
|
-
`[ZyfaiSDK] ${methodName}() is deprecated for partner integrations. Prefer
|
|
1622
|
+
`[ZyfaiSDK] ${methodName}() is deprecated for partner integrations. Prefer sendDeposit() \u2014 predeployed Safes and session keys are handled automatically on first deposit.`
|
|
1435
1623
|
);
|
|
1436
1624
|
}
|
|
1437
1625
|
/**
|
|
@@ -1458,8 +1646,8 @@ var _ZyfaiSDK = class _ZyfaiSDK {
|
|
|
1458
1646
|
uri = globalWindow.location.origin;
|
|
1459
1647
|
domain = globalWindow.location.host;
|
|
1460
1648
|
} else {
|
|
1461
|
-
uri =
|
|
1462
|
-
domain =
|
|
1649
|
+
uri = this.executionApiUrl;
|
|
1650
|
+
domain = new URL(this.executionApiUrl).host;
|
|
1463
1651
|
}
|
|
1464
1652
|
const messageObj = new SiweMessage({
|
|
1465
1653
|
address: userAddress,
|
|
@@ -1529,33 +1717,37 @@ var _ZyfaiSDK = class _ZyfaiSDK {
|
|
|
1529
1717
|
if (request.strategy) {
|
|
1530
1718
|
if (!isValidPublicStrategy(request.strategy)) {
|
|
1531
1719
|
throw new Error(
|
|
1532
|
-
`Invalid strategy: ${request.strategy}. Must be "conservative" or "
|
|
1720
|
+
`Invalid strategy: ${request.strategy}. Must be "conservative", "aggressive" or "yieldmaxxing".`
|
|
1533
1721
|
);
|
|
1534
1722
|
}
|
|
1535
|
-
rebalanceStrategy = toInternalStrategy(
|
|
1536
|
-
request.strategy
|
|
1537
|
-
);
|
|
1723
|
+
rebalanceStrategy = toInternalStrategy(request.strategy);
|
|
1538
1724
|
}
|
|
1539
1725
|
const assetSettings = {};
|
|
1540
|
-
if (rebalanceStrategy !== void 0)
|
|
1541
|
-
|
|
1542
|
-
if (request.
|
|
1543
|
-
|
|
1544
|
-
if (request.
|
|
1726
|
+
if (rebalanceStrategy !== void 0)
|
|
1727
|
+
assetSettings.rebalanceStrategy = rebalanceStrategy;
|
|
1728
|
+
if (request.autocompounding !== void 0)
|
|
1729
|
+
assetSettings.autocompounding = request.autocompounding;
|
|
1730
|
+
if (request.crosschainStrategy !== void 0)
|
|
1731
|
+
assetSettings.crosschainStrategy = request.crosschainStrategy;
|
|
1732
|
+
if (request.splitting !== void 0)
|
|
1733
|
+
assetSettings.splitting = request.splitting;
|
|
1734
|
+
if (request.minSplits !== void 0)
|
|
1735
|
+
assetSettings.minSplits = request.minSplits;
|
|
1545
1736
|
if (request.chains !== void 0) assetSettings.chains = request.chains;
|
|
1546
|
-
if (request.autoSelectProtocols !== void 0)
|
|
1547
|
-
|
|
1737
|
+
if (request.autoSelectProtocols !== void 0)
|
|
1738
|
+
assetSettings.autoSelectProtocols = request.autoSelectProtocols;
|
|
1739
|
+
if (request.protocols !== void 0)
|
|
1740
|
+
assetSettings.protocols = request.protocols;
|
|
1548
1741
|
const payload = {
|
|
1549
1742
|
assetTypeSettings: {
|
|
1550
1743
|
[internalAsset]: assetSettings
|
|
1551
1744
|
}
|
|
1552
1745
|
};
|
|
1553
|
-
if (request.omniAccount !== void 0)
|
|
1554
|
-
|
|
1555
|
-
|
|
1556
|
-
|
|
1557
|
-
|
|
1558
|
-
);
|
|
1746
|
+
if (request.omniAccount !== void 0)
|
|
1747
|
+
payload.omniAccount = request.omniAccount;
|
|
1748
|
+
if (request.agentName !== void 0)
|
|
1749
|
+
payload.agentName = request.agentName;
|
|
1750
|
+
await this.httpClient.patch(ENDPOINTS.USER_ME, payload);
|
|
1559
1751
|
return await this.getUserDetails(asset);
|
|
1560
1752
|
} catch (error) {
|
|
1561
1753
|
throw new Error(
|
|
@@ -1583,19 +1775,14 @@ var _ZyfaiSDK = class _ZyfaiSDK {
|
|
|
1583
1775
|
*/
|
|
1584
1776
|
async pauseAgent() {
|
|
1585
1777
|
try {
|
|
1586
|
-
|
|
1587
|
-
|
|
1588
|
-
protocols: []
|
|
1589
|
-
}
|
|
1590
|
-
|
|
1591
|
-
|
|
1592
|
-
|
|
1593
|
-
|
|
1594
|
-
const response = await this.updateUserProfile({
|
|
1595
|
-
asset: "EURC",
|
|
1596
|
-
protocols: []
|
|
1597
|
-
});
|
|
1598
|
-
return response;
|
|
1778
|
+
let latest;
|
|
1779
|
+
for (const asset of MANAGED_ASSETS) {
|
|
1780
|
+
latest = await this.updateUserProfile({ asset, protocols: [] });
|
|
1781
|
+
}
|
|
1782
|
+
if (!latest) {
|
|
1783
|
+
throw new Error("No supported assets to pause");
|
|
1784
|
+
}
|
|
1785
|
+
return latest;
|
|
1599
1786
|
} catch (error) {
|
|
1600
1787
|
throw new Error(`Failed to pause agent: ${error.message}`);
|
|
1601
1788
|
}
|
|
@@ -1620,46 +1807,22 @@ var _ZyfaiSDK = class _ZyfaiSDK {
|
|
|
1620
1807
|
*/
|
|
1621
1808
|
async resumeAgent() {
|
|
1622
1809
|
try {
|
|
1623
|
-
const userDetailsUSDC = await this.getUserDetails("USDC");
|
|
1624
|
-
const userDetailsETH = await this.getUserDetails("WETH");
|
|
1625
|
-
const userDetailsEURC = await this.getUserDetails("EURC");
|
|
1626
|
-
const chains = userDetailsUSDC.chains && userDetailsUSDC.chains.length > 0 ? userDetailsUSDC.chains : [8453, 42161];
|
|
1627
|
-
const eurcChains = userDetailsEURC.chains && userDetailsEURC.chains.length > 0 ? userDetailsEURC.chains.filter((c) => c === 1 || c === 8453) : [1, 8453];
|
|
1628
1810
|
const allProtocols = await this.httpClient.get(
|
|
1629
1811
|
ENDPOINTS.PROTOCOLS()
|
|
1630
1812
|
);
|
|
1631
|
-
|
|
1632
|
-
const
|
|
1633
|
-
|
|
1634
|
-
|
|
1635
|
-
|
|
1636
|
-
|
|
1637
|
-
|
|
1638
|
-
|
|
1639
|
-
|
|
1640
|
-
|
|
1641
|
-
|
|
1642
|
-
|
|
1643
|
-
|
|
1644
|
-
}
|
|
1645
|
-
return protocol.strategies?.includes("safe_strategy");
|
|
1646
|
-
}).map((protocol) => protocol.id);
|
|
1647
|
-
};
|
|
1648
|
-
const usdcProtocols = filterProtocolsByStrategy(usdcStrategy, chains);
|
|
1649
|
-
const ethProtocols = filterProtocolsByStrategy(ethStrategy, chains);
|
|
1650
|
-
const eurcProtocols = filterProtocolsByStrategy(eurcStrategy, eurcChains);
|
|
1651
|
-
await this.updateUserProfile({
|
|
1652
|
-
asset: "USDC",
|
|
1653
|
-
protocols: usdcProtocols
|
|
1654
|
-
});
|
|
1655
|
-
await this.updateUserProfile({
|
|
1656
|
-
asset: "WETH",
|
|
1657
|
-
protocols: ethProtocols
|
|
1658
|
-
});
|
|
1659
|
-
return await this.updateUserProfile({
|
|
1660
|
-
asset: "EURC",
|
|
1661
|
-
protocols: eurcProtocols
|
|
1662
|
-
});
|
|
1813
|
+
let latest;
|
|
1814
|
+
for (const asset of MANAGED_ASSETS) {
|
|
1815
|
+
latest = await this.updateUserProtocolsForAsset(
|
|
1816
|
+
asset,
|
|
1817
|
+
getAssetChainIds(asset),
|
|
1818
|
+
void 0,
|
|
1819
|
+
allProtocols
|
|
1820
|
+
);
|
|
1821
|
+
}
|
|
1822
|
+
if (!latest) {
|
|
1823
|
+
throw new Error("No supported assets to resume");
|
|
1824
|
+
}
|
|
1825
|
+
return latest;
|
|
1663
1826
|
} catch (error) {
|
|
1664
1827
|
throw new Error(`Failed to resume agent: ${error.message}`);
|
|
1665
1828
|
}
|
|
@@ -1694,7 +1857,9 @@ var _ZyfaiSDK = class _ZyfaiSDK {
|
|
|
1694
1857
|
});
|
|
1695
1858
|
return response;
|
|
1696
1859
|
} catch (error) {
|
|
1697
|
-
throw new Error(
|
|
1860
|
+
throw new Error(
|
|
1861
|
+
`Failed to enable splitting: ${error.message}`
|
|
1862
|
+
);
|
|
1698
1863
|
}
|
|
1699
1864
|
}
|
|
1700
1865
|
/**
|
|
@@ -1722,7 +1887,9 @@ var _ZyfaiSDK = class _ZyfaiSDK {
|
|
|
1722
1887
|
});
|
|
1723
1888
|
return response;
|
|
1724
1889
|
} catch (error) {
|
|
1725
|
-
throw new Error(
|
|
1890
|
+
throw new Error(
|
|
1891
|
+
`Failed to disable splitting: ${error.message}`
|
|
1892
|
+
);
|
|
1726
1893
|
}
|
|
1727
1894
|
}
|
|
1728
1895
|
/**
|
|
@@ -1754,7 +1921,9 @@ var _ZyfaiSDK = class _ZyfaiSDK {
|
|
|
1754
1921
|
});
|
|
1755
1922
|
return response;
|
|
1756
1923
|
} catch (error) {
|
|
1757
|
-
throw new Error(
|
|
1924
|
+
throw new Error(
|
|
1925
|
+
`Failed to update min splits: ${error.message}`
|
|
1926
|
+
);
|
|
1758
1927
|
}
|
|
1759
1928
|
}
|
|
1760
1929
|
/**
|
|
@@ -2052,20 +2221,21 @@ var _ZyfaiSDK = class _ZyfaiSDK {
|
|
|
2052
2221
|
/**
|
|
2053
2222
|
* Deploy Safe Smart Wallet for a user
|
|
2054
2223
|
*
|
|
2055
|
-
* @deprecated Prefer `
|
|
2224
|
+
* @deprecated Prefer `sendDeposit()`. Predeployed Safes and session keys are
|
|
2056
2225
|
* managed automatically on first deposit. This method remains available for
|
|
2057
2226
|
* legacy flows.
|
|
2058
2227
|
*
|
|
2059
2228
|
* @param userAddress - User's EOA address (the connected EOA, not the smart wallet address)
|
|
2060
2229
|
* @param chainId - Target chain ID
|
|
2061
|
-
* @param strategy - Optional strategy selection: "conservative" (default) or "
|
|
2230
|
+
* @param strategy - Optional strategy selection: "conservative" (default), "aggressive" or "yieldmaxxing"
|
|
2062
2231
|
* @param createSessionKey - If true, automatically creates a session key after deployment (default: false)
|
|
2063
2232
|
* @returns Deployment response with Safe address and transaction hash
|
|
2064
2233
|
*
|
|
2065
2234
|
* @example
|
|
2066
2235
|
* ```typescript
|
|
2067
|
-
* // Preferred:
|
|
2068
|
-
* await sdk.
|
|
2236
|
+
* // Preferred: sendDeposit handles predeployed wallet onboarding
|
|
2237
|
+
* const sent = await sdk.sendDeposit(userAddress, 8453, amount, "USDC");
|
|
2238
|
+
* await sdk.waitForDepositCredit(sent.registration.id, 8453);
|
|
2069
2239
|
*
|
|
2070
2240
|
* // Legacy: deploy with default conservative strategy
|
|
2071
2241
|
* await sdk.deploySafe(userAddress, 8453);
|
|
@@ -2183,7 +2353,7 @@ var _ZyfaiSDK = class _ZyfaiSDK {
|
|
|
2183
2353
|
} catch (error) {
|
|
2184
2354
|
console.error("Safe deployment failed:", error);
|
|
2185
2355
|
throw new Error(
|
|
2186
|
-
`Safe deployment failed: ${error.message}. deploySafe() is deprecated \u2014 prefer
|
|
2356
|
+
`Safe deployment failed: ${error.message}. deploySafe() is deprecated \u2014 prefer sendDeposit() for predeployed wallet onboarding.`
|
|
2187
2357
|
);
|
|
2188
2358
|
}
|
|
2189
2359
|
}
|
|
@@ -2191,7 +2361,7 @@ var _ZyfaiSDK = class _ZyfaiSDK {
|
|
|
2191
2361
|
* Create session key with auto-fetched configuration from Zyfai API
|
|
2192
2362
|
* This is the simplified method that automatically fetches session configuration
|
|
2193
2363
|
*
|
|
2194
|
-
* @deprecated Prefer `
|
|
2364
|
+
* @deprecated Prefer `sendDeposit()`. Predeployed wallets already have the
|
|
2195
2365
|
* agent session enabled; session activation is handled after first deposit.
|
|
2196
2366
|
* This method remains available for legacy flows.
|
|
2197
2367
|
*
|
|
@@ -2201,8 +2371,9 @@ var _ZyfaiSDK = class _ZyfaiSDK {
|
|
|
2201
2371
|
*
|
|
2202
2372
|
* @example
|
|
2203
2373
|
* ```typescript
|
|
2204
|
-
* // Preferred:
|
|
2205
|
-
* await sdk.
|
|
2374
|
+
* // Preferred: sendDeposit handles session onboarding for predeployed wallets
|
|
2375
|
+
* const sent = await sdk.sendDeposit(userAddress, 8453, amount, "USDC");
|
|
2376
|
+
* await sdk.waitForDepositCredit(sent.registration.id, 8453);
|
|
2206
2377
|
*
|
|
2207
2378
|
* // Legacy:
|
|
2208
2379
|
* const result = await sdk.createSessionKey(userAddress, 8453);
|
|
@@ -2283,7 +2454,7 @@ var _ZyfaiSDK = class _ZyfaiSDK {
|
|
|
2283
2454
|
};
|
|
2284
2455
|
} catch (error) {
|
|
2285
2456
|
throw new Error(
|
|
2286
|
-
`Failed to create session key: ${error.message}. createSessionKey() is deprecated \u2014 prefer
|
|
2457
|
+
`Failed to create session key: ${error.message}. createSessionKey() is deprecated \u2014 prefer sendDeposit() for predeployed wallet onboarding.`
|
|
2287
2458
|
);
|
|
2288
2459
|
}
|
|
2289
2460
|
}
|
|
@@ -2350,34 +2521,46 @@ var _ZyfaiSDK = class _ZyfaiSDK {
|
|
|
2350
2521
|
* asset/chain/strategy combo.
|
|
2351
2522
|
* 4. Persist via `updateUserProfile` (writes `assetTypeSettings`).
|
|
2352
2523
|
*
|
|
2353
|
-
* Called from `deploySafe` after every path, and from `
|
|
2524
|
+
* Called from `deploySafe` after every path, and from `sendDeposit` on
|
|
2354
2525
|
* the account's first deposit (when USDC chains are still empty).
|
|
2355
2526
|
*
|
|
2356
2527
|
* @internal
|
|
2357
2528
|
*/
|
|
2358
|
-
async updateUserProtocols(strategy) {
|
|
2529
|
+
async updateUserProtocols(strategy, options) {
|
|
2530
|
+
const strict = options?.strict ?? false;
|
|
2531
|
+
const assetErrors = [];
|
|
2359
2532
|
try {
|
|
2360
2533
|
const allProtocols = await this.httpClient.get(
|
|
2361
2534
|
ENDPOINTS.PROTOCOLS()
|
|
2362
2535
|
);
|
|
2363
|
-
const
|
|
2364
|
-
const assets = ["USDC", "WETH", "EURC"];
|
|
2365
|
-
for (const asset of assets) {
|
|
2536
|
+
for (const asset of MANAGED_ASSETS) {
|
|
2366
2537
|
try {
|
|
2367
|
-
const chainsForAsset = asset === "EURC" ? [1, 8453] : allChains;
|
|
2368
2538
|
await this.updateUserProtocolsForAsset(
|
|
2369
2539
|
asset,
|
|
2370
|
-
|
|
2540
|
+
getAssetChainIds(asset),
|
|
2371
2541
|
strategy,
|
|
2372
2542
|
allProtocols
|
|
2373
2543
|
);
|
|
2374
2544
|
} catch (assetError) {
|
|
2375
|
-
|
|
2376
|
-
|
|
2377
|
-
|
|
2545
|
+
const message = assetError.message;
|
|
2546
|
+
if (strict) {
|
|
2547
|
+
assetErrors.push(`${asset}: ${message}`);
|
|
2548
|
+
} else {
|
|
2549
|
+
console.warn(`Failed to update ${asset} protocols: ${message}`);
|
|
2550
|
+
}
|
|
2378
2551
|
}
|
|
2379
2552
|
}
|
|
2553
|
+
if (strict && assetErrors.length > 0) {
|
|
2554
|
+
throw new Error(
|
|
2555
|
+
`Failed to configure user protocols for first deposit: ${assetErrors.join(
|
|
2556
|
+
"; "
|
|
2557
|
+
)}`
|
|
2558
|
+
);
|
|
2559
|
+
}
|
|
2380
2560
|
} catch (error) {
|
|
2561
|
+
if (strict) {
|
|
2562
|
+
throw error;
|
|
2563
|
+
}
|
|
2381
2564
|
console.warn(
|
|
2382
2565
|
`Failed to update user protocols: ${error.message}`
|
|
2383
2566
|
);
|
|
@@ -2404,27 +2587,100 @@ var _ZyfaiSDK = class _ZyfaiSDK {
|
|
|
2404
2587
|
const withPools = await this.filterProtocolIdsWithPools(
|
|
2405
2588
|
matching,
|
|
2406
2589
|
effectiveChains,
|
|
2407
|
-
asset
|
|
2590
|
+
asset,
|
|
2591
|
+
internalStrategy
|
|
2408
2592
|
);
|
|
2409
|
-
await this.updateUserProfile({
|
|
2593
|
+
return await this.updateUserProfile({
|
|
2410
2594
|
asset,
|
|
2411
2595
|
protocols: withPools,
|
|
2412
|
-
chains: effectiveChains
|
|
2596
|
+
chains: effectiveChains,
|
|
2597
|
+
...strategy !== void 0 && { strategy }
|
|
2413
2598
|
});
|
|
2414
2599
|
}
|
|
2600
|
+
/**
|
|
2601
|
+
* Switch one asset to a strategy and select the protocols that go with it.
|
|
2602
|
+
*
|
|
2603
|
+
* `updateUserProfile` stores a strategy but does not compute a protocol
|
|
2604
|
+
* list, so on its own it leaves the asset with nothing to deploy into. This
|
|
2605
|
+
* method does both in one call: it resolves the protocols that support the
|
|
2606
|
+
* asset on the requested chains under the requested strategy, drops those
|
|
2607
|
+
* with no pool available, and persists strategy, chains and protocols
|
|
2608
|
+
* together.
|
|
2609
|
+
*
|
|
2610
|
+
* Mostly needed for assets that are not set up by the account's first
|
|
2611
|
+
* deposit, or to change an existing account's strategy — `sendDeposit`
|
|
2612
|
+
* ignores its `strategy` argument after the first deposit.
|
|
2613
|
+
*
|
|
2614
|
+
* @param params.asset - Asset to configure
|
|
2615
|
+
* @param params.strategy - Strategy to apply; defaults to the one already
|
|
2616
|
+
* stored for this asset (`"conservative"` on a fresh account), which lets
|
|
2617
|
+
* you recompute a protocol list without changing the strategy
|
|
2618
|
+
* @param params.chains - Chains to enable. Defaults to every chain the asset
|
|
2619
|
+
* exists on. **Additive**: chains already enabled are kept, so this cannot
|
|
2620
|
+
* be used to disable one.
|
|
2621
|
+
* @returns The updated profile for that asset
|
|
2622
|
+
*
|
|
2623
|
+
* @example
|
|
2624
|
+
* ```typescript
|
|
2625
|
+
* // NVDAc only lives in async protocols, so it needs "yieldmaxxing".
|
|
2626
|
+
* // Chains default to Base, the only chain it exists on.
|
|
2627
|
+
* const profile = await sdk.setAssetStrategy({
|
|
2628
|
+
* asset: "NVDAc",
|
|
2629
|
+
* strategy: "yieldmaxxing",
|
|
2630
|
+
* });
|
|
2631
|
+
* console.log(profile.protocols); // Ipor + Superform
|
|
2632
|
+
* ```
|
|
2633
|
+
*/
|
|
2634
|
+
async setAssetStrategy(params) {
|
|
2635
|
+
const { asset, strategy, chains } = params;
|
|
2636
|
+
try {
|
|
2637
|
+
if (strategy !== void 0 && !isValidPublicStrategy(strategy)) {
|
|
2638
|
+
throw new Error(
|
|
2639
|
+
`Invalid strategy: ${strategy}. Must be "conservative", "aggressive" or "yieldmaxxing".`
|
|
2640
|
+
);
|
|
2641
|
+
}
|
|
2642
|
+
const supported = getAssetChainIds(asset);
|
|
2643
|
+
if (supported.length === 0) {
|
|
2644
|
+
throw new Error(`Unsupported asset: ${asset}.`);
|
|
2645
|
+
}
|
|
2646
|
+
const targetChains = chains ?? supported;
|
|
2647
|
+
const unsupported = targetChains.filter((c) => !supported.includes(c));
|
|
2648
|
+
if (unsupported.length > 0) {
|
|
2649
|
+
throw new Error(
|
|
2650
|
+
`${asset} is not available on chain ${unsupported.join(
|
|
2651
|
+
", "
|
|
2652
|
+
)}. Supported chains: ${supported.join(", ")}.`
|
|
2653
|
+
);
|
|
2654
|
+
}
|
|
2655
|
+
const allProtocols = await this.httpClient.get(
|
|
2656
|
+
ENDPOINTS.PROTOCOLS()
|
|
2657
|
+
);
|
|
2658
|
+
return await this.updateUserProtocolsForAsset(
|
|
2659
|
+
asset,
|
|
2660
|
+
targetChains,
|
|
2661
|
+
strategy,
|
|
2662
|
+
allProtocols
|
|
2663
|
+
);
|
|
2664
|
+
} catch (error) {
|
|
2665
|
+
throw new Error(
|
|
2666
|
+
`Failed to set ${asset} strategy: ${error.message}`
|
|
2667
|
+
);
|
|
2668
|
+
}
|
|
2669
|
+
}
|
|
2415
2670
|
/**
|
|
2416
2671
|
* Drop protocols that have no pools on any of the selected chains for the
|
|
2417
|
-
* requested asset.
|
|
2418
|
-
*
|
|
2419
|
-
*
|
|
2672
|
+
* requested asset. The /customization/pools endpoint filters server-side on
|
|
2673
|
+
* the strategy, and each tier is a superset of the previous one, so the
|
|
2674
|
+
* caller's strategy must be passed through — asking for `degen_strategy`
|
|
2675
|
+
* returns an empty pool set for async-only assets.
|
|
2420
2676
|
* @internal
|
|
2421
2677
|
*/
|
|
2422
|
-
async filterProtocolIdsWithPools(protocolIds, chains, asset) {
|
|
2678
|
+
async filterProtocolIdsWithPools(protocolIds, chains, asset, internalStrategy = "degen_strategy") {
|
|
2423
2679
|
if (protocolIds.length === 0) return [];
|
|
2424
2680
|
const results = await Promise.allSettled(
|
|
2425
2681
|
protocolIds.map(async (id) => {
|
|
2426
2682
|
const poolsData = await this.httpClient.get(
|
|
2427
|
-
ENDPOINTS.CUSTOMIZATION_POOLS(id,
|
|
2683
|
+
ENDPOINTS.CUSTOMIZATION_POOLS(id, internalStrategy)
|
|
2428
2684
|
);
|
|
2429
2685
|
return { id, hasPool: hasMatchingPool(poolsData, chains, asset) };
|
|
2430
2686
|
})
|
|
@@ -2465,47 +2721,6 @@ var _ZyfaiSDK = class _ZyfaiSDK {
|
|
|
2465
2721
|
return value;
|
|
2466
2722
|
});
|
|
2467
2723
|
}
|
|
2468
|
-
/**
|
|
2469
|
-
* Deposit funds from EOA to Safe smart wallet
|
|
2470
|
-
* Transfers tokens from the connected wallet to the user's Safe and logs the deposit
|
|
2471
|
-
*
|
|
2472
|
-
* Token address is selected from `asset` for the given chain:
|
|
2473
|
-
* - Ethereum Mainnet (1), Base (8453), Arbitrum (42161): USDC or WETH
|
|
2474
|
-
* - Ethereum Mainnet (1), Base (8453): EURC
|
|
2475
|
-
*
|
|
2476
|
-
* On the account's first deposit (USDC profile has no chains yet), patches
|
|
2477
|
-
* protocol selection for USDC, WETH, and EURC across all supported chains
|
|
2478
|
-
* (EURC on Mainnet/Base only) before the transfer and log_deposit.
|
|
2479
|
-
* Pass `strategy` to select protocols for that first-deposit setup
|
|
2480
|
-
* (same role as the former `deploySafe` strategy argument).
|
|
2481
|
-
*
|
|
2482
|
-
* Minimum portfolio balance enforced (Safe balance + deposit amount):
|
|
2483
|
-
* - Stablecoins: `MIN_PORTFOLIO_BALANCE` (Mainnet 10,000 USDC/EURC; Base/Arbitrum 100)
|
|
2484
|
-
* - WETH: about $10,000 on Mainnet, $100 on Base/Arbitrum, from Data API `/price?token=eth`
|
|
2485
|
-
*
|
|
2486
|
-
* @param userAddress - User's address (owner of the Safe)
|
|
2487
|
-
* @param chainId - Target chain ID
|
|
2488
|
-
* @param amount - Amount in least decimal units (e.g., "100000000" for 100 USDC with 6 decimals)
|
|
2489
|
-
* @param asset - Asset symbol: "USDC", "WETH", or "EURC".
|
|
2490
|
-
* EURC is supported on Ethereum Mainnet and Base only.
|
|
2491
|
-
* @param strategy - Optional strategy for first-deposit protocol patching:
|
|
2492
|
-
* "conservative" (default) or "aggressive"
|
|
2493
|
-
* @returns Deposit response with transaction hash
|
|
2494
|
-
*
|
|
2495
|
-
* @example
|
|
2496
|
-
* ```typescript
|
|
2497
|
-
* // Deposit 10,000 USDC (6 decimals) to Safe on Base
|
|
2498
|
-
* const result = await sdk.depositFunds(
|
|
2499
|
-
* "0xUser...",
|
|
2500
|
-
* 8453,
|
|
2501
|
-
* "10000000000",
|
|
2502
|
-
* "USDC"
|
|
2503
|
-
* );
|
|
2504
|
-
*
|
|
2505
|
-
* // First deposit with aggressive strategy
|
|
2506
|
-
* await sdk.depositFunds(userAddress, 8453, "10000000000", "USDC", "aggressive");
|
|
2507
|
-
* ```
|
|
2508
|
-
*/
|
|
2509
2724
|
/**
|
|
2510
2725
|
* Deploy the connected predeployed (pool) wallet on one or more chains.
|
|
2511
2726
|
*
|
|
@@ -2516,7 +2731,7 @@ var _ZyfaiSDK = class _ZyfaiSDK {
|
|
|
2516
2731
|
* resolves once all requested chains have landed on-chain. Idempotent — chains
|
|
2517
2732
|
* already deployed are a no-op.
|
|
2518
2733
|
*
|
|
2519
|
-
* Optional for deposits: `
|
|
2734
|
+
* Optional for deposits: `sendDeposit` no longer pre-deploys the target chain — the ERC20
|
|
2520
2735
|
* transfer lands on the counterfactual address and the backend deploys + hands over on first
|
|
2521
2736
|
* deposit (report-deposit). Use this only to pre-provision chains ahead of time.
|
|
2522
2737
|
*
|
|
@@ -2532,7 +2747,13 @@ var _ZyfaiSDK = class _ZyfaiSDK {
|
|
|
2532
2747
|
await this.authenticateUser();
|
|
2533
2748
|
return this.httpClient.post(ENDPOINTS.DEPLOY_CHAINS, { chainIds });
|
|
2534
2749
|
}
|
|
2535
|
-
|
|
2750
|
+
/**
|
|
2751
|
+
* Send a deposit from an EOA to its Safe smart wallet.
|
|
2752
|
+
*
|
|
2753
|
+
* Confirms the ERC-20 transfer and starts the custody-credit lifecycle. Use
|
|
2754
|
+
* `waitForDepositCredit(result.registration.id, chainId)` to await credit.
|
|
2755
|
+
*/
|
|
2756
|
+
async sendDeposit(userAddress, chainId, amount, asset, strategy) {
|
|
2536
2757
|
try {
|
|
2537
2758
|
if (!userAddress) {
|
|
2538
2759
|
throw new Error("User address is required");
|
|
@@ -2548,37 +2769,54 @@ var _ZyfaiSDK = class _ZyfaiSDK {
|
|
|
2548
2769
|
}
|
|
2549
2770
|
if (strategy !== void 0 && !isValidPublicStrategy(strategy)) {
|
|
2550
2771
|
throw new Error(
|
|
2551
|
-
`Invalid strategy: ${strategy}. Must be "conservative" or "
|
|
2772
|
+
`Invalid strategy: ${strategy}. Must be "conservative", "aggressive" or "yieldmaxxing".`
|
|
2552
2773
|
);
|
|
2553
2774
|
}
|
|
2554
|
-
const assetSymbol = asset
|
|
2775
|
+
const assetSymbol = resolveAssetSymbol(asset);
|
|
2555
2776
|
const assetConfig = ASSET_CONFIGS[assetSymbol];
|
|
2556
|
-
|
|
2777
|
+
const assetChains = getAssetChainIds(assetSymbol);
|
|
2778
|
+
if (!assetChains.includes(chainId)) {
|
|
2557
2779
|
throw new Error(
|
|
2558
|
-
|
|
2559
|
-
|
|
2560
|
-
|
|
2561
|
-
let minRequired = MIN_PORTFOLIO_BALANCE[chainId]?.[assetSymbol];
|
|
2562
|
-
if (assetSymbol === "WETH") {
|
|
2563
|
-
const priceResponse = await this.httpClient.dataGet(
|
|
2564
|
-
DATA_ENDPOINTS.TOKEN_PRICE("eth")
|
|
2565
|
-
);
|
|
2566
|
-
minRequired = minWethWeiForUsd(
|
|
2567
|
-
parseEthUsdPrice(priceResponse),
|
|
2568
|
-
MIN_WETH_USD[chainId]
|
|
2780
|
+
`${assetSymbol} is not available on chain ${chainId}. Supported chains: ${assetChains.join(
|
|
2781
|
+
", "
|
|
2782
|
+
)}.`
|
|
2569
2783
|
);
|
|
2570
2784
|
}
|
|
2785
|
+
let minRequired = this.bypassMinPortfolio ? void 0 : MIN_PORTFOLIO_BALANCE[chainId]?.[assetSymbol];
|
|
2786
|
+
const minUsd = this.bypassMinPortfolio ? void 0 : MIN_PORTFOLIO_USD[chainId]?.[assetSymbol];
|
|
2571
2787
|
const token = getDefaultTokenAddress(chainId, assetSymbol);
|
|
2572
2788
|
const walletClient = this.getWalletClient();
|
|
2573
2789
|
const chainConfig = getChainConfig(chainId, this.rpcUrls);
|
|
2790
|
+
if (minUsd !== void 0) {
|
|
2791
|
+
const [, priceResponse] = await Promise.all([
|
|
2792
|
+
this.authenticateUser(),
|
|
2793
|
+
this.httpClient.dataGet(
|
|
2794
|
+
DATA_ENDPOINTS.TOKEN_PRICE(assetConfig.priceTokenSymbol)
|
|
2795
|
+
)
|
|
2796
|
+
]);
|
|
2797
|
+
minRequired = usdToTokenUnits(
|
|
2798
|
+
minUsd,
|
|
2799
|
+
parseTokenUsdPrice(priceResponse),
|
|
2800
|
+
assetConfig.decimals
|
|
2801
|
+
);
|
|
2802
|
+
} else {
|
|
2803
|
+
await this.authenticateUser();
|
|
2804
|
+
}
|
|
2574
2805
|
const safeAddress = await this.getSafeAddressFor(userAddress, chainId);
|
|
2575
2806
|
if (!safeAddress) {
|
|
2576
2807
|
throw new Error("Smart wallet address is not available");
|
|
2577
2808
|
}
|
|
2578
|
-
const
|
|
2579
|
-
|
|
2580
|
-
chainConfig.publicClient
|
|
2581
|
-
|
|
2809
|
+
const amountBigInt = BigInt(amount);
|
|
2810
|
+
const [isDeployed, currentSafeBalance] = await Promise.all([
|
|
2811
|
+
isSafeDeployed(safeAddress, chainConfig.publicClient),
|
|
2812
|
+
minRequired !== void 0 ? chainConfig.publicClient.readContract({
|
|
2813
|
+
address: token,
|
|
2814
|
+
abi: ERC20_ABI,
|
|
2815
|
+
functionName: "balanceOf",
|
|
2816
|
+
args: [safeAddress]
|
|
2817
|
+
}) : Promise.resolve(void 0),
|
|
2818
|
+
this.prepareFirstDeposit(strategy)
|
|
2819
|
+
]).then(([deployed, balance]) => [deployed, balance]);
|
|
2582
2820
|
if (!isDeployed) {
|
|
2583
2821
|
if (!(this.isPredeployed && this.isConnectedUser(userAddress))) {
|
|
2584
2822
|
throw new Error(
|
|
@@ -2586,26 +2824,9 @@ var _ZyfaiSDK = class _ZyfaiSDK {
|
|
|
2586
2824
|
);
|
|
2587
2825
|
}
|
|
2588
2826
|
}
|
|
2589
|
-
try {
|
|
2590
|
-
const usdcDetails = await this.getUserDetails("USDC");
|
|
2591
|
-
if ((usdcDetails.chains?.length ?? 0) === 0) {
|
|
2592
|
-
await this.updateUserProtocols(strategy);
|
|
2593
|
-
}
|
|
2594
|
-
} catch (protocolError) {
|
|
2595
|
-
console.warn(
|
|
2596
|
-
"Failed to update user protocols before deposit:",
|
|
2597
|
-
protocolError.message
|
|
2598
|
-
);
|
|
2599
|
-
}
|
|
2600
|
-
const amountBigInt = BigInt(amount);
|
|
2601
2827
|
if (minRequired !== void 0) {
|
|
2602
|
-
const
|
|
2603
|
-
|
|
2604
|
-
abi: ERC20_ABI,
|
|
2605
|
-
functionName: "balanceOf",
|
|
2606
|
-
args: [safeAddress]
|
|
2607
|
-
});
|
|
2608
|
-
const totalAfterDeposit = currentSafeBalance + amountBigInt;
|
|
2828
|
+
const safeBalance = currentSafeBalance;
|
|
2829
|
+
const totalAfterDeposit = safeBalance + amountBigInt;
|
|
2609
2830
|
if (totalAfterDeposit < minRequired) {
|
|
2610
2831
|
const minLabel = formatMinPortfolioLabel(
|
|
2611
2832
|
minRequired,
|
|
@@ -2613,7 +2834,7 @@ var _ZyfaiSDK = class _ZyfaiSDK {
|
|
|
2613
2834
|
assetSymbol
|
|
2614
2835
|
);
|
|
2615
2836
|
throw new Error(
|
|
2616
|
-
`Minimum portfolio balance not met on chain ${chainId}. Total portfolio must be at least ${minLabel}. Current Safe balance: ${
|
|
2837
|
+
`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).`
|
|
2617
2838
|
);
|
|
2618
2839
|
}
|
|
2619
2840
|
}
|
|
@@ -2628,38 +2849,220 @@ var _ZyfaiSDK = class _ZyfaiSDK {
|
|
|
2628
2849
|
const receipt = await chainConfig.publicClient.waitForTransactionReceipt({
|
|
2629
2850
|
hash: txHash
|
|
2630
2851
|
});
|
|
2631
|
-
try {
|
|
2632
|
-
await this.httpClient.post(ENDPOINTS.LOG_DEPOSIT, {
|
|
2633
|
-
chainId,
|
|
2634
|
-
transaction: txHash,
|
|
2635
|
-
token,
|
|
2636
|
-
amount
|
|
2637
|
-
});
|
|
2638
|
-
} catch (logError) {
|
|
2639
|
-
console.warn("Failed to log deposit:", logError.message);
|
|
2640
|
-
}
|
|
2641
2852
|
if (receipt.status !== "success") {
|
|
2642
2853
|
throw new Error("Deposit transaction failed");
|
|
2643
2854
|
}
|
|
2855
|
+
const registration = await this.registerDeposit(
|
|
2856
|
+
chainId,
|
|
2857
|
+
txHash,
|
|
2858
|
+
amount,
|
|
2859
|
+
token
|
|
2860
|
+
);
|
|
2644
2861
|
return {
|
|
2645
2862
|
success: true,
|
|
2646
2863
|
txHash,
|
|
2647
2864
|
smartWallet: safeAddress,
|
|
2648
|
-
amount: amountBigInt.toString()
|
|
2865
|
+
amount: amountBigInt.toString(),
|
|
2866
|
+
registration
|
|
2649
2867
|
};
|
|
2650
2868
|
} catch (error) {
|
|
2651
2869
|
throw new Error(`Deposit failed: ${error.message}`);
|
|
2652
2870
|
}
|
|
2653
2871
|
}
|
|
2872
|
+
/**
|
|
2873
|
+
* @deprecated Compatibility convenience method. Prefer `sendDeposit()` followed by
|
|
2874
|
+
* `waitForDepositCredit()` when the caller owns the completion UX.
|
|
2875
|
+
*/
|
|
2876
|
+
async depositFunds(userAddress, chainId, amount, asset, strategy) {
|
|
2877
|
+
this.warnDeprecatedOnboardingMethod("depositFunds");
|
|
2878
|
+
const sent = await this.sendDeposit(
|
|
2879
|
+
userAddress,
|
|
2880
|
+
chainId,
|
|
2881
|
+
amount,
|
|
2882
|
+
asset,
|
|
2883
|
+
strategy
|
|
2884
|
+
);
|
|
2885
|
+
return {
|
|
2886
|
+
...sent,
|
|
2887
|
+
registration: await this.waitForDepositCredit(
|
|
2888
|
+
sent.registration.id,
|
|
2889
|
+
chainId
|
|
2890
|
+
)
|
|
2891
|
+
};
|
|
2892
|
+
}
|
|
2893
|
+
/**
|
|
2894
|
+
* Prepare ERC-20 transfer calldata for builders using a custom signer,
|
|
2895
|
+
* sponsored transaction provider, or mobile wallet. Most custom-wallet
|
|
2896
|
+
* integrations can compose this with `ensureFirstDepositSetup()` and
|
|
2897
|
+
* `logDeposit()` instead.
|
|
2898
|
+
*/
|
|
2899
|
+
async buildDepositTransfer(params) {
|
|
2900
|
+
const { userAddress, chainId, amount, asset } = params;
|
|
2901
|
+
if (!userAddress || !amount || BigInt(amount) <= 0n) {
|
|
2902
|
+
throw new Error("A user address and positive amount are required");
|
|
2903
|
+
}
|
|
2904
|
+
if (!isSupportedChain(chainId)) {
|
|
2905
|
+
throw new Error(`Unsupported chain ID: ${chainId}`);
|
|
2906
|
+
}
|
|
2907
|
+
const assetSymbol = resolveAssetSymbol(asset);
|
|
2908
|
+
const assetChains = getAssetChainIds(assetSymbol);
|
|
2909
|
+
if (!assetChains.includes(chainId)) {
|
|
2910
|
+
throw new Error(
|
|
2911
|
+
`${assetSymbol} is not available on chain ${chainId}. Supported chains: ${assetChains.join(
|
|
2912
|
+
", "
|
|
2913
|
+
)}.`
|
|
2914
|
+
);
|
|
2915
|
+
}
|
|
2916
|
+
const safeAddress = await this.getSafeAddressFor(userAddress, chainId);
|
|
2917
|
+
if (!safeAddress) {
|
|
2918
|
+
throw new Error("Smart wallet address is not available");
|
|
2919
|
+
}
|
|
2920
|
+
const chainConfig = getChainConfig(chainId, this.rpcUrls);
|
|
2921
|
+
const isDeployed = await isSafeDeployed(
|
|
2922
|
+
safeAddress,
|
|
2923
|
+
chainConfig.publicClient
|
|
2924
|
+
);
|
|
2925
|
+
if (!(isDeployed || this.isPredeployed && this.isConnectedUser(userAddress))) {
|
|
2926
|
+
throw new Error(
|
|
2927
|
+
`Safe not available for ${userAddress} on chain ${chainId}.`
|
|
2928
|
+
);
|
|
2929
|
+
}
|
|
2930
|
+
const amountBigInt = BigInt(amount);
|
|
2931
|
+
await this.enforceMinimumPortfolioBalance(
|
|
2932
|
+
chainId,
|
|
2933
|
+
asset,
|
|
2934
|
+
amountBigInt,
|
|
2935
|
+
safeAddress
|
|
2936
|
+
);
|
|
2937
|
+
const tokenAddress = getDefaultTokenAddress(
|
|
2938
|
+
chainId,
|
|
2939
|
+
assetSymbol
|
|
2940
|
+
);
|
|
2941
|
+
return {
|
|
2942
|
+
safeAddress,
|
|
2943
|
+
tokenAddress,
|
|
2944
|
+
to: tokenAddress,
|
|
2945
|
+
data: encodeFunctionData({
|
|
2946
|
+
abi: ERC20_ABI,
|
|
2947
|
+
functionName: "transfer",
|
|
2948
|
+
args: [safeAddress, amountBigInt]
|
|
2949
|
+
}),
|
|
2950
|
+
value: "0"
|
|
2951
|
+
};
|
|
2952
|
+
}
|
|
2953
|
+
/** Apply the same per-asset minimum portfolio rule as sendDeposit. */
|
|
2954
|
+
async enforceMinimumPortfolioBalance(chainId, asset, amount, safeAddress) {
|
|
2955
|
+
if (this.bypassMinPortfolio) {
|
|
2956
|
+
return;
|
|
2957
|
+
}
|
|
2958
|
+
const assetSymbol = resolveAssetSymbol(asset);
|
|
2959
|
+
const assetConfig = ASSET_CONFIGS[assetSymbol];
|
|
2960
|
+
let minRequired = MIN_PORTFOLIO_BALANCE[chainId]?.[assetSymbol];
|
|
2961
|
+
const minUsd = MIN_PORTFOLIO_USD[chainId]?.[assetSymbol];
|
|
2962
|
+
if (minUsd !== void 0) {
|
|
2963
|
+
const [, priceResponse] = await Promise.all([
|
|
2964
|
+
this.authenticateUser(),
|
|
2965
|
+
this.httpClient.dataGet(
|
|
2966
|
+
DATA_ENDPOINTS.TOKEN_PRICE(assetConfig.priceTokenSymbol)
|
|
2967
|
+
)
|
|
2968
|
+
]);
|
|
2969
|
+
minRequired = usdToTokenUnits(
|
|
2970
|
+
minUsd,
|
|
2971
|
+
parseTokenUsdPrice(priceResponse),
|
|
2972
|
+
assetConfig.decimals
|
|
2973
|
+
);
|
|
2974
|
+
}
|
|
2975
|
+
if (minRequired === void 0) return;
|
|
2976
|
+
const chainConfig = getChainConfig(chainId, this.rpcUrls);
|
|
2977
|
+
const token = getDefaultTokenAddress(chainId, assetSymbol);
|
|
2978
|
+
const currentSafeBalance = await chainConfig.publicClient.readContract({
|
|
2979
|
+
address: token,
|
|
2980
|
+
abi: ERC20_ABI,
|
|
2981
|
+
functionName: "balanceOf",
|
|
2982
|
+
args: [safeAddress]
|
|
2983
|
+
});
|
|
2984
|
+
const totalAfterDeposit = currentSafeBalance + amount;
|
|
2985
|
+
if (totalAfterDeposit < minRequired) {
|
|
2986
|
+
const minLabel = formatMinPortfolioLabel(
|
|
2987
|
+
minRequired,
|
|
2988
|
+
assetConfig.decimals,
|
|
2989
|
+
assetSymbol
|
|
2990
|
+
);
|
|
2991
|
+
throw new Error(
|
|
2992
|
+
`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).`
|
|
2993
|
+
);
|
|
2994
|
+
}
|
|
2995
|
+
}
|
|
2996
|
+
/**
|
|
2997
|
+
* Idempotently apply the first-deposit profile configuration for builders
|
|
2998
|
+
* composing an advanced custom transfer flow. Most custom-wallet
|
|
2999
|
+
* integrations can use this with `buildDepositTransfer()` and `logDeposit()`.
|
|
3000
|
+
*
|
|
3001
|
+
* When setup runs (`applied: true`), protocol configuration is persisted
|
|
3002
|
+
* before returning. Failures throw so callers can abort before submitting a
|
|
3003
|
+
* transfer. High-level deposit methods still treat setup as best-effort.
|
|
3004
|
+
*/
|
|
3005
|
+
async ensureFirstDepositSetup(strategy) {
|
|
3006
|
+
if (strategy !== void 0 && !isValidPublicStrategy(strategy)) {
|
|
3007
|
+
throw new Error(
|
|
3008
|
+
`Invalid strategy: ${strategy}. Must be "conservative", "aggressive" or "yieldmaxxing".`
|
|
3009
|
+
);
|
|
3010
|
+
}
|
|
3011
|
+
await this.authenticateUser();
|
|
3012
|
+
const usdcDetails = await this.getUserDetails("USDC");
|
|
3013
|
+
if ((usdcDetails.chains?.length ?? 0) > 0) {
|
|
3014
|
+
return { applied: false };
|
|
3015
|
+
}
|
|
3016
|
+
await this.updateUserProtocols(strategy, { strict: true });
|
|
3017
|
+
const usdcAfterSetup = await this.getUserDetails("USDC");
|
|
3018
|
+
if ((usdcAfterSetup.chains?.length ?? 0) === 0) {
|
|
3019
|
+
throw new Error(
|
|
3020
|
+
"First-deposit setup did not persist USDC chain configuration."
|
|
3021
|
+
);
|
|
3022
|
+
}
|
|
3023
|
+
return { applied: true };
|
|
3024
|
+
}
|
|
3025
|
+
/** Best-effort first-deposit setup shared by both high-level deposit flows. */
|
|
3026
|
+
async prepareFirstDeposit(strategy) {
|
|
3027
|
+
try {
|
|
3028
|
+
await this.ensureFirstDepositSetup(strategy);
|
|
3029
|
+
} catch (protocolError) {
|
|
3030
|
+
console.warn(
|
|
3031
|
+
"Failed to update user protocols before deposit:",
|
|
3032
|
+
protocolError.message
|
|
3033
|
+
);
|
|
3034
|
+
}
|
|
3035
|
+
}
|
|
3036
|
+
/** Shared post-transfer registration path for every deposit flow. */
|
|
3037
|
+
async registerDeposit(chainId, txHash, amount, tokenAddress) {
|
|
3038
|
+
let registration;
|
|
3039
|
+
try {
|
|
3040
|
+
registration = await this.logDeposit(
|
|
3041
|
+
chainId,
|
|
3042
|
+
txHash,
|
|
3043
|
+
amount,
|
|
3044
|
+
tokenAddress
|
|
3045
|
+
);
|
|
3046
|
+
} catch (logError) {
|
|
3047
|
+
throw new Error(
|
|
3048
|
+
`On-chain deposit succeeded (tx=${txHash}) but backend registration failed: ${logError.message}. Call connectAccount() then logDeposit(${chainId}, "${txHash}", "${amount}") to retry.`
|
|
3049
|
+
);
|
|
3050
|
+
}
|
|
3051
|
+
return registration.deposit;
|
|
3052
|
+
}
|
|
2654
3053
|
/**
|
|
2655
3054
|
* Log a deposit that was executed client-side.
|
|
2656
3055
|
*
|
|
2657
|
-
* `
|
|
3056
|
+
* `sendDeposit()` already calls this after the ERC20 transfer. If you send the
|
|
2658
3057
|
* transfer yourself (front, Privy, Biconomy, custom wallet) you **must** call
|
|
2659
3058
|
* `logDeposit` — otherwise the backend never sees the deposit: a reserved pool
|
|
2660
3059
|
* wallet stays reserved (no ownership rotation), and yield/agent tracking does
|
|
2661
3060
|
* not start.
|
|
2662
3061
|
*
|
|
3062
|
+
* Requires `connectAccount()` on the same SDK instance first (SIWE user JWT).
|
|
3063
|
+
* The SDK API key alone is not enough — `log_deposit` returns 401 without a
|
|
3064
|
+
* Bearer token.
|
|
3065
|
+
*
|
|
2663
3066
|
* Use this method when you execute the deposit transaction yourself and need to
|
|
2664
3067
|
* register it with the Zyfai backend.
|
|
2665
3068
|
*
|
|
@@ -2706,26 +3109,110 @@ var _ZyfaiSDK = class _ZyfaiSDK {
|
|
|
2706
3109
|
throw new Error("Valid amount is required");
|
|
2707
3110
|
}
|
|
2708
3111
|
const token = tokenAddress || getDefaultTokenAddress(chainId);
|
|
2709
|
-
await this.
|
|
2710
|
-
|
|
2711
|
-
|
|
2712
|
-
|
|
2713
|
-
|
|
2714
|
-
|
|
3112
|
+
await this.authenticateUser();
|
|
3113
|
+
const deposit = await this.httpClient.post(
|
|
3114
|
+
ENDPOINTS.LOG_DEPOSIT,
|
|
3115
|
+
{
|
|
3116
|
+
chainId,
|
|
3117
|
+
transaction: txHash,
|
|
3118
|
+
token,
|
|
3119
|
+
amount
|
|
3120
|
+
}
|
|
3121
|
+
);
|
|
2715
3122
|
return {
|
|
2716
3123
|
success: true,
|
|
2717
|
-
message: "Deposit
|
|
3124
|
+
message: deposit.status === "credited" ? "Deposit credited successfully" : "Deposit accepted; custody handover is pending",
|
|
3125
|
+
deposit
|
|
2718
3126
|
};
|
|
2719
3127
|
} catch (error) {
|
|
2720
3128
|
throw new Error(`Log deposit failed: ${error.message}`);
|
|
2721
3129
|
}
|
|
2722
3130
|
}
|
|
3131
|
+
/**
|
|
3132
|
+
* Fetch the custody handover and balance-credit lifecycle for a registered
|
|
3133
|
+
* deposit. A status of `credited` is required before funds are investable.
|
|
3134
|
+
*/
|
|
3135
|
+
async getDepositStatus(depositId) {
|
|
3136
|
+
if (!depositId) {
|
|
3137
|
+
throw new Error("Deposit ID is required");
|
|
3138
|
+
}
|
|
3139
|
+
await this.authenticateUser();
|
|
3140
|
+
return this.httpClient.get(
|
|
3141
|
+
ENDPOINTS.DEPOSIT_STATUS(depositId)
|
|
3142
|
+
);
|
|
3143
|
+
}
|
|
3144
|
+
/**
|
|
3145
|
+
* Await deposit credit after `logDeposit` returns `handover_pending`.
|
|
3146
|
+
*
|
|
3147
|
+
* Polls `getDepositStatus` until `status === "credited"` and
|
|
3148
|
+
* `balanceCredited === true`. Rejects on recovery, timeout, or poll errors.
|
|
3149
|
+
*
|
|
3150
|
+
* Poll interval and timeout are chain-specific. Mainnet defaults to a 2s
|
|
3151
|
+
* interval and 1 minute ceiling; Base/Arbitrum use tighter polling (~500ms /
|
|
3152
|
+
* ~250ms) with a ~20 second completion window. Override `timeoutMs` when a
|
|
3153
|
+
* caller intentionally wants to wait longer than the normal UX window.
|
|
3154
|
+
*
|
|
3155
|
+
* Requires `connectAccount()` on the same SDK instance first.
|
|
3156
|
+
*/
|
|
3157
|
+
async waitForDepositCredit(depositId, chainId, options) {
|
|
3158
|
+
if (!depositId) {
|
|
3159
|
+
throw new Error("Deposit ID is required");
|
|
3160
|
+
}
|
|
3161
|
+
if (!isSupportedChain(chainId)) {
|
|
3162
|
+
throw new Error(`Unsupported chain ID: ${chainId}`);
|
|
3163
|
+
}
|
|
3164
|
+
const intervalMs = options?.intervalMs ?? getDepositCreditIntervalMs(chainId);
|
|
3165
|
+
const timeoutMs = options?.timeoutMs ?? getDepositCreditTimeoutMs(chainId);
|
|
3166
|
+
const started = Date.now();
|
|
3167
|
+
while (Date.now() - started < timeoutMs) {
|
|
3168
|
+
const status = await this.getDepositStatus(depositId);
|
|
3169
|
+
if (status.status === "credited" && status.balanceCredited) {
|
|
3170
|
+
return status;
|
|
3171
|
+
}
|
|
3172
|
+
if (status.status === "recovered_to_eoa") {
|
|
3173
|
+
throw new Error(
|
|
3174
|
+
`Deposit ${depositId} recovered to EOA (status=${status.status}); balance was not credited`
|
|
3175
|
+
);
|
|
3176
|
+
}
|
|
3177
|
+
if (Date.now() - started >= timeoutMs) {
|
|
3178
|
+
break;
|
|
3179
|
+
}
|
|
3180
|
+
await sleep(intervalMs);
|
|
3181
|
+
}
|
|
3182
|
+
throw new DepositCreditTimeoutError(depositId);
|
|
3183
|
+
}
|
|
2723
3184
|
/**
|
|
2724
3185
|
* Withdraw funds from Safe smart wallet
|
|
2725
3186
|
* Initiates a withdrawal request to the Zyfai API
|
|
2726
3187
|
* Note: The withdrawal is processed asynchronously, so txHash may not be immediately available
|
|
2727
3188
|
* Funds are always withdrawn to the Safe owner's address (userAddress)
|
|
2728
3189
|
*
|
|
3190
|
+
* **Delayed withdrawals.** Positions held under the `"yieldmaxxing"`
|
|
3191
|
+
* strategy sit in protocols that cannot be exited on demand. For those the
|
|
3192
|
+
* backend transfers the immediately available portion, then queues a
|
|
3193
|
+
* redemption for the rest and forwards the funds to the EOA once the
|
|
3194
|
+
* protocol releases them — about a day on Ipor, three on Superform. No
|
|
3195
|
+
* further call is needed, but the returned `txHash` only covers the
|
|
3196
|
+
* immediate portion. Track the remainder through
|
|
3197
|
+
* `getPortfolio().portfolio.pendingAsyncWithdrawals`, whose entries carry a
|
|
3198
|
+
* `status` and an `estimatedClaimAt`.
|
|
3199
|
+
*
|
|
3200
|
+
* When every source is an async pool nothing settles on-chain at that point,
|
|
3201
|
+
* so `txHash` is `undefined` on a successful call.
|
|
3202
|
+
*
|
|
3203
|
+
* **One redemption per pool at a time.** While an entry for a pool is
|
|
3204
|
+
* `REQUESTED` or `CLAIMABLE`, the backend drops a further withdrawal aimed at
|
|
3205
|
+
* that same pool — the protocols behind it (ERC-7540) hold a single request
|
|
3206
|
+
* slot per user. This method throws rather than reporting that no-op as a
|
|
3207
|
+
* success. It only throws when nothing the call could reach is withdrawable:
|
|
3208
|
+
* another pool, another asset or an idle Safe balance still goes through.
|
|
3209
|
+
*
|
|
3210
|
+
* Once requested, that amount can no longer be withdrawn: it is gone from
|
|
3211
|
+
* both the position snapshot and the Safe balance, so a second call silently
|
|
3212
|
+
* returns only what is left. Validate user-entered amounts against
|
|
3213
|
+
* `portfolioByAssetType`, not against the total that includes in-flight
|
|
3214
|
+
* funds — see `getPortfolio`.
|
|
3215
|
+
*
|
|
2729
3216
|
* @param userAddress - User's address (owner of the Safe)
|
|
2730
3217
|
* @param chainId - Target chain ID
|
|
2731
3218
|
* @param amount - Optional: Amount in least decimal units to withdraw (partial withdrawal). If not specified, withdraws all funds
|
|
@@ -2768,6 +3255,11 @@ var _ZyfaiSDK = class _ZyfaiSDK {
|
|
|
2768
3255
|
);
|
|
2769
3256
|
}
|
|
2770
3257
|
await this.authenticateUser();
|
|
3258
|
+
await this.assertAsyncRedemptionSlotFree(
|
|
3259
|
+
userAddress,
|
|
3260
|
+
chainId,
|
|
3261
|
+
tokenSymbol
|
|
3262
|
+
);
|
|
2771
3263
|
let response = {};
|
|
2772
3264
|
if (amount) {
|
|
2773
3265
|
response = await this.httpClient.post(ENDPOINTS.PARTIAL_WITHDRAW, {
|
|
@@ -2795,6 +3287,31 @@ var _ZyfaiSDK = class _ZyfaiSDK {
|
|
|
2795
3287
|
throw new Error(`Withdrawal failed: ${error.message}`);
|
|
2796
3288
|
}
|
|
2797
3289
|
}
|
|
3290
|
+
/**
|
|
3291
|
+
* Turn a withdrawal the backend would silently drop — one aimed only at
|
|
3292
|
+
* async pools that already hold an in-flight redemption — into an error, so
|
|
3293
|
+
* the caller gets an answer rather than a `success: true` no-op.
|
|
3294
|
+
*
|
|
3295
|
+
* @internal
|
|
3296
|
+
*/
|
|
3297
|
+
async assertAsyncRedemptionSlotFree(userAddress, chainId, tokenSymbol) {
|
|
3298
|
+
let portfolio;
|
|
3299
|
+
try {
|
|
3300
|
+
({ portfolio } = await this.getPortfolio(userAddress));
|
|
3301
|
+
} catch {
|
|
3302
|
+
return;
|
|
3303
|
+
}
|
|
3304
|
+
const blocking = findBlockingAsyncRedemption(
|
|
3305
|
+
portfolio,
|
|
3306
|
+
chainId,
|
|
3307
|
+
tokenSymbol
|
|
3308
|
+
);
|
|
3309
|
+
if (!blocking) return;
|
|
3310
|
+
const eta = blocking.estimatedClaimAt ? ` Estimated settlement: ${blocking.estimatedClaimAt}.` : "";
|
|
3311
|
+
throw new Error(
|
|
3312
|
+
`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}`
|
|
3313
|
+
);
|
|
3314
|
+
}
|
|
2798
3315
|
/**
|
|
2799
3316
|
* Get available DeFi protocols and pools for a specific chain
|
|
2800
3317
|
*
|
|
@@ -2890,6 +3407,29 @@ var _ZyfaiSDK = class _ZyfaiSDK {
|
|
|
2890
3407
|
* Note: portfolio balances are live; earnings used for the fee may be from
|
|
2891
3408
|
* a snapshot, so net values can differ slightly from a fully live calc.
|
|
2892
3409
|
*
|
|
3410
|
+
* **Total balance.** `portfolioByAssetType` sums deployed positions and idle
|
|
3411
|
+
* Safe balances, and nothing else. Under the `"yieldmaxxing"` strategy a
|
|
3412
|
+
* redemption in flight has already left its position and has not landed in
|
|
3413
|
+
* the Safe yet, so its funds appear in no balance field at all. That makes
|
|
3414
|
+
* two distinct numbers:
|
|
3415
|
+
*
|
|
3416
|
+
* ```
|
|
3417
|
+
* total = portfolioByAssetType[assetType].balance
|
|
3418
|
+
* + sum(pendingAsyncWithdrawals where REQUESTED or CLAIMABLE)
|
|
3419
|
+
*
|
|
3420
|
+
* requestable = portfolioByAssetType[assetType].balance
|
|
3421
|
+
* ```
|
|
3422
|
+
*
|
|
3423
|
+
* An in-flight amount is no longer withdrawable: `withdrawFunds` only reaches
|
|
3424
|
+
* the current positions and idle balances, so calling it again neither speeds
|
|
3425
|
+
* those funds up nor errors. They reach the EOA on their own. Cap any
|
|
3426
|
+
* user-entered withdrawal amount at `requestable`, never at `total`.
|
|
3427
|
+
*
|
|
3428
|
+
* Do not add `staleBalances` on top — those are the same idle balances
|
|
3429
|
+
* `portfolioByAssetType` already counts, exposed as a per-chain view.
|
|
3430
|
+
* Do not add `CLAIMED` withdrawals either (the array keeps them for 24
|
|
3431
|
+
* hours); their funds are back in the Safe and already counted.
|
|
3432
|
+
*
|
|
2893
3433
|
* @param userAddress - User's EOA address
|
|
2894
3434
|
* @returns Portfolio with optional fee-adjusted balance fields
|
|
2895
3435
|
*
|
|
@@ -2897,6 +3437,11 @@ var _ZyfaiSDK = class _ZyfaiSDK {
|
|
|
2897
3437
|
* ```typescript
|
|
2898
3438
|
* const { portfolio } = await sdk.getPortfolio(userAddress);
|
|
2899
3439
|
* console.log(portfolio.portfolioByAssetType?.usdc?.balanceWithFee);
|
|
3440
|
+
*
|
|
3441
|
+
* // Funds still locked in an async redemption
|
|
3442
|
+
* const inFlight = (portfolio.pendingAsyncWithdrawals ?? []).filter(
|
|
3443
|
+
* (w) => w.status === "REQUESTED" || w.status === "CLAIMABLE"
|
|
3444
|
+
* );
|
|
2900
3445
|
* ```
|
|
2901
3446
|
*/
|
|
2902
3447
|
async getPortfolio(userAddress) {
|
|
@@ -2970,7 +3515,11 @@ var _ZyfaiSDK = class _ZyfaiSDK {
|
|
|
2970
3515
|
omniAccount: convertedResponse.omniAccount,
|
|
2971
3516
|
asset,
|
|
2972
3517
|
autoSelectProtocols: convertedResponse.assetTypeSettings?.[internalAsset]?.autoSelectProtocols,
|
|
2973
|
-
strategy
|
|
3518
|
+
// `convertStrategyToPublic` only touches the root `strategy` field;
|
|
3519
|
+
// the per-asset one is nested and has to be converted here.
|
|
3520
|
+
strategy: toPublicStrategyOrUndefined(
|
|
3521
|
+
convertedResponse.assetTypeSettings?.[internalAsset]?.rebalanceStrategy
|
|
3522
|
+
),
|
|
2974
3523
|
autocompounding: convertedResponse.assetTypeSettings?.[internalAsset]?.autocompounding,
|
|
2975
3524
|
crosschainStrategy: convertedResponse.assetTypeSettings?.[internalAsset]?.crosschainStrategy,
|
|
2976
3525
|
splitting: convertedResponse.assetTypeSettings?.[internalAsset]?.splitting,
|
|
@@ -3017,7 +3566,7 @@ var _ZyfaiSDK = class _ZyfaiSDK {
|
|
|
3017
3566
|
*
|
|
3018
3567
|
* @param crossChain - Whether to get cross-chain APY (true = omni account, false = simple account)
|
|
3019
3568
|
* @param days - Time period: 7, 14, or 30
|
|
3020
|
-
* @param strategy - Strategy type: "conservative" (default) or "
|
|
3569
|
+
* @param strategy - Strategy type: "conservative" (default), "aggressive" or "yieldmaxxing"
|
|
3021
3570
|
* @param chainId - Optional chain ID filter
|
|
3022
3571
|
* @param tokenSymbol - Optional token symbol filter (e.g. "USDC", "WETH", "WBTC")
|
|
3023
3572
|
* @returns APY per strategy for a specific chain
|
|
@@ -3068,7 +3617,9 @@ var _ZyfaiSDK = class _ZyfaiSDK {
|
|
|
3068
3617
|
*/
|
|
3069
3618
|
async getVolume(assetType = "usdc") {
|
|
3070
3619
|
try {
|
|
3071
|
-
const response = await this.httpClient.get(
|
|
3620
|
+
const response = await this.httpClient.get(
|
|
3621
|
+
ENDPOINTS.DATA_VOLUME(assetType)
|
|
3622
|
+
);
|
|
3072
3623
|
return {
|
|
3073
3624
|
success: true,
|
|
3074
3625
|
volumeInUSD: response.volumeInUSD || "0"
|
|
@@ -3484,6 +4035,53 @@ var _ZyfaiSDK = class _ZyfaiSDK {
|
|
|
3484
4035
|
);
|
|
3485
4036
|
}
|
|
3486
4037
|
}
|
|
4038
|
+
/**
|
|
4039
|
+
* Get yieldmaxxing opportunities — pools reachable only with the
|
|
4040
|
+
* `"yieldmaxxing"` strategy, including protocols whose withdrawals are
|
|
4041
|
+
* asynchronous (Ipor, Superform). Exiting these pools takes about a day
|
|
4042
|
+
* on Ipor and three on Superform; track the redemption through
|
|
4043
|
+
* `getPortfolio().portfolio.pendingAsyncWithdrawals`.
|
|
4044
|
+
*
|
|
4045
|
+
* @param chainId - Optional chain ID filter
|
|
4046
|
+
* @param asset - Optional asset filter (e.g. "USDC", "WETH")
|
|
4047
|
+
* @returns List of yieldmaxxing opportunities
|
|
4048
|
+
*
|
|
4049
|
+
* @example
|
|
4050
|
+
* ```typescript
|
|
4051
|
+
* const opportunities = await sdk.getAsyncOpportunities(8453);
|
|
4052
|
+
* opportunities.data.forEach(o => console.log(o.protocolName, o.apy));
|
|
4053
|
+
* ```
|
|
4054
|
+
*/
|
|
4055
|
+
async getAsyncOpportunities(chainId, asset, status) {
|
|
4056
|
+
try {
|
|
4057
|
+
const response = await this.httpClient.dataGet(
|
|
4058
|
+
DATA_ENDPOINTS.OPPORTUNITIES_ASYNC(chainId, asset, status)
|
|
4059
|
+
);
|
|
4060
|
+
const data = response.data || response || [];
|
|
4061
|
+
return {
|
|
4062
|
+
success: true,
|
|
4063
|
+
chainId,
|
|
4064
|
+
strategyType: "yieldmaxxing",
|
|
4065
|
+
data: Array.isArray(data) ? data.map((o) => ({
|
|
4066
|
+
id: o.id,
|
|
4067
|
+
protocolId: o.protocol_id || o.protocolId,
|
|
4068
|
+
protocolName: o.protocol_name || o.protocolName,
|
|
4069
|
+
poolName: o.pool_name || o.poolName,
|
|
4070
|
+
chainId: o.chain_id || o.chainId,
|
|
4071
|
+
apy: o.combined_apy || 0,
|
|
4072
|
+
tvl: o.tvl || o.zyfiTvl,
|
|
4073
|
+
asset: o.asset || o.underlying_token,
|
|
4074
|
+
risk: o.risk,
|
|
4075
|
+
strategyType: "yieldmaxxing",
|
|
4076
|
+
status: o.status
|
|
4077
|
+
})) : []
|
|
4078
|
+
};
|
|
4079
|
+
} catch (error) {
|
|
4080
|
+
throw new Error(
|
|
4081
|
+
`Failed to get yieldmaxxing opportunities: ${error.message}`
|
|
4082
|
+
);
|
|
4083
|
+
}
|
|
4084
|
+
}
|
|
3487
4085
|
/**
|
|
3488
4086
|
* Get active conservative opportunities (status = "live") with risk and utilization data
|
|
3489
4087
|
* Returns pool info, liquidity depth (true if > 1M), utilization rate, stability metrics, avg APY, and collateral
|
|
@@ -3798,9 +4396,7 @@ var _ZyfaiSDK = class _ZyfaiSDK {
|
|
|
3798
4396
|
}
|
|
3799
4397
|
};
|
|
3800
4398
|
} catch (error) {
|
|
3801
|
-
throw new Error(
|
|
3802
|
-
`Failed to get SDK key TVL: ${error.message}`
|
|
3803
|
-
);
|
|
4399
|
+
throw new Error(`Failed to get SDK key TVL: ${error.message}`);
|
|
3804
4400
|
}
|
|
3805
4401
|
}
|
|
3806
4402
|
// ============================================================================
|
|
@@ -3860,7 +4456,7 @@ var _ZyfaiSDK = class _ZyfaiSDK {
|
|
|
3860
4456
|
* Returns the list of pools available for a given protocol, optionally filtered by strategy.
|
|
3861
4457
|
*
|
|
3862
4458
|
* @param protocolId - The protocol UUID
|
|
3863
|
-
* @param strategy - Optional strategy filter ("conservative" or "
|
|
4459
|
+
* @param strategy - Optional strategy filter ("conservative", "aggressive" or "yieldmaxxing")
|
|
3864
4460
|
* @returns List of available pool names
|
|
3865
4461
|
*
|
|
3866
4462
|
* @example
|
|
@@ -3882,7 +4478,7 @@ var _ZyfaiSDK = class _ZyfaiSDK {
|
|
|
3882
4478
|
if (strategy) {
|
|
3883
4479
|
if (!isValidPublicStrategy(strategy)) {
|
|
3884
4480
|
throw new Error(
|
|
3885
|
-
`Invalid strategy: ${strategy}. Must be "conservative" or "
|
|
4481
|
+
`Invalid strategy: ${strategy}. Must be "conservative", "aggressive" or "yieldmaxxing".`
|
|
3886
4482
|
);
|
|
3887
4483
|
}
|
|
3888
4484
|
internalStrategy = toInternalStrategy(strategy);
|
|
@@ -3928,7 +4524,7 @@ var _ZyfaiSDK = class _ZyfaiSDK {
|
|
|
3928
4524
|
try {
|
|
3929
4525
|
if (!isValidPublicStrategy(params.strategy)) {
|
|
3930
4526
|
throw new Error(
|
|
3931
|
-
`Invalid strategy: ${params.strategy}. Must be "conservative" or "
|
|
4527
|
+
`Invalid strategy: ${params.strategy}. Must be "conservative", "aggressive" or "yieldmaxxing".`
|
|
3932
4528
|
);
|
|
3933
4529
|
}
|
|
3934
4530
|
const internalStrategy = toInternalStrategy(params.strategy);
|
|
@@ -3983,7 +4579,9 @@ var _ZyfaiSDK = class _ZyfaiSDK {
|
|
|
3983
4579
|
* Check if a chain ID supports the Identity Registry
|
|
3984
4580
|
*/
|
|
3985
4581
|
isSupportedIdentityRegistryChain(chainId) {
|
|
3986
|
-
return _ZyfaiSDK.IDENTITY_REGISTRY_CHAIN_IDS.includes(
|
|
4582
|
+
return _ZyfaiSDK.IDENTITY_REGISTRY_CHAIN_IDS.includes(
|
|
4583
|
+
chainId
|
|
4584
|
+
);
|
|
3987
4585
|
}
|
|
3988
4586
|
/**
|
|
3989
4587
|
* Register an agent on the Identity Registry (ERC-8004)
|
|
@@ -4080,7 +4678,9 @@ var _ZyfaiSDK = class _ZyfaiSDK {
|
|
|
4080
4678
|
const chainConfig = getChainConfig(chainId, this.rpcUrls);
|
|
4081
4679
|
const tokenAddress = getDefaultTokenAddress(chainId, asset);
|
|
4082
4680
|
const decimals = 6;
|
|
4083
|
-
const parsedAmount = BigInt(
|
|
4681
|
+
const parsedAmount = BigInt(
|
|
4682
|
+
Math.floor(parseFloat(amount) * 10 ** decimals)
|
|
4683
|
+
);
|
|
4084
4684
|
try {
|
|
4085
4685
|
const allowance = await chainConfig.publicClient.readContract({
|
|
4086
4686
|
address: tokenAddress,
|
|
@@ -4158,7 +4758,9 @@ var _ZyfaiSDK = class _ZyfaiSDK {
|
|
|
4158
4758
|
args: [userAddress]
|
|
4159
4759
|
});
|
|
4160
4760
|
if (maxShares === 0n) {
|
|
4161
|
-
throw new Error(
|
|
4761
|
+
throw new Error(
|
|
4762
|
+
"No shares available to redeem or withdrawals are paused"
|
|
4763
|
+
);
|
|
4162
4764
|
}
|
|
4163
4765
|
sharesToRedeem = maxShares;
|
|
4164
4766
|
}
|
|
@@ -4202,7 +4804,9 @@ var _ZyfaiSDK = class _ZyfaiSDK {
|
|
|
4202
4804
|
status: isClaimable ? "claimable" : "pending"
|
|
4203
4805
|
};
|
|
4204
4806
|
} catch (error) {
|
|
4205
|
-
throw new Error(
|
|
4807
|
+
throw new Error(
|
|
4808
|
+
`Vault withdraw request failed: ${error.message}`
|
|
4809
|
+
);
|
|
4206
4810
|
}
|
|
4207
4811
|
}
|
|
4208
4812
|
/**
|
|
@@ -4282,7 +4886,9 @@ var _ZyfaiSDK = class _ZyfaiSDK {
|
|
|
4282
4886
|
nonce
|
|
4283
4887
|
};
|
|
4284
4888
|
} catch (error) {
|
|
4285
|
-
throw new Error(
|
|
4889
|
+
throw new Error(
|
|
4890
|
+
`Failed to get withdraw status: ${error.message}`
|
|
4891
|
+
);
|
|
4286
4892
|
}
|
|
4287
4893
|
}
|
|
4288
4894
|
/**
|
|
@@ -4325,7 +4931,9 @@ var _ZyfaiSDK = class _ZyfaiSDK {
|
|
|
4325
4931
|
if (isClaimed) {
|
|
4326
4932
|
throw new Error("This withdrawal has already been claimed");
|
|
4327
4933
|
}
|
|
4328
|
-
throw new Error(
|
|
4934
|
+
throw new Error(
|
|
4935
|
+
"Withdrawal is not yet claimable. Please wait for processing."
|
|
4936
|
+
);
|
|
4329
4937
|
}
|
|
4330
4938
|
const claimTx = await this.walletClient.writeContract({
|
|
4331
4939
|
address: VAULT_ADDRESS,
|
|
@@ -4365,7 +4973,9 @@ var _ZyfaiSDK = class _ZyfaiSDK {
|
|
|
4365
4973
|
async getVaultShares(userAddress, chainId = 8453) {
|
|
4366
4974
|
const address = userAddress || this.walletClient?.account?.address;
|
|
4367
4975
|
if (!address) {
|
|
4368
|
-
throw new Error(
|
|
4976
|
+
throw new Error(
|
|
4977
|
+
"User address required. Provide address or connect wallet first."
|
|
4978
|
+
);
|
|
4369
4979
|
}
|
|
4370
4980
|
const chainConfig = getChainConfig(chainId, this.rpcUrls);
|
|
4371
4981
|
const [shareBalance, tokenSymbol] = await Promise.all([
|
|
@@ -4636,21 +5246,36 @@ function createBankrProvider(config) {
|
|
|
4636
5246
|
}
|
|
4637
5247
|
export {
|
|
4638
5248
|
ALLOWED_HISTORY_DAYS,
|
|
5249
|
+
API_ENDPOINT,
|
|
5250
|
+
DATA_API_BASE_URLS,
|
|
5251
|
+
DATA_API_ENDPOINT,
|
|
4639
5252
|
DEFAULT_TOKEN_ADDRESSES,
|
|
4640
5253
|
ERC7579_LAUNCHPAD_ADDRESS,
|
|
5254
|
+
EXECUTION_API_BASE_URLS,
|
|
4641
5255
|
INTENT_EXECUTOR,
|
|
4642
5256
|
INTENT_SMART_SESSIONS,
|
|
5257
|
+
LOCAL_DATA_API_BASE_URL,
|
|
5258
|
+
LOCAL_EXECUTION_API_BASE_URL,
|
|
5259
|
+
LOCAL_WS_URL,
|
|
4643
5260
|
OWNABLE_VALIDATOR,
|
|
4644
5261
|
POOL_MODULE_ADDRESSES,
|
|
4645
5262
|
PROXY_EXECUTOR,
|
|
4646
5263
|
SAFE_7579_ADDRESS,
|
|
4647
5264
|
SMART_SESSIONS_FALLBACK,
|
|
4648
5265
|
SMART_SESSIONS_VALIDATOR,
|
|
5266
|
+
STAGING_DATA_API_BASE_URL,
|
|
5267
|
+
STAGING_EXECUTION_API_BASE_URL,
|
|
5268
|
+
STAGING_WS_URL,
|
|
4649
5269
|
VAULT_ADDRESS,
|
|
5270
|
+
WS_ENDPOINT,
|
|
5271
|
+
WS_URLS,
|
|
4650
5272
|
ZyfaiSDK,
|
|
4651
5273
|
createBankrProvider,
|
|
4652
5274
|
getChainConfig,
|
|
5275
|
+
getDataApiBaseUrl,
|
|
4653
5276
|
getDefaultTokenAddress,
|
|
5277
|
+
getExecutionApiBaseUrl,
|
|
4654
5278
|
getSupportedChainIds,
|
|
5279
|
+
getWsUrl,
|
|
4655
5280
|
isSupportedChain
|
|
4656
5281
|
};
|