@owney/sdk 0.7.34 → 0.8.0-beta.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 +25 -4
- package/dist/index.cjs +423 -150
- package/dist/index.d.cts +70 -46
- package/dist/index.d.ts +70 -46
- package/dist/index.js +423 -150
- package/package.json +1 -1
package/dist/index.cjs
CHANGED
|
@@ -211,7 +211,7 @@ var P_SUPPORTED_CHAINS = {
|
|
|
211
211
|
chainIds: [8453, 42161, 1],
|
|
212
212
|
chains: ["BASE", "ARBITRUM", "ETHEREUM"]
|
|
213
213
|
};
|
|
214
|
-
var SUPPORTED_TOKENS = ["USDC", "WETH"];
|
|
214
|
+
var SUPPORTED_TOKENS = ["USDC", "WETH", "EURC", "USDT"];
|
|
215
215
|
var SUPPORTED_CHAIN_IDS = P_SUPPORTED_CHAINS.chainIds;
|
|
216
216
|
var SUPPORTED_CHAINS = P_SUPPORTED_CHAINS.chains;
|
|
217
217
|
var SupportedAssets = [
|
|
@@ -250,8 +250,31 @@ var SupportedAssets = [
|
|
|
250
250
|
symbol: "WETH",
|
|
251
251
|
chainId: 1,
|
|
252
252
|
decimals: 18
|
|
253
|
+
},
|
|
254
|
+
{
|
|
255
|
+
address: `0x1aBaEA1f7C830bD89Acc67eC4af516284b1bC33c`,
|
|
256
|
+
symbol: "EURC",
|
|
257
|
+
chainId: 1,
|
|
258
|
+
decimals: 6
|
|
259
|
+
},
|
|
260
|
+
{
|
|
261
|
+
address: `0x60a3E35Cc302bFA44Cb288Bc5a4F316Fdb1adb42`,
|
|
262
|
+
symbol: "EURC",
|
|
263
|
+
chainId: 8453,
|
|
264
|
+
decimals: 6
|
|
265
|
+
},
|
|
266
|
+
{
|
|
267
|
+
address: `0xdAC17F958D2ee523a2206206994597C13D831ec7`,
|
|
268
|
+
symbol: "USDT",
|
|
269
|
+
chainId: 1,
|
|
270
|
+
decimals: 6
|
|
253
271
|
}
|
|
254
272
|
];
|
|
273
|
+
function tokenAddress(symbol, chainId) {
|
|
274
|
+
return SupportedAssets.find(
|
|
275
|
+
(a) => a.symbol === symbol && a.chainId === chainId
|
|
276
|
+
)?.address;
|
|
277
|
+
}
|
|
255
278
|
|
|
256
279
|
// src/lib/debug.ts
|
|
257
280
|
var configuredDebug = false;
|
|
@@ -316,6 +339,8 @@ function matchesAsset(symbol, asset) {
|
|
|
316
339
|
// src/agents/zyfai/zyfai.mapper.ts
|
|
317
340
|
var DECIMALS_BY_SYMBOL = {
|
|
318
341
|
usdc: 6,
|
|
342
|
+
eurc: 6,
|
|
343
|
+
usdt: 6,
|
|
319
344
|
weth: 18,
|
|
320
345
|
eth: 18,
|
|
321
346
|
cbeth: 18,
|
|
@@ -512,7 +537,7 @@ function netApy(net, gross, field) {
|
|
|
512
537
|
}
|
|
513
538
|
function usdPerUnit(tokenSymbol, prices) {
|
|
514
539
|
const symbol = tokenSymbol?.toUpperCase();
|
|
515
|
-
if (symbol === "USDC") return 1;
|
|
540
|
+
if (symbol === "USDC" || symbol === "USDT") return 1;
|
|
516
541
|
const price = symbol ? prices?.[symbol] : void 0;
|
|
517
542
|
return typeof price === "number" && Number.isFinite(price) && price > 0 ? price : void 0;
|
|
518
543
|
}
|
|
@@ -1211,6 +1236,7 @@ var CHAINLINK_ETH_USD_FEED = {
|
|
|
1211
1236
|
42161: "0x639Fe6ab55C921f74e7fac1ee960C0B6293ba612",
|
|
1212
1237
|
1: "0x5f4eC3Df9cbd43714FE2740f5E3616155c5b8419"
|
|
1213
1238
|
};
|
|
1239
|
+
var CHAINLINK_EUR_USD_FEED = "0xb49f677943BC038e9857d61E7d053CaA2C1734C1";
|
|
1214
1240
|
var CHAINLINK_ABI = (0, import_viem.parseAbi)([
|
|
1215
1241
|
"function latestRoundData() view returns (uint80, int256, uint256, uint256, uint80)"
|
|
1216
1242
|
]);
|
|
@@ -1220,13 +1246,8 @@ var DEFAULT_ZYFAI_RPC_URLS = {
|
|
|
1220
1246
|
42161: "https://arb-mainnet.g.alchemy.com/v2/ZWyVU-9XfS3z8Rn-xkq7V",
|
|
1221
1247
|
1: "https://eth-mainnet.g.alchemy.com/v2/ZWyVU-9XfS3z8Rn-xkq7V"
|
|
1222
1248
|
};
|
|
1223
|
-
var WETH_ADDRESS_BY_CHAIN = {
|
|
1224
|
-
8453: "0x4200000000000000000000000000000000000006",
|
|
1225
|
-
42161: "0x82aF49447D8a07e3bd95BD0d56f35241523fBab1",
|
|
1226
|
-
1: "0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2"
|
|
1227
|
-
};
|
|
1228
1249
|
var VIEM_CHAIN = { 8453: import_chains.base, 42161: import_chains.arbitrum, 1: import_chains.mainnet };
|
|
1229
|
-
var SPLITTING_ASSETS =
|
|
1250
|
+
var SPLITTING_ASSETS = SUPPORTED_TOKENS;
|
|
1230
1251
|
var POOL_POLICY_CHAIN_IDS = [8453, 42161, 1];
|
|
1231
1252
|
var EARNINGS_REFRESH_COOLDOWN_MS = 60 * 60 * 1e3;
|
|
1232
1253
|
var ZyfaiAgent = class _ZyfaiAgent {
|
|
@@ -1238,7 +1259,8 @@ var ZyfaiAgent = class _ZyfaiAgent {
|
|
|
1238
1259
|
chain: "BASE",
|
|
1239
1260
|
assets: [
|
|
1240
1261
|
{ symbol: "USDC", minDepositAmount: "1500000" },
|
|
1241
|
-
{ symbol: "WETH", minDepositAmount: "500000000000000" }
|
|
1262
|
+
{ symbol: "WETH", minDepositAmount: "500000000000000" },
|
|
1263
|
+
{ symbol: "EURC", minDepositAmount: "1500000" }
|
|
1242
1264
|
]
|
|
1243
1265
|
},
|
|
1244
1266
|
{
|
|
@@ -1259,7 +1281,12 @@ var ZyfaiAgent = class _ZyfaiAgent {
|
|
|
1259
1281
|
// the shipped code enforces 0.005 WETH, so match it or deposits reject on-chain.
|
|
1260
1282
|
assets: [
|
|
1261
1283
|
{ symbol: "USDC", minDepositAmount: "100000000" },
|
|
1262
|
-
{ symbol: "WETH", minDepositAmount: "5000000000000000" }
|
|
1284
|
+
{ symbol: "WETH", minDepositAmount: "5000000000000000" },
|
|
1285
|
+
// ROUT-308: same floor as USDC (6 decimals). Zyfai's own
|
|
1286
|
+
// MIN_PORTFOLIO_BALANCE says 10,000 here, but that is only enforced by
|
|
1287
|
+
// its sendDeposit, which we don't use. Confirm with Zyfai before release.
|
|
1288
|
+
{ symbol: "EURC", minDepositAmount: "100000000" },
|
|
1289
|
+
{ symbol: "USDT", minDepositAmount: "100000000" }
|
|
1263
1290
|
]
|
|
1264
1291
|
}
|
|
1265
1292
|
];
|
|
@@ -1281,6 +1308,7 @@ var ZyfaiAgent = class _ZyfaiAgent {
|
|
|
1281
1308
|
// RPC error retries on the next fetch.
|
|
1282
1309
|
withdrawAmountCache = /* @__PURE__ */ new Map();
|
|
1283
1310
|
ethUsd = null;
|
|
1311
|
+
eurUsd = null;
|
|
1284
1312
|
earningsReads = /* @__PURE__ */ new Map();
|
|
1285
1313
|
earningsRefreshes = /* @__PURE__ */ new Map();
|
|
1286
1314
|
earningsSnapshot = null;
|
|
@@ -1502,15 +1530,15 @@ var ZyfaiAgent = class _ZyfaiAgent {
|
|
|
1502
1530
|
* it diffs available-vs-enabled by protocol id and writes the full union
|
|
1503
1531
|
* back, or does nothing when none are missing.
|
|
1504
1532
|
*
|
|
1505
|
-
* Non-fatal: a sync failure must never block activation.
|
|
1506
|
-
*
|
|
1533
|
+
* Non-fatal: a sync failure must never block activation. Assets that do not
|
|
1534
|
+
* exist on `chainId` (no token address there) are skipped.
|
|
1507
1535
|
*/
|
|
1508
|
-
async ensureProtocolsSynced(chainId, asset) {
|
|
1509
|
-
if (asset
|
|
1536
|
+
async ensureProtocolsSynced(chainId, asset, availableProtocols) {
|
|
1537
|
+
if (!tokenAddress(asset, chainId)) return;
|
|
1510
1538
|
try {
|
|
1511
1539
|
const [current, { protocols: available }] = await Promise.all([
|
|
1512
1540
|
this.sdk.getUserDetails(asset),
|
|
1513
|
-
|
|
1541
|
+
availableProtocols
|
|
1514
1542
|
]);
|
|
1515
1543
|
debugLog("zyfai:protocol-sync", `${asset}: profile before sync`, {
|
|
1516
1544
|
chains: current.chains,
|
|
@@ -1579,9 +1607,15 @@ var ZyfaiAgent = class _ZyfaiAgent {
|
|
|
1579
1607
|
ms: Date.now() - startedAt
|
|
1580
1608
|
});
|
|
1581
1609
|
const validChainId = isValidChainId(chainId);
|
|
1610
|
+
const availableProtocols = Promise.resolve().then(
|
|
1611
|
+
() => this.sdk.getAvailableProtocols(validChainId)
|
|
1612
|
+
);
|
|
1613
|
+
availableProtocols.catch(() => {
|
|
1614
|
+
});
|
|
1582
1615
|
await Promise.all([
|
|
1583
|
-
|
|
1584
|
-
|
|
1616
|
+
...SUPPORTED_TOKENS.map(
|
|
1617
|
+
(asset) => this.ensureProtocolsSynced(validChainId, asset, availableProtocols)
|
|
1618
|
+
),
|
|
1585
1619
|
// Retrofit a session key for old wallets that are already deployed and
|
|
1586
1620
|
// funded but never got one — otherwise their balance stays idle until
|
|
1587
1621
|
// they happen to deposit again. Only touches Safes that are missing the
|
|
@@ -1695,34 +1729,41 @@ var ZyfaiAgent = class _ZyfaiAgent {
|
|
|
1695
1729
|
);
|
|
1696
1730
|
const desiredAutoSelect = policy.autoApproveProtocols;
|
|
1697
1731
|
for (const asset of SPLITTING_ASSETS) {
|
|
1698
|
-
|
|
1699
|
-
|
|
1700
|
-
strategy
|
|
1701
|
-
|
|
1702
|
-
|
|
1703
|
-
|
|
1704
|
-
|
|
1705
|
-
|
|
1706
|
-
|
|
1707
|
-
|
|
1708
|
-
|
|
1709
|
-
|
|
1710
|
-
|
|
1711
|
-
|
|
1712
|
-
|
|
1713
|
-
|
|
1732
|
+
try {
|
|
1733
|
+
const current = await this.sdk.getUserDetails(asset);
|
|
1734
|
+
if (strategy === void 0 && (current.strategy === "conservative" || current.strategy === "aggressive")) {
|
|
1735
|
+
strategy = current.strategy;
|
|
1736
|
+
}
|
|
1737
|
+
const needsUpdate = protocolsPolicyNeedsUpdate(
|
|
1738
|
+
current,
|
|
1739
|
+
desiredProtocols,
|
|
1740
|
+
desiredAutoSelect
|
|
1741
|
+
);
|
|
1742
|
+
debugLog("zyfai:pools", `${asset}: comparing protocols`, {
|
|
1743
|
+
current: {
|
|
1744
|
+
protocols: current.protocols,
|
|
1745
|
+
autoSelectProtocols: current.autoSelectProtocols
|
|
1746
|
+
},
|
|
1747
|
+
desired: {
|
|
1748
|
+
protocols: desiredProtocols,
|
|
1749
|
+
autoSelectProtocols: desiredAutoSelect
|
|
1750
|
+
},
|
|
1751
|
+
decision: needsUpdate ? "will write \u2014 profile differs from the org policy" : "skipping \u2014 profile already matches"
|
|
1752
|
+
});
|
|
1753
|
+
if (!needsUpdate) continue;
|
|
1754
|
+
const update = {
|
|
1755
|
+
asset,
|
|
1714
1756
|
autoSelectProtocols: desiredAutoSelect
|
|
1715
|
-
}
|
|
1716
|
-
|
|
1717
|
-
|
|
1718
|
-
|
|
1719
|
-
|
|
1720
|
-
|
|
1721
|
-
|
|
1722
|
-
|
|
1723
|
-
|
|
1724
|
-
|
|
1725
|
-
debugLog("zyfai:pools", `${asset}: wrote protocols update`, update);
|
|
1757
|
+
};
|
|
1758
|
+
if (desiredProtocols !== null) update.protocols = desiredProtocols;
|
|
1759
|
+
await this.sdk.updateUserProfile(update);
|
|
1760
|
+
debugLog("zyfai:pools", `${asset}: wrote protocols update`, update);
|
|
1761
|
+
} catch (error) {
|
|
1762
|
+
console.warn(
|
|
1763
|
+
`[zyfai] applyPoolPolicy(${asset}) failed (non-fatal):`,
|
|
1764
|
+
error instanceof Error ? error.message : String(error)
|
|
1765
|
+
);
|
|
1766
|
+
}
|
|
1726
1767
|
}
|
|
1727
1768
|
const poolResults = await Promise.all(
|
|
1728
1769
|
universe.map(async (protocol) => {
|
|
@@ -1848,9 +1889,7 @@ var ZyfaiAgent = class _ZyfaiAgent {
|
|
|
1848
1889
|
await Promise.all(
|
|
1849
1890
|
selection.strategies.map(async ({ asset, strategy }) => {
|
|
1850
1891
|
const current = await this.sdk.getUserDetails(asset);
|
|
1851
|
-
const selectedProtocols = selection.selections.filter(
|
|
1852
|
-
(entry) => entry.asset === asset && entry.pools.length > 0
|
|
1853
|
-
).map((entry) => entry.protocolId);
|
|
1892
|
+
const selectedProtocols = selection.selections.filter((entry) => entry.asset === asset && entry.pools.length > 0).map((entry) => entry.protocolId);
|
|
1854
1893
|
const protocols = [
|
|
1855
1894
|
.../* @__PURE__ */ new Set([...current.protocols ?? [], ...selectedProtocols])
|
|
1856
1895
|
];
|
|
@@ -2209,11 +2248,10 @@ var ZyfaiAgent = class _ZyfaiAgent {
|
|
|
2209
2248
|
requestedStrategy: "aggressive",
|
|
2210
2249
|
setupResult
|
|
2211
2250
|
});
|
|
2251
|
+
await this.syncAutoSelect(validChainId, asset);
|
|
2212
2252
|
if (isOwneyDebug()) {
|
|
2213
2253
|
try {
|
|
2214
|
-
const profileAfterSetup = await this.sdk.getUserDetails(
|
|
2215
|
-
asset === "WETH" ? "WETH" : "USDC"
|
|
2216
|
-
);
|
|
2254
|
+
const profileAfterSetup = await this.sdk.getUserDetails(asset);
|
|
2217
2255
|
debugLog("zyfai:first-deposit", "profile immediately after setup", {
|
|
2218
2256
|
asset,
|
|
2219
2257
|
strategy: profileAfterSetup.strategy,
|
|
@@ -2231,9 +2269,9 @@ var ZyfaiAgent = class _ZyfaiAgent {
|
|
|
2231
2269
|
validChainId
|
|
2232
2270
|
);
|
|
2233
2271
|
const txHash = await depositCallback(smartWallet, validChainId, amount);
|
|
2234
|
-
const
|
|
2272
|
+
const tokenAddress2 = asset === "USDC" ? void 0 : tokenAddress(asset, validChainId);
|
|
2235
2273
|
try {
|
|
2236
|
-
await (
|
|
2274
|
+
await (tokenAddress2 ? this.sdk.logDeposit(validChainId, txHash, amount, tokenAddress2) : this.sdk.logDeposit(validChainId, txHash, amount));
|
|
2237
2275
|
} catch (logError) {
|
|
2238
2276
|
console.warn(
|
|
2239
2277
|
"[owney-sdk] Deposit landed on-chain but logDeposit failed (non-fatal):",
|
|
@@ -2339,13 +2377,22 @@ var ZyfaiAgent = class _ZyfaiAgent {
|
|
|
2339
2377
|
}
|
|
2340
2378
|
async getAccountApy(state, chainId, days, tokenSymbol, scopeChainId) {
|
|
2341
2379
|
const { smartWallet, chainId: validChainId } = await this.resolveSmartWallet(state, chainId);
|
|
2342
|
-
const [raw, ethUsd] = await Promise.all([
|
|
2380
|
+
const [raw, ethUsd, eurUsd] = await Promise.all([
|
|
2343
2381
|
this.sdk.getDailyApyHistory(smartWallet, days),
|
|
2344
|
-
tokenSymbol ? void 0 : this.readEthUsd(validChainId)
|
|
2382
|
+
tokenSymbol ? void 0 : this.readEthUsd(validChainId),
|
|
2383
|
+
tokenSymbol ? void 0 : this.readEurUsd()
|
|
2345
2384
|
]);
|
|
2346
2385
|
const scope = scopeChainId === null ? void 0 : scopeChainId ?? chainId;
|
|
2347
|
-
const usdPrices =
|
|
2348
|
-
|
|
2386
|
+
const usdPrices = {
|
|
2387
|
+
...ethUsd ? { WETH: ethUsd, ETH: ethUsd } : {},
|
|
2388
|
+
...eurUsd ? { EURC: eurUsd } : {}
|
|
2389
|
+
};
|
|
2390
|
+
return mapApyHistory(
|
|
2391
|
+
raw,
|
|
2392
|
+
scope,
|
|
2393
|
+
tokenSymbol,
|
|
2394
|
+
Object.keys(usdPrices).length ? usdPrices : void 0
|
|
2395
|
+
);
|
|
2349
2396
|
}
|
|
2350
2397
|
/**
|
|
2351
2398
|
* Today's ETH/USD from Chainlink, cached for a minute. Every day of the
|
|
@@ -2353,24 +2400,38 @@ var ZyfaiAgent = class _ZyfaiAgent {
|
|
|
2353
2400
|
* move over the window is not reflected (ROUT-682). Undefined on failure,
|
|
2354
2401
|
* which leaves the series on token-amount weighting rather than failing it.
|
|
2355
2402
|
*/
|
|
2356
|
-
|
|
2357
|
-
|
|
2358
|
-
|
|
2403
|
+
readEthUsd(chainId) {
|
|
2404
|
+
return this.readChainlinkUsd(
|
|
2405
|
+
chainId,
|
|
2406
|
+
CHAINLINK_ETH_USD_FEED[chainId],
|
|
2407
|
+
"ethUsd"
|
|
2408
|
+
);
|
|
2409
|
+
}
|
|
2410
|
+
/** Today's EUR/USD from Chainlink on Ethereum, for pricing EURC (ROUT-308). */
|
|
2411
|
+
readEurUsd() {
|
|
2412
|
+
return this.readChainlinkUsd(1, CHAINLINK_EUR_USD_FEED, "eurUsd");
|
|
2413
|
+
}
|
|
2414
|
+
async readChainlinkUsd(chainId, feed, cache) {
|
|
2415
|
+
const cached = this[cache];
|
|
2416
|
+
if (cached && Date.now() - cached.at < ETH_USD_TTL_MS) {
|
|
2417
|
+
return cached.price;
|
|
2359
2418
|
}
|
|
2360
2419
|
try {
|
|
2361
2420
|
const [, answer] = await this.getPublicClient(chainId).readContract({
|
|
2362
|
-
address:
|
|
2421
|
+
address: feed,
|
|
2363
2422
|
abi: CHAINLINK_ABI,
|
|
2364
2423
|
functionName: "latestRoundData"
|
|
2365
2424
|
});
|
|
2366
2425
|
const price = Number(answer) / 1e8;
|
|
2367
2426
|
if (!Number.isFinite(price) || price <= 0) return void 0;
|
|
2368
|
-
this
|
|
2427
|
+
this[cache] = { price, at: Date.now() };
|
|
2369
2428
|
return price;
|
|
2370
2429
|
} catch (err) {
|
|
2371
|
-
debugLog(
|
|
2372
|
-
|
|
2373
|
-
|
|
2430
|
+
debugLog(
|
|
2431
|
+
"zyfai:apy",
|
|
2432
|
+
`${cache === "ethUsd" ? "ETH/USD" : "EUR/USD"} read failed; token-amount weighting`,
|
|
2433
|
+
{ err }
|
|
2434
|
+
);
|
|
2374
2435
|
return void 0;
|
|
2375
2436
|
}
|
|
2376
2437
|
}
|
|
@@ -2401,6 +2462,7 @@ var ZyfaiAgent = class _ZyfaiAgent {
|
|
|
2401
2462
|
return "eth";
|
|
2402
2463
|
case "EURC":
|
|
2403
2464
|
return "eurc";
|
|
2465
|
+
// Zyfai has no "usdt" history filter, so USDT is filtered client-side.
|
|
2404
2466
|
default:
|
|
2405
2467
|
return void 0;
|
|
2406
2468
|
}
|
|
@@ -2409,6 +2471,9 @@ var ZyfaiAgent = class _ZyfaiAgent {
|
|
|
2409
2471
|
const { smartWallet, chainId: validChainId } = await this.resolveSmartWallet(state, chainId);
|
|
2410
2472
|
const limit = options?.limit ?? 10;
|
|
2411
2473
|
const assetType = _ZyfaiAgent.toZyfaiAssetType(options?.tokenSymbol);
|
|
2474
|
+
const clientSideAsset = !assetType && options?.tokenSymbol && SUPPORTED_TOKENS.includes(
|
|
2475
|
+
options.tokenSymbol.toUpperCase()
|
|
2476
|
+
) ? options.tokenSymbol : void 0;
|
|
2412
2477
|
const cursor = options?.cursor ? decodeHistoryCursor(options.cursor) : null;
|
|
2413
2478
|
const toDate = cursor?.toDate ?? options?.toDate ?? (/* @__PURE__ */ new Date()).toISOString();
|
|
2414
2479
|
let offset = cursor?.rawOffset ?? 0;
|
|
@@ -2430,6 +2495,12 @@ var ZyfaiAgent = class _ZyfaiAgent {
|
|
|
2430
2495
|
assetType
|
|
2431
2496
|
});
|
|
2432
2497
|
raw.data.forEach((entry, idx) => {
|
|
2498
|
+
if (clientSideAsset && !matchesAsset(
|
|
2499
|
+
entry.positions?.[0]?.token_symbol ?? "",
|
|
2500
|
+
clientSideAsset
|
|
2501
|
+
)) {
|
|
2502
|
+
return;
|
|
2503
|
+
}
|
|
2433
2504
|
if (entry.chainId === validChainId) {
|
|
2434
2505
|
matched.push({ entry, rawIdx: offset + idx });
|
|
2435
2506
|
}
|
|
@@ -2472,6 +2543,20 @@ var ZyfaiAgent = class _ZyfaiAgent {
|
|
|
2472
2543
|
}
|
|
2473
2544
|
async ensureAutoSelectProtocols(state, chainId, asset) {
|
|
2474
2545
|
await this.connectAuth(state, chainId);
|
|
2546
|
+
return this.syncAutoSelect(chainId, asset);
|
|
2547
|
+
}
|
|
2548
|
+
/**
|
|
2549
|
+
* Zyfai's first-deposit setup keys off the USDC profile alone: once USDC is
|
|
2550
|
+
* configured it reports `{ applied: false }` for every asset, so an existing
|
|
2551
|
+
* user's first EURC/USDT keeps a chainless profile and the deposit sits as
|
|
2552
|
+
* an idle stale balance (ROUT-308). Configured USDC is what marks such a
|
|
2553
|
+
* user; a brand-new one is still left to first-deposit setup.
|
|
2554
|
+
*/
|
|
2555
|
+
async isExistingZyfaiUser() {
|
|
2556
|
+
const usdc = await this.sdk.getUserDetails("USDC");
|
|
2557
|
+
return (usdc.chains?.length ?? 0) > 0 && (usdc.protocols?.length ?? 0) > 0;
|
|
2558
|
+
}
|
|
2559
|
+
async syncAutoSelect(chainId, asset) {
|
|
2475
2560
|
const current = await this.sdk.getUserDetails(asset);
|
|
2476
2561
|
debugLog("zyfai:auto-select", `${asset}: profile before check`, {
|
|
2477
2562
|
autoSelectProtocols: current.autoSelectProtocols,
|
|
@@ -2479,7 +2564,7 @@ var ZyfaiAgent = class _ZyfaiAgent {
|
|
|
2479
2564
|
protocols: current.protocols,
|
|
2480
2565
|
strategy: current.strategy
|
|
2481
2566
|
});
|
|
2482
|
-
if ((current.chains?.length ?? 0) === 0) {
|
|
2567
|
+
if ((current.chains?.length ?? 0) === 0 && (asset === "USDC" || !await this.isExistingZyfaiUser())) {
|
|
2483
2568
|
debugLog(
|
|
2484
2569
|
"zyfai:auto-select",
|
|
2485
2570
|
`${asset}: skipping untouched profile until first deposit`
|
|
@@ -2628,6 +2713,35 @@ function mergeDailyEarnings(series) {
|
|
|
2628
2713
|
|
|
2629
2714
|
// src/lib/routing-api.ts
|
|
2630
2715
|
var ROUTING_API_BASE_URL = "https://owney-routing-api-243946518160.europe-west4.run.app";
|
|
2716
|
+
async function fetchApyIncentives(apiKey, input, baseUrl = ROUTING_API_BASE_URL) {
|
|
2717
|
+
const query = new URLSearchParams({
|
|
2718
|
+
walletAddress: input.walletAddress,
|
|
2719
|
+
agentId: input.agentId,
|
|
2720
|
+
chainId: String(input.chainId),
|
|
2721
|
+
asset: input.asset.toUpperCase(),
|
|
2722
|
+
from: input.from,
|
|
2723
|
+
to: input.to
|
|
2724
|
+
});
|
|
2725
|
+
try {
|
|
2726
|
+
const response = await fetch(`${baseUrl}/api/v1/apy-incentives?${query}`, {
|
|
2727
|
+
headers: {
|
|
2728
|
+
Accept: "application/json",
|
|
2729
|
+
"x-owney-api-key": apiKey
|
|
2730
|
+
}
|
|
2731
|
+
});
|
|
2732
|
+
if (!response.ok) return [];
|
|
2733
|
+
const body = await response.json();
|
|
2734
|
+
if (!body.success || !Array.isArray(body.data)) return [];
|
|
2735
|
+
return body.data.filter(
|
|
2736
|
+
(item) => item && typeof item.date === "string" && item.source === "merkl" && typeof item.opportunityId === "string" && Array.isArray(item.campaignIds) && Number.isFinite(item.apr) && Number.isFinite(item.apyContribution)
|
|
2737
|
+
);
|
|
2738
|
+
} catch (error) {
|
|
2739
|
+
debugLog("owney-sdk", "APY incentives unavailable; using native APY", {
|
|
2740
|
+
error: error instanceof Error ? error.message : String(error)
|
|
2741
|
+
});
|
|
2742
|
+
return [];
|
|
2743
|
+
}
|
|
2744
|
+
}
|
|
2631
2745
|
async function fetchOrgAgentConfig(apiKey, baseUrl = ROUTING_API_BASE_URL) {
|
|
2632
2746
|
const url = `${baseUrl}/api/v1/agent/org-config`;
|
|
2633
2747
|
try {
|
|
@@ -3335,6 +3449,20 @@ async function readErc20Balance(publicClient, token, owner) {
|
|
|
3335
3449
|
});
|
|
3336
3450
|
}
|
|
3337
3451
|
|
|
3452
|
+
// src/lib/erc20-approve.ts
|
|
3453
|
+
var ZERO_RESET_TOKENS = /* @__PURE__ */ new Set([
|
|
3454
|
+
"0xdac17f958d2ee523a2206206994597c13d831ec7"
|
|
3455
|
+
]);
|
|
3456
|
+
function needsAllowanceReset(token) {
|
|
3457
|
+
return ZERO_RESET_TOKENS.has(token.toLowerCase());
|
|
3458
|
+
}
|
|
3459
|
+
async function approveWithResetIfNeeded(input) {
|
|
3460
|
+
if (input.currentAllowance > 0n && needsAllowanceReset(input.token)) {
|
|
3461
|
+
await input.approve(input.spender, 0n);
|
|
3462
|
+
}
|
|
3463
|
+
return input.approve(input.spender, input.amount);
|
|
3464
|
+
}
|
|
3465
|
+
|
|
3338
3466
|
// src/lib/swap/swap.secrets.ts
|
|
3339
3467
|
var import_viem4 = require("viem");
|
|
3340
3468
|
var SECRET_BYTES = 32;
|
|
@@ -3693,6 +3821,15 @@ async function executeSwap(deps, options) {
|
|
|
3693
3821
|
}
|
|
3694
3822
|
return { received: arrived.toString(), ...result ?? {} };
|
|
3695
3823
|
}
|
|
3824
|
+
function approveMax(deps, token, current, spender) {
|
|
3825
|
+
return approveWithResetIfNeeded({
|
|
3826
|
+
token,
|
|
3827
|
+
currentAllowance: current,
|
|
3828
|
+
spender,
|
|
3829
|
+
amount: MAX_UINT256,
|
|
3830
|
+
approve: deps.approve
|
|
3831
|
+
});
|
|
3832
|
+
}
|
|
3696
3833
|
async function runClassic(deps, options) {
|
|
3697
3834
|
const {
|
|
3698
3835
|
quote,
|
|
@@ -3729,7 +3866,7 @@ async function runClassic(deps, options) {
|
|
|
3729
3866
|
if (current < needed) {
|
|
3730
3867
|
onStage?.("approving");
|
|
3731
3868
|
await deps.ensureChain(quote.src.chainId);
|
|
3732
|
-
await deps.
|
|
3869
|
+
await approveMax(deps, quote.src.address, current, tx.to);
|
|
3733
3870
|
debugLog(
|
|
3734
3871
|
"owney-sdk",
|
|
3735
3872
|
"swap: re-fetching classic calldata after approval"
|
|
@@ -3818,7 +3955,7 @@ async function authoriseSpend(deps, options, amount, isNativeSource) {
|
|
|
3818
3955
|
});
|
|
3819
3956
|
return permit;
|
|
3820
3957
|
}
|
|
3821
|
-
await deps.
|
|
3958
|
+
await approveMax(deps, quote.src.address, current, quote.spender);
|
|
3822
3959
|
debugLog("owney-sdk", "swap: approved limit order protocol");
|
|
3823
3960
|
return void 0;
|
|
3824
3961
|
}
|
|
@@ -4316,9 +4453,40 @@ function aggregateApyHistory(agentApys) {
|
|
|
4316
4453
|
const total = points.reduce((sum, p) => sum + p.historicalBalance.amount, 0);
|
|
4317
4454
|
if (total <= 0 || !Number.isFinite(total)) return [];
|
|
4318
4455
|
const apy = points.reduce((sum, p) => sum + p.apy * (p.historicalBalance.amount / total), 0);
|
|
4319
|
-
|
|
4456
|
+
if (!Number.isFinite(apy)) return [];
|
|
4457
|
+
const incentives = aggregateIncentives(points, total);
|
|
4458
|
+
return [{ date, apy, ...incentives.length > 0 ? { incentives } : {} }];
|
|
4320
4459
|
});
|
|
4321
4460
|
}
|
|
4461
|
+
function incentiveKey(incentive) {
|
|
4462
|
+
return JSON.stringify([
|
|
4463
|
+
incentive.source,
|
|
4464
|
+
incentive.agentId,
|
|
4465
|
+
incentive.opportunityId,
|
|
4466
|
+
[...incentive.campaignIds].sort()
|
|
4467
|
+
]);
|
|
4468
|
+
}
|
|
4469
|
+
function aggregateIncentives(points, totalBalance) {
|
|
4470
|
+
const byProgram = /* @__PURE__ */ new Map();
|
|
4471
|
+
for (const point of points) {
|
|
4472
|
+
const weight = point.historicalBalance.amount / totalBalance;
|
|
4473
|
+
for (const incentive of point.incentives ?? []) {
|
|
4474
|
+
if (!Number.isFinite(incentive.apr) || !Number.isFinite(incentive.apyContribution)) continue;
|
|
4475
|
+
const key2 = incentiveKey(incentive);
|
|
4476
|
+
const existing = byProgram.get(key2);
|
|
4477
|
+
if (existing) {
|
|
4478
|
+
existing.apyContribution += incentive.apyContribution * weight;
|
|
4479
|
+
} else {
|
|
4480
|
+
byProgram.set(key2, {
|
|
4481
|
+
...incentive,
|
|
4482
|
+
campaignIds: [...incentive.campaignIds],
|
|
4483
|
+
apyContribution: incentive.apyContribution * weight
|
|
4484
|
+
});
|
|
4485
|
+
}
|
|
4486
|
+
}
|
|
4487
|
+
}
|
|
4488
|
+
return [...byProgram.values()];
|
|
4489
|
+
}
|
|
4322
4490
|
function aggregateApyByChainAndAsset(agentApys, agentBalances) {
|
|
4323
4491
|
const sums = {};
|
|
4324
4492
|
const weights = {};
|
|
@@ -4726,7 +4894,7 @@ function makeSponsoredWethCallback(deps) {
|
|
|
4726
4894
|
if (!token) {
|
|
4727
4895
|
throw new OwneyError(
|
|
4728
4896
|
"CHAIN_UNSUPPORTED",
|
|
4729
|
-
`No sponsored
|
|
4897
|
+
`No sponsored ${deps.assetSymbol} configured for chain ${chainId}`
|
|
4730
4898
|
);
|
|
4731
4899
|
}
|
|
4732
4900
|
const amountWei = BigInt(amount);
|
|
@@ -4739,14 +4907,14 @@ function makeSponsoredWethCallback(deps) {
|
|
|
4739
4907
|
if (balance < amountWei) {
|
|
4740
4908
|
throw new OwneyError(
|
|
4741
4909
|
"DEPOSIT_INSUFFICIENT_BALANCE",
|
|
4742
|
-
|
|
4910
|
+
`Insufficient ${deps.assetSymbol} balance for this deposit.`,
|
|
4743
4911
|
{ token, chainId: cid, balance: balance.toString(), amount }
|
|
4744
4912
|
);
|
|
4745
4913
|
}
|
|
4746
4914
|
} catch (err) {
|
|
4747
4915
|
if (err instanceof OwneyError) throw err;
|
|
4748
4916
|
console.warn(
|
|
4749
|
-
|
|
4917
|
+
`[owney-sdk] ${deps.assetSymbol} balance pre-check failed (non-fatal):`,
|
|
4750
4918
|
err instanceof Error ? err.message : String(err)
|
|
4751
4919
|
);
|
|
4752
4920
|
}
|
|
@@ -4758,7 +4926,7 @@ function makeSponsoredWethCallback(deps) {
|
|
|
4758
4926
|
if (allowance < amountWei) {
|
|
4759
4927
|
throw new OwneyError(
|
|
4760
4928
|
"PERMIT2_APPROVAL_REQUIRED",
|
|
4761
|
-
|
|
4929
|
+
`${deps.assetSymbol} gasless deposits need a one-time Permit2 approval; call approvePermit2() first`,
|
|
4762
4930
|
{ token, chainId: cid, allowance: allowance.toString(), amount }
|
|
4763
4931
|
);
|
|
4764
4932
|
}
|
|
@@ -4945,8 +5113,22 @@ var SPONSORED_WETH_BY_CHAIN = {
|
|
|
4945
5113
|
42161: "0x82aF49447D8a07e3bd95BD0d56f35241523fBab1",
|
|
4946
5114
|
1: "0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2"
|
|
4947
5115
|
};
|
|
5116
|
+
function sponsoredTokenMap(asset) {
|
|
5117
|
+
if (asset === "USDC") return SPONSORED_USDC_BY_CHAIN;
|
|
5118
|
+
if (asset === "WETH") return SPONSORED_WETH_BY_CHAIN;
|
|
5119
|
+
return Object.fromEntries(
|
|
5120
|
+
SUPPORTED_CHAIN_IDS.flatMap((id) => {
|
|
5121
|
+
const a = tokenAddress(asset, id);
|
|
5122
|
+
return a ? [[id, a]] : [];
|
|
5123
|
+
})
|
|
5124
|
+
);
|
|
5125
|
+
}
|
|
5126
|
+
var PERMIT2_ASSETS = /* @__PURE__ */ new Set(["WETH", "USDT"]);
|
|
5127
|
+
function isPermit2Asset(asset) {
|
|
5128
|
+
return PERMIT2_ASSETS.has(asset);
|
|
5129
|
+
}
|
|
4948
5130
|
function shouldFallbackToUserPaid(error, asset, appCallback) {
|
|
4949
|
-
return (asset
|
|
5131
|
+
return SUPPORTED_TOKENS.includes(asset) && appCallback === void 0 && error instanceof OwneyError && error.code === "SPONSOR_REQUEST_FAILED" && error.details?.safeToFallback === true;
|
|
4950
5132
|
}
|
|
4951
5133
|
var OwneySDK = class {
|
|
4952
5134
|
agents = /* @__PURE__ */ new Map();
|
|
@@ -4969,8 +5151,8 @@ var OwneySDK = class {
|
|
|
4969
5151
|
userPoolCustomization = false;
|
|
4970
5152
|
routingApiBaseUrl;
|
|
4971
5153
|
referralSource;
|
|
4972
|
-
|
|
4973
|
-
|
|
5154
|
+
cachedSponsoredCallbacks = /* @__PURE__ */ new Map();
|
|
5155
|
+
cachedPermit2SponsoredCallbacks = /* @__PURE__ */ new Map();
|
|
4974
5156
|
paymasterServiceUrl;
|
|
4975
5157
|
cachedSponsoredCallsCallbacks = /* @__PURE__ */ new Map();
|
|
4976
5158
|
agentReads = new AgentReads();
|
|
@@ -5018,8 +5200,8 @@ var OwneySDK = class {
|
|
|
5018
5200
|
walletAddress,
|
|
5019
5201
|
chainId: null
|
|
5020
5202
|
};
|
|
5021
|
-
this.
|
|
5022
|
-
this.
|
|
5203
|
+
this.cachedSponsoredCallbacks.clear();
|
|
5204
|
+
this.cachedPermit2SponsoredCallbacks.clear();
|
|
5023
5205
|
this.cachedSponsoredCallsCallbacks.clear();
|
|
5024
5206
|
}
|
|
5025
5207
|
/**
|
|
@@ -5035,8 +5217,8 @@ var OwneySDK = class {
|
|
|
5035
5217
|
this.agentReads.clearInFlight();
|
|
5036
5218
|
this.activationChecks.clear();
|
|
5037
5219
|
this.state = null;
|
|
5038
|
-
this.
|
|
5039
|
-
this.
|
|
5220
|
+
this.cachedSponsoredCallbacks.clear();
|
|
5221
|
+
this.cachedPermit2SponsoredCallbacks.clear();
|
|
5040
5222
|
this.cachedSponsoredCallsCallbacks.clear();
|
|
5041
5223
|
}
|
|
5042
5224
|
isAgentDisabled(agentId) {
|
|
@@ -5086,9 +5268,9 @@ var OwneySDK = class {
|
|
|
5086
5268
|
* provider with viem `custom(provider)` to read token meta and sign the
|
|
5087
5269
|
* `TransferWithAuthorization`, then POSTs to the sponsor API.
|
|
5088
5270
|
*/
|
|
5089
|
-
getDefaultSponsoredCallback(onApproved) {
|
|
5090
|
-
|
|
5091
|
-
|
|
5271
|
+
getDefaultSponsoredCallback(asset, onApproved) {
|
|
5272
|
+
const cached = this.cachedSponsoredCallbacks.get(asset);
|
|
5273
|
+
if (!onApproved && cached) return cached;
|
|
5092
5274
|
const provider = this.requireConnectedProvider();
|
|
5093
5275
|
const owner = this.state.walletAddress;
|
|
5094
5276
|
const callback = makeSponsoredDepositCallback({
|
|
@@ -5096,7 +5278,7 @@ var OwneySDK = class {
|
|
|
5096
5278
|
baseUrl: this.routingApiBaseUrl,
|
|
5097
5279
|
ownerAddress: owner,
|
|
5098
5280
|
onApproved,
|
|
5099
|
-
tokenAddressByChain:
|
|
5281
|
+
tokenAddressByChain: sponsoredTokenMap(asset),
|
|
5100
5282
|
// Casts work around viem's chain-narrowed Client vs the generic
|
|
5101
5283
|
// PublicClient/WalletClient param types — structurally identical at
|
|
5102
5284
|
// runtime, but the two share a name TS treats as unrelated.
|
|
@@ -5113,14 +5295,13 @@ var OwneySDK = class {
|
|
|
5113
5295
|
transport: (0, import_viem9.custom)(provider)
|
|
5114
5296
|
})
|
|
5115
5297
|
});
|
|
5116
|
-
if (!onApproved) this.
|
|
5298
|
+
if (!onApproved) this.cachedSponsoredCallbacks.set(asset, callback);
|
|
5117
5299
|
return callback;
|
|
5118
5300
|
}
|
|
5119
5301
|
/**
|
|
5120
|
-
* Lazily builds (and caches) the default
|
|
5121
|
-
* callback used when the caller omits `depositCallback`
|
|
5122
|
-
*
|
|
5123
|
-
* `PermitTransferFrom` instead of an EIP-3009 authorization.
|
|
5302
|
+
* Lazily builds (and caches, per asset) the default paymaster-sponsored
|
|
5303
|
+
* deposit callback used when the caller omits `depositCallback` and a
|
|
5304
|
+
* `paymasterServiceUrl` is configured. One rail serves every asset.
|
|
5124
5305
|
*/
|
|
5125
5306
|
getDefaultSponsoredCallsCallback(asset, onApproved) {
|
|
5126
5307
|
const cached = this.cachedSponsoredCallsCallbacks.get(asset);
|
|
@@ -5131,20 +5312,20 @@ var OwneySDK = class {
|
|
|
5131
5312
|
ownerAddress: this.state.walletAddress,
|
|
5132
5313
|
paymasterServiceUrl: this.paymasterServiceUrl,
|
|
5133
5314
|
onApproved,
|
|
5134
|
-
tokenAddressByChain: asset
|
|
5315
|
+
tokenAddressByChain: sponsoredTokenMap(asset)
|
|
5135
5316
|
});
|
|
5136
5317
|
if (!onApproved) this.cachedSponsoredCallsCallbacks.set(asset, callback);
|
|
5137
5318
|
return callback;
|
|
5138
5319
|
}
|
|
5139
5320
|
/**
|
|
5140
|
-
* Lazily builds (and caches) the default Permit2 sponsored
|
|
5141
|
-
* callback used when the caller omits `depositCallback` for a
|
|
5142
|
-
* Mirrors `getDefaultSponsoredCallback()` but
|
|
5143
|
-
* `PermitTransferFrom` instead of an EIP-3009 authorization.
|
|
5321
|
+
* Lazily builds (and caches, per asset) the default Permit2 sponsored
|
|
5322
|
+
* deposit callback used when the caller omits `depositCallback` for a
|
|
5323
|
+
* Permit2 asset (WETH, USDT). Mirrors `getDefaultSponsoredCallback()` but
|
|
5324
|
+
* signs a Permit2 `PermitTransferFrom` instead of an EIP-3009 authorization.
|
|
5144
5325
|
*/
|
|
5145
|
-
|
|
5146
|
-
|
|
5147
|
-
|
|
5326
|
+
getDefaultPermit2SponsoredCallback(asset, onApproved) {
|
|
5327
|
+
const cached = this.cachedPermit2SponsoredCallbacks.get(asset);
|
|
5328
|
+
if (!onApproved && cached) return cached;
|
|
5148
5329
|
const provider = this.requireConnectedProvider();
|
|
5149
5330
|
const owner = this.state.walletAddress;
|
|
5150
5331
|
const callback = makeSponsoredWethCallback({
|
|
@@ -5152,7 +5333,8 @@ var OwneySDK = class {
|
|
|
5152
5333
|
baseUrl: this.routingApiBaseUrl,
|
|
5153
5334
|
ownerAddress: owner,
|
|
5154
5335
|
onApproved,
|
|
5155
|
-
tokenAddressByChain:
|
|
5336
|
+
tokenAddressByChain: sponsoredTokenMap(asset),
|
|
5337
|
+
assetSymbol: asset,
|
|
5156
5338
|
// Casts work around viem's chain-narrowed Client vs the generic
|
|
5157
5339
|
// PublicClient/WalletClient param types — structurally identical at
|
|
5158
5340
|
// runtime, but the two share a name TS treats as unrelated.
|
|
@@ -5169,7 +5351,7 @@ var OwneySDK = class {
|
|
|
5169
5351
|
transport: (0, import_viem9.custom)(provider)
|
|
5170
5352
|
})
|
|
5171
5353
|
});
|
|
5172
|
-
if (!onApproved) this.
|
|
5354
|
+
if (!onApproved) this.cachedPermit2SponsoredCallbacks.set(asset, callback);
|
|
5173
5355
|
return callback;
|
|
5174
5356
|
}
|
|
5175
5357
|
getAgent(agentId) {
|
|
@@ -5427,7 +5609,8 @@ var OwneySDK = class {
|
|
|
5427
5609
|
}
|
|
5428
5610
|
const state = this.requireState();
|
|
5429
5611
|
const chainId = options.chainId ?? this.requireChainId();
|
|
5430
|
-
const
|
|
5612
|
+
const sponsoredAsset = asset;
|
|
5613
|
+
const effectiveCallback = depositCallback ?? (this.paymasterServiceUrl ? this.getDefaultSponsoredCallsCallback(sponsoredAsset, onApproved) : isPermit2Asset(sponsoredAsset) ? this.getDefaultPermit2SponsoredCallback(sponsoredAsset, onApproved) : this.getDefaultSponsoredCallback(sponsoredAsset, onApproved));
|
|
5431
5614
|
if (agentId) {
|
|
5432
5615
|
if (this.isAgentDisabled(agentId)) {
|
|
5433
5616
|
throw new OwneyError(
|
|
@@ -5541,15 +5724,16 @@ var OwneySDK = class {
|
|
|
5541
5724
|
*
|
|
5542
5725
|
* 1. Missing Permit2 allowance: when the app did not supply its own
|
|
5543
5726
|
* callback and the attempt fails with `PERMIT2_APPROVAL_REQUIRED` on a
|
|
5544
|
-
* WETH
|
|
5545
|
-
* the one-time (user-paid) Permit2
|
|
5546
|
-
* retry the SAME sponsored
|
|
5547
|
-
*
|
|
5548
|
-
*
|
|
5727
|
+
* Permit2 asset (WETH, USDT), this is the wallet's first gasless deposit
|
|
5728
|
+
* of that asset on this chain. We send the one-time (user-paid) Permit2
|
|
5729
|
+
* approval via `approvePermit2(asset)` and retry the SAME sponsored
|
|
5730
|
+
* attempt once. Bounded to one approval attempt per call so a
|
|
5731
|
+
* wallet/agent that keeps reporting the allowance as missing can't loop
|
|
5732
|
+
* forever. If `approvePermit2()` itself throws (e.g.
|
|
5549
5733
|
* the user rejects the wallet prompt), that error propagates as-is —
|
|
5550
5734
|
* the user said no to a transaction, so we must not turn around and ask
|
|
5551
5735
|
* them to pay for a different one via the fallback below.
|
|
5552
|
-
* 2. `shouldFallbackToUserPaid`: the SDK's own
|
|
5736
|
+
* 2. `shouldFallbackToUserPaid`: the SDK's own sponsor path failed at
|
|
5553
5737
|
* the infrastructure layer in a provably safe-to-retry way, so we warn
|
|
5554
5738
|
* and retry once with `undefined`, falling through to a user-paid
|
|
5555
5739
|
* native deposit. This still applies after a successful Permit2
|
|
@@ -5578,12 +5762,12 @@ var OwneySDK = class {
|
|
|
5578
5762
|
try {
|
|
5579
5763
|
return await attempt(effectiveCallback);
|
|
5580
5764
|
} catch (error) {
|
|
5581
|
-
if (!approvalAttempted && appCallback === void 0 && asset
|
|
5765
|
+
if (!approvalAttempted && appCallback === void 0 && isPermit2Asset(asset) && error instanceof OwneyError && error.code === "PERMIT2_APPROVAL_REQUIRED") {
|
|
5582
5766
|
approvalAttempted = true;
|
|
5583
5767
|
console.warn(
|
|
5584
|
-
|
|
5768
|
+
`[owney-sdk] First ${asset} deposit: sending one-time Permit2 approval...`
|
|
5585
5769
|
);
|
|
5586
|
-
await this.approvePermit2();
|
|
5770
|
+
await this.approvePermit2(asset);
|
|
5587
5771
|
continue;
|
|
5588
5772
|
}
|
|
5589
5773
|
if (!shouldFallbackToUserPaid(error, asset, appCallback)) throw error;
|
|
@@ -6029,11 +6213,18 @@ var OwneySDK = class {
|
|
|
6029
6213
|
account: state.walletAddress,
|
|
6030
6214
|
chain: srcChain
|
|
6031
6215
|
});
|
|
6032
|
-
await srcPublic.waitForTransactionReceipt({
|
|
6216
|
+
const receipt = await srcPublic.waitForTransactionReceipt({
|
|
6033
6217
|
hash,
|
|
6034
6218
|
confirmations: 1,
|
|
6035
6219
|
timeout: receiptTimeoutMs(quote.src.chainId)
|
|
6036
6220
|
});
|
|
6221
|
+
if (receipt.status !== "success") {
|
|
6222
|
+
throw new OwneyError(
|
|
6223
|
+
"SWAP_REQUEST_FAILED",
|
|
6224
|
+
`Approval transaction reverted (tx ${hash})`,
|
|
6225
|
+
{ hash }
|
|
6226
|
+
);
|
|
6227
|
+
}
|
|
6037
6228
|
return hash;
|
|
6038
6229
|
},
|
|
6039
6230
|
ensureChain: (chainId) => this.ensureSwapChain(chainId),
|
|
@@ -6123,30 +6314,33 @@ var OwneySDK = class {
|
|
|
6123
6314
|
* figure directly. It is the entire arrival, so there is no slack: anything
|
|
6124
6315
|
* that spends the target asset between the two fails the deposit outright.
|
|
6125
6316
|
*
|
|
6126
|
-
* Something does. A first
|
|
6127
|
-
* and that approval is a transaction.
|
|
6128
|
-
*
|
|
6129
|
-
* for it out of the WETH. The
|
|
6130
|
-
*
|
|
6131
|
-
* the funds were safe
|
|
6317
|
+
* Something does. A first deposit of a Permit2 asset (WETH, USDT) needs a
|
|
6318
|
+
* one-time Permit2 approval, and that approval is a transaction. For WETH,
|
|
6319
|
+
* a wallet holding no native gas token - the normal state of someone who
|
|
6320
|
+
* just swapped everything INTO WETH - pays for it out of the WETH. The
|
|
6321
|
+
* deposit then asked for ~2e12 wei more than was left and refused with
|
|
6322
|
+
* DEPOSIT_INSUFFICIENT_BALANCE, under a wrapper saying the funds were safe
|
|
6323
|
+
* but unadded (ROUT-242). For USDT the gas cannot come out of the token, so
|
|
6324
|
+
* this step only adds the one-time approval and the read changes nothing.
|
|
6132
6325
|
*
|
|
6133
6326
|
* So the approval happens here, before the amount is settled, and the amount
|
|
6134
6327
|
* comes from a read taken after it. Two things this deliberately is not:
|
|
6135
6328
|
*
|
|
6136
6329
|
* - It is not a balance sweep. `received` is a DELTA over the pre-swap
|
|
6137
|
-
* balance, so a wallet already holding
|
|
6138
|
-
* the balance would move funds the user never offered. The
|
|
6139
|
-
* ceiling and the balance is only ever allowed to lower it.
|
|
6140
|
-
* - It does not touch USDC, which
|
|
6141
|
-
* nothing of the user's in between, nor a
|
|
6142
|
-
* where the sponsor covers the transfer and
|
|
6330
|
+
* balance, so a wallet already holding the asset reads far above it;
|
|
6331
|
+
* depositing the balance would move funds the user never offered. The
|
|
6332
|
+
* arrival is the ceiling and the balance is only ever allowed to lower it.
|
|
6333
|
+
* - It does not touch USDC or EURC, which move on signed typed data
|
|
6334
|
+
* (EIP-3009) and so spend nothing of the user's in between, nor a
|
|
6335
|
+
* paymaster-configured client, where the sponsor covers the transfer and
|
|
6336
|
+
* Permit2 never applies.
|
|
6143
6337
|
*/
|
|
6144
6338
|
async settleSwapDepositAmount(chainId, token, symbol, received) {
|
|
6145
|
-
if (symbol
|
|
6339
|
+
if (!isPermit2Asset(symbol) || this.paymasterServiceUrl) {
|
|
6146
6340
|
return received.toString();
|
|
6147
6341
|
}
|
|
6148
6342
|
const allowance = await this.readTokenPermit2Allowance(chainId, token);
|
|
6149
|
-
if (allowance < received) await this.approvePermit2();
|
|
6343
|
+
if (allowance < received) await this.approvePermit2(symbol);
|
|
6150
6344
|
const balance = await this.readTokenBalance(chainId, token);
|
|
6151
6345
|
return (balance < received ? balance : received).toString();
|
|
6152
6346
|
}
|
|
@@ -6311,7 +6505,10 @@ var OwneySDK = class {
|
|
|
6311
6505
|
);
|
|
6312
6506
|
}
|
|
6313
6507
|
await this.ensureSwapChain(entry.chainId);
|
|
6314
|
-
const
|
|
6508
|
+
const supported = SUPPORTED_TOKENS.includes(
|
|
6509
|
+
entry.symbol
|
|
6510
|
+
);
|
|
6511
|
+
const token = supported ? sponsoredTokenMap(entry.symbol)[entry.chainId] : void 0;
|
|
6315
6512
|
const amount = token ? await this.settleSwapDepositAmount(
|
|
6316
6513
|
entry.chainId,
|
|
6317
6514
|
token,
|
|
@@ -7211,12 +7408,18 @@ var OwneySDK = class {
|
|
|
7211
7408
|
const scopeChainId = scope === "all" ? null : scope;
|
|
7212
7409
|
if (agentId) {
|
|
7213
7410
|
const agent = this.getAgent(agentId);
|
|
7214
|
-
|
|
7411
|
+
const accountApy = await this.readAgent(
|
|
7215
7412
|
agent,
|
|
7216
7413
|
"accountApy",
|
|
7217
7414
|
() => agent.getAccountApy(state, chainId, days, tokenSymbol, scopeChainId),
|
|
7218
7415
|
{ days, tokenSymbol, scopeChainId }
|
|
7219
7416
|
);
|
|
7417
|
+
return this.enrichApyHistory(
|
|
7418
|
+
accountApy,
|
|
7419
|
+
agentId,
|
|
7420
|
+
scopeChainId === null ? void 0 : scopeChainId ?? chainId,
|
|
7421
|
+
tokenSymbol
|
|
7422
|
+
);
|
|
7220
7423
|
}
|
|
7221
7424
|
const activeAgents = this.getActiveAgents();
|
|
7222
7425
|
const entries = [...activeAgents.entries()];
|
|
@@ -7251,7 +7454,12 @@ var OwneySDK = class {
|
|
|
7251
7454
|
]);
|
|
7252
7455
|
const results = {};
|
|
7253
7456
|
for (const [id, apy] of apyResults) {
|
|
7254
|
-
results[id] =
|
|
7457
|
+
results[id] = await this.enrichApyHistory(
|
|
7458
|
+
apy,
|
|
7459
|
+
id,
|
|
7460
|
+
scopeChainId === null ? void 0 : scopeChainId ?? chainId,
|
|
7461
|
+
tokenSymbol
|
|
7462
|
+
);
|
|
7255
7463
|
}
|
|
7256
7464
|
const balances = {};
|
|
7257
7465
|
for (const [id, bal] of balanceResults) {
|
|
@@ -7281,6 +7489,36 @@ var OwneySDK = class {
|
|
|
7281
7489
|
history
|
|
7282
7490
|
};
|
|
7283
7491
|
}
|
|
7492
|
+
async enrichApyHistory(accountApy, agentId, chainId, tokenSymbol) {
|
|
7493
|
+
const history = accountApy.history;
|
|
7494
|
+
if (agentId !== "zyfai" || chainId === void 0 || !tokenSymbol || !history?.length) return accountApy;
|
|
7495
|
+
const incentives = await fetchApyIncentives(
|
|
7496
|
+
this.apiKey,
|
|
7497
|
+
{
|
|
7498
|
+
walletAddress: accountApy.walletAddress,
|
|
7499
|
+
agentId,
|
|
7500
|
+
chainId,
|
|
7501
|
+
asset: tokenSymbol,
|
|
7502
|
+
from: history[0].date,
|
|
7503
|
+
to: history[history.length - 1].date
|
|
7504
|
+
},
|
|
7505
|
+
this.routingApiBaseUrl
|
|
7506
|
+
);
|
|
7507
|
+
if (incentives.length === 0) return accountApy;
|
|
7508
|
+
const byDate = /* @__PURE__ */ new Map();
|
|
7509
|
+
for (const { date, ...incentive } of incentives) {
|
|
7510
|
+
const entries = byDate.get(date) ?? [];
|
|
7511
|
+
entries.push(incentive);
|
|
7512
|
+
byDate.set(date, entries);
|
|
7513
|
+
}
|
|
7514
|
+
return {
|
|
7515
|
+
...accountApy,
|
|
7516
|
+
history: history.map((point) => {
|
|
7517
|
+
const pointIncentives = byDate.get(point.date);
|
|
7518
|
+
return pointIncentives?.length ? { ...point, incentives: pointIncentives } : point;
|
|
7519
|
+
})
|
|
7520
|
+
};
|
|
7521
|
+
}
|
|
7284
7522
|
/**
|
|
7285
7523
|
* Get transaction history for a specific agent, or all agents.
|
|
7286
7524
|
*
|
|
@@ -7423,7 +7661,7 @@ var OwneySDK = class {
|
|
|
7423
7661
|
/**
|
|
7424
7662
|
* Ensure the given asset uses backend protocol auto-selection for the active
|
|
7425
7663
|
* chain's account. No-op (returns false) for agents that don't support it.
|
|
7426
|
-
* @param asset -
|
|
7664
|
+
* @param asset - Asset symbol (e.g. "USDC").
|
|
7427
7665
|
* @param agentId - Agent to target. Defaults to "zyfai".
|
|
7428
7666
|
* @returns whether a profile write occurred.
|
|
7429
7667
|
*/
|
|
@@ -7448,23 +7686,28 @@ var OwneySDK = class {
|
|
|
7448
7686
|
return pending;
|
|
7449
7687
|
}
|
|
7450
7688
|
/**
|
|
7451
|
-
* One-time, user-paid approval of Permit2 on the sponsored WETH
|
|
7452
|
-
* the active chain. Required once per wallet per chain before
|
|
7453
|
-
* deposits; afterwards deposit() is signature-only.
|
|
7454
|
-
* approval transaction is mined (1 confirmation), so
|
|
7455
|
-
* will see the new allowance; throws if the
|
|
7689
|
+
* One-time, user-paid approval of Permit2 on the sponsored WETH (default) or
|
|
7690
|
+
* USDT token for the active chain. Required once per wallet per chain before
|
|
7691
|
+
* gasless deposits of that asset; afterwards deposit() is signature-only.
|
|
7692
|
+
* Resolves only after the approval transaction is mined (1 confirmation), so
|
|
7693
|
+
* a subsequent deposit() will see the new allowance; throws if the
|
|
7694
|
+
* transaction reverted.
|
|
7695
|
+
*
|
|
7696
|
+
* On mainnet USDT only (`needsAllowanceReset`), a non-zero existing allowance
|
|
7697
|
+
* is first zeroed in its own transaction. If the user rejects the second
|
|
7698
|
+
* prompt, the previous Permit2 allowance stays zeroed; calling this again
|
|
7699
|
+
* approves from zero in a single transaction.
|
|
7456
7700
|
* @returns the approval transaction hash.
|
|
7457
7701
|
*/
|
|
7458
7702
|
async approvePermit2(asset = "WETH") {
|
|
7459
|
-
void asset;
|
|
7460
7703
|
const state = this.requireState();
|
|
7461
7704
|
const chainId = this.requireChainId();
|
|
7462
|
-
this.validateAssetSupport(this.getAgent("zyfai"), chainId,
|
|
7463
|
-
const token =
|
|
7705
|
+
this.validateAssetSupport(this.getAgent("zyfai"), chainId, asset);
|
|
7706
|
+
const token = sponsoredTokenMap(asset)[chainId];
|
|
7464
7707
|
if (!token) {
|
|
7465
7708
|
throw new OwneyError(
|
|
7466
7709
|
"CHAIN_UNSUPPORTED",
|
|
7467
|
-
`No sponsored
|
|
7710
|
+
`No sponsored ${asset} on chain ${chainId}`
|
|
7468
7711
|
);
|
|
7469
7712
|
}
|
|
7470
7713
|
const provider = this.requireConnectedProvider();
|
|
@@ -7482,22 +7725,52 @@ var OwneySDK = class {
|
|
|
7482
7725
|
wallet,
|
|
7483
7726
|
chainId
|
|
7484
7727
|
);
|
|
7485
|
-
const
|
|
7486
|
-
|
|
7487
|
-
|
|
7488
|
-
|
|
7489
|
-
|
|
7490
|
-
|
|
7491
|
-
|
|
7728
|
+
const currentAllowance = await this.readTokenPermit2Allowance(
|
|
7729
|
+
chainId,
|
|
7730
|
+
token
|
|
7731
|
+
).catch(
|
|
7732
|
+
() => readPermit2Allowance(
|
|
7733
|
+
publicClient,
|
|
7734
|
+
token,
|
|
7735
|
+
state.walletAddress
|
|
7736
|
+
)
|
|
7737
|
+
).catch((err) => {
|
|
7738
|
+
if (!needsAllowanceReset(token)) return 0n;
|
|
7739
|
+
throw new OwneyError(
|
|
7740
|
+
"PERMIT2_APPROVAL_REQUIRED",
|
|
7741
|
+
`Could not read the current ${asset} allowance for Permit2; please try again.`,
|
|
7742
|
+
{
|
|
7743
|
+
token,
|
|
7744
|
+
chainId,
|
|
7745
|
+
reason: "ALLOWANCE_UNREADABLE",
|
|
7746
|
+
cause: err instanceof Error ? err.message : String(err)
|
|
7747
|
+
}
|
|
7748
|
+
);
|
|
7492
7749
|
});
|
|
7493
|
-
|
|
7494
|
-
|
|
7495
|
-
|
|
7750
|
+
return approveWithResetIfNeeded({
|
|
7751
|
+
token,
|
|
7752
|
+
currentAllowance,
|
|
7753
|
+
spender: PERMIT2_ADDRESS,
|
|
7754
|
+
amount: MAX_UINT256,
|
|
7755
|
+
approve: async (spender, amount) => {
|
|
7756
|
+
const hash = await wallet.writeContract({
|
|
7757
|
+
address: token,
|
|
7758
|
+
abi: ERC20_ALLOWANCE_ABI,
|
|
7759
|
+
functionName: "approve",
|
|
7760
|
+
args: [spender, amount],
|
|
7761
|
+
account: state.walletAddress,
|
|
7762
|
+
chain: VIEM_CHAIN2[chainId]
|
|
7763
|
+
});
|
|
7764
|
+
const receipt = await publicClient.waitForTransactionReceipt({
|
|
7765
|
+
hash,
|
|
7766
|
+
confirmations: 1
|
|
7767
|
+
});
|
|
7768
|
+
if (receipt.status !== "success") {
|
|
7769
|
+
throw new Error(`Permit2 approval reverted (tx ${hash})`);
|
|
7770
|
+
}
|
|
7771
|
+
return hash;
|
|
7772
|
+
}
|
|
7496
7773
|
});
|
|
7497
|
-
if (receipt.status !== "success") {
|
|
7498
|
-
throw new Error(`Permit2 approval reverted (tx ${hash})`);
|
|
7499
|
-
}
|
|
7500
|
-
return hash;
|
|
7501
7774
|
}
|
|
7502
7775
|
// --- Discovery (no wallet required) ---
|
|
7503
7776
|
/**
|