@owney/sdk 0.7.32-beta.4 → 0.7.32-beta.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.cjs +1204 -154
- package/dist/index.d.cts +445 -39
- package/dist/index.d.ts +445 -39
- package/dist/index.js +1203 -154
- package/package.json +2 -2
package/dist/index.js
CHANGED
|
@@ -982,7 +982,7 @@ var SnapshotHistory = class {
|
|
|
982
982
|
};
|
|
983
983
|
|
|
984
984
|
// src/lib/funding-ledger.ts
|
|
985
|
-
var SDK_VERSION = "0.7.32-beta.
|
|
985
|
+
var SDK_VERSION = "0.7.32-beta.5";
|
|
986
986
|
var SCOPE2 = "funding-ledger";
|
|
987
987
|
var REQUEST_TIMEOUT_MS2 = 5e3;
|
|
988
988
|
var RETRY_DELAYS_MS = [1e3, 4e3, 16e3];
|
|
@@ -999,6 +999,12 @@ function normalizeAppName(appName) {
|
|
|
999
999
|
const lower = appName.toLowerCase();
|
|
1000
1000
|
return APP_NAME_RE.test(lower) ? lower : void 0;
|
|
1001
1001
|
}
|
|
1002
|
+
var BATCH_ID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/;
|
|
1003
|
+
function normalizeBatchId(batchId) {
|
|
1004
|
+
if (typeof batchId !== "string") return void 0;
|
|
1005
|
+
const lower = batchId.toLowerCase();
|
|
1006
|
+
return BATCH_ID_RE.test(lower) ? lower : void 0;
|
|
1007
|
+
}
|
|
1002
1008
|
function compact(obj) {
|
|
1003
1009
|
const out = {};
|
|
1004
1010
|
for (const [key2, value] of Object.entries(obj)) {
|
|
@@ -1134,6 +1140,7 @@ function buildReporter(config) {
|
|
|
1134
1140
|
asset: input.asset.toLowerCase(),
|
|
1135
1141
|
requestedAmountRaw: input.requestedAmountRaw,
|
|
1136
1142
|
isMax: input.isMax,
|
|
1143
|
+
batchId: normalizeBatchId(input.batchId),
|
|
1137
1144
|
sdkVersion: SDK_VERSION,
|
|
1138
1145
|
app,
|
|
1139
1146
|
legs: input.legs?.map((leg) => compact({ ...leg }))
|
|
@@ -1143,9 +1150,16 @@ function buildReporter(config) {
|
|
|
1143
1150
|
debugLog(SCOPE2, `task failed: ${describeError2(err)}`);
|
|
1144
1151
|
});
|
|
1145
1152
|
};
|
|
1153
|
+
let postBody = createBody;
|
|
1146
1154
|
const create = async () => {
|
|
1147
1155
|
if (disabled) return false;
|
|
1148
|
-
|
|
1156
|
+
let res = await request2("POST", endpoint2, postBody);
|
|
1157
|
+
if (res?.status === 400 && "batchId" in postBody) {
|
|
1158
|
+
const { batchId: _dropped, ...withoutBatchId } = postBody;
|
|
1159
|
+
postBody = withoutBatchId;
|
|
1160
|
+
debugLog(SCOPE2, "create rejected with 400: retrying once without batchId");
|
|
1161
|
+
res = await request2("POST", endpoint2, postBody);
|
|
1162
|
+
}
|
|
1149
1163
|
if (!res) return false;
|
|
1150
1164
|
if (res.status === 404) {
|
|
1151
1165
|
disabled = true;
|
|
@@ -2321,6 +2335,36 @@ async function ensureWalletOnChain(pub, wallet, expected, options = {}) {
|
|
|
2321
2335
|
{ expectedChainId: expected, actualChainId: after ?? actual }
|
|
2322
2336
|
);
|
|
2323
2337
|
}
|
|
2338
|
+
function isActiveChainMismatch(error) {
|
|
2339
|
+
const message = error instanceof Error ? error.message : String(error ?? "");
|
|
2340
|
+
return /must match the active chain/i.test(message) || /does not match the target chain/i.test(message);
|
|
2341
|
+
}
|
|
2342
|
+
async function signWithChainRetry(pub, wallet, expected, sign) {
|
|
2343
|
+
try {
|
|
2344
|
+
return await sign();
|
|
2345
|
+
} catch (error) {
|
|
2346
|
+
if (!isActiveChainMismatch(error)) throw error;
|
|
2347
|
+
try {
|
|
2348
|
+
await wallet.switchChain({ id: expected });
|
|
2349
|
+
} catch {
|
|
2350
|
+
}
|
|
2351
|
+
try {
|
|
2352
|
+
return await sign();
|
|
2353
|
+
} catch (retryError) {
|
|
2354
|
+
if (!isActiveChainMismatch(retryError)) throw retryError;
|
|
2355
|
+
const actual = await readChainId(pub);
|
|
2356
|
+
throw new OwneyError(
|
|
2357
|
+
"CHAIN_MISMATCH",
|
|
2358
|
+
`Your wallet would not sign for ${chainName(expected)}. Open it, switch to ${chainName(expected)}, and try again.`,
|
|
2359
|
+
{
|
|
2360
|
+
expectedChainId: expected,
|
|
2361
|
+
...actual !== void 0 ? { actualChainId: actual } : {},
|
|
2362
|
+
cause: retryError instanceof Error ? retryError.message : String(retryError)
|
|
2363
|
+
}
|
|
2364
|
+
);
|
|
2365
|
+
}
|
|
2366
|
+
}
|
|
2367
|
+
}
|
|
2324
2368
|
|
|
2325
2369
|
// src/lib/sponsored-deposit.ts
|
|
2326
2370
|
var AUTH_WINDOW_SECONDS = 15 * 60;
|
|
@@ -2843,6 +2887,9 @@ var NAME_TO_CHAIN_ID = Object.entries(
|
|
|
2843
2887
|
acc[name.toLowerCase()] = Number(id);
|
|
2844
2888
|
return acc;
|
|
2845
2889
|
}, {});
|
|
2890
|
+
NAME_TO_CHAIN_ID.mainnet = 1;
|
|
2891
|
+
NAME_TO_CHAIN_ID["ethereum mainnet"] = 1;
|
|
2892
|
+
NAME_TO_CHAIN_ID["arbitrum one"] = 42161;
|
|
2846
2893
|
function resolveChainId(chain2) {
|
|
2847
2894
|
const asNum = Number(chain2);
|
|
2848
2895
|
if (Number.isFinite(asNum) && asNum > 0) return asNum;
|
|
@@ -3093,7 +3140,7 @@ function rawPoolApyForChain(entry, chainId, tokenSymbol) {
|
|
|
3093
3140
|
let weightedSum = 0;
|
|
3094
3141
|
let totalBalance = 0;
|
|
3095
3142
|
for (const p of entry.positions ?? []) {
|
|
3096
|
-
if (p.chainId !== chainId) continue;
|
|
3143
|
+
if (chainId !== void 0 && p.chainId !== chainId) continue;
|
|
3097
3144
|
if (tokenSymbol && p.tokenSymbol?.toUpperCase() !== tokenSymbol.toUpperCase()) continue;
|
|
3098
3145
|
const balance = p.balance ?? 0;
|
|
3099
3146
|
const apy = netApy(p.apy_withFee, p.apy, "apy_withFee");
|
|
@@ -3103,27 +3150,89 @@ function rawPoolApyForChain(entry, chainId, tokenSymbol) {
|
|
|
3103
3150
|
}
|
|
3104
3151
|
return totalBalance > 0 ? weightedSum / totalBalance : null;
|
|
3105
3152
|
}
|
|
3106
|
-
function
|
|
3107
|
-
const
|
|
3108
|
-
|
|
3109
|
-
|
|
3110
|
-
|
|
3111
|
-
|
|
3112
|
-
|
|
3113
|
-
|
|
3114
|
-
|
|
3115
|
-
|
|
3116
|
-
|
|
3117
|
-
|
|
3118
|
-
|
|
3119
|
-
|
|
3120
|
-
|
|
3121
|
-
|
|
3153
|
+
function historyCoverage(raw2) {
|
|
3154
|
+
const chains = /* @__PURE__ */ new Map();
|
|
3155
|
+
const assets = /* @__PURE__ */ new Map();
|
|
3156
|
+
const pairs = /* @__PURE__ */ new Map();
|
|
3157
|
+
for (const date of Object.keys(raw2.history ?? {}).sort()) {
|
|
3158
|
+
void date;
|
|
3159
|
+
const seenChains = /* @__PURE__ */ new Set();
|
|
3160
|
+
const seenAssets = /* @__PURE__ */ new Set();
|
|
3161
|
+
const seenPairs = /* @__PURE__ */ new Map();
|
|
3162
|
+
for (const p of (raw2.history ?? {})[date].positions ?? []) {
|
|
3163
|
+
const balance = p.balance ?? 0;
|
|
3164
|
+
const apy = netApy(p.apy_withFee, p.apy, "apy_withFee");
|
|
3165
|
+
if (balance <= 0 || typeof apy !== "number") continue;
|
|
3166
|
+
seenChains.add(p.chainId);
|
|
3167
|
+
if (p.tokenSymbol) {
|
|
3168
|
+
const asset = p.tokenSymbol.toUpperCase();
|
|
3169
|
+
seenAssets.add(asset);
|
|
3170
|
+
seenPairs.set(`${p.chainId}:${asset}`, { chainId: p.chainId, asset });
|
|
3171
|
+
}
|
|
3172
|
+
}
|
|
3173
|
+
for (const c of seenChains) chains.set(c, (chains.get(c) ?? 0) + 1);
|
|
3174
|
+
for (const a of seenAssets) assets.set(a, (assets.get(a) ?? 0) + 1);
|
|
3175
|
+
for (const [key2, pair] of seenPairs) {
|
|
3176
|
+
pairs.set(key2, { ...pair, days: (pairs.get(key2)?.days ?? 0) + 1 });
|
|
3177
|
+
}
|
|
3178
|
+
}
|
|
3179
|
+
return {
|
|
3180
|
+
chains: [...chains].map(([chainId, days]) => ({ chainId, days })),
|
|
3181
|
+
assets: [...assets].map(([asset, days]) => ({ asset, days })),
|
|
3182
|
+
pairs: [...pairs.values()]
|
|
3183
|
+
};
|
|
3184
|
+
}
|
|
3185
|
+
function isEthToken(symbol2) {
|
|
3186
|
+
const upper = symbol2?.toUpperCase();
|
|
3187
|
+
return upper === "WETH" || upper === "ETH";
|
|
3188
|
+
}
|
|
3189
|
+
function holdsEthPosition(raw2) {
|
|
3190
|
+
return Object.values(raw2.history ?? {}).some((entry) => (entry.positions ?? []).some((p) => isEthToken(p.tokenSymbol)));
|
|
3191
|
+
}
|
|
3192
|
+
function usdPerToken(symbol2, ethUsd) {
|
|
3193
|
+
if (symbol2?.toUpperCase() === "USDC") return 1;
|
|
3194
|
+
return isEthToken(symbol2) ? ethUsd : void 0;
|
|
3195
|
+
}
|
|
3196
|
+
function dollarDay(entry, chainId, ethUsd) {
|
|
3197
|
+
let weightedSum = 0;
|
|
3198
|
+
let totalUsd = 0;
|
|
3199
|
+
for (const p of entry.positions ?? []) {
|
|
3200
|
+
if (chainId !== void 0 && p.chainId !== chainId) continue;
|
|
3201
|
+
const balance = p.balance ?? 0;
|
|
3202
|
+
const apy = netApy(p.apy_withFee, p.apy, "apy_withFee");
|
|
3203
|
+
if (balance <= 0 || typeof apy !== "number") continue;
|
|
3204
|
+
const price = usdPerToken(p.tokenSymbol, ethUsd);
|
|
3205
|
+
if (price === void 0) return void 0;
|
|
3206
|
+
weightedSum += apy * balance * price;
|
|
3207
|
+
totalUsd += balance * price;
|
|
3208
|
+
}
|
|
3209
|
+
return totalUsd > 0 ? { apy: weightedSum / totalUsd, usd: totalUsd } : void 0;
|
|
3210
|
+
}
|
|
3211
|
+
function mapApyHistory(raw2, chainId, tokenSymbol, ethUsd) {
|
|
3212
|
+
const history = Object.entries(raw2.history ?? {}).map(([date, entry]) => {
|
|
3213
|
+
const dollars = tokenSymbol ? void 0 : dollarDay(entry, chainId, ethUsd);
|
|
3214
|
+
return {
|
|
3215
|
+
date,
|
|
3216
|
+
apy: dollars ? dollars.apy : rawPoolApyForChain(entry, chainId, tokenSymbol),
|
|
3217
|
+
// Provider position balances are treated as decimal amounts of the
|
|
3218
|
+
// selected token. Carry its unit dynamically for every asset; an
|
|
3219
|
+
// unscoped mix of assets is carried in dollars, or not at all.
|
|
3220
|
+
...tokenSymbol ? {
|
|
3221
|
+
historicalBalance: {
|
|
3222
|
+
amount: (entry.positions ?? []).filter(
|
|
3223
|
+
(p) => (chainId === void 0 || p.chainId === chainId) && p.tokenSymbol?.toUpperCase() === tokenSymbol.toUpperCase() && Number.isFinite(p.balance) && p.balance > 0 && Number.isFinite(p.apy_withFee ?? p.apy)
|
|
3224
|
+
).reduce((sum, p) => sum + p.balance, 0),
|
|
3225
|
+
unit: tokenSymbol.toUpperCase()
|
|
3226
|
+
}
|
|
3227
|
+
} : dollars ? { historicalBalance: { amount: dollars.usd, unit: "USD" } } : {}
|
|
3228
|
+
};
|
|
3229
|
+
}).filter((p) => p.apy !== null).sort((a, b) => a.date.localeCompare(b.date));
|
|
3122
3230
|
return {
|
|
3123
3231
|
walletAddress: raw2.walletAddress,
|
|
3124
3232
|
weightedApyAfterFee: raw2.weightedApyAfterFee ? sumTokenValues(raw2.weightedApyAfterFee) : void 0,
|
|
3125
3233
|
apyByChainAndAsset: mapWeightedApyByChain(raw2.weightedApyAfterFeeByChain),
|
|
3126
|
-
history
|
|
3234
|
+
history,
|
|
3235
|
+
coverage: historyCoverage(raw2)
|
|
3127
3236
|
};
|
|
3128
3237
|
}
|
|
3129
3238
|
function splitOpportunity(opportunity) {
|
|
@@ -3144,6 +3253,9 @@ function mapEntries(rawEntries, chainId) {
|
|
|
3144
3253
|
// "Top up wallet" and for slightly less (gas). `Deposit` already exists in
|
|
3145
3254
|
// the public HistoryAction union, so no consumer type change is needed.
|
|
3146
3255
|
"Deposit to protocol": "Deposit",
|
|
3256
|
+
// Withdrawing from an async vault (Superform) is logged under its own
|
|
3257
|
+
// label and paid out later in a separate batch (ROUT-624).
|
|
3258
|
+
"Request async withdrawal": "Withdraw",
|
|
3147
3259
|
Rebalance: "Rebalance"
|
|
3148
3260
|
};
|
|
3149
3261
|
void chainId;
|
|
@@ -3188,8 +3300,9 @@ function mapEntries(rawEntries, chainId) {
|
|
|
3188
3300
|
];
|
|
3189
3301
|
}
|
|
3190
3302
|
const mappedAction = (entry.action ? actionMap[entry.action] : void 0) ?? entry.action;
|
|
3303
|
+
const asyncRequest = entry.action === "Request async withdrawal";
|
|
3191
3304
|
const rawAmount2 = entry?.positions?.[0]?.amount;
|
|
3192
|
-
const hasAmount = mappedAction !== "Withdraw" && typeof rawAmount2 === "string" && rawAmount2 !== "" && rawAmount2 !== "0x" && rawAmount2 !== "0x0" && rawAmount2 !== "0";
|
|
3305
|
+
const hasAmount = (mappedAction !== "Withdraw" || asyncRequest) && typeof rawAmount2 === "string" && rawAmount2 !== "" && rawAmount2 !== "0x" && rawAmount2 !== "0x0" && rawAmount2 !== "0";
|
|
3193
3306
|
const rawDelta = mappedAction === "Deposit" ? decodeDeltaAmount(
|
|
3194
3307
|
entry?.positions?.[0]?.deltaAmount,
|
|
3195
3308
|
tokenDecimals(entry?.positions?.[0]?.token_symbol)
|
|
@@ -3215,6 +3328,7 @@ function mapEntries(rawEntries, chainId) {
|
|
|
3215
3328
|
newApy: newApy === null ? null : String(newApy),
|
|
3216
3329
|
oldApy: oldApy === null ? null : String(oldApy),
|
|
3217
3330
|
...mappedPositions.length ? { positions: mappedPositions } : {},
|
|
3331
|
+
...asyncRequest ? { asyncRequest: true } : {},
|
|
3218
3332
|
transactions: [
|
|
3219
3333
|
{
|
|
3220
3334
|
txHashes: entry.transactionHash ? [entry.transactionHash] : [],
|
|
@@ -3374,6 +3488,43 @@ function mapDailyEarnings(raw2, chainId, tokenSymbol) {
|
|
|
3374
3488
|
return { walletAddress: raw2.walletAddress, chainId, assets };
|
|
3375
3489
|
}
|
|
3376
3490
|
|
|
3491
|
+
// src/lib/eth-usd-price.ts
|
|
3492
|
+
var BASE_ETH_USD_FEED = "0x71041dddad3595F9CEd3DcCFBe3D1F4b0a16Bb70";
|
|
3493
|
+
var FEED_DECIMALS = 8;
|
|
3494
|
+
var PRICE_TTL_MS = 6e4;
|
|
3495
|
+
var AGGREGATOR_V3_ABI = [{
|
|
3496
|
+
type: "function",
|
|
3497
|
+
name: "latestRoundData",
|
|
3498
|
+
stateMutability: "view",
|
|
3499
|
+
inputs: [],
|
|
3500
|
+
outputs: [
|
|
3501
|
+
{ name: "roundId", type: "uint80" },
|
|
3502
|
+
{ name: "answer", type: "int256" },
|
|
3503
|
+
{ name: "startedAt", type: "uint256" },
|
|
3504
|
+
{ name: "updatedAt", type: "uint256" },
|
|
3505
|
+
{ name: "answeredInRound", type: "uint80" }
|
|
3506
|
+
]
|
|
3507
|
+
}];
|
|
3508
|
+
var prices = /* @__PURE__ */ new WeakMap();
|
|
3509
|
+
async function readEthUsdPrice(client, now = Date.now()) {
|
|
3510
|
+
const cached = prices.get(client);
|
|
3511
|
+
if (cached && now - cached.at < PRICE_TTL_MS) return cached.value;
|
|
3512
|
+
try {
|
|
3513
|
+
const [, answer] = await client.readContract({
|
|
3514
|
+
address: BASE_ETH_USD_FEED,
|
|
3515
|
+
abi: AGGREGATOR_V3_ABI,
|
|
3516
|
+
functionName: "latestRoundData"
|
|
3517
|
+
});
|
|
3518
|
+
if (answer <= 0n) return void 0;
|
|
3519
|
+
const value = Number(answer) / 10 ** FEED_DECIMALS;
|
|
3520
|
+
if (!Number.isFinite(value)) return void 0;
|
|
3521
|
+
prices.set(client, { value, at: now });
|
|
3522
|
+
return value;
|
|
3523
|
+
} catch {
|
|
3524
|
+
return void 0;
|
|
3525
|
+
}
|
|
3526
|
+
}
|
|
3527
|
+
|
|
3377
3528
|
// src/agents/zyfai/zyfai.history-cursor.ts
|
|
3378
3529
|
var InvalidHistoryCursorError = class extends Error {
|
|
3379
3530
|
code = "invalid_cursor";
|
|
@@ -3569,6 +3720,9 @@ function splittingNeedsUpdate(current, desired) {
|
|
|
3569
3720
|
}
|
|
3570
3721
|
|
|
3571
3722
|
// src/agents/zyfai/pool-policy.ts
|
|
3723
|
+
function orgPolicyForConnect(policy, userPoolCustomization) {
|
|
3724
|
+
return userPoolCustomization ? { ...policy, poolPolicy: null } : policy;
|
|
3725
|
+
}
|
|
3572
3726
|
function toZyfaiCustomizations(policy, availableByProtocol, chainsByProtocol) {
|
|
3573
3727
|
const selectionByKey = /* @__PURE__ */ new Map();
|
|
3574
3728
|
for (const selection of policy.selections) {
|
|
@@ -3660,6 +3814,54 @@ function protocolsPolicyNeedsUpdate(current, desiredProtocols, desiredAutoSelect
|
|
|
3660
3814
|
if (desiredProtocols === null) return false;
|
|
3661
3815
|
return !protocolListsEqual(current.protocols, desiredProtocols);
|
|
3662
3816
|
}
|
|
3817
|
+
function mergeScopedPoolNames(current, scoped, allAvailableNames) {
|
|
3818
|
+
const managed = new Set(scoped.flatMap((entry) => entry.availablePools));
|
|
3819
|
+
const existing = current.autoselect ? allAvailableNames : current.pools;
|
|
3820
|
+
const preserved = existing.filter((name) => !managed.has(name));
|
|
3821
|
+
const selected = scoped.flatMap((entry) => entry.pools);
|
|
3822
|
+
return [.../* @__PURE__ */ new Set([...preserved, ...selected])];
|
|
3823
|
+
}
|
|
3824
|
+
function mapAvailablePools(raw2) {
|
|
3825
|
+
const byChain = raw2 ?? {};
|
|
3826
|
+
if (typeof byChain !== "object" || byChain === null) return [];
|
|
3827
|
+
const result = [];
|
|
3828
|
+
for (const [chainIdStr, byToken] of Object.entries(byChain)) {
|
|
3829
|
+
const chainId = Number(chainIdStr);
|
|
3830
|
+
if (!Number.isFinite(chainId)) continue;
|
|
3831
|
+
for (const [token, entry] of Object.entries(byToken ?? {})) {
|
|
3832
|
+
for (const pool of entry?.pools ?? []) {
|
|
3833
|
+
if (!pool?.name) continue;
|
|
3834
|
+
result.push({
|
|
3835
|
+
chainId,
|
|
3836
|
+
token,
|
|
3837
|
+
name: pool.name,
|
|
3838
|
+
apy: pool.info?.combined_apy ?? null,
|
|
3839
|
+
tvlUsd: pool.info?.tvlUsd ?? null,
|
|
3840
|
+
link: pool.info?.link ?? null
|
|
3841
|
+
});
|
|
3842
|
+
}
|
|
3843
|
+
}
|
|
3844
|
+
}
|
|
3845
|
+
return result;
|
|
3846
|
+
}
|
|
3847
|
+
function assemblePoolCatalog(protocols, poolsByProtocol, asset, chains) {
|
|
3848
|
+
const wanted = asset.toUpperCase();
|
|
3849
|
+
const allowedChains = chains && chains.length > 0 ? new Set(chains) : void 0;
|
|
3850
|
+
const catalog = [];
|
|
3851
|
+
for (const protocol of protocols) {
|
|
3852
|
+
const pools = (poolsByProtocol.get(protocol.id) ?? []).filter(
|
|
3853
|
+
(p) => p.token.toUpperCase() === wanted && (allowedChains === void 0 || allowedChains.has(p.chainId))
|
|
3854
|
+
);
|
|
3855
|
+
if (pools.length === 0) continue;
|
|
3856
|
+
catalog.push({
|
|
3857
|
+
protocolId: protocol.id,
|
|
3858
|
+
name: protocol.name,
|
|
3859
|
+
logo: protocol.imageUrl ?? null,
|
|
3860
|
+
pools
|
|
3861
|
+
});
|
|
3862
|
+
}
|
|
3863
|
+
return catalog;
|
|
3864
|
+
}
|
|
3663
3865
|
|
|
3664
3866
|
// src/lib/agent-accounts.ts
|
|
3665
3867
|
var SCOPE5 = "agent-accounts";
|
|
@@ -4159,7 +4361,7 @@ var ZyfaiAgent = class _ZyfaiAgent {
|
|
|
4159
4361
|
*/
|
|
4160
4362
|
async resolveFundingTransfers(entries, chainId, recipient, smartWallet, tokenSymbol) {
|
|
4161
4363
|
const movements = entries.filter(
|
|
4162
|
-
(e) => (e.action === "Withdraw" || e.action === "Top up") && e.transactions[0]?.txHashes[0]
|
|
4364
|
+
(e) => (e.action === "Withdraw" && !e.asyncRequest || e.action === "Top up") && e.transactions[0]?.txHashes[0]
|
|
4163
4365
|
);
|
|
4164
4366
|
if (movements.length === 0) return;
|
|
4165
4367
|
const client = this.getPublicClient(chainId);
|
|
@@ -4390,9 +4592,22 @@ var ZyfaiAgent = class _ZyfaiAgent {
|
|
|
4390
4592
|
this.sdk.getUserDetails(asset),
|
|
4391
4593
|
this.sdk.getAvailableProtocols(chainId)
|
|
4392
4594
|
]);
|
|
4595
|
+
debugLog("zyfai:protocol-sync", `${asset}: profile before sync`, {
|
|
4596
|
+
chains: current.chains,
|
|
4597
|
+
protocols: current.protocols,
|
|
4598
|
+
strategy: current.strategy
|
|
4599
|
+
});
|
|
4600
|
+
if ((current.chains?.length ?? 0) === 0 && (current.protocols?.length ?? 0) === 0) {
|
|
4601
|
+
debugLog(
|
|
4602
|
+
"zyfai:protocol-sync",
|
|
4603
|
+
`${asset}: skipping untouched profile until first deposit`
|
|
4604
|
+
);
|
|
4605
|
+
return;
|
|
4606
|
+
}
|
|
4393
4607
|
const update = buildProtocolMergeUpdate(available, current, asset);
|
|
4394
4608
|
if (!update) return;
|
|
4395
4609
|
await this.sdk.updateUserProfile(update);
|
|
4610
|
+
debugLog("zyfai:protocol-sync", `${asset}: wrote profile update`, update);
|
|
4396
4611
|
} catch (error) {
|
|
4397
4612
|
console.warn(
|
|
4398
4613
|
"[zyfai] ensureProtocolsSynced failed (non-fatal):",
|
|
@@ -4401,10 +4616,28 @@ var ZyfaiAgent = class _ZyfaiAgent {
|
|
|
4401
4616
|
}
|
|
4402
4617
|
}
|
|
4403
4618
|
/** Connect + resolve smart wallet address for read operations. */
|
|
4619
|
+
/**
|
|
4620
|
+
* Sign-in for reads: any live session of this owner will do. Zyfai's session
|
|
4621
|
+
* is per user and its data calls name the chain themselves, so reading
|
|
4622
|
+
* Arbitrum while signed in on Base needs no new sign-in. `connectAuth` pins
|
|
4623
|
+
* the chain, and reconnecting per chain made the whole-portfolio reads (one
|
|
4624
|
+
* per chain, in parallel) cancel each other's sign-in. Funding keeps
|
|
4625
|
+
* `connectAuth`/`ensureConnected`. Returns the owner verified for this call,
|
|
4626
|
+
* so a later reconnect cannot leave the caller without an address.
|
|
4627
|
+
*/
|
|
4628
|
+
async ensureReadSession(state, chainId) {
|
|
4629
|
+
const owner = state.walletAddress?.toLowerCase();
|
|
4630
|
+
if (this.connectAuthPromise) await this.connectAuthPromise.catch(() => void 0);
|
|
4631
|
+
if (!owner || this.connectedAddress?.toLowerCase() !== owner) await this.connectAuth(state, chainId);
|
|
4632
|
+
}
|
|
4633
|
+
/** `ensureReadSession`, then the owner it verified, read in the same turn. */
|
|
4634
|
+
async connectForRead(state, chainId) {
|
|
4635
|
+
await this.ensureReadSession(state, chainId);
|
|
4636
|
+
return this.getAddress();
|
|
4637
|
+
}
|
|
4404
4638
|
async resolveSmartWallet(state, chainId) {
|
|
4405
|
-
await this.connectAuth(state, chainId);
|
|
4406
4639
|
const validChainId = isValidChainId(chainId);
|
|
4407
|
-
const ownerAddress = this.
|
|
4640
|
+
const ownerAddress = await this.connectForRead(state, validChainId);
|
|
4408
4641
|
const smartWallet = await this.readSmartWallet(ownerAddress, validChainId);
|
|
4409
4642
|
return { smartWallet, chainId: validChainId };
|
|
4410
4643
|
}
|
|
@@ -4459,6 +4692,10 @@ var ZyfaiAgent = class _ZyfaiAgent {
|
|
|
4459
4692
|
// --- IAgent: Account lifecycle ---
|
|
4460
4693
|
async activateAgent(state, chainId) {
|
|
4461
4694
|
try {
|
|
4695
|
+
debugLog("zyfai:activation", "starting", {
|
|
4696
|
+
walletAddress: state.walletAddress,
|
|
4697
|
+
chainId
|
|
4698
|
+
});
|
|
4462
4699
|
await this.connectAuth(state, chainId);
|
|
4463
4700
|
const validChainId = isValidChainId(chainId);
|
|
4464
4701
|
await Promise.all([
|
|
@@ -4470,6 +4707,7 @@ var ZyfaiAgent = class _ZyfaiAgent {
|
|
|
4470
4707
|
// validator, so pool-wallet users see no prompt. Non-fatal.
|
|
4471
4708
|
this.ensureSessionKeyIfDeployed(validChainId)
|
|
4472
4709
|
]);
|
|
4710
|
+
debugLog("zyfai:activation", "completed", { chainId: validChainId });
|
|
4473
4711
|
} catch (error) {
|
|
4474
4712
|
throw error;
|
|
4475
4713
|
}
|
|
@@ -4550,8 +4788,9 @@ var ZyfaiAgent = class _ZyfaiAgent {
|
|
|
4550
4788
|
* connecting, so a Zyfai hiccup must leave the user connected with their
|
|
4551
4789
|
* profile unchanged, never fail activation.
|
|
4552
4790
|
*/
|
|
4553
|
-
async applyPoolPolicy(policy) {
|
|
4791
|
+
async applyPoolPolicy(policy, opts = {}) {
|
|
4554
4792
|
try {
|
|
4793
|
+
await this.sdk.ensureFirstDepositSetup("aggressive");
|
|
4555
4794
|
const { protocols: universe } = await this.sdk.getAvailableProtocols(
|
|
4556
4795
|
this.supportedChainIds[0]
|
|
4557
4796
|
);
|
|
@@ -4564,7 +4803,7 @@ var ZyfaiAgent = class _ZyfaiAgent {
|
|
|
4564
4803
|
universeIds,
|
|
4565
4804
|
chainsByProtocol
|
|
4566
4805
|
});
|
|
4567
|
-
let strategy;
|
|
4806
|
+
let strategy = opts.strategy;
|
|
4568
4807
|
const desiredProtocols = deriveProtocols(
|
|
4569
4808
|
policy,
|
|
4570
4809
|
universeIds,
|
|
@@ -4644,6 +4883,143 @@ var ZyfaiAgent = class _ZyfaiAgent {
|
|
|
4644
4883
|
);
|
|
4645
4884
|
}
|
|
4646
4885
|
}
|
|
4886
|
+
/**
|
|
4887
|
+
* The deposit-time Pools step's catalogue: every protocol Zyfai offers this
|
|
4888
|
+
* user, each with the pools (name, APY, TVL, link) selectable for `asset`
|
|
4889
|
+
* under `strategy`. Sourced from the same two Zyfai calls `applyPoolPolicy`
|
|
4890
|
+
* uses, so "shown" and "selectable" are one set. A protocol whose pool
|
|
4891
|
+
* lookup fails is skipped rather than failing the whole catalogue.
|
|
4892
|
+
*/
|
|
4893
|
+
async getPoolCatalog(params) {
|
|
4894
|
+
const { protocols: universe } = await this.sdk.getAvailableProtocols(
|
|
4895
|
+
this.supportedChainIds[0]
|
|
4896
|
+
);
|
|
4897
|
+
const poolResults = await Promise.all(
|
|
4898
|
+
universe.map(async (protocol) => {
|
|
4899
|
+
try {
|
|
4900
|
+
const raw2 = await this.sdk.getAvailablePools(
|
|
4901
|
+
protocol.id,
|
|
4902
|
+
params.strategy
|
|
4903
|
+
);
|
|
4904
|
+
return [protocol.id, mapAvailablePools(raw2)];
|
|
4905
|
+
} catch (error) {
|
|
4906
|
+
console.warn(
|
|
4907
|
+
`[zyfai] getPoolCatalog: getAvailablePools(${protocol.id}) failed, skipping (non-fatal):`,
|
|
4908
|
+
error instanceof Error ? error.message : String(error)
|
|
4909
|
+
);
|
|
4910
|
+
return null;
|
|
4911
|
+
}
|
|
4912
|
+
})
|
|
4913
|
+
);
|
|
4914
|
+
const poolsByProtocol = /* @__PURE__ */ new Map();
|
|
4915
|
+
for (const result of poolResults) {
|
|
4916
|
+
if (result) poolsByProtocol.set(result[0], result[1]);
|
|
4917
|
+
}
|
|
4918
|
+
return assemblePoolCatalog(universe, poolsByProtocol, params.asset);
|
|
4919
|
+
}
|
|
4920
|
+
/**
|
|
4921
|
+
* Persist an explicitly saved deposit-time draft at Zyfai profile level.
|
|
4922
|
+
* Pool choices are merged into protocol/chain records and each active asset
|
|
4923
|
+
* is kept at aggressive unless the draft includes a yieldmaxxing-only pool.
|
|
4924
|
+
* The whole operation must succeed before the caller starts moving funds.
|
|
4925
|
+
*/
|
|
4926
|
+
async setPoolSelection(selection) {
|
|
4927
|
+
try {
|
|
4928
|
+
await this.sdk.ensureFirstDepositSetup("aggressive");
|
|
4929
|
+
const byPair = /* @__PURE__ */ new Map();
|
|
4930
|
+
for (const entry of selection.selections) {
|
|
4931
|
+
const pair = `${entry.protocolId}:${entry.chainId}`;
|
|
4932
|
+
const group = byPair.get(pair) ?? [];
|
|
4933
|
+
group.push(entry);
|
|
4934
|
+
byPair.set(pair, group);
|
|
4935
|
+
}
|
|
4936
|
+
const customizations = await Promise.all(
|
|
4937
|
+
[...byPair.values()].map(async (scoped) => {
|
|
4938
|
+
const { protocolId, chainId } = scoped[0];
|
|
4939
|
+
const [current, rawAvailable] = await Promise.all([
|
|
4940
|
+
this.sdk.getSelectedPools(protocolId, chainId),
|
|
4941
|
+
this.sdk.getAvailablePools(protocolId, "yieldmaxxing")
|
|
4942
|
+
]);
|
|
4943
|
+
const allAvailableNames = mapAvailablePools(rawAvailable).filter((pool) => pool.chainId === chainId).map((pool) => pool.name);
|
|
4944
|
+
return {
|
|
4945
|
+
protocolId,
|
|
4946
|
+
chainId,
|
|
4947
|
+
pools: mergeScopedPoolNames(
|
|
4948
|
+
{
|
|
4949
|
+
pools: current.pools ?? [],
|
|
4950
|
+
autoselect: current.autoselect
|
|
4951
|
+
},
|
|
4952
|
+
scoped,
|
|
4953
|
+
allAvailableNames
|
|
4954
|
+
),
|
|
4955
|
+
// An explicit Save freezes exactly the choices the user saw.
|
|
4956
|
+
// This also lets an empty list disable the pair deliberately.
|
|
4957
|
+
autoselect: false
|
|
4958
|
+
};
|
|
4959
|
+
})
|
|
4960
|
+
);
|
|
4961
|
+
if (customizations.length > 0) {
|
|
4962
|
+
await this.sdk.customizeBatch(customizations);
|
|
4963
|
+
}
|
|
4964
|
+
await Promise.all(
|
|
4965
|
+
selection.strategies.map(async ({ asset, strategy }) => {
|
|
4966
|
+
const current = await this.sdk.getUserDetails(asset);
|
|
4967
|
+
const selectedProtocols = selection.selections.filter(
|
|
4968
|
+
(entry) => entry.asset === asset && entry.pools.length > 0
|
|
4969
|
+
).map((entry) => entry.protocolId);
|
|
4970
|
+
const protocols = [
|
|
4971
|
+
.../* @__PURE__ */ new Set([...current.protocols ?? [], ...selectedProtocols])
|
|
4972
|
+
];
|
|
4973
|
+
await this.sdk.updateUserProfile({ asset, strategy, protocols });
|
|
4974
|
+
})
|
|
4975
|
+
);
|
|
4976
|
+
} catch (error) {
|
|
4977
|
+
console.warn(
|
|
4978
|
+
"[zyfai] setPoolSelection failed:",
|
|
4979
|
+
error instanceof Error ? error.message : String(error)
|
|
4980
|
+
);
|
|
4981
|
+
throw error;
|
|
4982
|
+
}
|
|
4983
|
+
}
|
|
4984
|
+
/**
|
|
4985
|
+
* Read back what `setPoolSelection` wrote (ROUT-650). Zyfai keeps the saved
|
|
4986
|
+
* pools per protocol/chain and the strategy per asset; both are read for the
|
|
4987
|
+
* pairs and assets asked about. A pair still on autoselect, or one whose
|
|
4988
|
+
* lookup fails, is left out so the caller falls back to its default for it.
|
|
4989
|
+
*/
|
|
4990
|
+
async getPoolSelection(state, chainId, params) {
|
|
4991
|
+
await this.connectAuth(state, chainId);
|
|
4992
|
+
const [pairs, strategies] = await Promise.all([
|
|
4993
|
+
Promise.all(
|
|
4994
|
+
params.pairs.map(async ({ protocolId, chainId: chainId2 }) => {
|
|
4995
|
+
try {
|
|
4996
|
+
const current = await this.sdk.getSelectedPools(
|
|
4997
|
+
protocolId,
|
|
4998
|
+
chainId2
|
|
4999
|
+
);
|
|
5000
|
+
if (current.autoselect) return null;
|
|
5001
|
+
return { protocolId, chainId: chainId2, pools: current.pools ?? [] };
|
|
5002
|
+
} catch {
|
|
5003
|
+
return null;
|
|
5004
|
+
}
|
|
5005
|
+
})
|
|
5006
|
+
),
|
|
5007
|
+
Promise.all(
|
|
5008
|
+
params.assets.map(async (asset) => {
|
|
5009
|
+
try {
|
|
5010
|
+
const current = await this.sdk.getUserDetails(asset);
|
|
5011
|
+
return current.strategy ? { asset, strategy: current.strategy } : null;
|
|
5012
|
+
} catch {
|
|
5013
|
+
return null;
|
|
5014
|
+
}
|
|
5015
|
+
})
|
|
5016
|
+
)
|
|
5017
|
+
]);
|
|
5018
|
+
return {
|
|
5019
|
+
pairs: pairs.filter((value) => value !== null),
|
|
5020
|
+
strategies: strategies.filter((value) => value !== null)
|
|
5021
|
+
};
|
|
5022
|
+
}
|
|
4647
5023
|
/**
|
|
4648
5024
|
* True when `smartWallet` is the backend-managed pool wallet Zyfai assigned
|
|
4649
5025
|
* to this EOA — the "new wallet" kind that is predeployed on the chains it
|
|
@@ -4800,11 +5176,7 @@ var ZyfaiAgent = class _ZyfaiAgent {
|
|
|
4800
5176
|
);
|
|
4801
5177
|
return;
|
|
4802
5178
|
}
|
|
4803
|
-
await this.ensureSessionKey(
|
|
4804
|
-
ownerAddress,
|
|
4805
|
-
chainId,
|
|
4806
|
-
wallet.address
|
|
4807
|
-
);
|
|
5179
|
+
await this.ensureSessionKey(ownerAddress, chainId, wallet.address);
|
|
4808
5180
|
} catch (error) {
|
|
4809
5181
|
console.warn(
|
|
4810
5182
|
"[zyfai] session-key check at activation failed (non-fatal):",
|
|
@@ -4915,11 +5287,7 @@ var ZyfaiAgent = class _ZyfaiAgent {
|
|
|
4915
5287
|
"zyfai:onboard",
|
|
4916
5288
|
"Safe already has code -> no deploy needed, checking the session key"
|
|
4917
5289
|
);
|
|
4918
|
-
await this.ensureSessionKey(
|
|
4919
|
-
ownerAddress,
|
|
4920
|
-
chainId,
|
|
4921
|
-
wallet.address
|
|
4922
|
-
);
|
|
5290
|
+
await this.ensureSessionKey(ownerAddress, chainId, wallet.address);
|
|
4923
5291
|
return wallet.address;
|
|
4924
5292
|
}
|
|
4925
5293
|
const poolFirst = await this.isPredeployedPoolWallet(
|
|
@@ -4985,6 +5353,25 @@ var ZyfaiAgent = class _ZyfaiAgent {
|
|
|
4985
5353
|
throw new OwneyError("NOT_CONNECTED", "Wallet changed while preparing Zyfai deposit.", void 0, this.id);
|
|
4986
5354
|
};
|
|
4987
5355
|
assertCurrent();
|
|
5356
|
+
const setupResult = await executionSdk.ensureFirstDepositSetup("aggressive");
|
|
5357
|
+
debugLog("zyfai:first-deposit", "setup call completed", { asset, chainId: validChainId, requestedStrategy: "aggressive", setupResult });
|
|
5358
|
+
if (isOwneyDebug()) {
|
|
5359
|
+
try {
|
|
5360
|
+
const profile = await executionSdk.getUserDetails(asset === "WETH" ? "WETH" : "USDC");
|
|
5361
|
+
debugLog(
|
|
5362
|
+
"zyfai:first-deposit",
|
|
5363
|
+
"profile immediately after setup",
|
|
5364
|
+
{ asset, strategy: profile.strategy, chains: profile.chains, protocols: profile.protocols }
|
|
5365
|
+
);
|
|
5366
|
+
} catch (debugError) {
|
|
5367
|
+
debugLog(
|
|
5368
|
+
"zyfai:first-deposit",
|
|
5369
|
+
"post-setup profile read failed",
|
|
5370
|
+
{ error: debugError instanceof Error ? debugError.message : String(debugError) }
|
|
5371
|
+
);
|
|
5372
|
+
}
|
|
5373
|
+
}
|
|
5374
|
+
assertCurrent();
|
|
4988
5375
|
const smartWallet = await this.ensureWalletDeployed(owner, validChainId);
|
|
4989
5376
|
assertCurrent();
|
|
4990
5377
|
let server;
|
|
@@ -6212,7 +6599,7 @@ var ZyfaiAgent = class _ZyfaiAgent {
|
|
|
6212
6599
|
}
|
|
6213
6600
|
async refreshEarnings(state, chainId) {
|
|
6214
6601
|
const generation = this.earningsGeneration;
|
|
6215
|
-
await this.
|
|
6602
|
+
await this.ensureReadSession(state, chainId);
|
|
6216
6603
|
const executionSdk = this.sdk;
|
|
6217
6604
|
const connectionGeneration = this.connectionGeneration;
|
|
6218
6605
|
const assertCurrent = () => {
|
|
@@ -6254,14 +6641,18 @@ var ZyfaiAgent = class _ZyfaiAgent {
|
|
|
6254
6641
|
this.earningsRefreshes.set(key2, pending);
|
|
6255
6642
|
return pending;
|
|
6256
6643
|
}
|
|
6257
|
-
async getAccountApy(state, chainId, days, tokenSymbol) {
|
|
6644
|
+
async getAccountApy(state, chainId, days, tokenSymbol, scopeChainId) {
|
|
6258
6645
|
const { smartWallet } = await this.resolveSmartWallet(state, chainId);
|
|
6259
6646
|
const raw2 = await this.sdk.getDailyApyHistory(smartWallet, days);
|
|
6260
|
-
|
|
6647
|
+
const scope = scopeChainId === null ? void 0 : scopeChainId ?? chainId;
|
|
6648
|
+
const ethUsd = tokenSymbol === void 0 && holdsEthPosition(raw2) ? await readEthUsdPrice(this.getPublicClient(8453)) : void 0;
|
|
6649
|
+
return mapApyHistory(raw2, scope, tokenSymbol, ethUsd);
|
|
6261
6650
|
}
|
|
6262
6651
|
async getDailyEarnings(state, chainId, days, tokenSymbol) {
|
|
6263
6652
|
const { smartWallet } = await this.resolveSmartWallet(state, chainId);
|
|
6264
|
-
const start = new Date(
|
|
6653
|
+
const start = new Date(
|
|
6654
|
+
Date.now() - (DayFilterMapping[days] + 1) * 864e5
|
|
6655
|
+
);
|
|
6265
6656
|
const raw2 = await this.sdk.getDailyEarnings(
|
|
6266
6657
|
smartWallet,
|
|
6267
6658
|
start.toISOString().slice(0, 10)
|
|
@@ -6354,7 +6745,7 @@ var ZyfaiAgent = class _ZyfaiAgent {
|
|
|
6354
6745
|
};
|
|
6355
6746
|
}
|
|
6356
6747
|
async getUserProfile(state, chainId) {
|
|
6357
|
-
await this.
|
|
6748
|
+
await this.ensureReadSession(state, chainId);
|
|
6358
6749
|
const raw2 = await this.sdk.getUserDetails();
|
|
6359
6750
|
debugLog("zyfai:profile", "getUserProfile \u2014 Zyfai reports", {
|
|
6360
6751
|
asset: "USDC (default \u2014 no asset passed)",
|
|
@@ -6371,6 +6762,19 @@ var ZyfaiAgent = class _ZyfaiAgent {
|
|
|
6371
6762
|
async ensureAutoSelectProtocols(state, chainId, asset) {
|
|
6372
6763
|
await this.connectAuth(state, chainId);
|
|
6373
6764
|
const current = await this.sdk.getUserDetails(asset);
|
|
6765
|
+
debugLog("zyfai:auto-select", `${asset}: profile before check`, {
|
|
6766
|
+
autoSelectProtocols: current.autoSelectProtocols,
|
|
6767
|
+
chains: current.chains,
|
|
6768
|
+
protocols: current.protocols,
|
|
6769
|
+
strategy: current.strategy
|
|
6770
|
+
});
|
|
6771
|
+
if ((current.chains?.length ?? 0) === 0) {
|
|
6772
|
+
debugLog(
|
|
6773
|
+
"zyfai:auto-select",
|
|
6774
|
+
`${asset}: skipping untouched profile until first deposit`
|
|
6775
|
+
);
|
|
6776
|
+
return false;
|
|
6777
|
+
}
|
|
6374
6778
|
const update = buildAutoSelectUpdate(
|
|
6375
6779
|
{
|
|
6376
6780
|
autoSelectProtocols: current.autoSelectProtocols,
|
|
@@ -6381,6 +6785,7 @@ var ZyfaiAgent = class _ZyfaiAgent {
|
|
|
6381
6785
|
);
|
|
6382
6786
|
if (!update) return false;
|
|
6383
6787
|
await this.sdk.updateUserProfile(update);
|
|
6788
|
+
debugLog("zyfai:auto-select", `${asset}: wrote profile update`, update);
|
|
6384
6789
|
return true;
|
|
6385
6790
|
}
|
|
6386
6791
|
// --- IAgent: Discovery (no wallet required) ---
|
|
@@ -6615,6 +7020,14 @@ var YieldseekerAuth = class {
|
|
|
6615
7020
|
}
|
|
6616
7021
|
return this.getToken(state, chainId);
|
|
6617
7022
|
}
|
|
7023
|
+
/** Drop a proof the provider refused, without signing a new one: a
|
|
7024
|
+
* promptless read cannot renew it, and must stop offering it. */
|
|
7025
|
+
discardToken(state, chainId, rejectedToken) {
|
|
7026
|
+
const key2 = this.key(state, chainId);
|
|
7027
|
+
if (this.tokens.get(key2) === rejectedToken) this.tokens.delete(key2);
|
|
7028
|
+
if (readYieldseekerSession(state.walletAddress, chainId) === rejectedToken)
|
|
7029
|
+
clearYieldseekerSession(state.walletAddress, chainId);
|
|
7030
|
+
}
|
|
6618
7031
|
isReusable(token, state, chainId) {
|
|
6619
7032
|
try {
|
|
6620
7033
|
const message = new SiweMessage(JSON.parse(atob(token)).message);
|
|
@@ -7070,18 +7483,19 @@ function dailyApy(point) {
|
|
|
7070
7483
|
if (principal <= 0n || earned === 0n) return 0;
|
|
7071
7484
|
return Number(earned) / Number(principal) * 365 * 100;
|
|
7072
7485
|
}
|
|
7073
|
-
function aggregateHistory(contexts, dayCount, now) {
|
|
7486
|
+
function aggregateHistory(contexts, dayCount, now, scopedAsset) {
|
|
7074
7487
|
const today = new Date(now).toISOString().slice(0, 10);
|
|
7075
7488
|
const cutoff = new Date(Date.parse(today) - (dayCount - 1) * 864e5).toISOString().slice(0, 10);
|
|
7076
7489
|
const assets = new Set(contexts.map((context) => context.asset.toUpperCase()));
|
|
7077
|
-
const
|
|
7490
|
+
const tokenUnits = scopedAsset !== void 0 && assets.size <= 1;
|
|
7491
|
+
const unit = tokenUnits ? scopedAsset.toUpperCase() : "USD";
|
|
7078
7492
|
const byDate = /* @__PURE__ */ new Map();
|
|
7079
7493
|
for (const context of contexts) {
|
|
7080
7494
|
const points = context.historic?.dailyYieldSnapshots ?? [];
|
|
7081
7495
|
for (const point of points) {
|
|
7082
7496
|
if (!/^\d{4}-\d{2}-\d{2}$/.test(point.date) || !Number.isFinite(Date.parse(point.date)) || point.date < cutoff || point.date > today) continue;
|
|
7083
7497
|
const tokens = Number(decimal(point.totalValueBase, point.baseAssetDecimals, "historic position"));
|
|
7084
|
-
const amount =
|
|
7498
|
+
const amount = tokenUnits ? tokens : tokens * point.baseAssetPriceUsd;
|
|
7085
7499
|
if (!Number.isFinite(amount) || amount < 0) {
|
|
7086
7500
|
invalid("historic position", "expected a finite non-negative balance");
|
|
7087
7501
|
}
|
|
@@ -7097,7 +7511,30 @@ function aggregateHistory(contexts, dayCount, now) {
|
|
|
7097
7511
|
historicalBalance: { amount: value.amount, unit }
|
|
7098
7512
|
}));
|
|
7099
7513
|
}
|
|
7100
|
-
function
|
|
7514
|
+
function historyCoverage2(contexts, dayCount, now) {
|
|
7515
|
+
const today = new Date(now).toISOString().slice(0, 10);
|
|
7516
|
+
const cutoff = new Date(Date.parse(today) - (dayCount - 1) * 864e5).toISOString().slice(0, 10);
|
|
7517
|
+
const datesByAsset = /* @__PURE__ */ new Map();
|
|
7518
|
+
const allDates = /* @__PURE__ */ new Set();
|
|
7519
|
+
for (const context of contexts) {
|
|
7520
|
+
for (const point of context.historic?.dailyYieldSnapshots ?? []) {
|
|
7521
|
+
if (!/^\d{4}-\d{2}-\d{2}$/.test(point.date) || point.date < cutoff || point.date > today) continue;
|
|
7522
|
+
if (!(Number(decimal(point.totalValueBase, point.baseAssetDecimals, "historic position")) > 0)) continue;
|
|
7523
|
+
const asset = context.asset.toUpperCase();
|
|
7524
|
+
const dates = datesByAsset.get(asset) ?? /* @__PURE__ */ new Set();
|
|
7525
|
+
dates.add(point.date);
|
|
7526
|
+
datesByAsset.set(asset, dates);
|
|
7527
|
+
allDates.add(point.date);
|
|
7528
|
+
}
|
|
7529
|
+
}
|
|
7530
|
+
const assets = [...datesByAsset].map(([asset, dates]) => ({ asset, days: dates.size }));
|
|
7531
|
+
return {
|
|
7532
|
+
chains: allDates.size ? [{ chainId: 8453, days: allDates.size }] : [],
|
|
7533
|
+
assets,
|
|
7534
|
+
pairs: assets.map((entry) => ({ chainId: 8453, ...entry }))
|
|
7535
|
+
};
|
|
7536
|
+
}
|
|
7537
|
+
function mapYieldseekerApy(walletAddress, contexts, days, now = Date.now(), scopedAsset) {
|
|
7101
7538
|
let weighted = 0;
|
|
7102
7539
|
let totalUsd = 0;
|
|
7103
7540
|
const byAsset = {};
|
|
@@ -7118,7 +7555,8 @@ function mapYieldseekerApy(walletAddress, contexts, days, now = Date.now()) {
|
|
|
7118
7555
|
walletAddress,
|
|
7119
7556
|
...days !== "14D" || Object.keys(byAsset).length > 0 ? { weightedApyAfterFee: totalUsd > 0 ? weighted / totalUsd : 0 } : {},
|
|
7120
7557
|
apyByChainAndAsset: { 8453: byAsset },
|
|
7121
|
-
history: aggregateHistory(contexts, dayCount, now)
|
|
7558
|
+
history: aggregateHistory(contexts, dayCount, now, scopedAsset),
|
|
7559
|
+
coverage: historyCoverage2(contexts, dayCount, now)
|
|
7122
7560
|
};
|
|
7123
7561
|
}
|
|
7124
7562
|
function actionType(value) {
|
|
@@ -9913,6 +10351,9 @@ var YieldseekerAgent = class {
|
|
|
9913
10351
|
if (timer) clearTimeout(timer);
|
|
9914
10352
|
}
|
|
9915
10353
|
}
|
|
10354
|
+
hasReadSession(state, chainId) {
|
|
10355
|
+
return this.supportedChainIds.includes(chainId) && this.auth.peekToken(state, chainId) !== void 0;
|
|
10356
|
+
}
|
|
9916
10357
|
async getBalances(state, chainId, asset) {
|
|
9917
10358
|
this.assertChain(chainId);
|
|
9918
10359
|
if (asset !== void 0) this.assertAsset(asset);
|
|
@@ -10051,15 +10492,17 @@ var YieldseekerAgent = class {
|
|
|
10051
10492
|
const contexts = await this.loadPortfolio(state, chainId, { includePositions: false, ledger: true });
|
|
10052
10493
|
return mapYieldseekerEarnings(await Promise.all(contexts.map((context) => this.applyEarningsHold(state, chainId, context))));
|
|
10053
10494
|
}
|
|
10054
|
-
async getAccountApy(state, chainId, days, tokenSymbol) {
|
|
10495
|
+
async getAccountApy(state, chainId, days, tokenSymbol, scopeChainId) {
|
|
10055
10496
|
this.assertChain(chainId);
|
|
10056
10497
|
const asset = tokenSymbol?.toUpperCase();
|
|
10057
10498
|
if (asset !== void 0) this.assertAsset(asset);
|
|
10499
|
+
if (typeof scopeChainId === "number" && !this.supportedChainIds.includes(scopeChainId))
|
|
10500
|
+
return mapYieldseekerApy(state.walletAddress, [], days);
|
|
10058
10501
|
const contexts = await this.loadPortfolio(state, chainId, {
|
|
10059
10502
|
...asset ? { asset } : {},
|
|
10060
10503
|
historic: true
|
|
10061
10504
|
});
|
|
10062
|
-
return mapYieldseekerApy(state.walletAddress, contexts, days);
|
|
10505
|
+
return mapYieldseekerApy(state.walletAddress, contexts, days, Date.now(), asset);
|
|
10063
10506
|
}
|
|
10064
10507
|
async getDailyEarnings(state, chainId, days, tokenSymbol) {
|
|
10065
10508
|
this.assertChain(chainId);
|
|
@@ -11413,8 +11856,9 @@ var YieldseekerAgent = class {
|
|
|
11413
11856
|
options.assertCurrent?.();
|
|
11414
11857
|
return this.api.request(path, { method: options.method, body: options.body, signature: signature2 });
|
|
11415
11858
|
};
|
|
11416
|
-
const
|
|
11417
|
-
|
|
11859
|
+
const promptless = options.promptless || state.promptless === true;
|
|
11860
|
+
const cached = promptless ? this.auth.peekToken(state, chainId) : void 0;
|
|
11861
|
+
if (promptless && !cached)
|
|
11418
11862
|
throw new OwneyError(
|
|
11419
11863
|
"AGENT_AUTH_FAILED",
|
|
11420
11864
|
"No Yieldseeker sign-in is available without a prompt.",
|
|
@@ -11428,7 +11872,10 @@ var YieldseekerAgent = class {
|
|
|
11428
11872
|
if (!(error instanceof YieldseekerApiError)) throw error;
|
|
11429
11873
|
if (error.providerCode === "NO_USER") throw error;
|
|
11430
11874
|
if (!error.isAuthenticationError) throw error;
|
|
11431
|
-
if (
|
|
11875
|
+
if (promptless) {
|
|
11876
|
+
this.auth.discardToken(state, chainId, signature);
|
|
11877
|
+
throw error;
|
|
11878
|
+
}
|
|
11432
11879
|
signature = await this.auth.refreshToken(state, chainId, signature);
|
|
11433
11880
|
try {
|
|
11434
11881
|
return await request2(signature);
|
|
@@ -11655,6 +12102,120 @@ var YieldseekerAgent = class {
|
|
|
11655
12102
|
}
|
|
11656
12103
|
};
|
|
11657
12104
|
|
|
12105
|
+
// src/lib/history-fanout.ts
|
|
12106
|
+
var SEPARATOR = "@";
|
|
12107
|
+
function isSupportedChainId(value) {
|
|
12108
|
+
return SUPPORTED_CHAIN_IDS.includes(value);
|
|
12109
|
+
}
|
|
12110
|
+
function fanoutKey(leg) {
|
|
12111
|
+
return leg.chainId === void 0 ? leg.agentId : `${leg.agentId}${SEPARATOR}${leg.chainId}`;
|
|
12112
|
+
}
|
|
12113
|
+
function encodeFanoutCursor(map) {
|
|
12114
|
+
return Buffer.from(JSON.stringify(map), "utf8").toString("base64");
|
|
12115
|
+
}
|
|
12116
|
+
function decodeFanoutCursor(token) {
|
|
12117
|
+
let parsed;
|
|
12118
|
+
try {
|
|
12119
|
+
parsed = JSON.parse(Buffer.from(token, "base64").toString("utf8"));
|
|
12120
|
+
} catch {
|
|
12121
|
+
throw new InvalidHistoryCursorError(
|
|
12122
|
+
"History fan-out cursor is not valid base64 JSON."
|
|
12123
|
+
);
|
|
12124
|
+
}
|
|
12125
|
+
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed) || !Object.values(parsed).every((v) => typeof v === "string")) {
|
|
12126
|
+
throw new InvalidHistoryCursorError(
|
|
12127
|
+
"History fan-out cursor payload has wrong shape."
|
|
12128
|
+
);
|
|
12129
|
+
}
|
|
12130
|
+
return parsed;
|
|
12131
|
+
}
|
|
12132
|
+
function transactionChainId(entry) {
|
|
12133
|
+
let found;
|
|
12134
|
+
for (const tx of entry.transactions ?? []) {
|
|
12135
|
+
if (tx.chainId === void 0) continue;
|
|
12136
|
+
if (!isSupportedChainId(tx.chainId)) return void 0;
|
|
12137
|
+
if (found !== void 0 && found !== tx.chainId) return void 0;
|
|
12138
|
+
found = tx.chainId;
|
|
12139
|
+
}
|
|
12140
|
+
return found;
|
|
12141
|
+
}
|
|
12142
|
+
function mergeHistoryPages(pages) {
|
|
12143
|
+
const merged = [];
|
|
12144
|
+
const nextCursorMap = {};
|
|
12145
|
+
let hasMore = false;
|
|
12146
|
+
const identity = (e) => [
|
|
12147
|
+
e.agent,
|
|
12148
|
+
e.action,
|
|
12149
|
+
e.date ?? "",
|
|
12150
|
+
e.transactions?.[0]?.txHashes?.[0] ?? ""
|
|
12151
|
+
].join("\0");
|
|
12152
|
+
const seen = /* @__PURE__ */ new Map();
|
|
12153
|
+
for (const { leg, page } of pages) {
|
|
12154
|
+
if (!page) continue;
|
|
12155
|
+
for (const e of page.data) {
|
|
12156
|
+
const id = identity(e);
|
|
12157
|
+
const prior = seen.get(id);
|
|
12158
|
+
if (prior) {
|
|
12159
|
+
prior.legs += 1;
|
|
12160
|
+
const own = transactionChainId(prior.entry);
|
|
12161
|
+
if (own === void 0) delete prior.entry.chainId;
|
|
12162
|
+
else prior.entry.chainId = own;
|
|
12163
|
+
continue;
|
|
12164
|
+
}
|
|
12165
|
+
const entry = leg.chainId === void 0 ? { ...e } : { ...e, chainId: leg.chainId };
|
|
12166
|
+
seen.set(id, { entry, legs: 1 });
|
|
12167
|
+
merged.push(entry);
|
|
12168
|
+
}
|
|
12169
|
+
if (page.hasMore && page.nextCursor) {
|
|
12170
|
+
nextCursorMap[fanoutKey(leg)] = page.nextCursor;
|
|
12171
|
+
hasMore = true;
|
|
12172
|
+
}
|
|
12173
|
+
}
|
|
12174
|
+
merged.sort((a, b) => {
|
|
12175
|
+
const dateDiff = new Date(b.date).getTime() - new Date(a.date).getTime();
|
|
12176
|
+
if (dateDiff !== 0) return dateDiff;
|
|
12177
|
+
if (a.agent !== b.agent) return a.agent < b.agent ? -1 : 1;
|
|
12178
|
+
const aChain = a.chainId ?? 0;
|
|
12179
|
+
const bChain = b.chainId ?? 0;
|
|
12180
|
+
if (aChain !== bChain) return aChain - bChain;
|
|
12181
|
+
const aTx = a.transactions?.[0]?.txHashes?.[0] ?? "";
|
|
12182
|
+
const bTx = b.transactions?.[0]?.txHashes?.[0] ?? "";
|
|
12183
|
+
if (aTx !== bTx) return aTx < bTx ? -1 : 1;
|
|
12184
|
+
if (a.action !== b.action) return a.action < b.action ? -1 : 1;
|
|
12185
|
+
return 0;
|
|
12186
|
+
});
|
|
12187
|
+
return {
|
|
12188
|
+
data: merged,
|
|
12189
|
+
hasMore,
|
|
12190
|
+
nextCursor: hasMore ? encodeFanoutCursor(nextCursorMap) : void 0
|
|
12191
|
+
};
|
|
12192
|
+
}
|
|
12193
|
+
|
|
12194
|
+
// src/lib/daily-earnings-merge.ts
|
|
12195
|
+
function mergeDailyEarnings(series) {
|
|
12196
|
+
const byAsset = /* @__PURE__ */ new Map();
|
|
12197
|
+
for (const s of series) {
|
|
12198
|
+
for (const { asset, points } of s.assets) {
|
|
12199
|
+
const byDate = byAsset.get(asset) ?? /* @__PURE__ */ new Map();
|
|
12200
|
+
for (const point of points) {
|
|
12201
|
+
byDate.set(point.date, (byDate.get(point.date) ?? 0) + point.amount);
|
|
12202
|
+
}
|
|
12203
|
+
byAsset.set(asset, byDate);
|
|
12204
|
+
}
|
|
12205
|
+
}
|
|
12206
|
+
return {
|
|
12207
|
+
walletAddress: series[0]?.walletAddress ?? "",
|
|
12208
|
+
// Names the first source's chain. On a fanned-out read the payload spans
|
|
12209
|
+
// several, so this is provenance rather than scope — `assets` is the part
|
|
12210
|
+
// that carries the merged figures.
|
|
12211
|
+
chainId: series[0]?.chainId ?? 0,
|
|
12212
|
+
assets: [...byAsset.entries()].map(([asset, byDate]) => ({
|
|
12213
|
+
asset,
|
|
12214
|
+
points: [...byDate.entries()].map(([date, amount]) => ({ date, amount })).sort((a, b) => a.date.localeCompare(b.date))
|
|
12215
|
+
})).sort((a, b) => a.asset.localeCompare(b.asset))
|
|
12216
|
+
};
|
|
12217
|
+
}
|
|
12218
|
+
|
|
11658
12219
|
// src/lib/swap/swap-api.ts
|
|
11659
12220
|
var FUSION_SECRET_SERVER_PUBLISH = 1;
|
|
11660
12221
|
var FUSION_SECRET_HANDOFF_TIMEOUT_MS = 5e3;
|
|
@@ -12127,6 +12688,10 @@ var DEFAULT_POLL_MS2 = 5e3;
|
|
|
12127
12688
|
var MAX_BACKOFF_MS = 3e4;
|
|
12128
12689
|
var backoffFor = (failures, base7) => Math.min(base7 * 2 ** Math.min(failures, 5), MAX_BACKOFF_MS);
|
|
12129
12690
|
var DEFAULT_TIMEOUT_MS3 = 15 * 60 * 1e3;
|
|
12691
|
+
var NOT_FOUND_GRACE_MS = 2 * 60 * 1e3;
|
|
12692
|
+
function isNotFound(error) {
|
|
12693
|
+
return error instanceof OwneyError && error.details?.statusCode === 404;
|
|
12694
|
+
}
|
|
12130
12695
|
async function runFusionOrderInternal(deps, options) {
|
|
12131
12696
|
const {
|
|
12132
12697
|
orderHash,
|
|
@@ -12157,6 +12722,7 @@ async function runFusionOrderInternal(deps, options) {
|
|
|
12157
12722
|
assertTime();
|
|
12158
12723
|
};
|
|
12159
12724
|
let failures = 0;
|
|
12725
|
+
let notFoundSince;
|
|
12160
12726
|
const published = /* @__PURE__ */ new Set();
|
|
12161
12727
|
onStage?.("swapping");
|
|
12162
12728
|
for (; ; ) {
|
|
@@ -12192,7 +12758,20 @@ async function runFusionOrderInternal(deps, options) {
|
|
|
12192
12758
|
status = state.status;
|
|
12193
12759
|
partial ||= status === "partially-filled" || !!state.fills?.length;
|
|
12194
12760
|
failures = 0;
|
|
12195
|
-
|
|
12761
|
+
notFoundSince = void 0;
|
|
12762
|
+
} catch (error) {
|
|
12763
|
+
if (isNotFound(error)) {
|
|
12764
|
+
notFoundSince ??= deps.now();
|
|
12765
|
+
if (deps.now() - notFoundSince >= NOT_FOUND_GRACE_MS) {
|
|
12766
|
+
throw new OwneyError(
|
|
12767
|
+
"SWAP_ORDER_NOT_FOUND",
|
|
12768
|
+
"The swap provider has no record of this order, so nothing was exchanged.",
|
|
12769
|
+
{ orderHash }
|
|
12770
|
+
);
|
|
12771
|
+
}
|
|
12772
|
+
} else {
|
|
12773
|
+
notFoundSince = void 0;
|
|
12774
|
+
}
|
|
12196
12775
|
failures += 1;
|
|
12197
12776
|
await pause(backoffFor(failures, pollIntervalMs));
|
|
12198
12777
|
continue;
|
|
@@ -12464,7 +13043,7 @@ async function executeSwap(deps, options) {
|
|
|
12464
13043
|
});
|
|
12465
13044
|
const before = await deps.readTargetBalance();
|
|
12466
13045
|
debugLog("owney-sdk", "swap: target balance before", before.toString());
|
|
12467
|
-
const result = quote.rail === "classic" ? await runClassic(deps, options) : quote.rail === "fusion" ? await runSameChainFusion(deps, options, walletAddress) : await runFusion(deps, options, walletAddress);
|
|
13046
|
+
const result = quote.rail === "classic" ? await runClassic(deps, options) : quote.rail === "fusion" ? await runSameChainFusion(deps, options, walletAddress).catch((error) => doubtVerdict(deps, error, before)) : await runFusion(deps, options, walletAddress);
|
|
12468
13047
|
const { arrived } = await awaitBalanceIncrease({
|
|
12469
13048
|
readBalance: () => deps.readTargetBalance(),
|
|
12470
13049
|
baseline: before,
|
|
@@ -12483,6 +13062,17 @@ async function executeSwap(deps, options) {
|
|
|
12483
13062
|
active = false;
|
|
12484
13063
|
}
|
|
12485
13064
|
}
|
|
13065
|
+
async function doubtVerdict(deps, error, before) {
|
|
13066
|
+
if (!(error instanceof OwneyError) || error.code !== "SWAP_ORDER_EXPIRED" && error.code !== "SWAP_ORDER_CANCELLED" || error.details?.outcome !== "not-submitted") throw error;
|
|
13067
|
+
const now = await deps.readTargetBalance().catch(() => before);
|
|
13068
|
+
if (now <= before) throw error;
|
|
13069
|
+
debugLog("owney-sdk", "swap: rail said no but the wallet received funds", { status: error.details?.status });
|
|
13070
|
+
throw new OwneyError(
|
|
13071
|
+
"SWAP_REQUEST_FAILED",
|
|
13072
|
+
"The swap's status says it did not fill, but funds arrived in your wallet since it started. Check your wallet before retrying.",
|
|
13073
|
+
{ ...error.details, settlementUnconfirmed: true, outcome: "submitted-unknown" }
|
|
13074
|
+
);
|
|
13075
|
+
}
|
|
12486
13076
|
async function runClassic(deps, options) {
|
|
12487
13077
|
const {
|
|
12488
13078
|
quote,
|
|
@@ -12507,8 +13097,8 @@ async function runClassic(deps, options) {
|
|
|
12507
13097
|
onStage?.("quoting");
|
|
12508
13098
|
debugLog("owney-sdk", "swap: fetching classic calldata");
|
|
12509
13099
|
let { tx } = await deps.api.swapTx(swapTxRequest);
|
|
12510
|
-
const
|
|
12511
|
-
if (!
|
|
13100
|
+
const isNative2 = BigInt(tx.value ?? "0") > 0n;
|
|
13101
|
+
if (!isNative2) {
|
|
12512
13102
|
const needed = amount;
|
|
12513
13103
|
const current = await deps.readAllowance(tx.to);
|
|
12514
13104
|
debugLog("owney-sdk", "swap: allowance", {
|
|
@@ -12732,7 +13322,7 @@ async function runFusion(deps, options, walletAddress) {
|
|
|
12732
13322
|
...onStage ? { onStage } : {}
|
|
12733
13323
|
});
|
|
12734
13324
|
} catch (error) {
|
|
12735
|
-
if (error instanceof OwneyError && error.code === "SWAP_ORDER_REFUNDED" && error.details?.outcome === "refunded") {
|
|
13325
|
+
if (error instanceof OwneyError && (error.code === "SWAP_ORDER_REFUNDED" && error.details?.outcome === "refunded" || error.code === "SWAP_ORDER_NOT_FOUND")) {
|
|
12736
13326
|
clearOrder(built.orderHash);
|
|
12737
13327
|
}
|
|
12738
13328
|
throw error;
|
|
@@ -13014,6 +13604,33 @@ function verifiedFee(payout) {
|
|
|
13014
13604
|
return gross !== void 0 && fee !== void 0 && net !== void 0 && fee > 0n && gross === rawAmount(evidence.intendedAmount) && net === rawAmount(payout.result.amount) && net + fee === gross ? fee : 0n;
|
|
13015
13605
|
}
|
|
13016
13606
|
|
|
13607
|
+
// src/lib/swap/swap.gas-check.ts
|
|
13608
|
+
var CLASSIC_SWAP_GAS = 300000n;
|
|
13609
|
+
var APPROVE_GAS2 = 60000n;
|
|
13610
|
+
var isNative = (address) => address.toLowerCase().startsWith("0xeeee");
|
|
13611
|
+
async function swapGasShortfall(deps, quote) {
|
|
13612
|
+
if (quote.rail !== "classic" || isNative(quote.src.address)) return null;
|
|
13613
|
+
const gas = CLASSIC_SWAP_GAS + APPROVE_GAS2;
|
|
13614
|
+
const [balance, gasPrice] = await Promise.all([
|
|
13615
|
+
deps.readNativeBalance(),
|
|
13616
|
+
deps.getMaxFeePerGas()
|
|
13617
|
+
]);
|
|
13618
|
+
const required = gas * gasPrice;
|
|
13619
|
+
return balance < required ? { chainId: quote.src.chainId, balance, required } : null;
|
|
13620
|
+
}
|
|
13621
|
+
function swapGasError(shortfall, nativeSymbol) {
|
|
13622
|
+
return new OwneyError(
|
|
13623
|
+
"SWAP_INSUFFICIENT_GAS",
|
|
13624
|
+
`This swap needs a little ${nativeSymbol} for network fees, and your wallet has too little. Add some ${nativeSymbol}, or choose a different asset to receive.`,
|
|
13625
|
+
{
|
|
13626
|
+
chainId: shortfall.chainId,
|
|
13627
|
+
symbol: nativeSymbol,
|
|
13628
|
+
balance: shortfall.balance.toString(),
|
|
13629
|
+
required: shortfall.required.toString()
|
|
13630
|
+
}
|
|
13631
|
+
);
|
|
13632
|
+
}
|
|
13633
|
+
|
|
13017
13634
|
// src/lib/swap/swap.permit.ts
|
|
13018
13635
|
import {
|
|
13019
13636
|
domainSeparator,
|
|
@@ -14099,7 +14716,9 @@ async function execute(i, key2, plan) {
|
|
|
14099
14716
|
if (balance < total)
|
|
14100
14717
|
throw new OwneyError(
|
|
14101
14718
|
"DEPOSIT_INSUFFICIENT_BALANCE",
|
|
14102
|
-
"Insufficient token balance for this deposit."
|
|
14719
|
+
"Insufficient token balance for this deposit.",
|
|
14720
|
+
// What was seen: a swap's deposit retries once at a small shortfall (ROUT-618).
|
|
14721
|
+
{ token: i.token, chainId: i.chainId, balance: balance.toString(), amount: total.toString() }
|
|
14103
14722
|
);
|
|
14104
14723
|
if (allowance < total && !supportsSponsoredErc2612(i.chainId, i.token))
|
|
14105
14724
|
throw new OwneyError(
|
|
@@ -14134,15 +14753,20 @@ async function execute(i, key2, plan) {
|
|
|
14134
14753
|
tokenName,
|
|
14135
14754
|
tokenVersion
|
|
14136
14755
|
};
|
|
14137
|
-
const signature2 = await
|
|
14138
|
-
|
|
14139
|
-
|
|
14140
|
-
|
|
14141
|
-
|
|
14142
|
-
|
|
14143
|
-
|
|
14756
|
+
const signature2 = await signWithChainRetry(
|
|
14757
|
+
i.walletChain ?? i.pub,
|
|
14758
|
+
i.wallet,
|
|
14759
|
+
i.chainId,
|
|
14760
|
+
() => i.wallet.signTypedData({
|
|
14761
|
+
account: i.owner,
|
|
14762
|
+
...erc2612TypedData({
|
|
14763
|
+
chainId: i.chainId,
|
|
14764
|
+
token: i.token,
|
|
14765
|
+
owner: i.owner,
|
|
14766
|
+
permit: unsignedPermit
|
|
14767
|
+
})
|
|
14144
14768
|
})
|
|
14145
|
-
|
|
14769
|
+
);
|
|
14146
14770
|
erc2612Permit = { ...unsignedPermit, signature: signature2 };
|
|
14147
14771
|
}
|
|
14148
14772
|
const spender = await getSponsorRelayerAddress({
|
|
@@ -14159,10 +14783,15 @@ async function execute(i, key2, plan) {
|
|
|
14159
14783
|
deadline: (now + 900n).toString(),
|
|
14160
14784
|
...erc2612Permit ? { erc2612Permit } : {}
|
|
14161
14785
|
};
|
|
14162
|
-
const signature = await
|
|
14163
|
-
|
|
14164
|
-
|
|
14165
|
-
|
|
14786
|
+
const signature = await signWithChainRetry(
|
|
14787
|
+
i.walletChain ?? i.pub,
|
|
14788
|
+
i.wallet,
|
|
14789
|
+
i.chainId,
|
|
14790
|
+
() => i.wallet.signTypedData({
|
|
14791
|
+
account: i.owner,
|
|
14792
|
+
...batchTypedData(unsigned, spender)
|
|
14793
|
+
})
|
|
14794
|
+
);
|
|
14166
14795
|
i.onApproved?.();
|
|
14167
14796
|
return send({ ...unsigned, signature });
|
|
14168
14797
|
}
|
|
@@ -14191,6 +14820,7 @@ function makeSponsoredTokenCallback(deps) {
|
|
|
14191
14820
|
chainId,
|
|
14192
14821
|
transfers,
|
|
14193
14822
|
pub,
|
|
14823
|
+
walletChain,
|
|
14194
14824
|
wallet,
|
|
14195
14825
|
onApproved: deps.onApproved,
|
|
14196
14826
|
// Rest arguments keep the callbacks' arity: the flag appears only when set.
|
|
@@ -14463,6 +15093,19 @@ function makeSponsoredCallsCallback(deps) {
|
|
|
14463
15093
|
var WALLET_CATCHUP_TIMEOUT_MS = 3e4;
|
|
14464
15094
|
var PERMIT2_ALLOWANCE_VERIFY_ATTEMPTS = 6;
|
|
14465
15095
|
var PERMIT2_ALLOWANCE_VERIFY_DELAY_MS = 250;
|
|
15096
|
+
function shortfallBalance(error, asked) {
|
|
15097
|
+
if (!(error instanceof OwneyError)) return void 0;
|
|
15098
|
+
if (error.code !== "DEPOSIT_INSUFFICIENT_BALANCE") return void 0;
|
|
15099
|
+
const seen = error.details?.balance;
|
|
15100
|
+
if (typeof seen !== "string") return void 0;
|
|
15101
|
+
const balance = BigInt(seen);
|
|
15102
|
+
if (balance <= 0n || balance >= asked) return void 0;
|
|
15103
|
+
return (asked - balance) * 100n <= asked ? balance : void 0;
|
|
15104
|
+
}
|
|
15105
|
+
function agentRunsOn(agent, chainId) {
|
|
15106
|
+
const chains = agent.supportedChainIds;
|
|
15107
|
+
return !chains || chains.includes(chainId);
|
|
15108
|
+
}
|
|
14466
15109
|
function encodeMultiAgentCursor(map) {
|
|
14467
15110
|
return Buffer.from(JSON.stringify(map), "utf8").toString("base64");
|
|
14468
15111
|
}
|
|
@@ -14556,6 +15199,7 @@ var OwneySDK = class {
|
|
|
14556
15199
|
zyfaiRpcUrls;
|
|
14557
15200
|
yieldseekerApiBaseUrl;
|
|
14558
15201
|
yieldseekerSiweOrigin;
|
|
15202
|
+
userPoolCustomization = false;
|
|
14559
15203
|
routingApiBaseUrl;
|
|
14560
15204
|
referralSource;
|
|
14561
15205
|
ledger;
|
|
@@ -14606,6 +15250,7 @@ var OwneySDK = class {
|
|
|
14606
15250
|
this.routingApiBaseUrl = config.routingApiBaseUrl;
|
|
14607
15251
|
this.paymasterServiceUrl = config.paymasterServiceUrl;
|
|
14608
15252
|
this.referralSource = config.referralSource;
|
|
15253
|
+
this.userPoolCustomization = config.userPoolCustomization ?? false;
|
|
14609
15254
|
this.ledger = createFundingLedger({
|
|
14610
15255
|
apiKey: config.apiKey,
|
|
14611
15256
|
baseUrl: config.routingApiBaseUrl,
|
|
@@ -15066,6 +15711,31 @@ var OwneySDK = class {
|
|
|
15066
15711
|
}
|
|
15067
15712
|
return active;
|
|
15068
15713
|
}
|
|
15714
|
+
/**
|
|
15715
|
+
* Agents that do not run on the connection chain but can be read on their
|
|
15716
|
+
* own from a saved sign-in: Yieldseeker, Base-only, while the wallet sits on
|
|
15717
|
+
* Arbitrum or Ethereum. The whole-portfolio reads (ROUT-479) add them, under
|
|
15718
|
+
* a promptless state; with no saved sign-in they are left out, as before.
|
|
15719
|
+
*/
|
|
15720
|
+
offChainPortfolioAgents(state) {
|
|
15721
|
+
const connectionChain = state.chainId;
|
|
15722
|
+
if (connectionChain === null) return [];
|
|
15723
|
+
const active = this.getActiveAgents();
|
|
15724
|
+
const promptless = { ...state, promptless: true };
|
|
15725
|
+
return [...this.agents.values()].flatMap((agent) => {
|
|
15726
|
+
if (active.has(agent.id) || agentRunsOn(agent, connectionChain) || !agent.hasReadSession) return [];
|
|
15727
|
+
const chainIds = agent.supportedChainIds.filter((id) => agent.hasReadSession(promptless, id));
|
|
15728
|
+
return chainIds.length ? [{ agent, state: promptless, chainIds }] : [];
|
|
15729
|
+
});
|
|
15730
|
+
}
|
|
15731
|
+
/** Every agent a whole-portfolio read covers: the active ones on the
|
|
15732
|
+
* connection chain, then the off-chain ones on their own chain. */
|
|
15733
|
+
portfolioReads(state, chainId) {
|
|
15734
|
+
return [
|
|
15735
|
+
...[...this.getActiveAgents()].map(([id, agent]) => ({ id, agent, state, chainId })),
|
|
15736
|
+
...this.offChainPortfolioAgents(state).map(({ agent, state: readState, chainIds }) => ({ id: agent.id, agent, state: readState, chainId: chainIds[0] }))
|
|
15737
|
+
];
|
|
15738
|
+
}
|
|
15069
15739
|
/**
|
|
15070
15740
|
* Read the org's agent policy once and reuse it. fetchOrgAgentConfig never
|
|
15071
15741
|
* throws — it degrades to null — so this cannot break activation.
|
|
@@ -15102,7 +15772,8 @@ var OwneySDK = class {
|
|
|
15102
15772
|
try {
|
|
15103
15773
|
const policy = await this.getOrgAgentConfig();
|
|
15104
15774
|
if (!policy) return;
|
|
15105
|
-
|
|
15775
|
+
const effective = orgPolicyForConnect(policy, this.userPoolCustomization);
|
|
15776
|
+
await agent.applyOrgPolicy(state, chainId, effective);
|
|
15106
15777
|
} catch (error) {
|
|
15107
15778
|
console.warn(
|
|
15108
15779
|
`[owney-sdk] applyOrgPolicy(${agent.id}) failed (non-fatal):`,
|
|
@@ -15421,15 +16092,16 @@ var OwneySDK = class {
|
|
|
15421
16092
|
return { agentResults: {} };
|
|
15422
16093
|
}
|
|
15423
16094
|
const state = this.requireState();
|
|
15424
|
-
const chainId = this.requireChainId();
|
|
16095
|
+
const chainId = options.chainId ?? this.requireChainId();
|
|
16096
|
+
const activatedChain = state.chainId;
|
|
15425
16097
|
let checkpointFailure;
|
|
15426
16098
|
let checkpointFailedEvidence = [];
|
|
15427
16099
|
const checkpoint2 = options.onBeforeSubmission ? async (evidence) => {
|
|
15428
16100
|
try {
|
|
15429
|
-
if (this.state !== state || state.chainId !==
|
|
16101
|
+
if (this.state !== state || state.chainId !== activatedChain) throw new Error("Wallet changed before deposit submission.");
|
|
15430
16102
|
const submitting = evidence.map((leg) => ({ ...leg, depositSubmission: "started" }));
|
|
15431
16103
|
await options.onBeforeSubmission(submitting);
|
|
15432
|
-
if (this.state !== state || state.chainId !==
|
|
16104
|
+
if (this.state !== state || state.chainId !== activatedChain) throw new Error("Wallet changed before deposit submission.");
|
|
15433
16105
|
submitting.forEach((leg) => notifyFunding(onProgress, leg));
|
|
15434
16106
|
} catch (cause) {
|
|
15435
16107
|
checkpointFailedEvidence = evidence;
|
|
@@ -15471,7 +16143,8 @@ var OwneySDK = class {
|
|
|
15471
16143
|
chainId,
|
|
15472
16144
|
token: ledgerToken?.address ?? "",
|
|
15473
16145
|
asset: asset.toLowerCase(),
|
|
15474
|
-
requestedAmountRaw: amount
|
|
16146
|
+
requestedAmountRaw: amount,
|
|
16147
|
+
...options.batchId === void 0 ? {} : { batchId: options.batchId }
|
|
15475
16148
|
});
|
|
15476
16149
|
} catch {
|
|
15477
16150
|
}
|
|
@@ -15497,7 +16170,7 @@ var OwneySDK = class {
|
|
|
15497
16170
|
const wallet = await (agent.getFundingWallet ? agent.getFundingWallet(state, chainId, asset) : agent.getUserProfile(state, chainId).then((profile) => profile.smartWallet)).catch(() => void 0);
|
|
15498
16171
|
return { agent, wallet };
|
|
15499
16172
|
}));
|
|
15500
|
-
if (this.state !== state || this.state.chainId !==
|
|
16173
|
+
if (this.state !== state || this.state.chainId !== activatedChain)
|
|
15501
16174
|
throw new OwneyError("NOT_CONNECTED", "Wallet changed while recovering the deposit.");
|
|
15502
16175
|
const usedAgents = /* @__PURE__ */ new Set();
|
|
15503
16176
|
const legs = pending.transfers.map((transfer) => {
|
|
@@ -15537,6 +16210,7 @@ var OwneySDK = class {
|
|
|
15537
16210
|
);
|
|
15538
16211
|
}
|
|
15539
16212
|
const agent = this.getAgent(agentId);
|
|
16213
|
+
this.validateChainSupport(agent, chainId);
|
|
15540
16214
|
this.validateAssetSupport(agent, chainId, asset);
|
|
15541
16215
|
await this.validateMinDepositAmount(agent, state, chainId, asset, amount);
|
|
15542
16216
|
return ledgerDone(await this.depositWithFallback(
|
|
@@ -15555,6 +16229,7 @@ var OwneySDK = class {
|
|
|
15555
16229
|
));
|
|
15556
16230
|
}
|
|
15557
16231
|
const totalAmount = BigInt(amount);
|
|
16232
|
+
this.validateChainHasAgents(chainId);
|
|
15558
16233
|
const eligibleAgents = this.getEligibleAgents(chainId, asset, {
|
|
15559
16234
|
excludeDisabled: true
|
|
15560
16235
|
});
|
|
@@ -15911,6 +16586,41 @@ var OwneySDK = class {
|
|
|
15911
16586
|
return false;
|
|
15912
16587
|
}
|
|
15913
16588
|
}
|
|
16589
|
+
/**
|
|
16590
|
+
* Guard an explicitly requested chain against one agent's own list.
|
|
16591
|
+
*
|
|
16592
|
+
* Only reachable when the caller passes `chainId` — the activated chain has
|
|
16593
|
+
* already been checked by `activateAgent`. Kept separate from
|
|
16594
|
+
* `validateAssetSupport` so "this agent is not on Ethereum" does not arrive
|
|
16595
|
+
* worded as "this agent does not support USDC".
|
|
16596
|
+
*/
|
|
16597
|
+
validateChainSupport(agent, chainId) {
|
|
16598
|
+
if (!agent.supportedChainIds.includes(chainId)) {
|
|
16599
|
+
throw new AgentChainIncompatibleError(
|
|
16600
|
+
[{ agentId: agent.id, supportedChainIds: agent.supportedChainIds }],
|
|
16601
|
+
chainId
|
|
16602
|
+
);
|
|
16603
|
+
}
|
|
16604
|
+
}
|
|
16605
|
+
/**
|
|
16606
|
+
* Guard an explicitly requested chain before a fan-out.
|
|
16607
|
+
*
|
|
16608
|
+
* Without this the split simply produces no agents, and the caller is told
|
|
16609
|
+
* their amount "cannot activate every eligible agent" against a combined
|
|
16610
|
+
* minimum of 0 — an error about the amount when the chain is at fault.
|
|
16611
|
+
*/
|
|
16612
|
+
validateChainHasAgents(chainId) {
|
|
16613
|
+
const compatible = [...this.agents.values()].some(
|
|
16614
|
+
(agent) => agent.supportedChainIds.includes(chainId)
|
|
16615
|
+
);
|
|
16616
|
+
if (!compatible) {
|
|
16617
|
+
throw new OwneyError(
|
|
16618
|
+
"CHAIN_NO_COMPATIBLE_AGENTS",
|
|
16619
|
+
`No agents support chain ${chainId}.`,
|
|
16620
|
+
{ chainId }
|
|
16621
|
+
);
|
|
16622
|
+
}
|
|
16623
|
+
}
|
|
15914
16624
|
validateAssetSupport(agent, chainId, asset) {
|
|
15915
16625
|
const chainAssets = agent.supportedAssets.find(
|
|
15916
16626
|
(sa) => sa.chainId === chainId
|
|
@@ -16646,6 +17356,19 @@ var OwneySDK = class {
|
|
|
16646
17356
|
chain: dstChain,
|
|
16647
17357
|
transport: swapReadTransport(quote.dst.chainId, this.zyfaiRpcUrls)
|
|
16648
17358
|
});
|
|
17359
|
+
const walletPublic = createPublicClient4({
|
|
17360
|
+
chain: srcChain,
|
|
17361
|
+
transport: custom5(provider)
|
|
17362
|
+
});
|
|
17363
|
+
const signOnSource = (payload) => signWithChainRetry(
|
|
17364
|
+
walletPublic,
|
|
17365
|
+
wallet,
|
|
17366
|
+
quote.src.chainId,
|
|
17367
|
+
() => wallet.signTypedData({
|
|
17368
|
+
account: state.walletAddress,
|
|
17369
|
+
...payload
|
|
17370
|
+
})
|
|
17371
|
+
);
|
|
16649
17372
|
return {
|
|
16650
17373
|
api: this.swapApi(),
|
|
16651
17374
|
// Native-aware, like readSourceBalance below. Native ETH is never a
|
|
@@ -16696,10 +17419,7 @@ var OwneySDK = class {
|
|
|
16696
17419
|
},
|
|
16697
17420
|
signTypedData: (typedData) => {
|
|
16698
17421
|
assertWallet();
|
|
16699
|
-
return
|
|
16700
|
-
account: state.walletAddress,
|
|
16701
|
-
...typedData
|
|
16702
|
-
});
|
|
17422
|
+
return signOnSource(typedData);
|
|
16703
17423
|
},
|
|
16704
17424
|
// Chain-bound like every other read here: the wallet provider's chain is
|
|
16705
17425
|
// not ours to rely on mid-swap.
|
|
@@ -16768,10 +17488,7 @@ var OwneySDK = class {
|
|
|
16768
17488
|
chainId: quote.src.chainId,
|
|
16769
17489
|
signTypedData: (payload) => {
|
|
16770
17490
|
assertWallet();
|
|
16771
|
-
return
|
|
16772
|
-
account: state.walletAddress,
|
|
16773
|
-
...payload
|
|
16774
|
-
});
|
|
17491
|
+
return signOnSource(payload);
|
|
16775
17492
|
}
|
|
16776
17493
|
}
|
|
16777
17494
|
),
|
|
@@ -16798,13 +17515,27 @@ var OwneySDK = class {
|
|
|
16798
17515
|
* would strand funds we might have been able to move.
|
|
16799
17516
|
*/
|
|
16800
17517
|
/** ERC20 balance of the connected wallet, read through the wallet's own node. */
|
|
17518
|
+
/**
|
|
17519
|
+
* A read client pinned to `chainId`, over HTTP rather than the wallet.
|
|
17520
|
+
*
|
|
17521
|
+
* The swap rail has read this way from the start, and the reason is written
|
|
17522
|
+
* out at `buildSwapDeps`: a provider-backed client reads from whatever chain
|
|
17523
|
+
* the WALLET is on, which after a cross-chain swap is the source chain, not
|
|
17524
|
+
* the one the funds landed on. The deposit's own reads did not, so a Permit2
|
|
17525
|
+
* check for WETH on Arbitrum went to Base — where that address is not a
|
|
17526
|
+
* contract at all, so viem got "0x" back and threw "The contract function
|
|
17527
|
+
* 'allowance' returned no data".
|
|
17528
|
+
*/
|
|
17529
|
+
chainReader(chainId) {
|
|
17530
|
+
return createPublicClient4({
|
|
17531
|
+
chain: swapChain(chainId),
|
|
17532
|
+
transport: swapReadTransport(chainId, this.zyfaiRpcUrls)
|
|
17533
|
+
});
|
|
17534
|
+
}
|
|
16801
17535
|
async readTokenBalance(chainId, token) {
|
|
16802
17536
|
const state = this.requireState();
|
|
16803
17537
|
return readErc20Balance(
|
|
16804
|
-
|
|
16805
|
-
chain: swapChain(chainId),
|
|
16806
|
-
transport: custom5(this.requireConnectedProvider())
|
|
16807
|
-
}),
|
|
17538
|
+
this.chainReader(chainId),
|
|
16808
17539
|
token,
|
|
16809
17540
|
state.walletAddress
|
|
16810
17541
|
);
|
|
@@ -16813,10 +17544,7 @@ var OwneySDK = class {
|
|
|
16813
17544
|
async readTokenPermit2Allowance(chainId, token) {
|
|
16814
17545
|
const state = this.requireState();
|
|
16815
17546
|
return readPermit2Allowance(
|
|
16816
|
-
|
|
16817
|
-
chain: swapChain(chainId),
|
|
16818
|
-
transport: custom5(this.requireConnectedProvider())
|
|
16819
|
-
}),
|
|
17547
|
+
this.chainReader(chainId),
|
|
16820
17548
|
token,
|
|
16821
17549
|
state.walletAddress
|
|
16822
17550
|
);
|
|
@@ -16845,6 +17573,34 @@ var OwneySDK = class {
|
|
|
16845
17573
|
const balance = await this.readTokenBalance(chainId, token);
|
|
16846
17574
|
return (balance < received ? balance : received).toString();
|
|
16847
17575
|
}
|
|
17576
|
+
/**
|
|
17577
|
+
* Deposit a swap's output, retrying once at the balance the deposit saw.
|
|
17578
|
+
*
|
|
17579
|
+
* `settleSwapDepositAmount` approves and THEN reads, but the read and the
|
|
17580
|
+
* deposit's own pre-check can disagree: the approval is confirmed through
|
|
17581
|
+
* the wallet's node, the read goes to a pinned RPC, and gas paid in WETH
|
|
17582
|
+
* (MetaMask offers this to a wallet with no ETH) can land after either.
|
|
17583
|
+
* ROUT-618 failed that way with the settle step in place.
|
|
17584
|
+
*
|
|
17585
|
+
* The pre-check reports the balance it saw, and that is the authority, so
|
|
17586
|
+
* a shortfall is retried once at that figure. Only a small one: a node that
|
|
17587
|
+
* has not caught up can read near zero, and depositing that would leave the
|
|
17588
|
+
* rest of the swap stranded behind a "success".
|
|
17589
|
+
*/
|
|
17590
|
+
async depositSwapOutput(options) {
|
|
17591
|
+
const attempt = (amount) => this.deposit({ ...options, amount });
|
|
17592
|
+
try {
|
|
17593
|
+
return {
|
|
17594
|
+
deposit: await attempt(options.amount),
|
|
17595
|
+
deposited: options.amount
|
|
17596
|
+
};
|
|
17597
|
+
} catch (error) {
|
|
17598
|
+
const balance = shortfallBalance(error, BigInt(options.amount));
|
|
17599
|
+
if (balance === void 0) throw error;
|
|
17600
|
+
const deposited = balance.toString();
|
|
17601
|
+
return { deposit: await attempt(deposited), deposited };
|
|
17602
|
+
}
|
|
17603
|
+
}
|
|
16848
17604
|
async walletSeesBalance(chainId, token, amount) {
|
|
16849
17605
|
const provider = this.requireConnectedProvider();
|
|
16850
17606
|
const state = this.requireState();
|
|
@@ -16870,9 +17626,39 @@ var OwneySDK = class {
|
|
|
16870
17626
|
* Runs a quoted swap. A named seam rather than an inline `executeSwap` call
|
|
16871
17627
|
* so the deposit half of `swapAndDeposit` can be exercised on its own.
|
|
16872
17628
|
*/
|
|
16873
|
-
runSwap(quote, options, onTransactionHash) {
|
|
17629
|
+
async runSwap(quote, options, onTransactionHash) {
|
|
17630
|
+
await this.checkSwapGas(quote);
|
|
16874
17631
|
return executeSwap(this.buildSwapDeps(quote, options.assertCurrent, onTransactionHash), { quote, ...options });
|
|
16875
17632
|
}
|
|
17633
|
+
/**
|
|
17634
|
+
* Throws SWAP_INSUFFICIENT_GAS when the wallet cannot pay for this swap.
|
|
17635
|
+
*
|
|
17636
|
+
* Only the classic rail is ever refused: it is the one where the user sends
|
|
17637
|
+
* the transactions. Call it on a preview quote to warn BEFORE a withdrawal
|
|
17638
|
+
* moves anything — `withdrawAndSwap` repeats it on its own quote, but by
|
|
17639
|
+
* then the funds have already left the agent (ROUT-622).
|
|
17640
|
+
*/
|
|
17641
|
+
async checkSwapGas(quote) {
|
|
17642
|
+
const state = this.requireState();
|
|
17643
|
+
const chain2 = swapChain(quote.src.chainId);
|
|
17644
|
+
if (!chain2) return;
|
|
17645
|
+
const pub = createPublicClient4({
|
|
17646
|
+
chain: chain2,
|
|
17647
|
+
transport: swapReadTransport(quote.src.chainId, this.zyfaiRpcUrls)
|
|
17648
|
+
});
|
|
17649
|
+
const shortfall = await swapGasShortfall(
|
|
17650
|
+
{
|
|
17651
|
+
readNativeBalance: () => pub.getBalance({ address: state.walletAddress }),
|
|
17652
|
+
// The 1559 ceiling, as the wrap reserve reads it.
|
|
17653
|
+
getMaxFeePerGas: async () => {
|
|
17654
|
+
const fees = await pub.estimateFeesPerGas();
|
|
17655
|
+
return fees.maxFeePerGas ?? pub.getGasPrice();
|
|
17656
|
+
}
|
|
17657
|
+
},
|
|
17658
|
+
quote
|
|
17659
|
+
);
|
|
17660
|
+
if (shortfall) throw swapGasError(shortfall, chain2.nativeCurrency.symbol);
|
|
17661
|
+
}
|
|
16876
17662
|
/**
|
|
16877
17663
|
* The half of the swap deps that only ever talks to the routing API.
|
|
16878
17664
|
*
|
|
@@ -16944,12 +17730,20 @@ var OwneySDK = class {
|
|
|
16944
17730
|
);
|
|
16945
17731
|
}
|
|
16946
17732
|
await this.ensureSwapChain(entry.chainId);
|
|
16947
|
-
const
|
|
16948
|
-
|
|
17733
|
+
const token = entry.symbol === "WETH" ? SPONSORED_WETH_BY_CHAIN[entry.chainId] : void 0;
|
|
17734
|
+
const amount = token ? await this.settleSwapDepositAmount(
|
|
17735
|
+
entry.chainId,
|
|
17736
|
+
token,
|
|
17737
|
+
entry.symbol,
|
|
17738
|
+
BigInt(entry.received)
|
|
17739
|
+
) : entry.received;
|
|
17740
|
+
const { deposit } = await this.depositSwapOutput({
|
|
17741
|
+
amount,
|
|
16949
17742
|
asset: entry.symbol,
|
|
16950
17743
|
...entry.agentId ? { agentId: entry.agentId } : {},
|
|
16951
17744
|
// The swap's own funding-ledger operation; older records have none.
|
|
16952
|
-
...typeof entry.operationId === "string" ? { operationId: entry.operationId } : {}
|
|
17745
|
+
...typeof entry.operationId === "string" ? { operationId: entry.operationId } : {},
|
|
17746
|
+
...typeof entry.batchId === "string" ? { batchId: entry.batchId } : {}
|
|
16953
17747
|
});
|
|
16954
17748
|
clearPendingDeposit(entry.id);
|
|
16955
17749
|
return deposit;
|
|
@@ -17008,13 +17802,15 @@ var OwneySDK = class {
|
|
|
17008
17802
|
chainId: deposit.chainId,
|
|
17009
17803
|
createdAt: Date.now(),
|
|
17010
17804
|
...typeof deposit.agentId === "string" ? { agentId: deposit.agentId } : {},
|
|
17011
|
-
...typeof deposit.operationId === "string" ? { operationId: deposit.operationId } : {}
|
|
17805
|
+
...typeof deposit.operationId === "string" ? { operationId: deposit.operationId } : {},
|
|
17806
|
+
...typeof deposit.batchId === "string" ? { batchId: deposit.batchId } : {}
|
|
17012
17807
|
});
|
|
17013
17808
|
clearOrder(order.orderHash);
|
|
17014
17809
|
updateWithdrawSwap(order.orderHash, { status: "landed" });
|
|
17015
17810
|
return { orderHash: order.orderHash, status: "completed" };
|
|
17016
17811
|
} catch (error) {
|
|
17017
|
-
if (error instanceof OwneyError && error.code === "SWAP_ORDER_REFUNDED" && error.details?.outcome === "refunded"
|
|
17812
|
+
if (error instanceof OwneyError && (error.code === "SWAP_ORDER_REFUNDED" && error.details?.outcome === "refunded" || // The provider never accepted it: nothing was escrowed.
|
|
17813
|
+
error.code === "SWAP_ORDER_NOT_FOUND")) {
|
|
17018
17814
|
clearOrder(order.orderHash);
|
|
17019
17815
|
updateWithdrawSwap(order.orderHash, { status: "refunded" });
|
|
17020
17816
|
} else {
|
|
@@ -17187,7 +17983,8 @@ var OwneySDK = class {
|
|
|
17187
17983
|
owner: state.walletAddress,
|
|
17188
17984
|
chainId: options.to.chainId,
|
|
17189
17985
|
token: SupportedAssets.find((value) => value.chainId === options.to.chainId && value.symbol === options.to.symbol)?.address ?? "",
|
|
17190
|
-
asset: options.to.symbol.toLowerCase()
|
|
17986
|
+
asset: options.to.symbol.toLowerCase(),
|
|
17987
|
+
...options.batchId === void 0 ? {} : { batchId: options.batchId }
|
|
17191
17988
|
});
|
|
17192
17989
|
const secretHandoff = this.secretHandoffFor(ledgerOp, ledgerInput);
|
|
17193
17990
|
try {
|
|
@@ -17225,7 +18022,8 @@ var OwneySDK = class {
|
|
|
17225
18022
|
symbol: options.to.symbol,
|
|
17226
18023
|
chainId: quote.dst.chainId,
|
|
17227
18024
|
...options.agentId ? { agentId: options.agentId } : {},
|
|
17228
|
-
...ledgerOp ? { operationId: ledgerOp.operationId } : {}
|
|
18025
|
+
...ledgerOp ? { operationId: ledgerOp.operationId } : {},
|
|
18026
|
+
...options.batchId === void 0 ? {} : { batchId: options.batchId }
|
|
17229
18027
|
},
|
|
17230
18028
|
...secretHandoff ? { secretHandoff } : {},
|
|
17231
18029
|
...ledgerOp ? { onOrderSubmitted: (orderHash) => {
|
|
@@ -17268,7 +18066,7 @@ var OwneySDK = class {
|
|
|
17268
18066
|
options.assertCurrent?.();
|
|
17269
18067
|
await options.onBeforeDeposit?.();
|
|
17270
18068
|
options.assertCurrent?.();
|
|
17271
|
-
const deposit = await this.
|
|
18069
|
+
const { deposit, deposited } = await this.depositSwapOutput({
|
|
17272
18070
|
amount,
|
|
17273
18071
|
asset: options.to.symbol,
|
|
17274
18072
|
...options.agentId ? { agentId: options.agentId } : {},
|
|
@@ -17278,7 +18076,7 @@ var OwneySDK = class {
|
|
|
17278
18076
|
...ledgerOp ? { operationId: ledgerOp.operationId } : {}
|
|
17279
18077
|
});
|
|
17280
18078
|
if (backgroundDepositId) clearPendingDeposit(backgroundDepositId);
|
|
17281
|
-
return this.ledgerSucceeded(ledgerOp, { swap, deposit, deposited
|
|
18079
|
+
return this.ledgerSucceeded(ledgerOp, { swap, deposit, deposited });
|
|
17282
18080
|
} catch (error) {
|
|
17283
18081
|
const pending = {
|
|
17284
18082
|
// Keyed by the order when there is one, so it replaces any record a
|
|
@@ -17290,7 +18088,11 @@ var OwneySDK = class {
|
|
|
17290
18088
|
...options.agentId ? { agentId: options.agentId } : {},
|
|
17291
18089
|
createdAt: Date.now()
|
|
17292
18090
|
};
|
|
17293
|
-
savePendingDeposit(
|
|
18091
|
+
savePendingDeposit({
|
|
18092
|
+
...pending,
|
|
18093
|
+
...ledgerOp ? { operationId: ledgerOp.operationId } : {},
|
|
18094
|
+
...options.batchId === void 0 ? {} : { batchId: options.batchId }
|
|
18095
|
+
});
|
|
17294
18096
|
throw new OwneyError(
|
|
17295
18097
|
"SWAP_DEPOSIT_PENDING",
|
|
17296
18098
|
`The swap went through and your ${options.to.symbol} is in your wallet, but adding it to the agent didn't complete. Nothing needs swapping again.`,
|
|
@@ -17340,7 +18142,8 @@ var OwneySDK = class {
|
|
|
17340
18142
|
token: asset.address,
|
|
17341
18143
|
asset: asset.symbol.toLowerCase(),
|
|
17342
18144
|
isMax: recovery.requested === void 0,
|
|
17343
|
-
...recovery.requested === void 0 ? {} : { requestedAmountRaw: recovery.requested }
|
|
18145
|
+
...recovery.requested === void 0 ? {} : { requestedAmountRaw: recovery.requested },
|
|
18146
|
+
...record2.batchId === void 0 ? {} : { batchId: record2.batchId }
|
|
17344
18147
|
});
|
|
17345
18148
|
} catch {
|
|
17346
18149
|
}
|
|
@@ -17495,6 +18298,7 @@ var OwneySDK = class {
|
|
|
17495
18298
|
let ledgerInput;
|
|
17496
18299
|
ledgerOp = this.openSwapLedger(() => {
|
|
17497
18300
|
const requestedRaw = saved ? saved.recovery.requested : options.amount === void 0 ? void 0 : parseUnits4(options.amount, asset.decimals).toString();
|
|
18301
|
+
const batchId = saved?.batchId ?? options.batchId;
|
|
17498
18302
|
return ledgerInput = {
|
|
17499
18303
|
operationId: saved?.operationId ?? options.operationId,
|
|
17500
18304
|
kind: "withdraw_swap",
|
|
@@ -17503,7 +18307,8 @@ var OwneySDK = class {
|
|
|
17503
18307
|
token: asset.address,
|
|
17504
18308
|
asset: asset.symbol.toLowerCase(),
|
|
17505
18309
|
isMax: requestedRaw === void 0,
|
|
17506
|
-
...requestedRaw === void 0 ? {} : { requestedAmountRaw: requestedRaw }
|
|
18310
|
+
...requestedRaw === void 0 ? {} : { requestedAmountRaw: requestedRaw },
|
|
18311
|
+
...batchId === void 0 ? {} : { batchId }
|
|
17507
18312
|
};
|
|
17508
18313
|
});
|
|
17509
18314
|
const secretHandoff = this.secretHandoffFor(ledgerOp, ledgerInput);
|
|
@@ -17548,7 +18353,8 @@ var OwneySDK = class {
|
|
|
17548
18353
|
agentId: options.agentId,
|
|
17549
18354
|
evidence: {}
|
|
17550
18355
|
},
|
|
17551
|
-
...ledgerOp ? { operationId: ledgerOp.operationId } : {}
|
|
18356
|
+
...ledgerOp ? { operationId: ledgerOp.operationId } : {},
|
|
18357
|
+
...options.batchId === void 0 ? {} : { batchId: options.batchId }
|
|
17552
18358
|
};
|
|
17553
18359
|
if (ledgerOp && !record2.operationId) record2.operationId = ledgerOp.operationId;
|
|
17554
18360
|
hadDurableRecord = saveWithdrawSwap(record2);
|
|
@@ -17664,6 +18470,8 @@ var OwneySDK = class {
|
|
|
17664
18470
|
() => new OwneyError("SWAP_WALLET_PROMPT_TIMEOUT", "The wallet did not confirm its chain. No swap was submitted.", { outcome: "not-submitted" })
|
|
17665
18471
|
);
|
|
17666
18472
|
assertCurrent();
|
|
18473
|
+
await this.checkSwapGas(quote);
|
|
18474
|
+
assertCurrent();
|
|
17667
18475
|
const swap = await executeSwap(this.buildSwapDeps(quote, assertCurrent, (hash2) => {
|
|
17668
18476
|
record2.txHash = hash2;
|
|
17669
18477
|
saveWithdrawSwap(record2);
|
|
@@ -17793,7 +18601,7 @@ var OwneySDK = class {
|
|
|
17793
18601
|
{ phase: "prepare", rejectedBeforeSubmission: true }
|
|
17794
18602
|
);
|
|
17795
18603
|
const state = this.requireState();
|
|
17796
|
-
const chainId = this.requireChainId();
|
|
18604
|
+
const chainId = options.chainId ?? this.requireChainId();
|
|
17797
18605
|
const submissionKey = `${state.walletAddress.toLowerCase()}:${chainId}:${options.asset.toUpperCase()}`;
|
|
17798
18606
|
if (this.withdrawalSubmissions.has(submissionKey))
|
|
17799
18607
|
throw new OwneyError(
|
|
@@ -17815,7 +18623,8 @@ var OwneySDK = class {
|
|
|
17815
18623
|
token: ledgerToken?.address ?? "",
|
|
17816
18624
|
asset: options.asset.toLowerCase(),
|
|
17817
18625
|
isMax: options.amount === void 0,
|
|
17818
|
-
...options.amount !== void 0 ? { requestedAmountRaw: BigInt(options.amount).toString() } : {}
|
|
18626
|
+
...options.amount !== void 0 ? { requestedAmountRaw: BigInt(options.amount).toString() } : {},
|
|
18627
|
+
...options.batchId === void 0 ? {} : { batchId: options.batchId }
|
|
17819
18628
|
});
|
|
17820
18629
|
} catch {
|
|
17821
18630
|
}
|
|
@@ -18140,6 +18949,7 @@ var OwneySDK = class {
|
|
|
18140
18949
|
}
|
|
18141
18950
|
async withdrawFromAgents(options, state, chainId, attempted, ledgerLeg, reservation, plannedLegs, settleLedger, serverLegs = /* @__PURE__ */ new Map()) {
|
|
18142
18951
|
const { asset, amount, agentId, onAgentResult } = options;
|
|
18952
|
+
const activatedChain = state.chainId;
|
|
18143
18953
|
const notifyAgentResult = (id, result) => {
|
|
18144
18954
|
try {
|
|
18145
18955
|
if (result.evidence) notifyFunding(options.onProgress, result.evidence);
|
|
@@ -18200,7 +19010,7 @@ var OwneySDK = class {
|
|
|
18200
19010
|
const plannedTask = serverLegs.get(agent.id);
|
|
18201
19011
|
const serverTask = plannedTask ? await plannedTask.answer : void 0;
|
|
18202
19012
|
if (serverTask) await settleLedger?.(3e3);
|
|
18203
|
-
if (this.state !== state || this.state.chainId !==
|
|
19013
|
+
if (this.state !== state || this.state.chainId !== activatedChain)
|
|
18204
19014
|
throw new OwneyError("NOT_CONNECTED", "Wallet connection changed before withdrawal submission.");
|
|
18205
19015
|
attempted.add(agent.id);
|
|
18206
19016
|
let evidence = {
|
|
@@ -18285,6 +19095,7 @@ var OwneySDK = class {
|
|
|
18285
19095
|
}
|
|
18286
19096
|
if (agentId) {
|
|
18287
19097
|
const agent = this.getAgent(agentId);
|
|
19098
|
+
this.validateChainSupport(agent, chainId);
|
|
18288
19099
|
this.validateAssetSupport(agent, chainId, asset);
|
|
18289
19100
|
const result = await withFailureReporting(
|
|
18290
19101
|
this.apiKey,
|
|
@@ -18508,7 +19319,7 @@ var OwneySDK = class {
|
|
|
18508
19319
|
const verified = await entry.agent.getWithdrawableBalance(state, chainId, token, minimumAmount);
|
|
18509
19320
|
if (typeof verified !== "bigint" || verified < 0n)
|
|
18510
19321
|
throw new OwneyError("WITHDRAW_BALANCE_UNAVAILABLE", "Invalid withdrawal balance proof.", {}, entry.agent.id);
|
|
18511
|
-
if (this.state !== state || this.state.walletAddress !== state.walletAddress || this.state.chainId !==
|
|
19322
|
+
if (this.state !== state || this.state.walletAddress !== state.walletAddress || this.state.chainId !== activatedChain)
|
|
18512
19323
|
throw new OwneyError("NOT_CONNECTED", "Account changed while planning withdrawal.");
|
|
18513
19324
|
entry.balance = verified;
|
|
18514
19325
|
const unavailableIndex = unavailableAgents.indexOf(entry.agent);
|
|
@@ -18523,7 +19334,7 @@ var OwneySDK = class {
|
|
|
18523
19334
|
};
|
|
18524
19335
|
}
|
|
18525
19336
|
}));
|
|
18526
|
-
if (this.state !== state || this.state.chainId !==
|
|
19337
|
+
if (this.state !== state || this.state.chainId !== activatedChain)
|
|
18527
19338
|
throw new OwneyError("NOT_CONNECTED", "Account changed while planning withdrawal.");
|
|
18528
19339
|
const unavailableAgentIds = unavailableAgents.map((agent) => agent.id);
|
|
18529
19340
|
const totalAvailable = balances.reduce((sum, x) => sum + x.balance, 0n);
|
|
@@ -18704,6 +19515,76 @@ var OwneySDK = class {
|
|
|
18704
19515
|
* @param agentId - Optional. Agent to query. Omit for aggregated balances.
|
|
18705
19516
|
* @returns {AgentBalance} for a single agent, or {OwneyBalances} with totalBalance and per-agent breakdown
|
|
18706
19517
|
*/
|
|
19518
|
+
/**
|
|
19519
|
+
* Withdraw every position the wallet holds, across chains and assets.
|
|
19520
|
+
*
|
|
19521
|
+
* `withdraw()` drains one asset on one chain, so this is N of those. It
|
|
19522
|
+
* deliberately does not stop at the first failure: the funds in the other
|
|
19523
|
+
* positions are just as withdrawable, and someone who asked for everything
|
|
19524
|
+
* is better served by three of four than by none. Each leg reports its own
|
|
19525
|
+
* outcome so the caller can name the ones that did not arrive; only a total
|
|
19526
|
+
* failure throws.
|
|
19527
|
+
*
|
|
19528
|
+
* @returns {OwneyWithdrawAllResult} one leg per position attempted.
|
|
19529
|
+
*/
|
|
19530
|
+
async withdrawAll() {
|
|
19531
|
+
this.requireState();
|
|
19532
|
+
const balances = await this.readBalances(void 0, false);
|
|
19533
|
+
const positions = /* @__PURE__ */ new Map();
|
|
19534
|
+
for (const agentBalance of Object.values(balances.agentBalances ?? {})) {
|
|
19535
|
+
for (const token of agentBalance.tokens ?? []) {
|
|
19536
|
+
if (!(Number(token.amount) > 0)) continue;
|
|
19537
|
+
const key2 = `${token.chainId}:${token.asset}`;
|
|
19538
|
+
const seen = positions.get(key2);
|
|
19539
|
+
if (seen) {
|
|
19540
|
+
seen.amount = String(Number(seen.amount) + Number(token.amount));
|
|
19541
|
+
continue;
|
|
19542
|
+
}
|
|
19543
|
+
positions.set(key2, {
|
|
19544
|
+
chainId: token.chainId,
|
|
19545
|
+
asset: token.asset,
|
|
19546
|
+
amount: token.amount
|
|
19547
|
+
});
|
|
19548
|
+
}
|
|
19549
|
+
}
|
|
19550
|
+
if (positions.size === 0) {
|
|
19551
|
+
throw new OwneyError(
|
|
19552
|
+
"WITHDRAW_NOTHING_TO_WITHDRAW",
|
|
19553
|
+
"There is nothing to withdraw."
|
|
19554
|
+
);
|
|
19555
|
+
}
|
|
19556
|
+
const legs = [];
|
|
19557
|
+
for (const position2 of positions.values()) {
|
|
19558
|
+
try {
|
|
19559
|
+
const result = await this.withdraw({
|
|
19560
|
+
asset: position2.asset,
|
|
19561
|
+
chainId: position2.chainId
|
|
19562
|
+
});
|
|
19563
|
+
legs.push({ ...position2, result });
|
|
19564
|
+
} catch (err) {
|
|
19565
|
+
console.error(
|
|
19566
|
+
`withdrawAll failed for ${position2.asset} on ${position2.chainId}:`,
|
|
19567
|
+
err
|
|
19568
|
+
);
|
|
19569
|
+
legs.push({
|
|
19570
|
+
...position2,
|
|
19571
|
+
error: err instanceof Error ? err.message : String(err)
|
|
19572
|
+
});
|
|
19573
|
+
}
|
|
19574
|
+
}
|
|
19575
|
+
if (legs.every((leg) => leg.error !== void 0)) {
|
|
19576
|
+
throw new OwneyError(
|
|
19577
|
+
"WITHDRAW_ALL_FAILED",
|
|
19578
|
+
"Failed to withdraw from every position.",
|
|
19579
|
+
{
|
|
19580
|
+
legErrors: Object.fromEntries(
|
|
19581
|
+
legs.map((leg) => [`${leg.asset}:${leg.chainId}`, leg.error])
|
|
19582
|
+
)
|
|
19583
|
+
}
|
|
19584
|
+
);
|
|
19585
|
+
}
|
|
19586
|
+
return { legs };
|
|
19587
|
+
}
|
|
18707
19588
|
async getBalances(agentId, options) {
|
|
18708
19589
|
if (agentId) {
|
|
18709
19590
|
const { state, chainId, assertCurrent } = this.captureReadScope(options?.chainId);
|
|
@@ -18721,7 +19602,11 @@ var OwneySDK = class {
|
|
|
18721
19602
|
balanceComposition: agent.balanceComposition ?? "tokens-include-positions"
|
|
18722
19603
|
};
|
|
18723
19604
|
}
|
|
18724
|
-
const
|
|
19605
|
+
const portfolio = options?.chainId === void 0 && options?.asset === void 0;
|
|
19606
|
+
return this.readBalances(options, portfolio);
|
|
19607
|
+
}
|
|
19608
|
+
async readBalances(options, portfolio) {
|
|
19609
|
+
const { balances, failures } = await this.readAggregatedBalances(options, portfolio);
|
|
18725
19610
|
if (Object.keys(balances.agentBalances).length === 0) {
|
|
18726
19611
|
throw new OwneyError(
|
|
18727
19612
|
"BALANCE_ALL_FAILED",
|
|
@@ -18732,21 +19617,27 @@ var OwneySDK = class {
|
|
|
18732
19617
|
return balances;
|
|
18733
19618
|
}
|
|
18734
19619
|
/** Preserve failure objects for withdrawal recovery without changing public balance results. */
|
|
18735
|
-
async readAggregatedBalances(options) {
|
|
19620
|
+
async readAggregatedBalances(options, portfolio = false) {
|
|
18736
19621
|
const { state, chainId, assertCurrent } = this.captureReadScope(options?.chainId);
|
|
18737
19622
|
const asset = options?.asset;
|
|
18738
|
-
const readBalance = (
|
|
18739
|
-
agent,
|
|
19623
|
+
const readBalance = (read2) => read2.state === state ? this.readAgent(
|
|
19624
|
+
read2.agent,
|
|
18740
19625
|
"balances",
|
|
18741
|
-
() => asset ? agent.getBalances(state, chainId, asset) : agent.getBalances(state, chainId),
|
|
19626
|
+
() => asset ? read2.agent.getBalances(state, chainId, asset) : read2.agent.getBalances(state, chainId),
|
|
18742
19627
|
asset ? { asset } : null
|
|
19628
|
+
) : this.readAgent(
|
|
19629
|
+
read2.agent,
|
|
19630
|
+
"balances",
|
|
19631
|
+
() => read2.agent.getBalances(read2.state, read2.chainId),
|
|
19632
|
+
{ chainId: read2.chainId }
|
|
18743
19633
|
);
|
|
18744
19634
|
let totalBalance = 0;
|
|
18745
19635
|
const results = {};
|
|
18746
|
-
const entries = [...this.getActiveAgents().
|
|
19636
|
+
const entries = portfolio ? this.portfolioReads(state, chainId).map((read2) => [read2.id, read2]) : [...this.getActiveAgents()].map(([id, agent]) => [id, { id, agent, state, chainId }]);
|
|
18747
19637
|
const balanceResults = await Promise.allSettled(
|
|
18748
|
-
entries.map(async ([id,
|
|
18749
|
-
const
|
|
19638
|
+
entries.map(async ([id, read2]) => {
|
|
19639
|
+
const { agent } = read2;
|
|
19640
|
+
const b = await readBalance(read2);
|
|
18750
19641
|
return [
|
|
18751
19642
|
id,
|
|
18752
19643
|
{
|
|
@@ -18803,10 +19694,14 @@ var OwneySDK = class {
|
|
|
18803
19694
|
() => agent.getEarnings(state, chainId)
|
|
18804
19695
|
);
|
|
18805
19696
|
}
|
|
18806
|
-
const entries = [...this.getActiveAgents().entries()];
|
|
18807
19697
|
return this.aggregateEarnings(
|
|
18808
|
-
|
|
18809
|
-
(
|
|
19698
|
+
this.portfolioReads(state, chainId),
|
|
19699
|
+
(read2) => this.readAgent(
|
|
19700
|
+
read2.agent,
|
|
19701
|
+
"earnings",
|
|
19702
|
+
() => read2.agent.getEarnings(read2.state, read2.chainId),
|
|
19703
|
+
read2.state === state ? null : { chainId: read2.chainId }
|
|
19704
|
+
)
|
|
18810
19705
|
);
|
|
18811
19706
|
}
|
|
18812
19707
|
/**
|
|
@@ -18816,23 +19711,24 @@ var OwneySDK = class {
|
|
|
18816
19711
|
async refreshEarnings(agentId) {
|
|
18817
19712
|
const state = this.requireState();
|
|
18818
19713
|
const chainId = this.requireChainId();
|
|
18819
|
-
const refreshAgent = (agent) => this.readAgent(
|
|
19714
|
+
const refreshAgent = ({ agent, state: readState, chainId: readChain }) => this.readAgent(
|
|
18820
19715
|
agent,
|
|
18821
19716
|
agent.refreshEarnings ? "refreshEarnings" : "earnings",
|
|
18822
|
-
() => agent.refreshEarnings?.(
|
|
19717
|
+
() => agent.refreshEarnings?.(readState, readChain) ?? agent.getEarnings(readState, readChain),
|
|
19718
|
+
readState === state ? null : { chainId: readChain }
|
|
18823
19719
|
);
|
|
18824
|
-
if (agentId) return refreshAgent(this.getAgent(agentId));
|
|
18825
|
-
return this.aggregateEarnings(
|
|
19720
|
+
if (agentId) return refreshAgent({ agent: this.getAgent(agentId), state, chainId });
|
|
19721
|
+
return this.aggregateEarnings(this.portfolioReads(state, chainId), refreshAgent);
|
|
18826
19722
|
}
|
|
18827
19723
|
async aggregateEarnings(entries, read2) {
|
|
18828
|
-
const settled = await Promise.allSettled(entries.map(
|
|
19724
|
+
const settled = await Promise.allSettled(entries.map(read2));
|
|
18829
19725
|
const agentEarnings = {};
|
|
18830
19726
|
const agentErrors = {};
|
|
18831
19727
|
const agentRetryAt = {};
|
|
18832
19728
|
const failures = [];
|
|
18833
19729
|
let totalEarnings = 0;
|
|
18834
19730
|
for (let i = 0; i < settled.length; i++) {
|
|
18835
|
-
const
|
|
19731
|
+
const { id } = entries[i];
|
|
18836
19732
|
const result = settled[i];
|
|
18837
19733
|
if (result.status === "fulfilled") {
|
|
18838
19734
|
agentEarnings[id] = result.value;
|
|
@@ -18879,9 +19775,46 @@ var OwneySDK = class {
|
|
|
18879
19775
|
async getDailyEarnings({
|
|
18880
19776
|
agentId,
|
|
18881
19777
|
days,
|
|
18882
|
-
tokenSymbol
|
|
19778
|
+
tokenSymbol,
|
|
19779
|
+
chainIds
|
|
18883
19780
|
}) {
|
|
18884
19781
|
const state = this.requireState();
|
|
19782
|
+
if (chainIds?.length) {
|
|
19783
|
+
const agents = (agentId ? [this.getAgent(agentId)] : [...this.getActiveAgents().values()]).filter((agent) => agent.getDailyEarnings);
|
|
19784
|
+
const legs = [];
|
|
19785
|
+
for (const agent of agents) {
|
|
19786
|
+
for (const legChainId of chainIds) {
|
|
19787
|
+
if (agentRunsOn(agent, legChainId))
|
|
19788
|
+
legs.push({ agent, legChainId, legState: state });
|
|
19789
|
+
}
|
|
19790
|
+
}
|
|
19791
|
+
if (!agentId) {
|
|
19792
|
+
for (const extra of this.offChainPortfolioAgents(state)) {
|
|
19793
|
+
if (!extra.agent.getDailyEarnings) continue;
|
|
19794
|
+
for (const legChainId of chainIds) {
|
|
19795
|
+
if (extra.chainIds.includes(legChainId))
|
|
19796
|
+
legs.push({ agent: extra.agent, legChainId, legState: extra.state });
|
|
19797
|
+
}
|
|
19798
|
+
}
|
|
19799
|
+
}
|
|
19800
|
+
const settled2 = await Promise.allSettled(
|
|
19801
|
+
legs.map(
|
|
19802
|
+
({ agent, legChainId, legState }) => this.readAgent(
|
|
19803
|
+
agent,
|
|
19804
|
+
"dailyEarnings",
|
|
19805
|
+
() => agent.getDailyEarnings(legState, legChainId, days, tokenSymbol),
|
|
19806
|
+
// The leg's chain must be in the key: the read key otherwise names
|
|
19807
|
+
// only the CONNECTION chain, so every leg shared the first leg's
|
|
19808
|
+
// request and the sum counted that chain once per leg. (ROUT-561)
|
|
19809
|
+
{ days, tokenSymbol, chainId: legChainId }
|
|
19810
|
+
)
|
|
19811
|
+
)
|
|
19812
|
+
);
|
|
19813
|
+
const series2 = settled2.flatMap((result) => result.status === "fulfilled" ? [result.value] : []);
|
|
19814
|
+
const failure = settled2.find((result) => result.status === "rejected");
|
|
19815
|
+
if (!series2.length && failure?.status === "rejected") throw failure.reason;
|
|
19816
|
+
return mergeDailyEarnings(series2);
|
|
19817
|
+
}
|
|
18885
19818
|
const chainId = this.requireChainId();
|
|
18886
19819
|
if (agentId) {
|
|
18887
19820
|
const agent = this.getAgent(agentId);
|
|
@@ -18923,46 +19856,113 @@ var OwneySDK = class {
|
|
|
18923
19856
|
assets: aggregateDailyEarnings(series, tokenSymbol)
|
|
18924
19857
|
};
|
|
18925
19858
|
}
|
|
19859
|
+
/**
|
|
19860
|
+
* The deposit-time pool catalogue (ROUT-569): every protocol with its
|
|
19861
|
+
* selectable pools (name, APY, TVL, link) for `asset` under `strategy`.
|
|
19862
|
+
* Defaults to the zyfai agent, the only one with pool customization today.
|
|
19863
|
+
*/
|
|
19864
|
+
async getPoolCatalog(params) {
|
|
19865
|
+
await this.ensureAgentsInitialized();
|
|
19866
|
+
const agent = this.getAgent(params.agentId ?? "zyfai");
|
|
19867
|
+
if (!agent.getPoolCatalog) {
|
|
19868
|
+
throw new OwneyError(
|
|
19869
|
+
"POOL_CATALOG_UNSUPPORTED",
|
|
19870
|
+
`Agent ${agent.id} does not support pool customization`
|
|
19871
|
+
);
|
|
19872
|
+
}
|
|
19873
|
+
return agent.getPoolCatalog({
|
|
19874
|
+
asset: params.asset,
|
|
19875
|
+
strategy: params.strategy
|
|
19876
|
+
});
|
|
19877
|
+
}
|
|
19878
|
+
/**
|
|
19879
|
+
* Apply a user's deposit-time pool selection to their account (ROUT-569).
|
|
19880
|
+
* The request carries explicit pool choices plus the resulting strategy for
|
|
19881
|
+
* each asset reviewed in the deposit flow.
|
|
19882
|
+
*/
|
|
19883
|
+
async setPoolSelection(params) {
|
|
19884
|
+
await this.ensureAgentsInitialized();
|
|
19885
|
+
const agent = this.getAgent(params.agentId ?? "zyfai");
|
|
19886
|
+
if (!agent.setPoolSelection) {
|
|
19887
|
+
throw new OwneyError(
|
|
19888
|
+
"POOL_SELECTION_UNSUPPORTED",
|
|
19889
|
+
`Agent ${agent.id} does not support pool customization`
|
|
19890
|
+
);
|
|
19891
|
+
}
|
|
19892
|
+
await agent.setPoolSelection(params.selection);
|
|
19893
|
+
}
|
|
19894
|
+
/**
|
|
19895
|
+
* The pool selection saved on the user's account (ROUT-650), so the Pools
|
|
19896
|
+
* step can show what applies now rather than the defaults. `pairs` and
|
|
19897
|
+
* `assets` say which protocol/chain lists and strategies to read.
|
|
19898
|
+
*/
|
|
19899
|
+
async getPoolSelection(params) {
|
|
19900
|
+
const state = this.requireState();
|
|
19901
|
+
const chainId = this.requireChainId();
|
|
19902
|
+
await this.ensureAgentsInitialized();
|
|
19903
|
+
const agent = this.getAgent(params.agentId ?? "zyfai");
|
|
19904
|
+
if (!agent.getPoolSelection) {
|
|
19905
|
+
throw new OwneyError(
|
|
19906
|
+
"POOL_SELECTION_UNSUPPORTED",
|
|
19907
|
+
`Agent ${agent.id} does not support pool customization`
|
|
19908
|
+
);
|
|
19909
|
+
}
|
|
19910
|
+
return agent.getPoolSelection(state, chainId, {
|
|
19911
|
+
pairs: params.pairs,
|
|
19912
|
+
assets: params.assets
|
|
19913
|
+
});
|
|
19914
|
+
}
|
|
18926
19915
|
async getAccountApy({
|
|
18927
19916
|
agentId,
|
|
18928
19917
|
days,
|
|
18929
|
-
tokenSymbol
|
|
19918
|
+
tokenSymbol,
|
|
19919
|
+
chainId: scope
|
|
18930
19920
|
}) {
|
|
18931
19921
|
const state = this.requireState();
|
|
18932
19922
|
const chainId = this.requireChainId();
|
|
19923
|
+
const scopeChainId = scope === "all" ? null : scope;
|
|
18933
19924
|
if (agentId) {
|
|
18934
19925
|
const agent = this.getAgent(agentId);
|
|
18935
19926
|
return this.readAgent(
|
|
18936
19927
|
agent,
|
|
18937
19928
|
"accountApy",
|
|
18938
|
-
() => agent.getAccountApy(state, chainId, days, tokenSymbol),
|
|
18939
|
-
{ days, tokenSymbol }
|
|
19929
|
+
() => agent.getAccountApy(state, chainId, days, tokenSymbol, scopeChainId),
|
|
19930
|
+
{ days, tokenSymbol, scopeChainId }
|
|
18940
19931
|
);
|
|
18941
19932
|
}
|
|
18942
|
-
const
|
|
18943
|
-
const
|
|
18944
|
-
|
|
18945
|
-
|
|
18946
|
-
|
|
18947
|
-
|
|
19933
|
+
const entries = scopeChainId === void 0 ? [...this.getActiveAgents()].map(([id, agent]) => ({ id, agent, state, chainId })) : this.portfolioReads(state, chainId).filter((read2) => read2.state === state || scopeChainId === null || agentRunsOn(read2.agent, scopeChainId));
|
|
19934
|
+
const reads = await Promise.all(
|
|
19935
|
+
entries.map(async ({ id, agent, state: readState, chainId: readChain }) => {
|
|
19936
|
+
const offChain = readState !== state;
|
|
19937
|
+
const pair = Promise.all([
|
|
19938
|
+
this.readAgent(
|
|
18948
19939
|
agent,
|
|
18949
19940
|
"accountApy",
|
|
18950
|
-
() => agent.getAccountApy(
|
|
18951
|
-
|
|
18952
|
-
|
|
18953
|
-
|
|
18954
|
-
|
|
18955
|
-
|
|
18956
|
-
|
|
18957
|
-
|
|
18958
|
-
|
|
18959
|
-
|
|
18960
|
-
|
|
18961
|
-
|
|
18962
|
-
|
|
18963
|
-
|
|
18964
|
-
|
|
18965
|
-
|
|
19941
|
+
() => agent.getAccountApy(
|
|
19942
|
+
readState,
|
|
19943
|
+
readChain,
|
|
19944
|
+
days,
|
|
19945
|
+
tokenSymbol,
|
|
19946
|
+
scopeChainId
|
|
19947
|
+
),
|
|
19948
|
+
offChain ? { days, tokenSymbol, scopeChainId, chainId: readChain } : { days, tokenSymbol, scopeChainId }
|
|
19949
|
+
),
|
|
19950
|
+
this.readAgent(
|
|
19951
|
+
agent,
|
|
19952
|
+
"balances",
|
|
19953
|
+
() => agent.getBalances(readState, readChain),
|
|
19954
|
+
offChain ? { chainId: readChain } : null
|
|
19955
|
+
).then((b) => balanceForApyScope(b, readChain, tokenSymbol))
|
|
19956
|
+
]);
|
|
19957
|
+
if (!offChain) return [id, ...await pair];
|
|
19958
|
+
return pair.then(([apy, balance]) => [id, apy, balance], (error) => {
|
|
19959
|
+
console.error(`[owney-sdk] APY fetch failed for agent "${id}" on chain ${readChain}:`, error);
|
|
19960
|
+
return null;
|
|
19961
|
+
});
|
|
19962
|
+
})
|
|
19963
|
+
);
|
|
19964
|
+
const apyResults = reads.flatMap((read2) => read2 ? [[read2[0], read2[1]]] : []);
|
|
19965
|
+
const balanceResults = reads.flatMap((read2) => read2 ? [[read2[0], read2[2]]] : []);
|
|
18966
19966
|
const results = {};
|
|
18967
19967
|
for (const [id, apy] of apyResults) {
|
|
18968
19968
|
results[id] = apy;
|
|
@@ -19013,8 +20013,57 @@ var OwneySDK = class {
|
|
|
19013
20013
|
* @returns {OwneyAgentHistory} `data` (up to `limit` entries), `hasMore`, `nextCursor`.
|
|
19014
20014
|
*/
|
|
19015
20015
|
async getHistory(options) {
|
|
20016
|
+
const { agentId, filters, chainIds } = options ?? {};
|
|
20017
|
+
if (chainIds?.length) {
|
|
20018
|
+
const state2 = this.requireState();
|
|
20019
|
+
const agents = agentId ? [this.getAgent(agentId)] : [...this.getActiveAgents().values()];
|
|
20020
|
+
const cursorMap2 = filters?.cursor ? decodeFanoutCursor(filters.cursor) : void 0;
|
|
20021
|
+
const legs = [];
|
|
20022
|
+
for (const agent of agents) {
|
|
20023
|
+
for (const legChainId of chainIds) {
|
|
20024
|
+
if (agentRunsOn(agent, legChainId))
|
|
20025
|
+
legs.push({ agentId: agent.id, chainId: legChainId, legState: state2 });
|
|
20026
|
+
}
|
|
20027
|
+
}
|
|
20028
|
+
if (!agentId) {
|
|
20029
|
+
for (const extra of this.offChainPortfolioAgents(state2)) {
|
|
20030
|
+
for (const legChainId of chainIds) {
|
|
20031
|
+
if (extra.chainIds.includes(legChainId))
|
|
20032
|
+
legs.push({ agentId: extra.agent.id, chainId: legChainId, legState: extra.state });
|
|
20033
|
+
}
|
|
20034
|
+
}
|
|
20035
|
+
}
|
|
20036
|
+
const agentErrors2 = {};
|
|
20037
|
+
let firstFailure;
|
|
20038
|
+
const pages = await Promise.all(
|
|
20039
|
+
legs.map(async (leg) => {
|
|
20040
|
+
const legCursor = cursorMap2?.[fanoutKey(leg)];
|
|
20041
|
+
if (cursorMap2 && legCursor === void 0) {
|
|
20042
|
+
return { leg, page: null };
|
|
20043
|
+
}
|
|
20044
|
+
const legFilters = { ...filters, cursor: legCursor };
|
|
20045
|
+
const agent = this.getAgent(leg.agentId);
|
|
20046
|
+
try {
|
|
20047
|
+
const page = await this.readAgent(
|
|
20048
|
+
agent,
|
|
20049
|
+
"history",
|
|
20050
|
+
() => agent.getHistory(leg.legState, leg.chainId, legFilters),
|
|
20051
|
+
// Keyed per leg for the same reason as getDailyEarnings' fan-out.
|
|
20052
|
+
{ ...legFilters, chainId: leg.chainId }
|
|
20053
|
+
);
|
|
20054
|
+
return { leg, page };
|
|
20055
|
+
} catch (error) {
|
|
20056
|
+
firstFailure ??= error;
|
|
20057
|
+
agentErrors2[leg.agentId] = error instanceof Error ? error.message : String(error);
|
|
20058
|
+
return { leg, page: null };
|
|
20059
|
+
}
|
|
20060
|
+
})
|
|
20061
|
+
);
|
|
20062
|
+
if (firstFailure !== void 0 && pages.every(({ page }) => page === null)) throw firstFailure;
|
|
20063
|
+
const merged2 = mergeHistoryPages(pages);
|
|
20064
|
+
return Object.keys(agentErrors2).length ? { ...merged2, agentErrors: agentErrors2 } : merged2;
|
|
20065
|
+
}
|
|
19016
20066
|
const { state, chainId, assertCurrent } = this.captureReadScope(options?.chainId);
|
|
19017
|
-
const { agentId, filters } = options ?? {};
|
|
19018
20067
|
if (agentId) {
|
|
19019
20068
|
const agent = this.getAgent(agentId);
|
|
19020
20069
|
const page = await this.readAgent(agent, "history", () => agent.getHistory(state, chainId, filters), filters);
|