@owney/sdk 0.7.32-beta.4 → 0.7.32-beta.6
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +23 -1
- package/dist/index.cjs +2688 -305
- package/dist/index.d.cts +907 -52
- package/dist/index.d.ts +907 -52
- package/dist/index.js +2686 -305
- package/package.json +2 -2
package/dist/index.cjs
CHANGED
|
@@ -679,6 +679,7 @@ __export(index_exports, {
|
|
|
679
679
|
saveWithdrawSwap: () => saveWithdrawSwap,
|
|
680
680
|
setOwneyDebug: () => setOwneyDebug,
|
|
681
681
|
subscribeWithdrawSwaps: () => subscribeWithdrawSwaps,
|
|
682
|
+
switchWalletConnectChain: () => switchWalletConnectChain,
|
|
682
683
|
updateWithdrawSwap: () => updateWithdrawSwap
|
|
683
684
|
});
|
|
684
685
|
module.exports = __toCommonJS(index_exports);
|
|
@@ -1123,6 +1124,35 @@ function debugLog(scope, message, data) {
|
|
|
1123
1124
|
init_errors();
|
|
1124
1125
|
var ROUTING_API_BASE_URL = "https://owney-routing-api-243946518160.europe-west4.run.app";
|
|
1125
1126
|
var getRoutingApiBaseUrl = (override) => override ?? ROUTING_API_BASE_URL;
|
|
1127
|
+
async function fetchApyIncentives(apiKey, input, baseUrl = ROUTING_API_BASE_URL) {
|
|
1128
|
+
const query2 = new URLSearchParams({
|
|
1129
|
+
walletAddress: input.walletAddress,
|
|
1130
|
+
agentId: input.agentId,
|
|
1131
|
+
chainId: String(input.chainId),
|
|
1132
|
+
asset: input.asset.toUpperCase(),
|
|
1133
|
+
from: input.from,
|
|
1134
|
+
to: input.to
|
|
1135
|
+
});
|
|
1136
|
+
try {
|
|
1137
|
+
const response = await fetch(`${baseUrl}/api/v1/apy-incentives?${query2}`, {
|
|
1138
|
+
headers: {
|
|
1139
|
+
Accept: "application/json",
|
|
1140
|
+
"x-owney-api-key": apiKey
|
|
1141
|
+
}
|
|
1142
|
+
});
|
|
1143
|
+
if (!response.ok) return [];
|
|
1144
|
+
const body = await response.json();
|
|
1145
|
+
if (!body.success || !Array.isArray(body.data)) return [];
|
|
1146
|
+
return body.data.filter(
|
|
1147
|
+
(item) => item && typeof item.date === "string" && item.source === "merkl" && typeof item.opportunityId === "string" && Array.isArray(item.campaignIds) && Number.isFinite(item.apr) && Number.isFinite(item.apyContribution)
|
|
1148
|
+
);
|
|
1149
|
+
} catch (error) {
|
|
1150
|
+
debugLog("owney-sdk", "APY incentives unavailable; using native APY", {
|
|
1151
|
+
error: error instanceof Error ? error.message : String(error)
|
|
1152
|
+
});
|
|
1153
|
+
return [];
|
|
1154
|
+
}
|
|
1155
|
+
}
|
|
1126
1156
|
async function fetchOrgAgentConfig(apiKey, baseUrl = ROUTING_API_BASE_URL) {
|
|
1127
1157
|
const url = `${baseUrl}/api/v1/agent/org-config`;
|
|
1128
1158
|
try {
|
|
@@ -1653,7 +1683,7 @@ var SnapshotHistory = class {
|
|
|
1653
1683
|
};
|
|
1654
1684
|
|
|
1655
1685
|
// src/lib/funding-ledger.ts
|
|
1656
|
-
var SDK_VERSION = "0.7.32-beta.
|
|
1686
|
+
var SDK_VERSION = "0.7.32-beta.6";
|
|
1657
1687
|
var SCOPE2 = "funding-ledger";
|
|
1658
1688
|
var REQUEST_TIMEOUT_MS2 = 5e3;
|
|
1659
1689
|
var RETRY_DELAYS_MS = [1e3, 4e3, 16e3];
|
|
@@ -1670,6 +1700,12 @@ function normalizeAppName(appName) {
|
|
|
1670
1700
|
const lower = appName.toLowerCase();
|
|
1671
1701
|
return APP_NAME_RE.test(lower) ? lower : void 0;
|
|
1672
1702
|
}
|
|
1703
|
+
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}$/;
|
|
1704
|
+
function normalizeBatchId(batchId) {
|
|
1705
|
+
if (typeof batchId !== "string") return void 0;
|
|
1706
|
+
const lower = batchId.toLowerCase();
|
|
1707
|
+
return BATCH_ID_RE.test(lower) ? lower : void 0;
|
|
1708
|
+
}
|
|
1673
1709
|
function compact(obj) {
|
|
1674
1710
|
const out = {};
|
|
1675
1711
|
for (const [key2, value] of Object.entries(obj)) {
|
|
@@ -1805,6 +1841,7 @@ function buildReporter(config) {
|
|
|
1805
1841
|
asset: input.asset.toLowerCase(),
|
|
1806
1842
|
requestedAmountRaw: input.requestedAmountRaw,
|
|
1807
1843
|
isMax: input.isMax,
|
|
1844
|
+
batchId: normalizeBatchId(input.batchId),
|
|
1808
1845
|
sdkVersion: SDK_VERSION,
|
|
1809
1846
|
app,
|
|
1810
1847
|
legs: input.legs?.map((leg) => compact({ ...leg }))
|
|
@@ -1814,9 +1851,16 @@ function buildReporter(config) {
|
|
|
1814
1851
|
debugLog(SCOPE2, `task failed: ${describeError2(err)}`);
|
|
1815
1852
|
});
|
|
1816
1853
|
};
|
|
1854
|
+
let postBody = createBody;
|
|
1817
1855
|
const create = async () => {
|
|
1818
1856
|
if (disabled) return false;
|
|
1819
|
-
|
|
1857
|
+
let res = await request2("POST", endpoint2, postBody);
|
|
1858
|
+
if (res?.status === 400 && "batchId" in postBody) {
|
|
1859
|
+
const { batchId: _dropped, ...withoutBatchId } = postBody;
|
|
1860
|
+
postBody = withoutBatchId;
|
|
1861
|
+
debugLog(SCOPE2, "create rejected with 400: retrying once without batchId");
|
|
1862
|
+
res = await request2("POST", endpoint2, postBody);
|
|
1863
|
+
}
|
|
1820
1864
|
if (!res) return false;
|
|
1821
1865
|
if (res.status === 404) {
|
|
1822
1866
|
disabled = true;
|
|
@@ -2954,7 +2998,7 @@ var CHAIN_NAMES = {
|
|
|
2954
2998
|
function chainName(chainId) {
|
|
2955
2999
|
return CHAIN_NAMES[chainId] ?? `chain ${chainId}`;
|
|
2956
3000
|
}
|
|
2957
|
-
var SETTLE_TIMEOUT_MS =
|
|
3001
|
+
var SETTLE_TIMEOUT_MS = 15e3;
|
|
2958
3002
|
var POLL_INTERVAL_MS = 200;
|
|
2959
3003
|
var wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
|
2960
3004
|
async function readChainId(pub) {
|
|
@@ -2997,6 +3041,36 @@ async function ensureWalletOnChain(pub, wallet, expected, options = {}) {
|
|
|
2997
3041
|
{ expectedChainId: expected, actualChainId: after ?? actual }
|
|
2998
3042
|
);
|
|
2999
3043
|
}
|
|
3044
|
+
function isActiveChainMismatch(error) {
|
|
3045
|
+
const message = error instanceof Error ? error.message : String(error ?? "");
|
|
3046
|
+
return /must match the active chain/i.test(message) || /does not match the target chain/i.test(message);
|
|
3047
|
+
}
|
|
3048
|
+
async function signWithChainRetry(pub, wallet, expected, sign) {
|
|
3049
|
+
try {
|
|
3050
|
+
return await sign();
|
|
3051
|
+
} catch (error) {
|
|
3052
|
+
if (!isActiveChainMismatch(error)) throw error;
|
|
3053
|
+
try {
|
|
3054
|
+
await wallet.switchChain({ id: expected });
|
|
3055
|
+
} catch {
|
|
3056
|
+
}
|
|
3057
|
+
try {
|
|
3058
|
+
return await sign();
|
|
3059
|
+
} catch (retryError) {
|
|
3060
|
+
if (!isActiveChainMismatch(retryError)) throw retryError;
|
|
3061
|
+
const actual = await readChainId(pub);
|
|
3062
|
+
throw new OwneyError(
|
|
3063
|
+
"CHAIN_MISMATCH",
|
|
3064
|
+
`Your wallet would not sign for ${chainName(expected)}. Open it, switch to ${chainName(expected)}, and try again.`,
|
|
3065
|
+
{
|
|
3066
|
+
expectedChainId: expected,
|
|
3067
|
+
...actual !== void 0 ? { actualChainId: actual } : {},
|
|
3068
|
+
cause: retryError instanceof Error ? retryError.message : String(retryError)
|
|
3069
|
+
}
|
|
3070
|
+
);
|
|
3071
|
+
}
|
|
3072
|
+
}
|
|
3073
|
+
}
|
|
3000
3074
|
|
|
3001
3075
|
// src/lib/sponsored-deposit.ts
|
|
3002
3076
|
var AUTH_WINDOW_SECONDS = 15 * 60;
|
|
@@ -3524,6 +3598,9 @@ var NAME_TO_CHAIN_ID = Object.entries(
|
|
|
3524
3598
|
acc[name.toLowerCase()] = Number(id);
|
|
3525
3599
|
return acc;
|
|
3526
3600
|
}, {});
|
|
3601
|
+
NAME_TO_CHAIN_ID.mainnet = 1;
|
|
3602
|
+
NAME_TO_CHAIN_ID["ethereum mainnet"] = 1;
|
|
3603
|
+
NAME_TO_CHAIN_ID["arbitrum one"] = 42161;
|
|
3527
3604
|
function resolveChainId(chain2) {
|
|
3528
3605
|
const asNum = Number(chain2);
|
|
3529
3606
|
if (Number.isFinite(asNum) && asNum > 0) return asNum;
|
|
@@ -3774,7 +3851,7 @@ function rawPoolApyForChain(entry, chainId, tokenSymbol) {
|
|
|
3774
3851
|
let weightedSum = 0;
|
|
3775
3852
|
let totalBalance = 0;
|
|
3776
3853
|
for (const p of entry.positions ?? []) {
|
|
3777
|
-
if (p.chainId !== chainId) continue;
|
|
3854
|
+
if (chainId !== void 0 && p.chainId !== chainId) continue;
|
|
3778
3855
|
if (tokenSymbol && p.tokenSymbol?.toUpperCase() !== tokenSymbol.toUpperCase()) continue;
|
|
3779
3856
|
const balance = p.balance ?? 0;
|
|
3780
3857
|
const apy = netApy(p.apy_withFee, p.apy, "apy_withFee");
|
|
@@ -3784,27 +3861,89 @@ function rawPoolApyForChain(entry, chainId, tokenSymbol) {
|
|
|
3784
3861
|
}
|
|
3785
3862
|
return totalBalance > 0 ? weightedSum / totalBalance : null;
|
|
3786
3863
|
}
|
|
3787
|
-
function
|
|
3788
|
-
const
|
|
3789
|
-
|
|
3790
|
-
|
|
3791
|
-
|
|
3792
|
-
|
|
3793
|
-
|
|
3794
|
-
|
|
3795
|
-
|
|
3796
|
-
|
|
3797
|
-
|
|
3798
|
-
|
|
3799
|
-
|
|
3800
|
-
|
|
3801
|
-
|
|
3802
|
-
|
|
3864
|
+
function historyCoverage(raw2) {
|
|
3865
|
+
const chains = /* @__PURE__ */ new Map();
|
|
3866
|
+
const assets = /* @__PURE__ */ new Map();
|
|
3867
|
+
const pairs = /* @__PURE__ */ new Map();
|
|
3868
|
+
for (const date of Object.keys(raw2.history ?? {}).sort()) {
|
|
3869
|
+
void date;
|
|
3870
|
+
const seenChains = /* @__PURE__ */ new Set();
|
|
3871
|
+
const seenAssets = /* @__PURE__ */ new Set();
|
|
3872
|
+
const seenPairs = /* @__PURE__ */ new Map();
|
|
3873
|
+
for (const p of (raw2.history ?? {})[date].positions ?? []) {
|
|
3874
|
+
const balance = p.balance ?? 0;
|
|
3875
|
+
const apy = netApy(p.apy_withFee, p.apy, "apy_withFee");
|
|
3876
|
+
if (balance <= 0 || typeof apy !== "number") continue;
|
|
3877
|
+
seenChains.add(p.chainId);
|
|
3878
|
+
if (p.tokenSymbol) {
|
|
3879
|
+
const asset = p.tokenSymbol.toUpperCase();
|
|
3880
|
+
seenAssets.add(asset);
|
|
3881
|
+
seenPairs.set(`${p.chainId}:${asset}`, { chainId: p.chainId, asset });
|
|
3882
|
+
}
|
|
3883
|
+
}
|
|
3884
|
+
for (const c of seenChains) chains.set(c, (chains.get(c) ?? 0) + 1);
|
|
3885
|
+
for (const a of seenAssets) assets.set(a, (assets.get(a) ?? 0) + 1);
|
|
3886
|
+
for (const [key2, pair] of seenPairs) {
|
|
3887
|
+
pairs.set(key2, { ...pair, days: (pairs.get(key2)?.days ?? 0) + 1 });
|
|
3888
|
+
}
|
|
3889
|
+
}
|
|
3890
|
+
return {
|
|
3891
|
+
chains: [...chains].map(([chainId, days]) => ({ chainId, days })),
|
|
3892
|
+
assets: [...assets].map(([asset, days]) => ({ asset, days })),
|
|
3893
|
+
pairs: [...pairs.values()]
|
|
3894
|
+
};
|
|
3895
|
+
}
|
|
3896
|
+
function isEthToken(symbol2) {
|
|
3897
|
+
const upper = symbol2?.toUpperCase();
|
|
3898
|
+
return upper === "WETH" || upper === "ETH";
|
|
3899
|
+
}
|
|
3900
|
+
function holdsEthPosition(raw2) {
|
|
3901
|
+
return Object.values(raw2.history ?? {}).some((entry) => (entry.positions ?? []).some((p) => isEthToken(p.tokenSymbol)));
|
|
3902
|
+
}
|
|
3903
|
+
function usdPerToken(symbol2, ethUsd) {
|
|
3904
|
+
if (symbol2?.toUpperCase() === "USDC") return 1;
|
|
3905
|
+
return isEthToken(symbol2) ? ethUsd : void 0;
|
|
3906
|
+
}
|
|
3907
|
+
function dollarDay(entry, chainId, ethUsd) {
|
|
3908
|
+
let weightedSum = 0;
|
|
3909
|
+
let totalUsd = 0;
|
|
3910
|
+
for (const p of entry.positions ?? []) {
|
|
3911
|
+
if (chainId !== void 0 && p.chainId !== chainId) continue;
|
|
3912
|
+
const balance = p.balance ?? 0;
|
|
3913
|
+
const apy = netApy(p.apy_withFee, p.apy, "apy_withFee");
|
|
3914
|
+
if (balance <= 0 || typeof apy !== "number") continue;
|
|
3915
|
+
const price = usdPerToken(p.tokenSymbol, ethUsd);
|
|
3916
|
+
if (price === void 0) return void 0;
|
|
3917
|
+
weightedSum += apy * balance * price;
|
|
3918
|
+
totalUsd += balance * price;
|
|
3919
|
+
}
|
|
3920
|
+
return totalUsd > 0 ? { apy: weightedSum / totalUsd, usd: totalUsd } : void 0;
|
|
3921
|
+
}
|
|
3922
|
+
function mapApyHistory(raw2, chainId, tokenSymbol, ethUsd) {
|
|
3923
|
+
const history = Object.entries(raw2.history ?? {}).map(([date, entry]) => {
|
|
3924
|
+
const dollars = tokenSymbol ? void 0 : dollarDay(entry, chainId, ethUsd);
|
|
3925
|
+
return {
|
|
3926
|
+
date,
|
|
3927
|
+
apy: dollars ? dollars.apy : rawPoolApyForChain(entry, chainId, tokenSymbol),
|
|
3928
|
+
// Provider position balances are treated as decimal amounts of the
|
|
3929
|
+
// selected token. Carry its unit dynamically for every asset; an
|
|
3930
|
+
// unscoped mix of assets is carried in dollars, or not at all.
|
|
3931
|
+
...tokenSymbol ? {
|
|
3932
|
+
historicalBalance: {
|
|
3933
|
+
amount: (entry.positions ?? []).filter(
|
|
3934
|
+
(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)
|
|
3935
|
+
).reduce((sum, p) => sum + p.balance, 0),
|
|
3936
|
+
unit: tokenSymbol.toUpperCase()
|
|
3937
|
+
}
|
|
3938
|
+
} : dollars ? { historicalBalance: { amount: dollars.usd, unit: "USD" } } : {}
|
|
3939
|
+
};
|
|
3940
|
+
}).filter((p) => p.apy !== null).sort((a, b) => a.date.localeCompare(b.date));
|
|
3803
3941
|
return {
|
|
3804
3942
|
walletAddress: raw2.walletAddress,
|
|
3805
3943
|
weightedApyAfterFee: raw2.weightedApyAfterFee ? sumTokenValues(raw2.weightedApyAfterFee) : void 0,
|
|
3806
3944
|
apyByChainAndAsset: mapWeightedApyByChain(raw2.weightedApyAfterFeeByChain),
|
|
3807
|
-
history
|
|
3945
|
+
history,
|
|
3946
|
+
coverage: historyCoverage(raw2)
|
|
3808
3947
|
};
|
|
3809
3948
|
}
|
|
3810
3949
|
function splitOpportunity(opportunity) {
|
|
@@ -3825,6 +3964,9 @@ function mapEntries(rawEntries, chainId) {
|
|
|
3825
3964
|
// "Top up wallet" and for slightly less (gas). `Deposit` already exists in
|
|
3826
3965
|
// the public HistoryAction union, so no consumer type change is needed.
|
|
3827
3966
|
"Deposit to protocol": "Deposit",
|
|
3967
|
+
// Withdrawing from an async vault (Superform) is logged under its own
|
|
3968
|
+
// label and paid out later in a separate batch (ROUT-624).
|
|
3969
|
+
"Request async withdrawal": "Withdraw",
|
|
3828
3970
|
Rebalance: "Rebalance"
|
|
3829
3971
|
};
|
|
3830
3972
|
void chainId;
|
|
@@ -3869,8 +4011,9 @@ function mapEntries(rawEntries, chainId) {
|
|
|
3869
4011
|
];
|
|
3870
4012
|
}
|
|
3871
4013
|
const mappedAction = (entry.action ? actionMap[entry.action] : void 0) ?? entry.action;
|
|
4014
|
+
const asyncRequest = entry.action === "Request async withdrawal";
|
|
3872
4015
|
const rawAmount2 = entry?.positions?.[0]?.amount;
|
|
3873
|
-
const hasAmount = mappedAction !== "Withdraw" && typeof rawAmount2 === "string" && rawAmount2 !== "" && rawAmount2 !== "0x" && rawAmount2 !== "0x0" && rawAmount2 !== "0";
|
|
4016
|
+
const hasAmount = (mappedAction !== "Withdraw" || asyncRequest) && typeof rawAmount2 === "string" && rawAmount2 !== "" && rawAmount2 !== "0x" && rawAmount2 !== "0x0" && rawAmount2 !== "0";
|
|
3874
4017
|
const rawDelta = mappedAction === "Deposit" ? decodeDeltaAmount(
|
|
3875
4018
|
entry?.positions?.[0]?.deltaAmount,
|
|
3876
4019
|
tokenDecimals(entry?.positions?.[0]?.token_symbol)
|
|
@@ -3896,6 +4039,7 @@ function mapEntries(rawEntries, chainId) {
|
|
|
3896
4039
|
newApy: newApy === null ? null : String(newApy),
|
|
3897
4040
|
oldApy: oldApy === null ? null : String(oldApy),
|
|
3898
4041
|
...mappedPositions.length ? { positions: mappedPositions } : {},
|
|
4042
|
+
...asyncRequest ? { asyncRequest: true } : {},
|
|
3899
4043
|
transactions: [
|
|
3900
4044
|
{
|
|
3901
4045
|
txHashes: entry.transactionHash ? [entry.transactionHash] : [],
|
|
@@ -4055,6 +4199,43 @@ function mapDailyEarnings(raw2, chainId, tokenSymbol) {
|
|
|
4055
4199
|
return { walletAddress: raw2.walletAddress, chainId, assets };
|
|
4056
4200
|
}
|
|
4057
4201
|
|
|
4202
|
+
// src/lib/eth-usd-price.ts
|
|
4203
|
+
var BASE_ETH_USD_FEED = "0x71041dddad3595F9CEd3DcCFBe3D1F4b0a16Bb70";
|
|
4204
|
+
var FEED_DECIMALS = 8;
|
|
4205
|
+
var PRICE_TTL_MS = 6e4;
|
|
4206
|
+
var AGGREGATOR_V3_ABI = [{
|
|
4207
|
+
type: "function",
|
|
4208
|
+
name: "latestRoundData",
|
|
4209
|
+
stateMutability: "view",
|
|
4210
|
+
inputs: [],
|
|
4211
|
+
outputs: [
|
|
4212
|
+
{ name: "roundId", type: "uint80" },
|
|
4213
|
+
{ name: "answer", type: "int256" },
|
|
4214
|
+
{ name: "startedAt", type: "uint256" },
|
|
4215
|
+
{ name: "updatedAt", type: "uint256" },
|
|
4216
|
+
{ name: "answeredInRound", type: "uint80" }
|
|
4217
|
+
]
|
|
4218
|
+
}];
|
|
4219
|
+
var prices = /* @__PURE__ */ new WeakMap();
|
|
4220
|
+
async function readEthUsdPrice(client, now = Date.now()) {
|
|
4221
|
+
const cached = prices.get(client);
|
|
4222
|
+
if (cached && now - cached.at < PRICE_TTL_MS) return cached.value;
|
|
4223
|
+
try {
|
|
4224
|
+
const [, answer] = await client.readContract({
|
|
4225
|
+
address: BASE_ETH_USD_FEED,
|
|
4226
|
+
abi: AGGREGATOR_V3_ABI,
|
|
4227
|
+
functionName: "latestRoundData"
|
|
4228
|
+
});
|
|
4229
|
+
if (answer <= 0n) return void 0;
|
|
4230
|
+
const value = Number(answer) / 10 ** FEED_DECIMALS;
|
|
4231
|
+
if (!Number.isFinite(value)) return void 0;
|
|
4232
|
+
prices.set(client, { value, at: now });
|
|
4233
|
+
return value;
|
|
4234
|
+
} catch {
|
|
4235
|
+
return void 0;
|
|
4236
|
+
}
|
|
4237
|
+
}
|
|
4238
|
+
|
|
4058
4239
|
// src/agents/zyfai/zyfai.history-cursor.ts
|
|
4059
4240
|
var InvalidHistoryCursorError = class extends Error {
|
|
4060
4241
|
code = "invalid_cursor";
|
|
@@ -4253,6 +4434,9 @@ function splittingNeedsUpdate(current, desired) {
|
|
|
4253
4434
|
}
|
|
4254
4435
|
|
|
4255
4436
|
// src/agents/zyfai/pool-policy.ts
|
|
4437
|
+
function orgPolicyForConnect(policy, userPoolCustomization) {
|
|
4438
|
+
return userPoolCustomization ? { ...policy, poolPolicy: null } : policy;
|
|
4439
|
+
}
|
|
4256
4440
|
function toZyfaiCustomizations(policy, availableByProtocol, chainsByProtocol) {
|
|
4257
4441
|
const selectionByKey = /* @__PURE__ */ new Map();
|
|
4258
4442
|
for (const selection of policy.selections) {
|
|
@@ -4344,6 +4528,54 @@ function protocolsPolicyNeedsUpdate(current, desiredProtocols, desiredAutoSelect
|
|
|
4344
4528
|
if (desiredProtocols === null) return false;
|
|
4345
4529
|
return !protocolListsEqual(current.protocols, desiredProtocols);
|
|
4346
4530
|
}
|
|
4531
|
+
function mergeScopedPoolNames(current, scoped, allAvailableNames) {
|
|
4532
|
+
const managed = new Set(scoped.flatMap((entry) => entry.availablePools));
|
|
4533
|
+
const existing = current.autoselect ? allAvailableNames : current.pools;
|
|
4534
|
+
const preserved = existing.filter((name) => !managed.has(name));
|
|
4535
|
+
const selected = scoped.flatMap((entry) => entry.pools);
|
|
4536
|
+
return [.../* @__PURE__ */ new Set([...preserved, ...selected])];
|
|
4537
|
+
}
|
|
4538
|
+
function mapAvailablePools(raw2) {
|
|
4539
|
+
const byChain = raw2 ?? {};
|
|
4540
|
+
if (typeof byChain !== "object" || byChain === null) return [];
|
|
4541
|
+
const result = [];
|
|
4542
|
+
for (const [chainIdStr, byToken] of Object.entries(byChain)) {
|
|
4543
|
+
const chainId = Number(chainIdStr);
|
|
4544
|
+
if (!Number.isFinite(chainId)) continue;
|
|
4545
|
+
for (const [token, entry] of Object.entries(byToken ?? {})) {
|
|
4546
|
+
for (const pool of entry?.pools ?? []) {
|
|
4547
|
+
if (!pool?.name) continue;
|
|
4548
|
+
result.push({
|
|
4549
|
+
chainId,
|
|
4550
|
+
token,
|
|
4551
|
+
name: pool.name,
|
|
4552
|
+
apy: pool.info?.combined_apy ?? null,
|
|
4553
|
+
tvlUsd: pool.info?.tvlUsd ?? null,
|
|
4554
|
+
link: pool.info?.link ?? null
|
|
4555
|
+
});
|
|
4556
|
+
}
|
|
4557
|
+
}
|
|
4558
|
+
}
|
|
4559
|
+
return result;
|
|
4560
|
+
}
|
|
4561
|
+
function assemblePoolCatalog(protocols, poolsByProtocol, asset, chains) {
|
|
4562
|
+
const wanted = asset.toUpperCase();
|
|
4563
|
+
const allowedChains = chains && chains.length > 0 ? new Set(chains) : void 0;
|
|
4564
|
+
const catalog = [];
|
|
4565
|
+
for (const protocol of protocols) {
|
|
4566
|
+
const pools = (poolsByProtocol.get(protocol.id) ?? []).filter(
|
|
4567
|
+
(p) => p.token.toUpperCase() === wanted && (allowedChains === void 0 || allowedChains.has(p.chainId))
|
|
4568
|
+
);
|
|
4569
|
+
if (pools.length === 0) continue;
|
|
4570
|
+
catalog.push({
|
|
4571
|
+
protocolId: protocol.id,
|
|
4572
|
+
name: protocol.name,
|
|
4573
|
+
logo: protocol.imageUrl ?? null,
|
|
4574
|
+
pools
|
|
4575
|
+
});
|
|
4576
|
+
}
|
|
4577
|
+
return catalog;
|
|
4578
|
+
}
|
|
4347
4579
|
|
|
4348
4580
|
// src/lib/agent-accounts.ts
|
|
4349
4581
|
var SCOPE5 = "agent-accounts";
|
|
@@ -4841,7 +5073,7 @@ var ZyfaiAgent = class _ZyfaiAgent {
|
|
|
4841
5073
|
*/
|
|
4842
5074
|
async resolveFundingTransfers(entries, chainId, recipient, smartWallet, tokenSymbol) {
|
|
4843
5075
|
const movements = entries.filter(
|
|
4844
|
-
(e) => (e.action === "Withdraw" || e.action === "Top up") && e.transactions[0]?.txHashes[0]
|
|
5076
|
+
(e) => (e.action === "Withdraw" && !e.asyncRequest || e.action === "Top up") && e.transactions[0]?.txHashes[0]
|
|
4845
5077
|
);
|
|
4846
5078
|
if (movements.length === 0) return;
|
|
4847
5079
|
const client = this.getPublicClient(chainId);
|
|
@@ -4912,11 +5144,12 @@ var ZyfaiAgent = class _ZyfaiAgent {
|
|
|
4912
5144
|
if (typeof window === "undefined") return;
|
|
4913
5145
|
const internals = sdk;
|
|
4914
5146
|
const original = internals.authenticateUser.bind(internals);
|
|
4915
|
-
|
|
5147
|
+
let inFlight2 = null;
|
|
5148
|
+
const authenticate = async () => {
|
|
4916
5149
|
if (internals.authenticatedUserId !== null) return;
|
|
4917
5150
|
const address = internals.walletClient?.account?.address;
|
|
4918
|
-
const chainId = internals.currentChainId;
|
|
4919
|
-
if (address
|
|
5151
|
+
const chainId = internals.currentChainId ?? 0;
|
|
5152
|
+
if (address) {
|
|
4920
5153
|
const cached = readSession(address, chainId);
|
|
4921
5154
|
if (cached) {
|
|
4922
5155
|
internals.httpClient.setAuthToken(cached.token);
|
|
@@ -4928,9 +5161,9 @@ var ZyfaiAgent = class _ZyfaiAgent {
|
|
|
4928
5161
|
}
|
|
4929
5162
|
await original();
|
|
4930
5163
|
const newAddress = internals.walletClient?.account?.address;
|
|
4931
|
-
const newChainId = internals.currentChainId;
|
|
5164
|
+
const newChainId = internals.currentChainId ?? 0;
|
|
4932
5165
|
const newToken = internals.httpClient.authToken;
|
|
4933
|
-
if (newAddress &&
|
|
5166
|
+
if (newAddress && newToken) {
|
|
4934
5167
|
writeSession(newAddress, newChainId, {
|
|
4935
5168
|
token: newToken,
|
|
4936
5169
|
userId: internals.authenticatedUserId,
|
|
@@ -4939,6 +5172,15 @@ var ZyfaiAgent = class _ZyfaiAgent {
|
|
|
4939
5172
|
});
|
|
4940
5173
|
}
|
|
4941
5174
|
};
|
|
5175
|
+
internals.authenticateUser = () => {
|
|
5176
|
+
const address = internals.walletClient?.account?.address?.toLowerCase();
|
|
5177
|
+
if (inFlight2 && inFlight2.address === address) return inFlight2.promise;
|
|
5178
|
+
const promise = authenticate().finally(() => {
|
|
5179
|
+
if (inFlight2?.promise === promise) inFlight2 = null;
|
|
5180
|
+
});
|
|
5181
|
+
inFlight2 = { address, promise };
|
|
5182
|
+
return promise;
|
|
5183
|
+
};
|
|
4942
5184
|
}
|
|
4943
5185
|
// --- Private helpers ---
|
|
4944
5186
|
getAddress() {
|
|
@@ -5072,9 +5314,22 @@ var ZyfaiAgent = class _ZyfaiAgent {
|
|
|
5072
5314
|
this.sdk.getUserDetails(asset),
|
|
5073
5315
|
this.sdk.getAvailableProtocols(chainId)
|
|
5074
5316
|
]);
|
|
5317
|
+
debugLog("zyfai:protocol-sync", `${asset}: profile before sync`, {
|
|
5318
|
+
chains: current.chains,
|
|
5319
|
+
protocols: current.protocols,
|
|
5320
|
+
strategy: current.strategy
|
|
5321
|
+
});
|
|
5322
|
+
if ((current.chains?.length ?? 0) === 0 && (current.protocols?.length ?? 0) === 0) {
|
|
5323
|
+
debugLog(
|
|
5324
|
+
"zyfai:protocol-sync",
|
|
5325
|
+
`${asset}: skipping untouched profile until first deposit`
|
|
5326
|
+
);
|
|
5327
|
+
return;
|
|
5328
|
+
}
|
|
5075
5329
|
const update = buildProtocolMergeUpdate(available, current, asset);
|
|
5076
5330
|
if (!update) return;
|
|
5077
5331
|
await this.sdk.updateUserProfile(update);
|
|
5332
|
+
debugLog("zyfai:protocol-sync", `${asset}: wrote profile update`, update);
|
|
5078
5333
|
} catch (error) {
|
|
5079
5334
|
console.warn(
|
|
5080
5335
|
"[zyfai] ensureProtocolsSynced failed (non-fatal):",
|
|
@@ -5083,10 +5338,28 @@ var ZyfaiAgent = class _ZyfaiAgent {
|
|
|
5083
5338
|
}
|
|
5084
5339
|
}
|
|
5085
5340
|
/** Connect + resolve smart wallet address for read operations. */
|
|
5341
|
+
/**
|
|
5342
|
+
* Sign-in for reads: any live session of this owner will do. Zyfai's session
|
|
5343
|
+
* is per user and its data calls name the chain themselves, so reading
|
|
5344
|
+
* Arbitrum while signed in on Base needs no new sign-in. `connectAuth` pins
|
|
5345
|
+
* the chain, and reconnecting per chain made the whole-portfolio reads (one
|
|
5346
|
+
* per chain, in parallel) cancel each other's sign-in. Funding keeps
|
|
5347
|
+
* `connectAuth`/`ensureConnected`. Returns the owner verified for this call,
|
|
5348
|
+
* so a later reconnect cannot leave the caller without an address.
|
|
5349
|
+
*/
|
|
5350
|
+
async ensureReadSession(state, chainId) {
|
|
5351
|
+
const owner = state.walletAddress?.toLowerCase();
|
|
5352
|
+
if (this.connectAuthPromise) await this.connectAuthPromise.catch(() => void 0);
|
|
5353
|
+
if (!owner || this.connectedAddress?.toLowerCase() !== owner) await this.connectAuth(state, chainId);
|
|
5354
|
+
}
|
|
5355
|
+
/** `ensureReadSession`, then the owner it verified, read in the same turn. */
|
|
5356
|
+
async connectForRead(state, chainId) {
|
|
5357
|
+
await this.ensureReadSession(state, chainId);
|
|
5358
|
+
return this.getAddress();
|
|
5359
|
+
}
|
|
5086
5360
|
async resolveSmartWallet(state, chainId) {
|
|
5087
|
-
await this.connectAuth(state, chainId);
|
|
5088
5361
|
const validChainId = isValidChainId(chainId);
|
|
5089
|
-
const ownerAddress = this.
|
|
5362
|
+
const ownerAddress = await this.connectForRead(state, validChainId);
|
|
5090
5363
|
const smartWallet = await this.readSmartWallet(ownerAddress, validChainId);
|
|
5091
5364
|
return { smartWallet, chainId: validChainId };
|
|
5092
5365
|
}
|
|
@@ -5140,8 +5413,16 @@ var ZyfaiAgent = class _ZyfaiAgent {
|
|
|
5140
5413
|
}
|
|
5141
5414
|
// --- IAgent: Account lifecycle ---
|
|
5142
5415
|
async activateAgent(state, chainId) {
|
|
5416
|
+
const startedAt = Date.now();
|
|
5143
5417
|
try {
|
|
5418
|
+
debugLog("zyfai:activation", "starting", {
|
|
5419
|
+
walletAddress: state.walletAddress,
|
|
5420
|
+
chainId
|
|
5421
|
+
});
|
|
5144
5422
|
await this.connectAuth(state, chainId);
|
|
5423
|
+
debugLog("zyfai:activation", "signed in", {
|
|
5424
|
+
ms: Date.now() - startedAt
|
|
5425
|
+
});
|
|
5145
5426
|
const validChainId = isValidChainId(chainId);
|
|
5146
5427
|
await Promise.all([
|
|
5147
5428
|
this.ensureProtocolsSynced(validChainId, "USDC"),
|
|
@@ -5152,6 +5433,10 @@ var ZyfaiAgent = class _ZyfaiAgent {
|
|
|
5152
5433
|
// validator, so pool-wallet users see no prompt. Non-fatal.
|
|
5153
5434
|
this.ensureSessionKeyIfDeployed(validChainId)
|
|
5154
5435
|
]);
|
|
5436
|
+
debugLog("zyfai:activation", "completed", {
|
|
5437
|
+
chainId: validChainId,
|
|
5438
|
+
ms: Date.now() - startedAt
|
|
5439
|
+
});
|
|
5155
5440
|
} catch (error) {
|
|
5156
5441
|
throw error;
|
|
5157
5442
|
}
|
|
@@ -5232,8 +5517,9 @@ var ZyfaiAgent = class _ZyfaiAgent {
|
|
|
5232
5517
|
* connecting, so a Zyfai hiccup must leave the user connected with their
|
|
5233
5518
|
* profile unchanged, never fail activation.
|
|
5234
5519
|
*/
|
|
5235
|
-
async applyPoolPolicy(policy) {
|
|
5520
|
+
async applyPoolPolicy(policy, opts = {}) {
|
|
5236
5521
|
try {
|
|
5522
|
+
await this.sdk.ensureFirstDepositSetup("aggressive");
|
|
5237
5523
|
const { protocols: universe } = await this.sdk.getAvailableProtocols(
|
|
5238
5524
|
this.supportedChainIds[0]
|
|
5239
5525
|
);
|
|
@@ -5246,7 +5532,7 @@ var ZyfaiAgent = class _ZyfaiAgent {
|
|
|
5246
5532
|
universeIds,
|
|
5247
5533
|
chainsByProtocol
|
|
5248
5534
|
});
|
|
5249
|
-
let strategy;
|
|
5535
|
+
let strategy = opts.strategy;
|
|
5250
5536
|
const desiredProtocols = deriveProtocols(
|
|
5251
5537
|
policy,
|
|
5252
5538
|
universeIds,
|
|
@@ -5326,6 +5612,143 @@ var ZyfaiAgent = class _ZyfaiAgent {
|
|
|
5326
5612
|
);
|
|
5327
5613
|
}
|
|
5328
5614
|
}
|
|
5615
|
+
/**
|
|
5616
|
+
* The deposit-time Pools step's catalogue: every protocol Zyfai offers this
|
|
5617
|
+
* user, each with the pools (name, APY, TVL, link) selectable for `asset`
|
|
5618
|
+
* under `strategy`. Sourced from the same two Zyfai calls `applyPoolPolicy`
|
|
5619
|
+
* uses, so "shown" and "selectable" are one set. A protocol whose pool
|
|
5620
|
+
* lookup fails is skipped rather than failing the whole catalogue.
|
|
5621
|
+
*/
|
|
5622
|
+
async getPoolCatalog(params) {
|
|
5623
|
+
const { protocols: universe } = await this.sdk.getAvailableProtocols(
|
|
5624
|
+
this.supportedChainIds[0]
|
|
5625
|
+
);
|
|
5626
|
+
const poolResults = await Promise.all(
|
|
5627
|
+
universe.map(async (protocol) => {
|
|
5628
|
+
try {
|
|
5629
|
+
const raw2 = await this.sdk.getAvailablePools(
|
|
5630
|
+
protocol.id,
|
|
5631
|
+
params.strategy
|
|
5632
|
+
);
|
|
5633
|
+
return [protocol.id, mapAvailablePools(raw2)];
|
|
5634
|
+
} catch (error) {
|
|
5635
|
+
console.warn(
|
|
5636
|
+
`[zyfai] getPoolCatalog: getAvailablePools(${protocol.id}) failed, skipping (non-fatal):`,
|
|
5637
|
+
error instanceof Error ? error.message : String(error)
|
|
5638
|
+
);
|
|
5639
|
+
return null;
|
|
5640
|
+
}
|
|
5641
|
+
})
|
|
5642
|
+
);
|
|
5643
|
+
const poolsByProtocol = /* @__PURE__ */ new Map();
|
|
5644
|
+
for (const result of poolResults) {
|
|
5645
|
+
if (result) poolsByProtocol.set(result[0], result[1]);
|
|
5646
|
+
}
|
|
5647
|
+
return assemblePoolCatalog(universe, poolsByProtocol, params.asset);
|
|
5648
|
+
}
|
|
5649
|
+
/**
|
|
5650
|
+
* Persist an explicitly saved deposit-time draft at Zyfai profile level.
|
|
5651
|
+
* Pool choices are merged into protocol/chain records and each active asset
|
|
5652
|
+
* is kept at aggressive unless the draft includes a yieldmaxxing-only pool.
|
|
5653
|
+
* The whole operation must succeed before the caller starts moving funds.
|
|
5654
|
+
*/
|
|
5655
|
+
async setPoolSelection(selection) {
|
|
5656
|
+
try {
|
|
5657
|
+
await this.sdk.ensureFirstDepositSetup("aggressive");
|
|
5658
|
+
const byPair = /* @__PURE__ */ new Map();
|
|
5659
|
+
for (const entry of selection.selections) {
|
|
5660
|
+
const pair = `${entry.protocolId}:${entry.chainId}`;
|
|
5661
|
+
const group = byPair.get(pair) ?? [];
|
|
5662
|
+
group.push(entry);
|
|
5663
|
+
byPair.set(pair, group);
|
|
5664
|
+
}
|
|
5665
|
+
const customizations = await Promise.all(
|
|
5666
|
+
[...byPair.values()].map(async (scoped) => {
|
|
5667
|
+
const { protocolId, chainId } = scoped[0];
|
|
5668
|
+
const [current, rawAvailable] = await Promise.all([
|
|
5669
|
+
this.sdk.getSelectedPools(protocolId, chainId),
|
|
5670
|
+
this.sdk.getAvailablePools(protocolId, "yieldmaxxing")
|
|
5671
|
+
]);
|
|
5672
|
+
const allAvailableNames = mapAvailablePools(rawAvailable).filter((pool) => pool.chainId === chainId).map((pool) => pool.name);
|
|
5673
|
+
return {
|
|
5674
|
+
protocolId,
|
|
5675
|
+
chainId,
|
|
5676
|
+
pools: mergeScopedPoolNames(
|
|
5677
|
+
{
|
|
5678
|
+
pools: current.pools ?? [],
|
|
5679
|
+
autoselect: current.autoselect
|
|
5680
|
+
},
|
|
5681
|
+
scoped,
|
|
5682
|
+
allAvailableNames
|
|
5683
|
+
),
|
|
5684
|
+
// An explicit Save freezes exactly the choices the user saw.
|
|
5685
|
+
// This also lets an empty list disable the pair deliberately.
|
|
5686
|
+
autoselect: false
|
|
5687
|
+
};
|
|
5688
|
+
})
|
|
5689
|
+
);
|
|
5690
|
+
if (customizations.length > 0) {
|
|
5691
|
+
await this.sdk.customizeBatch(customizations);
|
|
5692
|
+
}
|
|
5693
|
+
await Promise.all(
|
|
5694
|
+
selection.strategies.map(async ({ asset, strategy }) => {
|
|
5695
|
+
const current = await this.sdk.getUserDetails(asset);
|
|
5696
|
+
const selectedProtocols = selection.selections.filter(
|
|
5697
|
+
(entry) => entry.asset === asset && entry.pools.length > 0
|
|
5698
|
+
).map((entry) => entry.protocolId);
|
|
5699
|
+
const protocols = [
|
|
5700
|
+
.../* @__PURE__ */ new Set([...current.protocols ?? [], ...selectedProtocols])
|
|
5701
|
+
];
|
|
5702
|
+
await this.sdk.updateUserProfile({ asset, strategy, protocols });
|
|
5703
|
+
})
|
|
5704
|
+
);
|
|
5705
|
+
} catch (error) {
|
|
5706
|
+
console.warn(
|
|
5707
|
+
"[zyfai] setPoolSelection failed:",
|
|
5708
|
+
error instanceof Error ? error.message : String(error)
|
|
5709
|
+
);
|
|
5710
|
+
throw error;
|
|
5711
|
+
}
|
|
5712
|
+
}
|
|
5713
|
+
/**
|
|
5714
|
+
* Read back what `setPoolSelection` wrote (ROUT-650). Zyfai keeps the saved
|
|
5715
|
+
* pools per protocol/chain and the strategy per asset; both are read for the
|
|
5716
|
+
* pairs and assets asked about. A pair still on autoselect, or one whose
|
|
5717
|
+
* lookup fails, is left out so the caller falls back to its default for it.
|
|
5718
|
+
*/
|
|
5719
|
+
async getPoolSelection(state, chainId, params) {
|
|
5720
|
+
await this.connectAuth(state, chainId);
|
|
5721
|
+
const [pairs, strategies] = await Promise.all([
|
|
5722
|
+
Promise.all(
|
|
5723
|
+
params.pairs.map(async ({ protocolId, chainId: chainId2 }) => {
|
|
5724
|
+
try {
|
|
5725
|
+
const current = await this.sdk.getSelectedPools(
|
|
5726
|
+
protocolId,
|
|
5727
|
+
chainId2
|
|
5728
|
+
);
|
|
5729
|
+
if (current.autoselect) return null;
|
|
5730
|
+
return { protocolId, chainId: chainId2, pools: current.pools ?? [] };
|
|
5731
|
+
} catch {
|
|
5732
|
+
return null;
|
|
5733
|
+
}
|
|
5734
|
+
})
|
|
5735
|
+
),
|
|
5736
|
+
Promise.all(
|
|
5737
|
+
params.assets.map(async (asset) => {
|
|
5738
|
+
try {
|
|
5739
|
+
const current = await this.sdk.getUserDetails(asset);
|
|
5740
|
+
return current.strategy ? { asset, strategy: current.strategy } : null;
|
|
5741
|
+
} catch {
|
|
5742
|
+
return null;
|
|
5743
|
+
}
|
|
5744
|
+
})
|
|
5745
|
+
)
|
|
5746
|
+
]);
|
|
5747
|
+
return {
|
|
5748
|
+
pairs: pairs.filter((value) => value !== null),
|
|
5749
|
+
strategies: strategies.filter((value) => value !== null)
|
|
5750
|
+
};
|
|
5751
|
+
}
|
|
5329
5752
|
/**
|
|
5330
5753
|
* True when `smartWallet` is the backend-managed pool wallet Zyfai assigned
|
|
5331
5754
|
* to this EOA — the "new wallet" kind that is predeployed on the chains it
|
|
@@ -5482,11 +5905,7 @@ var ZyfaiAgent = class _ZyfaiAgent {
|
|
|
5482
5905
|
);
|
|
5483
5906
|
return;
|
|
5484
5907
|
}
|
|
5485
|
-
await this.ensureSessionKey(
|
|
5486
|
-
ownerAddress,
|
|
5487
|
-
chainId,
|
|
5488
|
-
wallet.address
|
|
5489
|
-
);
|
|
5908
|
+
await this.ensureSessionKey(ownerAddress, chainId, wallet.address);
|
|
5490
5909
|
} catch (error) {
|
|
5491
5910
|
console.warn(
|
|
5492
5911
|
"[zyfai] session-key check at activation failed (non-fatal):",
|
|
@@ -5597,11 +6016,7 @@ var ZyfaiAgent = class _ZyfaiAgent {
|
|
|
5597
6016
|
"zyfai:onboard",
|
|
5598
6017
|
"Safe already has code -> no deploy needed, checking the session key"
|
|
5599
6018
|
);
|
|
5600
|
-
await this.ensureSessionKey(
|
|
5601
|
-
ownerAddress,
|
|
5602
|
-
chainId,
|
|
5603
|
-
wallet.address
|
|
5604
|
-
);
|
|
6019
|
+
await this.ensureSessionKey(ownerAddress, chainId, wallet.address);
|
|
5605
6020
|
return wallet.address;
|
|
5606
6021
|
}
|
|
5607
6022
|
const poolFirst = await this.isPredeployedPoolWallet(
|
|
@@ -5667,6 +6082,25 @@ var ZyfaiAgent = class _ZyfaiAgent {
|
|
|
5667
6082
|
throw new OwneyError("NOT_CONNECTED", "Wallet changed while preparing Zyfai deposit.", void 0, this.id);
|
|
5668
6083
|
};
|
|
5669
6084
|
assertCurrent();
|
|
6085
|
+
const setupResult = await executionSdk.ensureFirstDepositSetup("aggressive");
|
|
6086
|
+
debugLog("zyfai:first-deposit", "setup call completed", { asset, chainId: validChainId, requestedStrategy: "aggressive", setupResult });
|
|
6087
|
+
if (isOwneyDebug()) {
|
|
6088
|
+
try {
|
|
6089
|
+
const profile = await executionSdk.getUserDetails(asset === "WETH" ? "WETH" : "USDC");
|
|
6090
|
+
debugLog(
|
|
6091
|
+
"zyfai:first-deposit",
|
|
6092
|
+
"profile immediately after setup",
|
|
6093
|
+
{ asset, strategy: profile.strategy, chains: profile.chains, protocols: profile.protocols }
|
|
6094
|
+
);
|
|
6095
|
+
} catch (debugError) {
|
|
6096
|
+
debugLog(
|
|
6097
|
+
"zyfai:first-deposit",
|
|
6098
|
+
"post-setup profile read failed",
|
|
6099
|
+
{ error: debugError instanceof Error ? debugError.message : String(debugError) }
|
|
6100
|
+
);
|
|
6101
|
+
}
|
|
6102
|
+
}
|
|
6103
|
+
assertCurrent();
|
|
5670
6104
|
const smartWallet = await this.ensureWalletDeployed(owner, validChainId);
|
|
5671
6105
|
assertCurrent();
|
|
5672
6106
|
let server;
|
|
@@ -6698,6 +7132,7 @@ var ZyfaiAgent = class _ZyfaiAgent {
|
|
|
6698
7132
|
const generation = this.earningsGeneration;
|
|
6699
7133
|
const { smartWallet, chainId: validChainId } = await this.resolveSmartWallet(state, chainId);
|
|
6700
7134
|
const raw2 = await this.sdk.getPortfolio(this.getAddress());
|
|
7135
|
+
debugLog("zyfai:balances", "read", { ms: Date.now() - requestedAt });
|
|
6701
7136
|
const balance = mapBalances(raw2, validChainId, smartWallet);
|
|
6702
7137
|
const reads = balance.readMetadata?.map((read2) => ({ ...read2, requestedAt })) ?? [];
|
|
6703
7138
|
for (const asset of SupportedAssets.filter((item) => item.chainId === chainId)) {
|
|
@@ -6894,7 +7329,7 @@ var ZyfaiAgent = class _ZyfaiAgent {
|
|
|
6894
7329
|
}
|
|
6895
7330
|
async refreshEarnings(state, chainId) {
|
|
6896
7331
|
const generation = this.earningsGeneration;
|
|
6897
|
-
await this.
|
|
7332
|
+
await this.ensureReadSession(state, chainId);
|
|
6898
7333
|
const executionSdk = this.sdk;
|
|
6899
7334
|
const connectionGeneration = this.connectionGeneration;
|
|
6900
7335
|
const assertCurrent = () => {
|
|
@@ -6936,14 +7371,18 @@ var ZyfaiAgent = class _ZyfaiAgent {
|
|
|
6936
7371
|
this.earningsRefreshes.set(key2, pending2);
|
|
6937
7372
|
return pending2;
|
|
6938
7373
|
}
|
|
6939
|
-
async getAccountApy(state, chainId, days, tokenSymbol) {
|
|
7374
|
+
async getAccountApy(state, chainId, days, tokenSymbol, scopeChainId) {
|
|
6940
7375
|
const { smartWallet } = await this.resolveSmartWallet(state, chainId);
|
|
6941
7376
|
const raw2 = await this.sdk.getDailyApyHistory(smartWallet, days);
|
|
6942
|
-
|
|
7377
|
+
const scope = scopeChainId === null ? void 0 : scopeChainId ?? chainId;
|
|
7378
|
+
const ethUsd = tokenSymbol === void 0 && holdsEthPosition(raw2) ? await readEthUsdPrice(this.getPublicClient(8453)) : void 0;
|
|
7379
|
+
return mapApyHistory(raw2, scope, tokenSymbol, ethUsd);
|
|
6943
7380
|
}
|
|
6944
7381
|
async getDailyEarnings(state, chainId, days, tokenSymbol) {
|
|
6945
7382
|
const { smartWallet } = await this.resolveSmartWallet(state, chainId);
|
|
6946
|
-
const start = new Date(
|
|
7383
|
+
const start = new Date(
|
|
7384
|
+
Date.now() - (DayFilterMapping[days] + 1) * 864e5
|
|
7385
|
+
);
|
|
6947
7386
|
const raw2 = await this.sdk.getDailyEarnings(
|
|
6948
7387
|
smartWallet,
|
|
6949
7388
|
start.toISOString().slice(0, 10)
|
|
@@ -7036,7 +7475,7 @@ var ZyfaiAgent = class _ZyfaiAgent {
|
|
|
7036
7475
|
};
|
|
7037
7476
|
}
|
|
7038
7477
|
async getUserProfile(state, chainId) {
|
|
7039
|
-
await this.
|
|
7478
|
+
await this.ensureReadSession(state, chainId);
|
|
7040
7479
|
const raw2 = await this.sdk.getUserDetails();
|
|
7041
7480
|
debugLog("zyfai:profile", "getUserProfile \u2014 Zyfai reports", {
|
|
7042
7481
|
asset: "USDC (default \u2014 no asset passed)",
|
|
@@ -7053,6 +7492,19 @@ var ZyfaiAgent = class _ZyfaiAgent {
|
|
|
7053
7492
|
async ensureAutoSelectProtocols(state, chainId, asset) {
|
|
7054
7493
|
await this.connectAuth(state, chainId);
|
|
7055
7494
|
const current = await this.sdk.getUserDetails(asset);
|
|
7495
|
+
debugLog("zyfai:auto-select", `${asset}: profile before check`, {
|
|
7496
|
+
autoSelectProtocols: current.autoSelectProtocols,
|
|
7497
|
+
chains: current.chains,
|
|
7498
|
+
protocols: current.protocols,
|
|
7499
|
+
strategy: current.strategy
|
|
7500
|
+
});
|
|
7501
|
+
if ((current.chains?.length ?? 0) === 0) {
|
|
7502
|
+
debugLog(
|
|
7503
|
+
"zyfai:auto-select",
|
|
7504
|
+
`${asset}: skipping untouched profile until first deposit`
|
|
7505
|
+
);
|
|
7506
|
+
return false;
|
|
7507
|
+
}
|
|
7056
7508
|
const update = buildAutoSelectUpdate(
|
|
7057
7509
|
{
|
|
7058
7510
|
autoSelectProtocols: current.autoSelectProtocols,
|
|
@@ -7063,6 +7515,7 @@ var ZyfaiAgent = class _ZyfaiAgent {
|
|
|
7063
7515
|
);
|
|
7064
7516
|
if (!update) return false;
|
|
7065
7517
|
await this.sdk.updateUserProfile(update);
|
|
7518
|
+
debugLog("zyfai:auto-select", `${asset}: wrote profile update`, update);
|
|
7066
7519
|
return true;
|
|
7067
7520
|
}
|
|
7068
7521
|
// --- IAgent: Discovery (no wallet required) ---
|
|
@@ -7083,6 +7536,27 @@ var import_viem17 = require("viem");
|
|
|
7083
7536
|
var import_chains4 = require("viem/chains");
|
|
7084
7537
|
init_errors();
|
|
7085
7538
|
|
|
7539
|
+
// src/lib/wallet-rejection.ts
|
|
7540
|
+
var REJECTION_MESSAGE = /user (?:rejected|denied)|rejected by user|request rejected/i;
|
|
7541
|
+
function isWalletRejection(error) {
|
|
7542
|
+
let current = error;
|
|
7543
|
+
const seen = /* @__PURE__ */ new Set();
|
|
7544
|
+
while (current && typeof current === "object" && !seen.has(current)) {
|
|
7545
|
+
seen.add(current);
|
|
7546
|
+
const candidate = current;
|
|
7547
|
+
if (candidate.code === 4001 || candidate.code === "4001" || candidate.code === "ACTION_REJECTED") return true;
|
|
7548
|
+
const message = [candidate.message, candidate.shortMessage].filter((value) => typeof value === "string").join(" ");
|
|
7549
|
+
if (REJECTION_MESSAGE.test(message)) return true;
|
|
7550
|
+
const details = candidate.details;
|
|
7551
|
+
if (details && typeof details === "object") {
|
|
7552
|
+
const cause = details.cause;
|
|
7553
|
+
if (typeof cause === "string" && REJECTION_MESSAGE.test(cause)) return true;
|
|
7554
|
+
}
|
|
7555
|
+
current = candidate.cause;
|
|
7556
|
+
}
|
|
7557
|
+
return false;
|
|
7558
|
+
}
|
|
7559
|
+
|
|
7086
7560
|
// src/agents/yieldseeker/yieldseeker.auth.ts
|
|
7087
7561
|
var import_siwe = require("siwe");
|
|
7088
7562
|
var import_viem11 = require("viem");
|
|
@@ -7281,6 +7755,14 @@ var YieldseekerAuth = class {
|
|
|
7281
7755
|
}
|
|
7282
7756
|
return this.getToken(state, chainId);
|
|
7283
7757
|
}
|
|
7758
|
+
/** Drop a proof the provider refused, without signing a new one: a
|
|
7759
|
+
* promptless read cannot renew it, and must stop offering it. */
|
|
7760
|
+
discardToken(state, chainId, rejectedToken) {
|
|
7761
|
+
const key2 = this.key(state, chainId);
|
|
7762
|
+
if (this.tokens.get(key2) === rejectedToken) this.tokens.delete(key2);
|
|
7763
|
+
if (readYieldseekerSession(state.walletAddress, chainId) === rejectedToken)
|
|
7764
|
+
clearYieldseekerSession(state.walletAddress, chainId);
|
|
7765
|
+
}
|
|
7284
7766
|
isReusable(token, state, chainId) {
|
|
7285
7767
|
try {
|
|
7286
7768
|
const message = new import_siwe.SiweMessage(JSON.parse(atob(token)).message);
|
|
@@ -7737,18 +8219,19 @@ function dailyApy(point) {
|
|
|
7737
8219
|
if (principal <= 0n || earned === 0n) return 0;
|
|
7738
8220
|
return Number(earned) / Number(principal) * 365 * 100;
|
|
7739
8221
|
}
|
|
7740
|
-
function aggregateHistory(contexts, dayCount, now) {
|
|
8222
|
+
function aggregateHistory(contexts, dayCount, now, scopedAsset) {
|
|
7741
8223
|
const today = new Date(now).toISOString().slice(0, 10);
|
|
7742
8224
|
const cutoff = new Date(Date.parse(today) - (dayCount - 1) * 864e5).toISOString().slice(0, 10);
|
|
7743
8225
|
const assets = new Set(contexts.map((context) => context.asset.toUpperCase()));
|
|
7744
|
-
const
|
|
8226
|
+
const tokenUnits = scopedAsset !== void 0 && assets.size <= 1;
|
|
8227
|
+
const unit = tokenUnits ? scopedAsset.toUpperCase() : "USD";
|
|
7745
8228
|
const byDate = /* @__PURE__ */ new Map();
|
|
7746
8229
|
for (const context of contexts) {
|
|
7747
8230
|
const points = context.historic?.dailyYieldSnapshots ?? [];
|
|
7748
8231
|
for (const point of points) {
|
|
7749
8232
|
if (!/^\d{4}-\d{2}-\d{2}$/.test(point.date) || !Number.isFinite(Date.parse(point.date)) || point.date < cutoff || point.date > today) continue;
|
|
7750
8233
|
const tokens = Number(decimal(point.totalValueBase, point.baseAssetDecimals, "historic position"));
|
|
7751
|
-
const amount =
|
|
8234
|
+
const amount = tokenUnits ? tokens : tokens * point.baseAssetPriceUsd;
|
|
7752
8235
|
if (!Number.isFinite(amount) || amount < 0) {
|
|
7753
8236
|
invalid("historic position", "expected a finite non-negative balance");
|
|
7754
8237
|
}
|
|
@@ -7764,7 +8247,30 @@ function aggregateHistory(contexts, dayCount, now) {
|
|
|
7764
8247
|
historicalBalance: { amount: value.amount, unit }
|
|
7765
8248
|
}));
|
|
7766
8249
|
}
|
|
7767
|
-
function
|
|
8250
|
+
function historyCoverage2(contexts, dayCount, now) {
|
|
8251
|
+
const today = new Date(now).toISOString().slice(0, 10);
|
|
8252
|
+
const cutoff = new Date(Date.parse(today) - (dayCount - 1) * 864e5).toISOString().slice(0, 10);
|
|
8253
|
+
const datesByAsset = /* @__PURE__ */ new Map();
|
|
8254
|
+
const allDates = /* @__PURE__ */ new Set();
|
|
8255
|
+
for (const context of contexts) {
|
|
8256
|
+
for (const point of context.historic?.dailyYieldSnapshots ?? []) {
|
|
8257
|
+
if (!/^\d{4}-\d{2}-\d{2}$/.test(point.date) || point.date < cutoff || point.date > today) continue;
|
|
8258
|
+
if (!(Number(decimal(point.totalValueBase, point.baseAssetDecimals, "historic position")) > 0)) continue;
|
|
8259
|
+
const asset = context.asset.toUpperCase();
|
|
8260
|
+
const dates = datesByAsset.get(asset) ?? /* @__PURE__ */ new Set();
|
|
8261
|
+
dates.add(point.date);
|
|
8262
|
+
datesByAsset.set(asset, dates);
|
|
8263
|
+
allDates.add(point.date);
|
|
8264
|
+
}
|
|
8265
|
+
}
|
|
8266
|
+
const assets = [...datesByAsset].map(([asset, dates]) => ({ asset, days: dates.size }));
|
|
8267
|
+
return {
|
|
8268
|
+
chains: allDates.size ? [{ chainId: 8453, days: allDates.size }] : [],
|
|
8269
|
+
assets,
|
|
8270
|
+
pairs: assets.map((entry) => ({ chainId: 8453, ...entry }))
|
|
8271
|
+
};
|
|
8272
|
+
}
|
|
8273
|
+
function mapYieldseekerApy(walletAddress, contexts, days, now = Date.now(), scopedAsset) {
|
|
7768
8274
|
let weighted = 0;
|
|
7769
8275
|
let totalUsd = 0;
|
|
7770
8276
|
const byAsset = {};
|
|
@@ -7785,7 +8291,8 @@ function mapYieldseekerApy(walletAddress, contexts, days, now = Date.now()) {
|
|
|
7785
8291
|
walletAddress,
|
|
7786
8292
|
...days !== "14D" || Object.keys(byAsset).length > 0 ? { weightedApyAfterFee: totalUsd > 0 ? weighted / totalUsd : 0 } : {},
|
|
7787
8293
|
apyByChainAndAsset: { 8453: byAsset },
|
|
7788
|
-
history: aggregateHistory(contexts, dayCount, now)
|
|
8294
|
+
history: aggregateHistory(contexts, dayCount, now, scopedAsset),
|
|
8295
|
+
coverage: historyCoverage2(contexts, dayCount, now)
|
|
7789
8296
|
};
|
|
7790
8297
|
}
|
|
7791
8298
|
function actionType(value) {
|
|
@@ -8092,11 +8599,13 @@ function mapYieldseekerProfile(address, contexts) {
|
|
|
8092
8599
|
protocols: [...protocols]
|
|
8093
8600
|
};
|
|
8094
8601
|
}
|
|
8095
|
-
function mapYieldseekerAgentApy(stats) {
|
|
8602
|
+
function mapYieldseekerAgentApy(stats, days) {
|
|
8096
8603
|
const perAsset = {};
|
|
8097
8604
|
const all = [];
|
|
8098
8605
|
for (const entry of stats) {
|
|
8099
|
-
const expected = percent(
|
|
8606
|
+
const expected = percent(
|
|
8607
|
+
days === "30D" ? entry.stats.expectedApy30d : entry.stats.expectedApy7d
|
|
8608
|
+
);
|
|
8100
8609
|
if (!Number.isFinite(expected)) continue;
|
|
8101
8610
|
perAsset[entry.asset] = expected;
|
|
8102
8611
|
all.push(expected);
|
|
@@ -8267,6 +8776,15 @@ function sponsorError(message, safeToFallback, details = {}) {
|
|
|
8267
8776
|
"yieldseeker"
|
|
8268
8777
|
);
|
|
8269
8778
|
}
|
|
8779
|
+
function cannotSignRawHash(error) {
|
|
8780
|
+
for (let current = error, depth = 0; current && depth < 5; depth++) {
|
|
8781
|
+
const code = current.code;
|
|
8782
|
+
if (code === -32602 || code === -32601 || code === 4200) return true;
|
|
8783
|
+
if (code === 4001) return false;
|
|
8784
|
+
current = current.cause;
|
|
8785
|
+
}
|
|
8786
|
+
return false;
|
|
8787
|
+
}
|
|
8270
8788
|
function assertIntentFresh(expiresAt) {
|
|
8271
8789
|
if (!Number.isFinite(expiresAt) || Date.now() + 5e3 >= expiresAt * 1e3)
|
|
8272
8790
|
throw sponsorError(
|
|
@@ -8628,7 +9146,18 @@ async function submitEoa(input) {
|
|
|
8628
9146
|
transport: (0, import_viem15.custom)(input.state.provider)
|
|
8629
9147
|
});
|
|
8630
9148
|
input.assertCurrent?.();
|
|
8631
|
-
|
|
9149
|
+
let signature;
|
|
9150
|
+
try {
|
|
9151
|
+
signature = await wallet.signMessage({ message: { raw: userOpHash } });
|
|
9152
|
+
} catch (error) {
|
|
9153
|
+
if (cannotSignRawHash(error))
|
|
9154
|
+
throw sponsorError(
|
|
9155
|
+
"This wallet cannot sign the gas-free withdrawal.",
|
|
9156
|
+
true,
|
|
9157
|
+
{ failureCode: "OWNER_SIGNATURE_UNSUPPORTED" }
|
|
9158
|
+
);
|
|
9159
|
+
throw error;
|
|
9160
|
+
}
|
|
8632
9161
|
operation = { ...operation, signature };
|
|
8633
9162
|
await assertOwnerSession(input.state, input.owner);
|
|
8634
9163
|
assertIntentFresh(input.expiresAt);
|
|
@@ -8900,11 +9429,47 @@ var YIELDSEEKER_USERNAME_RANDOM_LENGTH = 14;
|
|
|
8900
9429
|
var YIELDSEEKER_USERNAME_CREATE_ATTEMPTS = 3;
|
|
8901
9430
|
var YIELDSEEKER_VAULT_OPTIONS_CACHE_MS = 6e4;
|
|
8902
9431
|
var YIELDSEEKER_APY_STATS_CACHE_MS = 6e4;
|
|
9432
|
+
var YIELDSEEKER_MANAGED_VAULT_RULE = "ignored_vault";
|
|
9433
|
+
var YIELDSEEKER_POOL_MEMORY_PREFIX = "Only allocate to these vaults and never to any other vault:";
|
|
9434
|
+
var YIELDSEEKER_NO_POOLS_CONTENT = `${YIELDSEEKER_POOL_MEMORY_PREFIX} none.`;
|
|
9435
|
+
var YIELDSEEKER_MAX_ACTIVE_MEMORIES = 3;
|
|
8903
9436
|
var YIELDSEEKER_AGENT_LIST_CACHE_MS = 12e4;
|
|
8904
9437
|
var YIELDSEEKER_AGENT_ACCOUNTS_FAILURE_CACHE_MS = 6e4;
|
|
8905
9438
|
var YIELDSEEKER_CREATE_CONFLICT_RETRY_MS = 2e3;
|
|
8906
9439
|
var YIELDSEEKER_DEPLOY_VISIBILITY_WINDOW_MS = 12e4;
|
|
8907
9440
|
var YIELDSEEKER_DEPLOY_VISIBILITY_RETRY_MS = [1e3, 2e3];
|
|
9441
|
+
function apyAsPercent(fraction) {
|
|
9442
|
+
if (typeof fraction !== "number" || !Number.isFinite(fraction)) return null;
|
|
9443
|
+
return Number((fraction * 100).toPrecision(12));
|
|
9444
|
+
}
|
|
9445
|
+
function isActiveMemory(memory2) {
|
|
9446
|
+
return !!memory2 && memory2.isActive !== false && memory2.isDeleted !== true;
|
|
9447
|
+
}
|
|
9448
|
+
function vaultOptionsKey(asset, includeUnavailable) {
|
|
9449
|
+
return `${asset}:${includeUnavailable ? "all" : "usable"}`;
|
|
9450
|
+
}
|
|
9451
|
+
function isManagedVaultList(memory2) {
|
|
9452
|
+
return memory2.managedRuleType === YIELDSEEKER_MANAGED_VAULT_RULE;
|
|
9453
|
+
}
|
|
9454
|
+
function isLegacyPoolSelectionMemory(memory2) {
|
|
9455
|
+
if (isManagedVaultList(memory2) || typeof memory2.content !== "string") return false;
|
|
9456
|
+
const content = memory2.content.trim();
|
|
9457
|
+
return content.startsWith(YIELDSEEKER_POOL_MEMORY_PREFIX) && /0x[0-9a-fA-F]{40}/.test(content.slice(YIELDSEEKER_POOL_MEMORY_PREFIX.length));
|
|
9458
|
+
}
|
|
9459
|
+
function uniqueAddresses(addresses) {
|
|
9460
|
+
const seen = /* @__PURE__ */ new Set();
|
|
9461
|
+
return addresses.filter((address) => {
|
|
9462
|
+
const key2 = address.toLowerCase();
|
|
9463
|
+
if (seen.has(key2)) return false;
|
|
9464
|
+
seen.add(key2);
|
|
9465
|
+
return true;
|
|
9466
|
+
});
|
|
9467
|
+
}
|
|
9468
|
+
function sameVaults(actual, expected) {
|
|
9469
|
+
const want = new Set(expected.map((address) => address.toLowerCase()));
|
|
9470
|
+
const got = new Set(actual.map((address) => address.toLowerCase()));
|
|
9471
|
+
return got.size === want.size && [...want].every((address) => got.has(address));
|
|
9472
|
+
}
|
|
8908
9473
|
function isYieldseekerWalletCodeMissing(error) {
|
|
8909
9474
|
for (let current = error, depth = 0; current && depth < 8; current = current.cause, depth++) {
|
|
8910
9475
|
const { name, message } = current;
|
|
@@ -8914,6 +9479,8 @@ function isYieldseekerWalletCodeMissing(error) {
|
|
|
8914
9479
|
return false;
|
|
8915
9480
|
}
|
|
8916
9481
|
var YIELDSEEKER_CREATE_CONFLICT_CODES = /* @__PURE__ */ new Set(["AGENT_ACCOUNT_EXISTS", "AGENT_CREATE_IN_PROGRESS"]);
|
|
9482
|
+
var YIELDSEEKER_REACTIVATE_LIMIT_CODES = /* @__PURE__ */ new Set(["USER_MAX_ACTIVE_AGENTS_REACHED", "USER_ALREADY_HAS_AGENT_FOR_ASSET"]);
|
|
9483
|
+
var YIELDSEEKER_REACTIVATE_CLOSED_CODES = /* @__PURE__ */ new Set(["AGENT_WALLET_OUTDATED", "AGENT_TYPE_NOT_SUPPORTED"]);
|
|
8917
9484
|
var YIELDSEEKER_WALLET_MATCH_LIMIT = 5;
|
|
8918
9485
|
var YIELDSEEKER_PORTFOLIO_CACHE_MS = 12e4;
|
|
8919
9486
|
var YIELDSEEKER_SETTLEMENT_BACKOFF_MS = [5e3, 1e4, 2e4, 4e4, 6e4];
|
|
@@ -8933,6 +9500,7 @@ var YIELDSEEKER_ACTIVITY_CACHE_MS = 6e4;
|
|
|
8933
9500
|
var YIELDSEEKER_MAX_WITHDRAW_SWEEPS = 3;
|
|
8934
9501
|
var YIELDSEEKER_WITHDRAWAL_READ_TIMEOUT_MS = 3e4;
|
|
8935
9502
|
var YIELDSEEKER_MAX_POSITION_VERIFICATION_MS = 2e3;
|
|
9503
|
+
var YIELDSEEKER_LATE_FEE_RATE_MS = 5e3;
|
|
8936
9504
|
var YIELDSEEKER_WITHDRAWAL_CANDIDATE_LIMIT = 64;
|
|
8937
9505
|
var YIELDSEEKER_VAULTS_PER_RPC_BATCH = 10;
|
|
8938
9506
|
function generateYieldseekerUsername() {
|
|
@@ -9025,9 +9593,31 @@ var YieldseekerAgent = class {
|
|
|
9025
9593
|
walletContexts = /* @__PURE__ */ new Map();
|
|
9026
9594
|
agentAccountReads = /* @__PURE__ */ new Map();
|
|
9027
9595
|
reportedAccounts = /* @__PURE__ */ new Set();
|
|
9028
|
-
// Slots whose verified agent is missing even from a re-read list
|
|
9029
|
-
//
|
|
9596
|
+
// Slots whose verified agent is missing even from a re-read list (and could
|
|
9597
|
+
// not be reopened), with the error the lookup failed with, until the list
|
|
9598
|
+
// cache window ends. Stops a re-read and a reactivate on every portfolio poll.
|
|
9030
9599
|
missingSlots = /* @__PURE__ */ new Map();
|
|
9600
|
+
// A remembered rate limit rethrown with the time left on its marker
|
|
9601
|
+
// (throwIfSlotMissing), mapped to the remembered error it copies, so
|
|
9602
|
+
// isMarkedSlotFailure still recognises it.
|
|
9603
|
+
rethrownSlotFailures = /* @__PURE__ */ new WeakMap();
|
|
9604
|
+
// Slots whose verified agent Yieldseeker will never reopen (a reactivate
|
|
9605
|
+
// answered AGENT_WALLET_OUTDATED or AGENT_TYPE_NOT_SUPPORTED), keyed by
|
|
9606
|
+
// slotKey, with that YIELDSEEKER_AGENT_CLOSED error. A permanent answer, so
|
|
9607
|
+
// it is kept for the session, like unavailableSlots: reads and deposits get
|
|
9608
|
+
// it with no request until disconnect, or until a lookup selects an agent
|
|
9609
|
+
// for the slot.
|
|
9610
|
+
closedSlots = /* @__PURE__ */ new Map();
|
|
9611
|
+
// In-flight reopens (reactivate, then a fresh list read) keyed by slotKey,
|
|
9612
|
+
// shared by concurrent lookups of one slot.
|
|
9613
|
+
pendingReopens = /* @__PURE__ */ new Map();
|
|
9614
|
+
// Slots Yieldseeker will not give an agent this session (a reactivate answered
|
|
9615
|
+
// an active-agent limit), keyed by slotKey, with the provider's limit code.
|
|
9616
|
+
// Never expires: it answers without a request until disconnect.
|
|
9617
|
+
unavailableSlots = /* @__PURE__ */ new Map();
|
|
9618
|
+
// In-flight reactivates keyed by slotKey + agentId, shared by every caller
|
|
9619
|
+
// (a read-time reopen, deposits): one request however many ask.
|
|
9620
|
+
pendingReactivates = /* @__PURE__ */ new Map();
|
|
9031
9621
|
// In-flight cache-bypassing list reads, shared by concurrent callers.
|
|
9032
9622
|
freshListReads = /* @__PURE__ */ new Map();
|
|
9033
9623
|
// Every contextKey computed this session; asset-only calls fall back to them.
|
|
@@ -9080,6 +9670,7 @@ var YieldseekerAgent = class {
|
|
|
9080
9670
|
ledgerBudgetMs = LEDGER_READ_BUDGET_MS;
|
|
9081
9671
|
/** slotKey -> the last successful ledger rows and when they arrived. */
|
|
9082
9672
|
lastLedgerRows = /* @__PURE__ */ new Map();
|
|
9673
|
+
/** Keyed by `vaultOptionsKey`: each asset's usable list and its full list are cached apart. */
|
|
9083
9674
|
vaultOptions = /* @__PURE__ */ new Map();
|
|
9084
9675
|
pendingVaultOptions = /* @__PURE__ */ new Map();
|
|
9085
9676
|
assetApyStats = /* @__PURE__ */ new Map();
|
|
@@ -9137,36 +9728,57 @@ var YieldseekerAgent = class {
|
|
|
9137
9728
|
return { ...await pending2 };
|
|
9138
9729
|
}
|
|
9139
9730
|
/**
|
|
9140
|
-
* Deposits go only to
|
|
9141
|
-
*
|
|
9142
|
-
*
|
|
9143
|
-
*
|
|
9144
|
-
*
|
|
9145
|
-
*
|
|
9731
|
+
* Deposits go only to an agent Yieldseeker still has open. The session caches
|
|
9732
|
+
* the selected agent, so a tab left open can hold one Yieldseeker has since
|
|
9733
|
+
* closed (deactivated). This reads the agent wallet fresh from Yieldseeker,
|
|
9734
|
+
* bypassing the cached wallet contexts, and:
|
|
9735
|
+
* - open, same wallet address: returns the context to deposit with;
|
|
9736
|
+
* - closed (`deactivatedDate` set): reactivates it, re-reads the wallet, and
|
|
9737
|
+
* continues only when it is now open with the same address. Only the
|
|
9738
|
+
* verified record's agent is reopened: any other closed agent (a
|
|
9739
|
+
* superseded-wallet match, or a named agent with no verified record, also
|
|
9740
|
+
* when the accounts could not be read) refuses without a request;
|
|
9741
|
+
* - anything else refuses with nothing sent, before any progress event,
|
|
9742
|
+
* signature or callback. Every refusal carries `notSubmitted` and
|
|
9743
|
+
* `safeToFallback: false`, so no paid fallback runs.
|
|
9744
|
+
* A slot recorded unavailable (the active-agent limit) refuses at once with
|
|
9745
|
+
* no request. The reactivate goes through reactivateSlot, which shares one
|
|
9746
|
+
* request per slot and remembers a failure for the list-cache window, so
|
|
9747
|
+
* repeated deposits do not repeat it. A failed wallet read fails closed
|
|
9748
|
+
* (YIELDSEEKER_WALLET_UNVERIFIED, reason UNAVAILABLE), like the on-chain
|
|
9749
|
+
* gate. A reactivate that fails keeps its error code
|
|
9750
|
+
* (YIELDSEEKER_AGENT_CLOSED, or the mapped API error for a transient
|
|
9751
|
+
* failure). At the limit the slot is also recorded unavailable for the
|
|
9752
|
+
* session (see isSlotUnavailable). Session changes keep their own
|
|
9753
|
+
* NOT_CONNECTED error.
|
|
9146
9754
|
*/
|
|
9147
|
-
async
|
|
9755
|
+
async assertAgentOpen(state, chainId, asset, context) {
|
|
9148
9756
|
const generation = this.readGeneration;
|
|
9757
|
+
const agentId = context.agent.agentId;
|
|
9149
9758
|
const agentWallet = context.wallet.walletAddress;
|
|
9150
|
-
const
|
|
9151
|
-
const
|
|
9152
|
-
|
|
9153
|
-
|
|
9759
|
+
const refusal = { notSubmitted: true, safeToFallback: false };
|
|
9760
|
+
const slot = this.slotKey(state, chainId, asset);
|
|
9761
|
+
const unavailable = this.unavailableSlots.get(slot);
|
|
9762
|
+
if (unavailable !== void 0) throw this.agentClosed(chainId, asset, agentId, unavailable, refusal);
|
|
9763
|
+
const readWallet = async () => {
|
|
9764
|
+
let fresh2;
|
|
9154
9765
|
try {
|
|
9155
|
-
|
|
9156
|
-
|
|
9766
|
+
const answer = await this.walletRequest(
|
|
9767
|
+
state,
|
|
9768
|
+
chainId,
|
|
9769
|
+
this.agentPath(context, "wallet")
|
|
9770
|
+
);
|
|
9771
|
+
if (!answer?.agentWallet || !(0, import_viem17.isAddress)(answer.agentWallet.walletAddress)) {
|
|
9772
|
+
throw this.invalidResponse("agent wallet");
|
|
9773
|
+
}
|
|
9774
|
+
fresh2 = answer.agentWallet;
|
|
9157
9775
|
} catch (error) {
|
|
9158
9776
|
this.assertSession(generation, chainId, asset);
|
|
9159
|
-
if (justDeployed && attempt < YIELDSEEKER_DEPLOY_VISIBILITY_RETRY_MS.length && isYieldseekerWalletCodeMissing(error)) {
|
|
9160
|
-
await new Promise((resolve) => setTimeout(resolve, YIELDSEEKER_DEPLOY_VISIBILITY_RETRY_MS[attempt]));
|
|
9161
|
-
this.assertSession(generation, chainId, asset);
|
|
9162
|
-
continue;
|
|
9163
|
-
}
|
|
9164
9777
|
throw new OwneyError(
|
|
9165
9778
|
"YIELDSEEKER_WALLET_UNVERIFIED",
|
|
9166
|
-
"Could not
|
|
9779
|
+
"Could not check that the Yieldseeker agent is open. Nothing was sent. Please retry.",
|
|
9167
9780
|
{
|
|
9168
|
-
|
|
9169
|
-
safeToFallback: false,
|
|
9781
|
+
...refusal,
|
|
9170
9782
|
reason: "UNAVAILABLE",
|
|
9171
9783
|
agentWallet,
|
|
9172
9784
|
asset,
|
|
@@ -9175,20 +9787,114 @@ var YieldseekerAgent = class {
|
|
|
9175
9787
|
this.id
|
|
9176
9788
|
);
|
|
9177
9789
|
}
|
|
9178
|
-
|
|
9179
|
-
|
|
9180
|
-
|
|
9181
|
-
|
|
9182
|
-
|
|
9183
|
-
|
|
9184
|
-
|
|
9185
|
-
);
|
|
9186
|
-
|
|
9187
|
-
|
|
9188
|
-
|
|
9189
|
-
|
|
9190
|
-
|
|
9191
|
-
|
|
9790
|
+
this.assertSession(generation, chainId, asset);
|
|
9791
|
+
return fresh2;
|
|
9792
|
+
};
|
|
9793
|
+
let fresh = await readWallet();
|
|
9794
|
+
let reopened = false;
|
|
9795
|
+
if (fresh.deactivatedDate) {
|
|
9796
|
+
this.forgetAgentWallet(agentId);
|
|
9797
|
+
const accounts = await this.agentAccounts(state, chainId);
|
|
9798
|
+
this.assertSession(generation, chainId, asset);
|
|
9799
|
+
const verified = this.slotAccounts(accounts, chainId, asset).find((account) => account.status === "verified");
|
|
9800
|
+
if (!verified || verified.providerAgentId !== agentId) {
|
|
9801
|
+
throw this.agentClosed(chainId, asset, agentId, void 0, { ...refusal, reason: "NOT_VERIFIED_AGENT" });
|
|
9802
|
+
}
|
|
9803
|
+
let result;
|
|
9804
|
+
try {
|
|
9805
|
+
result = await this.reactivateSlot(state, chainId, context.user, asset, agentId);
|
|
9806
|
+
} catch (error) {
|
|
9807
|
+
this.assertSession(generation, chainId, asset);
|
|
9808
|
+
const failure = error instanceof OwneyError ? error : this.mapApiError(error);
|
|
9809
|
+
if (failure.code === "YIELDSEEKER_AGENT_CLOSED") {
|
|
9810
|
+
const { providerCode, reason } = failure.details ?? {};
|
|
9811
|
+
throw this.agentClosed(
|
|
9812
|
+
chainId,
|
|
9813
|
+
asset,
|
|
9814
|
+
agentId,
|
|
9815
|
+
typeof providerCode === "string" ? providerCode : void 0,
|
|
9816
|
+
{ ...refusal, ...typeof reason === "string" ? { reason } : {} }
|
|
9817
|
+
);
|
|
9818
|
+
}
|
|
9819
|
+
throw new OwneyError(
|
|
9820
|
+
failure.code,
|
|
9821
|
+
`Yieldseeker could not reopen the closed ${asset} agent. Nothing was sent. Please retry.`,
|
|
9822
|
+
{ ...failure.details, ...refusal, cause: failure.message },
|
|
9823
|
+
failure.agentId
|
|
9824
|
+
);
|
|
9825
|
+
}
|
|
9826
|
+
this.assertSession(generation, chainId, asset);
|
|
9827
|
+
if (result.outcome === "limit") throw this.agentClosed(chainId, asset, agentId, result.providerCode, refusal);
|
|
9828
|
+
this.forgetAgentWallet(agentId);
|
|
9829
|
+
fresh = await readWallet();
|
|
9830
|
+
if (fresh.deactivatedDate) {
|
|
9831
|
+
this.rememberMissingSlot(
|
|
9832
|
+
slot,
|
|
9833
|
+
generation,
|
|
9834
|
+
this.agentClosed(chainId, asset, agentId, void 0, { reason: "STILL_DEACTIVATED" })
|
|
9835
|
+
);
|
|
9836
|
+
throw this.agentClosed(chainId, asset, agentId, void 0, { ...refusal, reason: "STILL_DEACTIVATED" });
|
|
9837
|
+
}
|
|
9838
|
+
reopened = true;
|
|
9839
|
+
}
|
|
9840
|
+
if (fresh.walletAddress.toLowerCase() !== agentWallet.toLowerCase()) {
|
|
9841
|
+
throw this.agentClosed(chainId, asset, agentId, void 0, { ...refusal, reason: "WALLET_CHANGED" });
|
|
9842
|
+
}
|
|
9843
|
+
return reopened ? { ...context, wallet: fresh } : context;
|
|
9844
|
+
}
|
|
9845
|
+
/**
|
|
9846
|
+
* Deposits go only to a wallet whose identity is verified on chain (factory
|
|
9847
|
+
* mapping, owner, base asset, FACTORY). The API key is public, so the wallet
|
|
9848
|
+
* the provider API returned is not trusted on its own. V1 wallets still
|
|
9849
|
+
* accept deposits: only identity is required, not the V2 implementation.
|
|
9850
|
+
* A failed read fails closed (reason UNAVAILABLE): an unverified wallet never
|
|
9851
|
+
* receives funds. Session changes keep their own NOT_CONNECTED error.
|
|
9852
|
+
*/
|
|
9853
|
+
async assertDepositWalletVerified(state, chainId, asset, context) {
|
|
9854
|
+
const generation = this.readGeneration;
|
|
9855
|
+
const agentWallet = context.wallet.walletAddress;
|
|
9856
|
+
const deployedAt = this.recentDeployments.get(agentWallet.toLowerCase());
|
|
9857
|
+
const justDeployed = deployedAt !== void 0 && Date.now() - deployedAt < YIELDSEEKER_DEPLOY_VISIBILITY_WINDOW_MS;
|
|
9858
|
+
let status;
|
|
9859
|
+
for (let attempt = 0; ; attempt++) {
|
|
9860
|
+
try {
|
|
9861
|
+
status = await this.readWalletStatus(state, chainId, asset, context, true);
|
|
9862
|
+
break;
|
|
9863
|
+
} catch (error) {
|
|
9864
|
+
this.assertSession(generation, chainId, asset);
|
|
9865
|
+
if (justDeployed && attempt < YIELDSEEKER_DEPLOY_VISIBILITY_RETRY_MS.length && isYieldseekerWalletCodeMissing(error)) {
|
|
9866
|
+
await new Promise((resolve) => setTimeout(resolve, YIELDSEEKER_DEPLOY_VISIBILITY_RETRY_MS[attempt]));
|
|
9867
|
+
this.assertSession(generation, chainId, asset);
|
|
9868
|
+
continue;
|
|
9869
|
+
}
|
|
9870
|
+
throw new OwneyError(
|
|
9871
|
+
"YIELDSEEKER_WALLET_UNVERIFIED",
|
|
9872
|
+
"Could not verify the Yieldseeker Agent Wallet on chain. Nothing was sent. Please retry.",
|
|
9873
|
+
{
|
|
9874
|
+
notSubmitted: true,
|
|
9875
|
+
safeToFallback: false,
|
|
9876
|
+
reason: "UNAVAILABLE",
|
|
9877
|
+
agentWallet,
|
|
9878
|
+
asset,
|
|
9879
|
+
cause: error instanceof Error ? error.message : String(error)
|
|
9880
|
+
},
|
|
9881
|
+
this.id
|
|
9882
|
+
);
|
|
9883
|
+
}
|
|
9884
|
+
}
|
|
9885
|
+
if (!status.verified || status.agentWallet.toLowerCase() !== agentWallet.toLowerCase()) {
|
|
9886
|
+
throw new OwneyError(
|
|
9887
|
+
"YIELDSEEKER_WALLET_UNVERIFIED",
|
|
9888
|
+
"The Yieldseeker Agent Wallet failed on-chain verification. Nothing was sent.",
|
|
9889
|
+
{ notSubmitted: true, safeToFallback: false, reason: "IDENTITY_MISMATCH", agentWallet, asset },
|
|
9890
|
+
this.id
|
|
9891
|
+
);
|
|
9892
|
+
}
|
|
9893
|
+
}
|
|
9894
|
+
rememberWalletStatus(key2, status) {
|
|
9895
|
+
if (status.verified && status.version === "v2") {
|
|
9896
|
+
this.withdrawalVersionCache.set(key2, { at: Date.now(), status: { ...status } });
|
|
9897
|
+
if (this.withdrawalVersionCache.size > 128)
|
|
9192
9898
|
this.withdrawalVersionCache.delete(this.withdrawalVersionCache.keys().next().value);
|
|
9193
9899
|
} else this.withdrawalVersionCache.delete(key2);
|
|
9194
9900
|
}
|
|
@@ -9445,6 +10151,10 @@ var YieldseekerAgent = class {
|
|
|
9445
10151
|
this.pendingSlotInvalidations.clear();
|
|
9446
10152
|
this.knownContextKeys.clear();
|
|
9447
10153
|
this.missingSlots.clear();
|
|
10154
|
+
this.closedSlots.clear();
|
|
10155
|
+
this.pendingReopens.clear();
|
|
10156
|
+
this.pendingReactivates.clear();
|
|
10157
|
+
this.unavailableSlots.clear();
|
|
9448
10158
|
this.freshListReads.clear();
|
|
9449
10159
|
this.balanceVaults.clear();
|
|
9450
10160
|
this.pendingAgents.clear();
|
|
@@ -9472,11 +10182,43 @@ var YieldseekerAgent = class {
|
|
|
9472
10182
|
this.planHistoryKeys.clear();
|
|
9473
10183
|
this.lastLedgerRows.clear();
|
|
9474
10184
|
}
|
|
10185
|
+
/**
|
|
10186
|
+
* Ready every asset's agent, `asset` first: a missing one is created and a
|
|
10187
|
+
* closed one reopened (2026-11-06). A slot Yieldseeker will never let the
|
|
10188
|
+
* user have (the agent limit, closed for good, missing with no way to
|
|
10189
|
+
* reopen) is rethrown with `details.permanent`, which refuses the connect.
|
|
10190
|
+
* A temporary failure (an API error or timeout) on another asset does not:
|
|
10191
|
+
* that slot answers again where it is needed. On the selected asset every
|
|
10192
|
+
* failure is thrown as before, without readying the rest, so a failed
|
|
10193
|
+
* sign-in never opens a second prompt.
|
|
10194
|
+
*/
|
|
9475
10195
|
async activateAgent(state, chainId, asset) {
|
|
9476
10196
|
this.assertChain(chainId);
|
|
9477
10197
|
const targetAsset = asset ?? "USDC";
|
|
9478
10198
|
this.assertAsset(targetAsset);
|
|
9479
|
-
|
|
10199
|
+
const others = Object.keys(YIELDSEEKER_ASSET_METADATA).filter((each) => each !== targetAsset);
|
|
10200
|
+
for (const each of [targetAsset, ...others]) {
|
|
10201
|
+
try {
|
|
10202
|
+
await this.ensureAgent(state, chainId, each);
|
|
10203
|
+
} catch (error) {
|
|
10204
|
+
if (this.isSlotEmpty(error)) throw this.permanentFailure(error);
|
|
10205
|
+
const temporary = error instanceof OwneyError && (error.code === "AGENT_API_ERROR" || error.code === "AGENT_TIMEOUT");
|
|
10206
|
+
if (each === targetAsset || !temporary) throw error;
|
|
10207
|
+
debugLog("yieldseeker:connect", `${each}: agent not ready, connect continues`, {
|
|
10208
|
+
code: error.code,
|
|
10209
|
+
statusCode: error.details?.statusCode
|
|
10210
|
+
});
|
|
10211
|
+
}
|
|
10212
|
+
}
|
|
10213
|
+
}
|
|
10214
|
+
/** The same failure, marked as one that will not go away this session. */
|
|
10215
|
+
permanentFailure(error) {
|
|
10216
|
+
const message = error.message.replace(/^\[[^\]]*\](?:\[agent:[^\]]*\])?\s*/, "");
|
|
10217
|
+
return new OwneyError(error.code, message, { ...error.details, permanent: true }, this.id);
|
|
10218
|
+
}
|
|
10219
|
+
isSlotUnavailable(state, chainId, asset) {
|
|
10220
|
+
if (asset !== "USDC" && asset !== "WETH") return false;
|
|
10221
|
+
return this.unavailableSlots.has(this.slotKey(state, chainId, asset));
|
|
9480
10222
|
}
|
|
9481
10223
|
async deposit(state, chainId, amount, asset, depositCallback, onProgress, onBeforeSubmission) {
|
|
9482
10224
|
this.assertChain(chainId);
|
|
@@ -9489,7 +10231,20 @@ var YieldseekerAgent = class {
|
|
|
9489
10231
|
this.id
|
|
9490
10232
|
);
|
|
9491
10233
|
}
|
|
9492
|
-
const
|
|
10234
|
+
const selected = await this.ensureAgent(state, chainId, asset).catch((error) => {
|
|
10235
|
+
if (error instanceof OwneyError && error.code === "YIELDSEEKER_AGENT_CLOSED") {
|
|
10236
|
+
const { agentId, providerCode, reason } = error.details ?? {};
|
|
10237
|
+
throw this.agentClosed(
|
|
10238
|
+
chainId,
|
|
10239
|
+
asset,
|
|
10240
|
+
typeof agentId === "string" ? agentId : "",
|
|
10241
|
+
typeof providerCode === "string" ? providerCode : void 0,
|
|
10242
|
+
{ notSubmitted: true, safeToFallback: false, ...typeof reason === "string" ? { reason } : {} }
|
|
10243
|
+
);
|
|
10244
|
+
}
|
|
10245
|
+
throw error;
|
|
10246
|
+
});
|
|
10247
|
+
const context = await this.assertAgentOpen(state, chainId, asset, selected);
|
|
9493
10248
|
await this.assertDepositWalletVerified(state, chainId, asset, context);
|
|
9494
10249
|
const generation = this.readGeneration;
|
|
9495
10250
|
const movement = this.snapshotMovement(state, chainId, context, BigInt(amount));
|
|
@@ -9679,15 +10434,14 @@ var YieldseekerAgent = class {
|
|
|
9679
10434
|
if (timer) clearTimeout(timer);
|
|
9680
10435
|
}
|
|
9681
10436
|
};
|
|
9682
|
-
const
|
|
9683
|
-
|
|
9684
|
-
|
|
9685
|
-
|
|
9686
|
-
|
|
9687
|
-
|
|
9688
|
-
|
|
9689
|
-
|
|
9690
|
-
);
|
|
10437
|
+
const feeRateAnswer = amount === void 0 ? Promise.resolve(0) : (() => {
|
|
10438
|
+
try {
|
|
10439
|
+
return this.portfolioSnapshot(state, chainId, context, contextKey).read.then((value) => value.agentSnapshot.feeRateBps);
|
|
10440
|
+
} catch (error) {
|
|
10441
|
+
return Promise.reject(error);
|
|
10442
|
+
}
|
|
10443
|
+
})().catch(() => void 0);
|
|
10444
|
+
const feeRateRead = boundedVerification(feeRateAnswer);
|
|
9691
10445
|
const positionsRead = this.readWithdrawalPositions(state, chainId, context);
|
|
9692
10446
|
const metadata = YIELDSEEKER_ASSET_METADATA[asset];
|
|
9693
10447
|
const agentWallet = (0, import_viem17.getAddress)(context.wallet.walletAddress);
|
|
@@ -9997,9 +10751,10 @@ var YieldseekerAgent = class {
|
|
|
9997
10751
|
}
|
|
9998
10752
|
const ownerFunds = confirmedMovement ? await readOwnerFunds(latestUnwindBlock) : initialFunds;
|
|
9999
10753
|
const availableForOwner = ownerFunds.available;
|
|
10000
|
-
const feeRate = feeRateBps ?? 0;
|
|
10001
|
-
const maxFee = confirmedMovement && Number.isInteger(feeRate) && feeRate >= 0 && feeRate <= 1e3 ? (grossUnwound * BigInt(feeRate) + 9999n) / 10000n : 0n;
|
|
10002
10754
|
const shortfall = availableForOwner < requested ? requested - availableForOwner : 0n;
|
|
10755
|
+
const feeRate = feeRateBps ?? (confirmedMovement && amount !== void 0 && shortfall > confirmedUnwinds ? await boundedVerification(feeRateAnswer, YIELDSEEKER_LATE_FEE_RATE_MS) : void 0) ?? 0;
|
|
10756
|
+
this.assertSession(generation, chainId, asset);
|
|
10757
|
+
const maxFee = confirmedMovement && Number.isInteger(feeRate) && feeRate >= 0 && feeRate <= 1e3 ? (grossUnwound * BigInt(feeRate) + 9999n) / 10000n : 0n;
|
|
10003
10758
|
if (availableForOwner === 0n || amount !== void 0 && shortfall > maxFee + confirmedUnwinds) {
|
|
10004
10759
|
this.invalidateFundingRead(state, chainId, asset);
|
|
10005
10760
|
if (amount === void 0 && positionsStatus !== "empty")
|
|
@@ -10253,7 +11008,7 @@ var YieldseekerAgent = class {
|
|
|
10253
11008
|
positions.forEach((p) => vaults.set(p.vaultOption.address.toLowerCase(), p.vaultOption));
|
|
10254
11009
|
const needsInventory = !proof.inventoryComplete;
|
|
10255
11010
|
if (needsInventory || [...vaults.values()].some((option) => !option.provider)) {
|
|
10256
|
-
const catalog = await this.loadVaultOptions(asset).catch(() => []);
|
|
11011
|
+
const catalog = await this.loadVaultOptions(asset, { includeUnavailable: true }).catch(() => []);
|
|
10257
11012
|
const eligible = catalog.filter((o) => o.chainId === evidence.chainId && o.assetAddress?.toLowerCase() === metadata.address.toLowerCase() && (0, import_viem17.isAddress)(o.address));
|
|
10258
11013
|
if (needsInventory && !eligible.length) return unknown2("INVENTORY_INCOMPLETE");
|
|
10259
11014
|
for (const option of eligible) {
|
|
@@ -10329,7 +11084,8 @@ var YieldseekerAgent = class {
|
|
|
10329
11084
|
const hints = new Map(this.validateWithdrawalPositions(positions, chainId, context.asset).map((position2) => [position2.vaultOption.address.toLowerCase(), position2]));
|
|
10330
11085
|
const historic = this.readCache.get(`historic:${key2}`)?.value?.position;
|
|
10331
11086
|
const receivedAssets = new Set((historic?.movements ?? []).filter((movement) => movement.chainId === chainId && movement.agentWalletId === context.wallet.agentWalletId && movement.toAddress?.toLowerCase() === context.wallet.walletAddress.toLowerCase()).filter((movement) => typeof movement.assetAddress === "string").map((movement) => movement.assetAddress.toLowerCase()));
|
|
10332
|
-
|
|
11087
|
+
const cachedOptions = this.vaultOptions.get(vaultOptionsKey(context.asset, true)) ?? this.vaultOptions.get(vaultOptionsKey(context.asset, false));
|
|
11088
|
+
for (const option of cachedOptions?.value ?? []) {
|
|
10333
11089
|
if (option.chainId !== chainId || typeof option.assetAddress !== "string" || option.assetAddress.toLowerCase() !== YIELDSEEKER_ASSET_METADATA[context.asset].address.toLowerCase() || !(0, import_viem17.isAddress)(option.address) || !receivedAssets.has(option.address.toLowerCase()) || hints.has(option.address.toLowerCase())) continue;
|
|
10334
11090
|
hints.set(option.address.toLowerCase(), {
|
|
10335
11091
|
vaultOption: option,
|
|
@@ -10542,7 +11298,7 @@ var YieldseekerAgent = class {
|
|
|
10542
11298
|
assertReadCurrent();
|
|
10543
11299
|
return proof(true);
|
|
10544
11300
|
}
|
|
10545
|
-
const catalog = await this.loadVaultOptions(context.asset).catch(() => void 0);
|
|
11301
|
+
const catalog = await this.loadVaultOptions(context.asset, { includeUnavailable: true }).catch(() => void 0);
|
|
10546
11302
|
assertReadCurrent();
|
|
10547
11303
|
const eligible = /* @__PURE__ */ new Map();
|
|
10548
11304
|
for (const option of catalog ?? []) {
|
|
@@ -10572,6 +11328,9 @@ var YieldseekerAgent = class {
|
|
|
10572
11328
|
if (timer) clearTimeout(timer);
|
|
10573
11329
|
}
|
|
10574
11330
|
}
|
|
11331
|
+
hasReadSession(state, chainId) {
|
|
11332
|
+
return this.supportedChainIds.includes(chainId) && this.auth.peekToken(state, chainId) !== void 0;
|
|
11333
|
+
}
|
|
10575
11334
|
async getBalances(state, chainId, asset) {
|
|
10576
11335
|
this.assertChain(chainId);
|
|
10577
11336
|
if (asset !== void 0) this.assertAsset(asset);
|
|
@@ -10682,8 +11441,37 @@ var YieldseekerAgent = class {
|
|
|
10682
11441
|
}
|
|
10683
11442
|
return false;
|
|
10684
11443
|
}
|
|
11444
|
+
/**
|
|
11445
|
+
* Tells Yieldseeker a deposit landed (`deposit-made`), so the agent allocates
|
|
11446
|
+
* it now instead of on its next 30-minute check. Yieldseeker decides whether
|
|
11447
|
+
* anything moves (the funding minimum, a deployed agent, no manual
|
|
11448
|
+
* withdrawal in the last hour). Uses the agent this session already knows
|
|
11449
|
+
* for the asset and the saved sign-in only: never prompts, never retries,
|
|
11450
|
+
* never throws.
|
|
11451
|
+
*/
|
|
11452
|
+
async depositConfirmed(state, chainId, evidence) {
|
|
11453
|
+
try {
|
|
11454
|
+
const asset = String(evidence.token).toUpperCase();
|
|
11455
|
+
if (!this.supportedChainIds.includes(chainId) || !(asset in YIELDSEEKER_ASSET_METADATA))
|
|
11456
|
+
return { notified: false, reason: "UNSUPPORTED" };
|
|
11457
|
+
const context = this.agentContexts.get(this.slotKey(state, chainId, asset));
|
|
11458
|
+
if (!context || !evidence.agentWallet || context.wallet.walletAddress.toLowerCase() !== evidence.agentWallet.toLowerCase())
|
|
11459
|
+
return { notified: false, reason: "NO_AGENT" };
|
|
11460
|
+
if (!this.auth.peekToken(state, chainId)) return { notified: false, reason: "NO_SESSION" };
|
|
11461
|
+
await this.walletRequest(
|
|
11462
|
+
state,
|
|
11463
|
+
chainId,
|
|
11464
|
+
this.agentPath(context, "deposit-made"),
|
|
11465
|
+
{ method: "POST", body: {}, promptless: true }
|
|
11466
|
+
);
|
|
11467
|
+
return { notified: true };
|
|
11468
|
+
} catch (error) {
|
|
11469
|
+
return { notified: false, reason: error instanceof OwneyError ? error.code : "ERROR" };
|
|
11470
|
+
}
|
|
11471
|
+
}
|
|
10685
11472
|
async getFundingWallet(state, chainId, asset) {
|
|
10686
11473
|
this.assertAsset(asset);
|
|
11474
|
+
this.throwIfSlotUnavailable(state, chainId, asset);
|
|
10687
11475
|
const context = this.agentContexts.get(this.slotKey(state, chainId, asset));
|
|
10688
11476
|
if (!context) throw new OwneyError("NOT_CONNECTED", "Reconnect the agent before recovering funding.");
|
|
10689
11477
|
return context.wallet.walletAddress;
|
|
@@ -10710,15 +11498,17 @@ var YieldseekerAgent = class {
|
|
|
10710
11498
|
const contexts = await this.loadPortfolio(state, chainId, { includePositions: false, ledger: true });
|
|
10711
11499
|
return mapYieldseekerEarnings(await Promise.all(contexts.map((context) => this.applyEarningsHold(state, chainId, context))));
|
|
10712
11500
|
}
|
|
10713
|
-
async getAccountApy(state, chainId, days, tokenSymbol) {
|
|
11501
|
+
async getAccountApy(state, chainId, days, tokenSymbol, scopeChainId) {
|
|
10714
11502
|
this.assertChain(chainId);
|
|
10715
11503
|
const asset = tokenSymbol?.toUpperCase();
|
|
10716
11504
|
if (asset !== void 0) this.assertAsset(asset);
|
|
11505
|
+
if (typeof scopeChainId === "number" && !this.supportedChainIds.includes(scopeChainId))
|
|
11506
|
+
return mapYieldseekerApy(state.walletAddress, [], days);
|
|
10717
11507
|
const contexts = await this.loadPortfolio(state, chainId, {
|
|
10718
11508
|
...asset ? { asset } : {},
|
|
10719
11509
|
historic: true
|
|
10720
11510
|
});
|
|
10721
|
-
return mapYieldseekerApy(state.walletAddress, contexts, days);
|
|
11511
|
+
return mapYieldseekerApy(state.walletAddress, contexts, days, Date.now(), asset);
|
|
10722
11512
|
}
|
|
10723
11513
|
async getDailyEarnings(state, chainId, days, tokenSymbol) {
|
|
10724
11514
|
this.assertChain(chainId);
|
|
@@ -10742,7 +11532,7 @@ var YieldseekerAgent = class {
|
|
|
10742
11532
|
});
|
|
10743
11533
|
const catalog = await Promise.all(
|
|
10744
11534
|
[...new Set(contexts.map((context) => context.asset))].map(
|
|
10745
|
-
(contextAsset) => this.loadVaultOptions(contextAsset)
|
|
11535
|
+
(contextAsset) => this.loadVaultOptions(contextAsset, { includeUnavailable: true })
|
|
10746
11536
|
)
|
|
10747
11537
|
);
|
|
10748
11538
|
const vaultAddresses = new Set(
|
|
@@ -10767,11 +11557,11 @@ var YieldseekerAgent = class {
|
|
|
10767
11557
|
);
|
|
10768
11558
|
}
|
|
10769
11559
|
async getAgentApy(days, options) {
|
|
10770
|
-
if (
|
|
11560
|
+
if (days === "14D") {
|
|
10771
11561
|
throw new OwneyError(
|
|
10772
11562
|
"AGENT_APY_PERIOD_UNSUPPORTED",
|
|
10773
11563
|
`Yieldseeker does not provide a representative ${days} strategy APY.`,
|
|
10774
|
-
{ days, supportedDays: ["7D"] },
|
|
11564
|
+
{ days, supportedDays: ["7D", "30D"] },
|
|
10775
11565
|
this.id
|
|
10776
11566
|
);
|
|
10777
11567
|
}
|
|
@@ -10784,10 +11574,10 @@ var YieldseekerAgent = class {
|
|
|
10784
11574
|
return { asset, stats: await this.loadAssetApyStats(asset) };
|
|
10785
11575
|
})
|
|
10786
11576
|
);
|
|
10787
|
-
return mapYieldseekerAgentApy(values);
|
|
11577
|
+
return mapYieldseekerAgentApy(values, days);
|
|
10788
11578
|
}
|
|
10789
11579
|
supportsAgentApyPeriod(days) {
|
|
10790
|
-
return days === "7D";
|
|
11580
|
+
return days === "7D" || days === "30D";
|
|
10791
11581
|
}
|
|
10792
11582
|
async loadAssetApyStats(asset) {
|
|
10793
11583
|
const cached = this.assetApyStats.get(asset);
|
|
@@ -10799,7 +11589,7 @@ var YieldseekerAgent = class {
|
|
|
10799
11589
|
`/chains/8453/assets/${metadata.address}/apy-stats?rulePreset=explorative`
|
|
10800
11590
|
).then((response) => {
|
|
10801
11591
|
const stats = response?.assetApyStats;
|
|
10802
|
-
if (!stats || stats.chainId !== 8453 || typeof stats.assetAddress !== "string" || stats.assetAddress.toLowerCase() !== metadata.address.toLowerCase() || stats.rulePreset !== "explorative" || typeof stats.expectedApy7d !== "number" || !Number.isFinite(stats.expectedApy7d)) {
|
|
11592
|
+
if (!stats || stats.chainId !== 8453 || typeof stats.assetAddress !== "string" || stats.assetAddress.toLowerCase() !== metadata.address.toLowerCase() || stats.rulePreset !== "explorative" || typeof stats.expectedApy7d !== "number" || !Number.isFinite(stats.expectedApy7d) || typeof stats.expectedApy30d !== "number" || !Number.isFinite(stats.expectedApy30d)) {
|
|
10803
11593
|
throw this.invalidResponse("asset APY statistics");
|
|
10804
11594
|
}
|
|
10805
11595
|
this.assetApyStats.set(asset, {
|
|
@@ -10811,27 +11601,321 @@ var YieldseekerAgent = class {
|
|
|
10811
11601
|
this.pendingAssetApyStats.set(asset, request2);
|
|
10812
11602
|
return request2;
|
|
10813
11603
|
}
|
|
10814
|
-
|
|
10815
|
-
|
|
11604
|
+
/**
|
|
11605
|
+
* The deposit-time Pools step's catalogue: every vault Yieldseeker lists
|
|
11606
|
+
* for a new agent on `asset` on Base, grouped by provider (the provider is
|
|
11607
|
+
* both `protocolId` and `name`). Nothing is filtered on our side, on
|
|
11608
|
+
* liquidity, size or provider. `strategy` is accepted for the IAgent
|
|
11609
|
+
* contract and ignored.
|
|
11610
|
+
*/
|
|
11611
|
+
async getPoolCatalog(params) {
|
|
11612
|
+
const asset = params.asset.toUpperCase();
|
|
11613
|
+
this.assertAsset(asset);
|
|
11614
|
+
const byProvider = /* @__PURE__ */ new Map();
|
|
11615
|
+
for (const vault of await this.loadVaultOptions(asset)) {
|
|
11616
|
+
const pools = byProvider.get(vault.provider) ?? [];
|
|
11617
|
+
pools.push({
|
|
11618
|
+
chainId: 8453,
|
|
11619
|
+
token: asset,
|
|
11620
|
+
name: vault.name,
|
|
11621
|
+
apy: apyAsPercent(vault.totalApy),
|
|
11622
|
+
tvlUsd: Number.isFinite(vault.totalDepositsUsd) ? vault.totalDepositsUsd : null,
|
|
11623
|
+
link: null,
|
|
11624
|
+
address: vault.address
|
|
11625
|
+
});
|
|
11626
|
+
byProvider.set(vault.provider, pools);
|
|
11627
|
+
}
|
|
11628
|
+
return [...byProvider].map(([provider, pools]) => ({
|
|
11629
|
+
protocolId: provider,
|
|
11630
|
+
name: provider,
|
|
11631
|
+
logo: null,
|
|
11632
|
+
pools
|
|
11633
|
+
}));
|
|
11634
|
+
}
|
|
11635
|
+
/**
|
|
11636
|
+
* The asset's vaults on Base. By default only those a new agent can use:
|
|
11637
|
+
* Yieldseeker leaves out the ones it has disabled (40acres and Moonwell
|
|
11638
|
+
* among them), gated or can't use, so the picker follows its list
|
|
11639
|
+
* (2026-11-04). `includeUnavailable` adds those back, for anything about
|
|
11640
|
+
* money an agent may still hold in one: withdrawals and activity.
|
|
11641
|
+
*/
|
|
11642
|
+
async loadVaultOptions(asset, { includeUnavailable = false } = {}) {
|
|
11643
|
+
const key2 = vaultOptionsKey(asset, includeUnavailable);
|
|
11644
|
+
const cached = this.vaultOptions.get(key2);
|
|
10816
11645
|
if (cached && cached.expiresAt > Date.now()) return cached.value;
|
|
10817
|
-
const pending2 = this.pendingVaultOptions.get(
|
|
11646
|
+
const pending2 = this.pendingVaultOptions.get(key2);
|
|
10818
11647
|
if (pending2) return pending2;
|
|
10819
11648
|
const metadata = YIELDSEEKER_ASSET_METADATA[asset];
|
|
10820
11649
|
const request2 = this.api.request(
|
|
10821
|
-
`/chains/8453/assets/${metadata.address}/vault-options`
|
|
11650
|
+
`/chains/8453/assets/${metadata.address}/vault-options${includeUnavailable ? "?shouldIncludeUnavailable=true" : ""}`
|
|
10822
11651
|
).then((response) => {
|
|
10823
11652
|
if (!Array.isArray(response?.vaultOptions)) {
|
|
10824
11653
|
throw this.invalidResponse("vault options");
|
|
10825
11654
|
}
|
|
10826
|
-
this.vaultOptions.set(
|
|
11655
|
+
this.vaultOptions.set(key2, {
|
|
10827
11656
|
expiresAt: Date.now() + YIELDSEEKER_VAULT_OPTIONS_CACHE_MS,
|
|
10828
11657
|
value: response.vaultOptions
|
|
10829
11658
|
});
|
|
10830
11659
|
return response.vaultOptions;
|
|
10831
|
-
}).finally(() => this.pendingVaultOptions.delete(
|
|
10832
|
-
this.pendingVaultOptions.set(
|
|
11660
|
+
}).finally(() => this.pendingVaultOptions.delete(key2));
|
|
11661
|
+
this.pendingVaultOptions.set(key2, request2);
|
|
10833
11662
|
return request2;
|
|
10834
11663
|
}
|
|
11664
|
+
/**
|
|
11665
|
+
* Save the user's Yieldseeker picks as the agent's managed vault list, then
|
|
11666
|
+
* read the rules back before any money moves. Each asset has its own agent,
|
|
11667
|
+
* so each is saved on its own. `pools` and `availablePools` hold vault
|
|
11668
|
+
* addresses.
|
|
11669
|
+
*
|
|
11670
|
+
* - Only Base entries are ours. An asset with no picks whose entries showed
|
|
11671
|
+
* no vault is skipped and nothing is sent.
|
|
11672
|
+
* - Some vaults picked: the managed list names them. Saving it again
|
|
11673
|
+
* replaces it, so there is only ever one.
|
|
11674
|
+
* - None picked (vaults shown): the managed list names no vault, and the
|
|
11675
|
+
* rules must read back as an empty allow-list. Yieldseeker then keeps the
|
|
11676
|
+
* agent's money out of every vault, as Zyfai does with an empty pool list,
|
|
11677
|
+
* and the next Pools step reads "none". Only an agent that already exists
|
|
11678
|
+
* is written: one is never created just to hold "none".
|
|
11679
|
+
* - Every vault picked: the managed list is deleted, and no allow-list may
|
|
11680
|
+
* remain, so vaults Yieldseeker adds later are allowed too.
|
|
11681
|
+
* - A free-text allow-list we saved before the managed list existed is
|
|
11682
|
+
* deleted once the new state is written. A failed delete does not fail the
|
|
11683
|
+
* save; it is debug-logged, and the read-back decides.
|
|
11684
|
+
* - A read-back that differs puts the previous managed list back (or deletes
|
|
11685
|
+
* the one just created) and throws POOL_SELECTION_NOT_APPLIED. If putting
|
|
11686
|
+
* it back fails too, that is still the error thrown. An old free-text list
|
|
11687
|
+
* already deleted is not put back.
|
|
11688
|
+
* - An agent already holding the most active memories, none of them ours,
|
|
11689
|
+
* throws POOL_SELECTION_RULE_LIMIT before anything is written.
|
|
11690
|
+
*
|
|
11691
|
+
* Always Base, whichever chain the wallet is connected on.
|
|
11692
|
+
*/
|
|
11693
|
+
async setPoolSelection(selection, state) {
|
|
11694
|
+
if (!state) {
|
|
11695
|
+
throw new OwneyError(
|
|
11696
|
+
"NOT_CONNECTED",
|
|
11697
|
+
"Connect a wallet before saving Yieldseeker pool picks.",
|
|
11698
|
+
void 0,
|
|
11699
|
+
this.id
|
|
11700
|
+
);
|
|
11701
|
+
}
|
|
11702
|
+
const byAsset = /* @__PURE__ */ new Map();
|
|
11703
|
+
for (const entry of selection.selections) {
|
|
11704
|
+
if (entry.chainId !== 8453) continue;
|
|
11705
|
+
this.assertAsset(entry.asset);
|
|
11706
|
+
const group = byAsset.get(entry.asset) ?? { picked: [], shown: [] };
|
|
11707
|
+
group.picked.push(...entry.pools);
|
|
11708
|
+
group.shown.push(...entry.availablePools);
|
|
11709
|
+
byAsset.set(entry.asset, group);
|
|
11710
|
+
}
|
|
11711
|
+
for (const [asset, group] of byAsset) {
|
|
11712
|
+
const picks = uniqueAddresses(group.picked);
|
|
11713
|
+
const shown = uniqueAddresses(group.shown);
|
|
11714
|
+
if (picks.length === 0 && shown.length === 0) continue;
|
|
11715
|
+
const picked = new Set(picks.map((address) => address.toLowerCase()));
|
|
11716
|
+
const everyVaultPicked = shown.length > 0 && shown.every((address) => picked.has(address.toLowerCase()));
|
|
11717
|
+
await this.savePoolPicks(state, asset, picks, everyVaultPicked);
|
|
11718
|
+
}
|
|
11719
|
+
}
|
|
11720
|
+
async savePoolPicks(state, asset, picks, everyVaultPicked) {
|
|
11721
|
+
const context = picks.length === 0 ? await this.findAgent(state, 8453, asset) : await this.ensureAgent(state, 8453, asset);
|
|
11722
|
+
if (!context) {
|
|
11723
|
+
debugLog("yieldseeker:pools", `${asset}: no agent yet, "no pools" not saved`);
|
|
11724
|
+
return;
|
|
11725
|
+
}
|
|
11726
|
+
const active = (await this.listMemories(state, context)).filter(isActiveMemory);
|
|
11727
|
+
const managed = active.find(isManagedVaultList);
|
|
11728
|
+
const legacy = active.filter(isLegacyPoolSelectionMemory);
|
|
11729
|
+
const writing = !everyVaultPicked;
|
|
11730
|
+
if (writing && !managed && active.length - legacy.length >= YIELDSEEKER_MAX_ACTIVE_MEMORIES) {
|
|
11731
|
+
throw new OwneyError(
|
|
11732
|
+
"POOL_SELECTION_RULE_LIMIT",
|
|
11733
|
+
`This Yieldseeker ${asset} agent already has ${active.length} active memories, the most it allows, so the pool selection could not be saved. Nothing was written.`,
|
|
11734
|
+
{ asset, activeMemories: active.length, limit: YIELDSEEKER_MAX_ACTIVE_MEMORIES },
|
|
11735
|
+
this.id
|
|
11736
|
+
);
|
|
11737
|
+
}
|
|
11738
|
+
const content = writing ? await this.poolMemoryContent(asset, picks) : void 0;
|
|
11739
|
+
const change = { previous: managed, written: false };
|
|
11740
|
+
if (content === void 0) {
|
|
11741
|
+
if (managed) {
|
|
11742
|
+
await this.memoryRequest(state, context, `memories/${managed.agentMemoryId}/delete`, {
|
|
11743
|
+
method: "POST"
|
|
11744
|
+
});
|
|
11745
|
+
change.written = true;
|
|
11746
|
+
}
|
|
11747
|
+
} else {
|
|
11748
|
+
const answer = await this.memoryRequest(state, context, "memories", {
|
|
11749
|
+
method: "POST",
|
|
11750
|
+
body: { content, managedRuleType: YIELDSEEKER_MANAGED_VAULT_RULE }
|
|
11751
|
+
});
|
|
11752
|
+
change.written = true;
|
|
11753
|
+
if (!managed && answer?.memory?.agentMemoryId) change.createdId = answer.memory.agentMemoryId;
|
|
11754
|
+
}
|
|
11755
|
+
await this.deleteLegacyPoolMemories(state, context, asset, legacy);
|
|
11756
|
+
let failure;
|
|
11757
|
+
try {
|
|
11758
|
+
const allowed = await this.readAllowList(state, context);
|
|
11759
|
+
const applied = content === void 0 ? allowed === void 0 : allowed !== void 0 && sameVaults(allowed, picks);
|
|
11760
|
+
if (!applied) failure = "ALLOW_LIST_MISMATCH";
|
|
11761
|
+
} catch {
|
|
11762
|
+
failure = "READ_BACK_FAILED";
|
|
11763
|
+
}
|
|
11764
|
+
if (!failure) return;
|
|
11765
|
+
const restored = await this.restorePoolMemory(state, context, change);
|
|
11766
|
+
throw new OwneyError(
|
|
11767
|
+
"POOL_SELECTION_NOT_APPLIED",
|
|
11768
|
+
`Yieldseeker did not apply the ${asset} pool selection (${failure}).${restored ? "" : " The previous selection could not be put back."} Nothing was funded.`,
|
|
11769
|
+
{ asset, reason: failure, restored },
|
|
11770
|
+
this.id
|
|
11771
|
+
);
|
|
11772
|
+
}
|
|
11773
|
+
/**
|
|
11774
|
+
* Delete the free-text allow-lists we saved before the managed list existed.
|
|
11775
|
+
* Never throws: a list left behind is caught by the read-back. Logs no
|
|
11776
|
+
* sign-in token.
|
|
11777
|
+
*/
|
|
11778
|
+
async deleteLegacyPoolMemories(state, context, asset, memories) {
|
|
11779
|
+
for (const memory2 of memories) {
|
|
11780
|
+
try {
|
|
11781
|
+
await this.memoryRequest(state, context, `memories/${memory2.agentMemoryId}/delete`, {
|
|
11782
|
+
method: "POST"
|
|
11783
|
+
});
|
|
11784
|
+
} catch (error) {
|
|
11785
|
+
debugLog("yieldseeker:pools", `${asset}: an old pool memory could not be deleted`, {
|
|
11786
|
+
memoryId: memory2.agentMemoryId,
|
|
11787
|
+
code: error instanceof OwneyError ? error.code : void 0,
|
|
11788
|
+
message: error instanceof Error ? error.message : void 0
|
|
11789
|
+
});
|
|
11790
|
+
}
|
|
11791
|
+
}
|
|
11792
|
+
}
|
|
11793
|
+
/**
|
|
11794
|
+
* `<address> (<name>)` for each pick, under the prefix. An unnamed address
|
|
11795
|
+
* has no brackets. No picks names no vault.
|
|
11796
|
+
*/
|
|
11797
|
+
async poolMemoryContent(asset, picks) {
|
|
11798
|
+
if (picks.length === 0) return YIELDSEEKER_NO_POOLS_CONTENT;
|
|
11799
|
+
const vaults = new Map(
|
|
11800
|
+
(await this.loadVaultOptions(asset)).map((vault) => [vault.address.toLowerCase(), vault])
|
|
11801
|
+
);
|
|
11802
|
+
const entries = picks.map((pick) => {
|
|
11803
|
+
const vault = vaults.get(pick.toLowerCase());
|
|
11804
|
+
const address = vault?.address ?? pick;
|
|
11805
|
+
return vault?.name ? `${address} (${vault.name})` : address;
|
|
11806
|
+
});
|
|
11807
|
+
return `${YIELDSEEKER_POOL_MEMORY_PREFIX} ${entries.join(", ")}.`;
|
|
11808
|
+
}
|
|
11809
|
+
/** Undo a failed save of the managed list. Never throws: the caller reports the save's own failure. */
|
|
11810
|
+
async restorePoolMemory(state, context, change) {
|
|
11811
|
+
if (!change.written) return true;
|
|
11812
|
+
try {
|
|
11813
|
+
if (change.previous) {
|
|
11814
|
+
await this.memoryRequest(state, context, "memories", {
|
|
11815
|
+
method: "POST",
|
|
11816
|
+
body: { content: change.previous.content, managedRuleType: YIELDSEEKER_MANAGED_VAULT_RULE }
|
|
11817
|
+
});
|
|
11818
|
+
return true;
|
|
11819
|
+
}
|
|
11820
|
+
const ids = change.createdId ? [change.createdId] : (await this.listMemories(state, context)).filter((memory2) => isActiveMemory(memory2) && isManagedVaultList(memory2)).map((memory2) => memory2.agentMemoryId);
|
|
11821
|
+
for (const id of ids) {
|
|
11822
|
+
await this.memoryRequest(state, context, `memories/${id}/delete`, { method: "POST" });
|
|
11823
|
+
}
|
|
11824
|
+
return true;
|
|
11825
|
+
} catch {
|
|
11826
|
+
return false;
|
|
11827
|
+
}
|
|
11828
|
+
}
|
|
11829
|
+
/**
|
|
11830
|
+
* What the user's Yieldseeker agents currently allow, as `SavedPoolSelection`
|
|
11831
|
+
* pairs: the allowed vault addresses under the provider each belongs to, for
|
|
11832
|
+
* the vaults a new agent can use. An agent with no allow-list adds nothing,
|
|
11833
|
+
* and no pairs at all means every shown vault is on. Reads never create an
|
|
11834
|
+
* agent, and always read Base. A read that fails throws, because "no
|
|
11835
|
+
* allow-list" would wrongly mean "everything".
|
|
11836
|
+
*
|
|
11837
|
+
* An allow-list naming none of the listed vaults (the saved "none", or vaults
|
|
11838
|
+
* Yieldseeker has since stopped listing) leaves the agent nowhere to go, so
|
|
11839
|
+
* it reports none chosen for its asset: a pair with empty `pools` for every
|
|
11840
|
+
* provider listing vaults for it. With no vault listed at all there is
|
|
11841
|
+
* nothing to name that by, and it throws: the rules still restrict the agent.
|
|
11842
|
+
*
|
|
11843
|
+
* `pairs` is accepted for the contract but does not trim the answer: cutting
|
|
11844
|
+
* a real allow-list down to the pairs asked about could leave none, and none
|
|
11845
|
+
* reads as every vault on.
|
|
11846
|
+
*/
|
|
11847
|
+
async getPoolSelection(state, _chainId, params) {
|
|
11848
|
+
const byProvider = /* @__PURE__ */ new Map();
|
|
11849
|
+
for (const asset of new Set(params.assets)) {
|
|
11850
|
+
this.assertAsset(asset);
|
|
11851
|
+
const context = await this.findAgent(state, 8453, asset);
|
|
11852
|
+
if (!context) continue;
|
|
11853
|
+
const allowed = await this.readAllowList(state, context);
|
|
11854
|
+
if (allowed === void 0) continue;
|
|
11855
|
+
const options = await this.loadVaultOptions(asset);
|
|
11856
|
+
if (options.length === 0) {
|
|
11857
|
+
throw this.invalidResponse("pool selection", {
|
|
11858
|
+
reason: "vault-options lists no vault while an allow-list restricts the agent.",
|
|
11859
|
+
asset
|
|
11860
|
+
});
|
|
11861
|
+
}
|
|
11862
|
+
const vaults = new Map(options.map((vault) => [vault.address.toLowerCase(), vault]));
|
|
11863
|
+
const known = allowed.flatMap((address) => vaults.get(address.toLowerCase()) ?? []);
|
|
11864
|
+
if (known.length === 0) {
|
|
11865
|
+
for (const vault of options) {
|
|
11866
|
+
if (!byProvider.has(vault.provider)) byProvider.set(vault.provider, []);
|
|
11867
|
+
}
|
|
11868
|
+
continue;
|
|
11869
|
+
}
|
|
11870
|
+
for (const vault of known) {
|
|
11871
|
+
const pools = byProvider.get(vault.provider) ?? [];
|
|
11872
|
+
byProvider.set(vault.provider, uniqueAddresses([...pools, vault.address]));
|
|
11873
|
+
}
|
|
11874
|
+
}
|
|
11875
|
+
return {
|
|
11876
|
+
strategies: [],
|
|
11877
|
+
pairs: [...byProvider].map(([protocolId, pools]) => ({ protocolId, chainId: 8453, pools }))
|
|
11878
|
+
};
|
|
11879
|
+
}
|
|
11880
|
+
/**
|
|
11881
|
+
* The allow-list in the agent's rules: every `allowedVaultAddresses` on an
|
|
11882
|
+
* `ignored_vault` user rule. Undefined when no rule has one, which allows
|
|
11883
|
+
* every vault; an empty list allows none. A response that does not have the
|
|
11884
|
+
* expected shape throws rather than reading as no allow-list.
|
|
11885
|
+
*/
|
|
11886
|
+
async readAllowList(state, context) {
|
|
11887
|
+
const rules = await this.memoryRequest(
|
|
11888
|
+
state,
|
|
11889
|
+
context,
|
|
11890
|
+
"memories/effective-rules"
|
|
11891
|
+
);
|
|
11892
|
+
if (!Array.isArray(rules?.userRules)) throw this.invalidResponse("effective rules");
|
|
11893
|
+
let allowed;
|
|
11894
|
+
for (const rule of rules.userRules) {
|
|
11895
|
+
if (rule?.ruleType !== "ignored_vault") continue;
|
|
11896
|
+
const list = rule.ruleConfig?.allowedVaultAddresses;
|
|
11897
|
+
if (list === void 0 || list === null) continue;
|
|
11898
|
+
if (!Array.isArray(list) || list.some((address) => typeof address !== "string")) {
|
|
11899
|
+
throw this.invalidResponse("effective rules");
|
|
11900
|
+
}
|
|
11901
|
+
allowed = [...allowed ?? [], ...list];
|
|
11902
|
+
}
|
|
11903
|
+
return allowed;
|
|
11904
|
+
}
|
|
11905
|
+
async listMemories(state, context) {
|
|
11906
|
+
const response = await this.memoryRequest(state, context, "memories");
|
|
11907
|
+
if (!Array.isArray(response?.memories)) throw this.invalidResponse("memories");
|
|
11908
|
+
return response.memories;
|
|
11909
|
+
}
|
|
11910
|
+
/** A memory call for an agent, on Base whichever chain the wallet is on. */
|
|
11911
|
+
async memoryRequest(state, context, suffix, options = {}) {
|
|
11912
|
+
try {
|
|
11913
|
+
return await this.providerRequest(state, 8453, this.agentPath(context, suffix), options);
|
|
11914
|
+
} catch (error) {
|
|
11915
|
+
if (error instanceof OwneyError) throw error;
|
|
11916
|
+
throw this.mapRequestFailure(error);
|
|
11917
|
+
}
|
|
11918
|
+
}
|
|
10835
11919
|
userKey(state, chainId) {
|
|
10836
11920
|
return `${state.walletAddress.toLowerCase()}:${chainId}`;
|
|
10837
11921
|
}
|
|
@@ -10884,6 +11968,7 @@ var YieldseekerAgent = class {
|
|
|
10884
11968
|
this.agentContexts.set(slot, context);
|
|
10885
11969
|
this.pendingSlotInvalidations.delete(slot);
|
|
10886
11970
|
this.missingSlots.delete(slot);
|
|
11971
|
+
this.closedSlots.delete(slot);
|
|
10887
11972
|
}
|
|
10888
11973
|
assertSession(generation, chainId, asset) {
|
|
10889
11974
|
if (this.readGeneration !== generation) {
|
|
@@ -10995,8 +12080,10 @@ var YieldseekerAgent = class {
|
|
|
10995
12080
|
* highest-priority set of `priorities` (index 0 first). Hinted agentIds are
|
|
10996
12081
|
* resolved first and a hinted top-priority match ends the search; then other
|
|
10997
12082
|
* listed agents, at most YIELDSEEKER_WALLET_MATCH_LIMIT wallets in total.
|
|
12083
|
+
* A candidate whose wallet shows it closed (deactivated) never ranks, and its
|
|
12084
|
+
* agentId is added to `closed`.
|
|
10998
12085
|
*/
|
|
10999
|
-
async agentWithWallet(state, chainId, user, agents, asset, priorities, hints) {
|
|
12086
|
+
async agentWithWallet(state, chainId, user, agents, asset, priorities, hints, closed) {
|
|
11000
12087
|
const fitting = /* @__PURE__ */ new Map();
|
|
11001
12088
|
for (const agent of agents) {
|
|
11002
12089
|
if (this.agentFits(agent, chainId, asset) && !fitting.has(agent.agentId)) fitting.set(agent.agentId, agent);
|
|
@@ -11018,6 +12105,10 @@ var YieldseekerAgent = class {
|
|
|
11018
12105
|
failure ??= { error: result.reason };
|
|
11019
12106
|
continue;
|
|
11020
12107
|
}
|
|
12108
|
+
if (result.value.wallet.deactivatedDate) {
|
|
12109
|
+
closed?.add(result.value.agent.agentId);
|
|
12110
|
+
continue;
|
|
12111
|
+
}
|
|
11021
12112
|
const wallet = result.value.wallet.walletAddress.toLowerCase();
|
|
11022
12113
|
const rank = priorities.findIndex((wallets) => wallets.has(wallet));
|
|
11023
12114
|
if (rank >= 0 && (!best || rank < best.rank)) best = { rank, agent: result.value.agent };
|
|
@@ -11032,32 +12123,213 @@ var YieldseekerAgent = class {
|
|
|
11032
12123
|
}
|
|
11033
12124
|
/**
|
|
11034
12125
|
* chooseAgent, re-reading a cached list once (bypassing its cache) when the
|
|
11035
|
-
* verified agent is missing.
|
|
11036
|
-
*
|
|
11037
|
-
* list
|
|
12126
|
+
* verified agent is missing. Still missing, Yieldseeker may have closed
|
|
12127
|
+
* (deactivated) it: the verified record's agent is reactivated and selected
|
|
12128
|
+
* from a fresh list, by the verified wallet only (never created). A slot
|
|
12129
|
+
* that still fails is remembered with its error for the list cache window,
|
|
12130
|
+
* so later reads fail without another re-read or reactivate. A slot
|
|
12131
|
+
* Yieldseeker will not reopen because of its active-agent limit throws
|
|
12132
|
+
* YIELDSEEKER_SLOT_UNAVAILABLE, here and for the rest of the session, with
|
|
12133
|
+
* no request.
|
|
11038
12134
|
*/
|
|
11039
12135
|
async chooseAgentRefreshing(state, chainId, user, agents, accounts, asset) {
|
|
12136
|
+
this.throwIfSlotUnavailable(state, chainId, asset);
|
|
11040
12137
|
try {
|
|
11041
12138
|
return await this.chooseAgent(state, chainId, user, agents, accounts, asset);
|
|
11042
12139
|
} catch (error) {
|
|
11043
12140
|
if (!this.isAgentMissing(error)) throw error;
|
|
11044
12141
|
const slot = this.slotKey(state, chainId, asset);
|
|
11045
|
-
|
|
12142
|
+
this.throwIfSlotMissing(slot);
|
|
11046
12143
|
const generation = this.readGeneration;
|
|
11047
12144
|
const fresh = await this.listAgents(state, chainId, user, true);
|
|
11048
12145
|
this.assertSession(generation, chainId, asset);
|
|
12146
|
+
let missing;
|
|
11049
12147
|
try {
|
|
11050
12148
|
return await this.chooseAgent(state, chainId, user, fresh, accounts, asset);
|
|
11051
12149
|
} catch (retryError) {
|
|
11052
|
-
if (this.isAgentMissing(retryError)
|
|
11053
|
-
|
|
12150
|
+
if (!this.isAgentMissing(retryError)) throw retryError;
|
|
12151
|
+
missing = retryError;
|
|
12152
|
+
}
|
|
12153
|
+
const verified = this.slotAccounts(accounts, chainId, asset).find((account) => account.status === "verified");
|
|
12154
|
+
const agentId = verified?.providerAgentId;
|
|
12155
|
+
if (!verified || !agentId) {
|
|
12156
|
+
this.rememberMissingSlot(slot, generation, missing);
|
|
12157
|
+
throw missing;
|
|
12158
|
+
}
|
|
12159
|
+
this.throwIfSlotMissing(slot);
|
|
12160
|
+
let reopened;
|
|
12161
|
+
try {
|
|
12162
|
+
reopened = await this.reopenAgent(state, chainId, user, asset, agentId);
|
|
12163
|
+
this.assertSession(generation, chainId, asset);
|
|
12164
|
+
} catch (reopenError) {
|
|
12165
|
+
this.rememberMissingSlot(slot, generation, reopenError);
|
|
12166
|
+
throw reopenError;
|
|
12167
|
+
}
|
|
12168
|
+
try {
|
|
12169
|
+
const agent = await this.agentWithWallet(
|
|
12170
|
+
state,
|
|
12171
|
+
chainId,
|
|
12172
|
+
user,
|
|
12173
|
+
reopened,
|
|
12174
|
+
asset,
|
|
12175
|
+
[/* @__PURE__ */ new Set([verified.agentWallet.toLowerCase()])],
|
|
12176
|
+
[agentId]
|
|
12177
|
+
);
|
|
12178
|
+
if (agent) return agent;
|
|
12179
|
+
throw this.agentMissing(chainId, asset, agentId);
|
|
12180
|
+
} catch (reopenedError) {
|
|
12181
|
+
if (this.isAgentMissing(reopenedError)) this.rememberMissingSlot(slot, generation, reopenedError);
|
|
12182
|
+
throw reopenedError;
|
|
12183
|
+
}
|
|
12184
|
+
}
|
|
12185
|
+
}
|
|
12186
|
+
throwIfSlotUnavailable(state, chainId, asset) {
|
|
12187
|
+
const providerCode = this.unavailableSlots.get(this.slotKey(state, chainId, asset));
|
|
12188
|
+
if (providerCode !== void 0) throw this.slotUnavailable(chainId, asset, providerCode);
|
|
12189
|
+
}
|
|
12190
|
+
/**
|
|
12191
|
+
* Rethrow the error a slot's lookup failed with while the slot is still
|
|
12192
|
+
* marked, or for the session when Yieldseeker will never reopen its agent.
|
|
12193
|
+
* A remembered rate limit is rethrown with the time left on its marker as
|
|
12194
|
+
* its retry delay (`retryAfterSeconds`): no new attempt is made before then,
|
|
12195
|
+
* so a caller that waits it out retries once instead of every few seconds.
|
|
12196
|
+
*/
|
|
12197
|
+
throwIfSlotMissing(slot) {
|
|
12198
|
+
const closed = this.closedSlots.get(slot);
|
|
12199
|
+
if (closed) throw closed;
|
|
12200
|
+
const missing = this.missingSlots.get(slot);
|
|
12201
|
+
if (!missing || missing.until <= Date.now()) return;
|
|
12202
|
+
const { error } = missing;
|
|
12203
|
+
if (!(error instanceof OwneyError) || rateLimitDelay(error) === void 0) throw error;
|
|
12204
|
+
const prefix = error.agentId ? `[${error.code}][agent:${error.agentId}] ` : `[${error.code}] `;
|
|
12205
|
+
const rethrown = new OwneyError(
|
|
12206
|
+
error.code,
|
|
12207
|
+
error.message.startsWith(prefix) ? error.message.slice(prefix.length) : error.message,
|
|
12208
|
+
{ ...error.details, retryAfterSeconds: Math.ceil((missing.until - Date.now()) / 1e3) },
|
|
12209
|
+
error.agentId
|
|
12210
|
+
);
|
|
12211
|
+
this.rethrownSlotFailures.set(rethrown, error);
|
|
12212
|
+
throw rethrown;
|
|
12213
|
+
}
|
|
12214
|
+
/**
|
|
12215
|
+
* Remember a slot's failed lookup or reactivate for the list-cache window.
|
|
12216
|
+
* A sign-in failure is not remembered (the wallet's rejection,
|
|
12217
|
+
* AGENT_AUTH_FAILED, NOT_CONNECTED): it says nothing about the slot, and
|
|
12218
|
+
* remembered it would refuse the next sign-in, even one the user starts,
|
|
12219
|
+
* with no request for the whole window.
|
|
12220
|
+
*/
|
|
12221
|
+
rememberMissingSlot(slot, generation, error) {
|
|
12222
|
+
if (this.readGeneration !== generation) return;
|
|
12223
|
+
if (isWalletRejection(error) || error instanceof OwneyError && (error.code === "AGENT_AUTH_FAILED" || error.code === "NOT_CONNECTED")) return;
|
|
12224
|
+
this.missingSlots.set(slot, { until: Date.now() + YIELDSEEKER_AGENT_LIST_CACHE_MS, error });
|
|
12225
|
+
}
|
|
12226
|
+
/**
|
|
12227
|
+
* Reactivate the slot's verified agent, then read the list bypassing its
|
|
12228
|
+
* cache, with a read sent after the reactivate answered. Concurrent lookups
|
|
12229
|
+
* of one slot share one reopen. Resolves to the fresh list. At the
|
|
12230
|
+
* active-agent limit the slot is recorded unavailable and this throws
|
|
12231
|
+
* YIELDSEEKER_SLOT_UNAVAILABLE.
|
|
12232
|
+
*/
|
|
12233
|
+
reopenAgent(state, chainId, user, asset, agentId) {
|
|
12234
|
+
const slot = this.slotKey(state, chainId, asset);
|
|
12235
|
+
const pending2 = this.pendingReopens.get(slot);
|
|
12236
|
+
if (pending2) return pending2;
|
|
12237
|
+
const generation = this.readGeneration;
|
|
12238
|
+
const request2 = (async () => {
|
|
12239
|
+
const result = await this.reactivateSlot(state, chainId, user, asset, agentId);
|
|
12240
|
+
this.assertSession(generation, chainId, asset);
|
|
12241
|
+
if (result.outcome === "limit") throw this.slotUnavailable(chainId, asset, result.providerCode);
|
|
12242
|
+
this.forgetAgentWallet(agentId);
|
|
12243
|
+
this.missingSlots.delete(slot);
|
|
12244
|
+
await this.freshListReads.get(this.agentListKey(state, chainId))?.catch(() => void 0);
|
|
12245
|
+
this.assertSession(generation, chainId, asset);
|
|
12246
|
+
const fresh = await this.listAgents(state, chainId, user, true);
|
|
12247
|
+
this.assertSession(generation, chainId, asset);
|
|
12248
|
+
return fresh;
|
|
12249
|
+
})().finally(() => {
|
|
12250
|
+
if (this.pendingReopens.get(slot) === request2) this.pendingReopens.delete(slot);
|
|
12251
|
+
});
|
|
12252
|
+
this.pendingReopens.set(slot, request2);
|
|
12253
|
+
return request2;
|
|
12254
|
+
}
|
|
12255
|
+
/**
|
|
12256
|
+
* The one way to reactivate a slot's agent, for the slot lookup (reopenAgent)
|
|
12257
|
+
* and the pre-deposit check (assertAgentOpen), so a slot costs at most one
|
|
12258
|
+
* reactivate per list-cache window:
|
|
12259
|
+
* - a slot recorded unavailable (the limit) answers "limit" with no request;
|
|
12260
|
+
* - concurrent callers share one request;
|
|
12261
|
+
* - a failed reactivate (closed code, rate limit, timeout, 5xx...) is
|
|
12262
|
+
* remembered as the slot's failure for the list-cache window (missingSlots)
|
|
12263
|
+
* and rethrown to later callers with no request; a closed code
|
|
12264
|
+
* (closedSlots) for the session; a sign-in failure is not remembered;
|
|
12265
|
+
* - the limit is recorded in unavailableSlots only while the session is
|
|
12266
|
+
* unchanged, so a disconnect during the request is not undone by its late
|
|
12267
|
+
* answer.
|
|
12268
|
+
*/
|
|
12269
|
+
async reactivateSlot(state, chainId, user, asset, agentId) {
|
|
12270
|
+
const slot = this.slotKey(state, chainId, asset);
|
|
12271
|
+
const limit = this.unavailableSlots.get(slot);
|
|
12272
|
+
if (limit !== void 0) return { outcome: "limit", providerCode: limit };
|
|
12273
|
+
const key2 = `${slot}:${agentId}`;
|
|
12274
|
+
const pending2 = this.pendingReactivates.get(key2);
|
|
12275
|
+
if (pending2) return pending2;
|
|
12276
|
+
this.throwIfSlotMissing(slot);
|
|
12277
|
+
const generation = this.readGeneration;
|
|
12278
|
+
const request2 = (async () => {
|
|
12279
|
+
try {
|
|
12280
|
+
const result = await this.reactivateAgent(state, chainId, user, asset, agentId);
|
|
12281
|
+
if (result.outcome === "limit" && this.readGeneration === generation) {
|
|
12282
|
+
this.unavailableSlots.set(slot, result.providerCode);
|
|
11054
12283
|
}
|
|
11055
|
-
|
|
12284
|
+
return result;
|
|
12285
|
+
} catch (error) {
|
|
12286
|
+
if (this.readGeneration === generation && error instanceof OwneyError && error.code === "YIELDSEEKER_AGENT_CLOSED" && typeof error.details?.providerCode === "string" && YIELDSEEKER_REACTIVATE_CLOSED_CODES.has(error.details.providerCode)) {
|
|
12287
|
+
this.closedSlots.set(slot, error);
|
|
12288
|
+
}
|
|
12289
|
+
this.rememberMissingSlot(slot, generation, error);
|
|
12290
|
+
throw error;
|
|
12291
|
+
}
|
|
12292
|
+
})().finally(() => {
|
|
12293
|
+
if (this.pendingReactivates.get(key2) === request2) this.pendingReactivates.delete(key2);
|
|
12294
|
+
});
|
|
12295
|
+
this.pendingReactivates.set(key2, request2);
|
|
12296
|
+
return request2;
|
|
12297
|
+
}
|
|
12298
|
+
/**
|
|
12299
|
+
* Ask Yieldseeker to reopen a closed (deactivated) agent, with the user's
|
|
12300
|
+
* Yieldseeker sign-in. AGENT_NOT_DEACTIVATED (already open, e.g. reopened
|
|
12301
|
+
* by another tab) counts as reopened; the active-agent limit is an outcome,
|
|
12302
|
+
* not an error. An agent that cannot come back throws
|
|
12303
|
+
* YIELDSEEKER_AGENT_CLOSED; any other failure (rate limit, timeout, network,
|
|
12304
|
+
* 5xx, an unknown code) throws the mapped API error.
|
|
12305
|
+
*/
|
|
12306
|
+
async reactivateAgent(state, chainId, user, asset, agentId) {
|
|
12307
|
+
try {
|
|
12308
|
+
await this.providerRequest(
|
|
12309
|
+
state,
|
|
12310
|
+
chainId,
|
|
12311
|
+
`/users/${user.userId}/agents/${encodeURIComponent(agentId)}/reactivate`,
|
|
12312
|
+
{ method: "POST", body: {} }
|
|
12313
|
+
);
|
|
12314
|
+
return { outcome: "reopened" };
|
|
12315
|
+
} catch (error) {
|
|
12316
|
+
if (error instanceof OwneyError) throw error;
|
|
12317
|
+
const providerCode = error instanceof YieldseekerApiError ? error.providerCode : void 0;
|
|
12318
|
+
if (providerCode === "AGENT_NOT_DEACTIVATED") return { outcome: "reopened" };
|
|
12319
|
+
if (providerCode !== void 0 && YIELDSEEKER_REACTIVATE_LIMIT_CODES.has(providerCode)) {
|
|
12320
|
+
return { outcome: "limit", providerCode };
|
|
12321
|
+
}
|
|
12322
|
+
if (providerCode !== void 0 && YIELDSEEKER_REACTIVATE_CLOSED_CODES.has(providerCode)) {
|
|
12323
|
+
throw this.agentClosed(chainId, asset, agentId, providerCode);
|
|
11056
12324
|
}
|
|
12325
|
+
throw this.mapRequestFailure(error);
|
|
11057
12326
|
}
|
|
11058
12327
|
}
|
|
11059
|
-
|
|
11060
|
-
|
|
12328
|
+
/** Drop the cached and in-flight wallet contexts of one agent, in every slot. */
|
|
12329
|
+
forgetAgentWallet(agentId) {
|
|
12330
|
+
const ofAgent = (key2) => key2.split(":").slice(3).join(":") === agentId;
|
|
12331
|
+
for (const key2 of [...this.walletContexts.keys()]) if (ofAgent(key2)) this.walletContexts.delete(key2);
|
|
12332
|
+
for (const key2 of [...this.pendingWalletContexts.keys()]) if (ofAgent(key2)) this.pendingWalletContexts.delete(key2);
|
|
11061
12333
|
}
|
|
11062
12334
|
/**
|
|
11063
12335
|
* The agent that serves deposits and withdrawals for a slot (Ruling 23):
|
|
@@ -11065,7 +12337,8 @@ var YieldseekerAgent = class {
|
|
|
11065
12337
|
* whatever its name; the stored agentId is only a hint;
|
|
11066
12338
|
* 2. else a listed fitting agent whose wallet is a superseded account's wallet;
|
|
11067
12339
|
* 3. else the fitting agent named "owney" (first use, migration, or a
|
|
11068
|
-
* verified wallet that is not a fitting listed agent)
|
|
12340
|
+
* verified wallet that is not a fitting listed agent), unless step 1/2
|
|
12341
|
+
* read its wallet and it is closed (deactivated): that agent is not listed;
|
|
11069
12342
|
* 4. else, with a verified account, throw YIELDSEEKER_AGENT_MISSING (never
|
|
11070
12343
|
* create); without one, undefined (the caller may create).
|
|
11071
12344
|
* Steps 1 and 2 share one search of at most YIELDSEEKER_WALLET_MATCH_LIMIT
|
|
@@ -11076,6 +12349,7 @@ var YieldseekerAgent = class {
|
|
|
11076
12349
|
const slot = this.slotAccounts(accounts, chainId, asset);
|
|
11077
12350
|
const verified = slot.find((account) => account.status === "verified");
|
|
11078
12351
|
const superseded = slot.filter((account) => account.status === "superseded");
|
|
12352
|
+
const closed = /* @__PURE__ */ new Set();
|
|
11079
12353
|
if (verified || superseded.length) {
|
|
11080
12354
|
const priorities = [];
|
|
11081
12355
|
if (verified) priorities.push(/* @__PURE__ */ new Set([verified.agentWallet.toLowerCase()]));
|
|
@@ -11089,11 +12363,12 @@ var YieldseekerAgent = class {
|
|
|
11089
12363
|
agents,
|
|
11090
12364
|
asset,
|
|
11091
12365
|
priorities,
|
|
11092
|
-
[verified?.providerAgentId, ...superseded.map((account) => account.providerAgentId)]
|
|
12366
|
+
[verified?.providerAgentId, ...superseded.map((account) => account.providerAgentId)],
|
|
12367
|
+
closed
|
|
11093
12368
|
);
|
|
11094
12369
|
if (match) return match;
|
|
11095
12370
|
}
|
|
11096
|
-
const named = agents.find((agent) => this.isOwneyAgent(agent) && this.agentFits(agent, chainId, asset));
|
|
12371
|
+
const named = agents.find((agent) => this.isOwneyAgent(agent) && this.agentFits(agent, chainId, asset) && !closed.has(agent.agentId));
|
|
11097
12372
|
if (named) return named;
|
|
11098
12373
|
if (verified) throw this.agentMissing(chainId, asset, verified.providerAgentId);
|
|
11099
12374
|
return void 0;
|
|
@@ -11109,6 +12384,39 @@ var YieldseekerAgent = class {
|
|
|
11109
12384
|
this.id
|
|
11110
12385
|
);
|
|
11111
12386
|
}
|
|
12387
|
+
slotUnavailable(chainId, asset, providerCode) {
|
|
12388
|
+
return new OwneyError(
|
|
12389
|
+
"YIELDSEEKER_SLOT_UNAVAILABLE",
|
|
12390
|
+
`Yieldseeker has no ${asset} agent for this account this session: it will not reopen the closed agent (${providerCode}).`,
|
|
12391
|
+
{ rpcSource: "agent-api", chainId, asset, providerCode },
|
|
12392
|
+
this.id
|
|
12393
|
+
);
|
|
12394
|
+
}
|
|
12395
|
+
/** The slot has no usable agent: missing, at Yieldseeker's agent limit, or closed for good. */
|
|
12396
|
+
isSlotEmpty(error) {
|
|
12397
|
+
return error instanceof OwneyError && (error.code === "YIELDSEEKER_AGENT_MISSING" || error.code === "YIELDSEEKER_SLOT_UNAVAILABLE" || error.code === "YIELDSEEKER_AGENT_CLOSED");
|
|
12398
|
+
}
|
|
12399
|
+
/**
|
|
12400
|
+
* The slot's lookup failed through the missing-agent / reopen path and was
|
|
12401
|
+
* remembered with this very error, even a transient one (429, 5xx, timeout),
|
|
12402
|
+
* or with the copy of it a remembered rate limit is rethrown as. Compares
|
|
12403
|
+
* the remembered error, not its expiry, so it holds however long the rest
|
|
12404
|
+
* of the read takes.
|
|
12405
|
+
*/
|
|
12406
|
+
isMarkedSlotFailure(slot, error) {
|
|
12407
|
+
const marker = this.missingSlots.get(slot);
|
|
12408
|
+
if (!marker) return false;
|
|
12409
|
+
return marker.error === error || typeof error === "object" && error !== null && this.rethrownSlotFailures.get(error) === marker.error;
|
|
12410
|
+
}
|
|
12411
|
+
/** providerCode is absent when Yieldseeker named none (the agent stayed closed after a reopen). */
|
|
12412
|
+
agentClosed(chainId, asset, agentId, providerCode, extra) {
|
|
12413
|
+
return new OwneyError(
|
|
12414
|
+
"YIELDSEEKER_AGENT_CLOSED",
|
|
12415
|
+
`Yieldseeker closed the ${asset} agent for this account and it cannot be reopened${providerCode ? ` (${providerCode})` : ""}.`,
|
|
12416
|
+
{ rpcSource: "agent-api", chainId, asset, agentId, ...providerCode ? { providerCode } : {}, ...extra },
|
|
12417
|
+
this.id
|
|
12418
|
+
);
|
|
12419
|
+
}
|
|
11112
12420
|
/**
|
|
11113
12421
|
* Fire-and-forget: record which agent serves this slot. Never awaited on the
|
|
11114
12422
|
* funds path and never throws; once per agent wallet and deployment state
|
|
@@ -11198,7 +12506,7 @@ var YieldseekerAgent = class {
|
|
|
11198
12506
|
} catch (error) {
|
|
11199
12507
|
if (!(error instanceof YieldseekerApiError) || error.providerCode !== "NO_USER") {
|
|
11200
12508
|
if (error instanceof OwneyError) throw error;
|
|
11201
|
-
throw this.
|
|
12509
|
+
throw this.mapRequestFailure(error);
|
|
11202
12510
|
}
|
|
11203
12511
|
let created;
|
|
11204
12512
|
for (let attempt = 0; attempt < YIELDSEEKER_USERNAME_CREATE_ATTEMPTS; attempt += 1) {
|
|
@@ -11219,7 +12527,7 @@ var YieldseekerAgent = class {
|
|
|
11219
12527
|
} catch (createError) {
|
|
11220
12528
|
const canRetry = isUsernameConflict(createError) && attempt + 1 < YIELDSEEKER_USERNAME_CREATE_ATTEMPTS;
|
|
11221
12529
|
if (canRetry) continue;
|
|
11222
|
-
throw this.
|
|
12530
|
+
throw this.mapRequestFailure(createError);
|
|
11223
12531
|
}
|
|
11224
12532
|
}
|
|
11225
12533
|
user = created?.user ?? null;
|
|
@@ -11276,6 +12584,7 @@ var YieldseekerAgent = class {
|
|
|
11276
12584
|
return context;
|
|
11277
12585
|
}
|
|
11278
12586
|
async resolveAgent(state, chainId, asset, createIfMissing) {
|
|
12587
|
+
this.throwIfSlotUnavailable(state, chainId, asset);
|
|
11279
12588
|
const generation = this.readGeneration;
|
|
11280
12589
|
const accountsRead = this.agentAccounts(state, chainId);
|
|
11281
12590
|
const user = await this.resolveUser(state, chainId);
|
|
@@ -11318,7 +12627,7 @@ var YieldseekerAgent = class {
|
|
|
11318
12627
|
);
|
|
11319
12628
|
} catch (error) {
|
|
11320
12629
|
const conflict = error instanceof YieldseekerApiError && error.status === 409 && error.routing && YIELDSEEKER_CREATE_CONFLICT_CODES.has(error.routing.code) ? error.routing : void 0;
|
|
11321
|
-
if (!conflict) throw this.
|
|
12630
|
+
if (!conflict) throw this.mapRequestFailure(error);
|
|
11322
12631
|
this.assertSession(generation, chainId, asset);
|
|
11323
12632
|
return this.adoptConflictingAgent(
|
|
11324
12633
|
state,
|
|
@@ -11411,10 +12720,11 @@ var YieldseekerAgent = class {
|
|
|
11411
12720
|
const agent = await this.chooseAgentRefreshing(state, chainId, user, agents, accounts, asset);
|
|
11412
12721
|
if (agent) selected.set(asset, agent);
|
|
11413
12722
|
} catch (error) {
|
|
11414
|
-
if (assetFilter
|
|
12723
|
+
if (assetFilter) throw error;
|
|
12724
|
+
if (!this.isSlotEmpty(error) && !this.isMarkedSlotFailure(this.slotKey(state, chainId, asset), error)) throw error;
|
|
11415
12725
|
missing.push(error);
|
|
11416
12726
|
missingAssets?.add(asset);
|
|
11417
|
-
console.warn(`[owney-sdk] Yieldseeker ${asset} agent is
|
|
12727
|
+
console.warn(`[owney-sdk] Yieldseeker ${asset} agent is unavailable:`, error);
|
|
11418
12728
|
}
|
|
11419
12729
|
}));
|
|
11420
12730
|
this.assertSession(generation, chainId);
|
|
@@ -12049,6 +13359,7 @@ var YieldseekerAgent = class {
|
|
|
12049
13359
|
try {
|
|
12050
13360
|
return await this.providerRequest(state, chainId, path, options);
|
|
12051
13361
|
} catch (error) {
|
|
13362
|
+
if (isWalletRejection(error)) throw error;
|
|
12052
13363
|
const mapped = this.mapApiError(error);
|
|
12053
13364
|
const delay = read2 ? rateLimitDelay(mapped) : void 0;
|
|
12054
13365
|
if (delay !== void 0 && this.readGeneration === generation) {
|
|
@@ -12072,8 +13383,9 @@ var YieldseekerAgent = class {
|
|
|
12072
13383
|
options.assertCurrent?.();
|
|
12073
13384
|
return this.api.request(path, { method: options.method, body: options.body, signature: signature2 });
|
|
12074
13385
|
};
|
|
12075
|
-
const
|
|
12076
|
-
|
|
13386
|
+
const promptless = options.promptless || state.promptless === true;
|
|
13387
|
+
const cached = promptless ? this.auth.peekToken(state, chainId) : void 0;
|
|
13388
|
+
if (promptless && !cached)
|
|
12077
13389
|
throw new OwneyError(
|
|
12078
13390
|
"AGENT_AUTH_FAILED",
|
|
12079
13391
|
"No Yieldseeker sign-in is available without a prompt.",
|
|
@@ -12087,7 +13399,10 @@ var YieldseekerAgent = class {
|
|
|
12087
13399
|
if (!(error instanceof YieldseekerApiError)) throw error;
|
|
12088
13400
|
if (error.providerCode === "NO_USER") throw error;
|
|
12089
13401
|
if (!error.isAuthenticationError) throw error;
|
|
12090
|
-
if (
|
|
13402
|
+
if (promptless) {
|
|
13403
|
+
this.auth.discardToken(state, chainId, signature);
|
|
13404
|
+
throw error;
|
|
13405
|
+
}
|
|
12091
13406
|
signature = await this.auth.refreshToken(state, chainId, signature);
|
|
12092
13407
|
try {
|
|
12093
13408
|
return await request2(signature);
|
|
@@ -12099,6 +13414,16 @@ var YieldseekerAgent = class {
|
|
|
12099
13414
|
}
|
|
12100
13415
|
}
|
|
12101
13416
|
}
|
|
13417
|
+
/**
|
|
13418
|
+
* mapApiError for a request that may have opened the Yieldseeker sign-in
|
|
13419
|
+
* prompt (providerRequest signs when no sign-in is saved, and again when
|
|
13420
|
+
* Yieldseeker refuses one). The wallet's rejection, the user cancelling that
|
|
13421
|
+
* prompt, is returned unchanged: the client and the app must see the user's
|
|
13422
|
+
* cancel (no further prompt, no retry), never a provider failure.
|
|
13423
|
+
*/
|
|
13424
|
+
mapRequestFailure(error) {
|
|
13425
|
+
return isWalletRejection(error) ? error : this.mapApiError(error);
|
|
13426
|
+
}
|
|
12102
13427
|
mapApiError(error) {
|
|
12103
13428
|
if (!(error instanceof YieldseekerApiError)) {
|
|
12104
13429
|
return new OwneyError(
|
|
@@ -12317,6 +13642,120 @@ var YieldseekerAgent = class {
|
|
|
12317
13642
|
// src/client.ts
|
|
12318
13643
|
init_errors();
|
|
12319
13644
|
|
|
13645
|
+
// src/lib/history-fanout.ts
|
|
13646
|
+
var SEPARATOR = "@";
|
|
13647
|
+
function isSupportedChainId(value) {
|
|
13648
|
+
return SUPPORTED_CHAIN_IDS.includes(value);
|
|
13649
|
+
}
|
|
13650
|
+
function fanoutKey(leg) {
|
|
13651
|
+
return leg.chainId === void 0 ? leg.agentId : `${leg.agentId}${SEPARATOR}${leg.chainId}`;
|
|
13652
|
+
}
|
|
13653
|
+
function encodeFanoutCursor(map) {
|
|
13654
|
+
return Buffer.from(JSON.stringify(map), "utf8").toString("base64");
|
|
13655
|
+
}
|
|
13656
|
+
function decodeFanoutCursor(token) {
|
|
13657
|
+
let parsed;
|
|
13658
|
+
try {
|
|
13659
|
+
parsed = JSON.parse(Buffer.from(token, "base64").toString("utf8"));
|
|
13660
|
+
} catch {
|
|
13661
|
+
throw new InvalidHistoryCursorError(
|
|
13662
|
+
"History fan-out cursor is not valid base64 JSON."
|
|
13663
|
+
);
|
|
13664
|
+
}
|
|
13665
|
+
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed) || !Object.values(parsed).every((v) => typeof v === "string")) {
|
|
13666
|
+
throw new InvalidHistoryCursorError(
|
|
13667
|
+
"History fan-out cursor payload has wrong shape."
|
|
13668
|
+
);
|
|
13669
|
+
}
|
|
13670
|
+
return parsed;
|
|
13671
|
+
}
|
|
13672
|
+
function transactionChainId(entry) {
|
|
13673
|
+
let found;
|
|
13674
|
+
for (const tx of entry.transactions ?? []) {
|
|
13675
|
+
if (tx.chainId === void 0) continue;
|
|
13676
|
+
if (!isSupportedChainId(tx.chainId)) return void 0;
|
|
13677
|
+
if (found !== void 0 && found !== tx.chainId) return void 0;
|
|
13678
|
+
found = tx.chainId;
|
|
13679
|
+
}
|
|
13680
|
+
return found;
|
|
13681
|
+
}
|
|
13682
|
+
function mergeHistoryPages(pages) {
|
|
13683
|
+
const merged = [];
|
|
13684
|
+
const nextCursorMap = {};
|
|
13685
|
+
let hasMore = false;
|
|
13686
|
+
const identity = (e) => [
|
|
13687
|
+
e.agent,
|
|
13688
|
+
e.action,
|
|
13689
|
+
e.date ?? "",
|
|
13690
|
+
e.transactions?.[0]?.txHashes?.[0] ?? ""
|
|
13691
|
+
].join("\0");
|
|
13692
|
+
const seen = /* @__PURE__ */ new Map();
|
|
13693
|
+
for (const { leg, page } of pages) {
|
|
13694
|
+
if (!page) continue;
|
|
13695
|
+
for (const e of page.data) {
|
|
13696
|
+
const id = identity(e);
|
|
13697
|
+
const prior = seen.get(id);
|
|
13698
|
+
if (prior) {
|
|
13699
|
+
prior.legs += 1;
|
|
13700
|
+
const own = transactionChainId(prior.entry);
|
|
13701
|
+
if (own === void 0) delete prior.entry.chainId;
|
|
13702
|
+
else prior.entry.chainId = own;
|
|
13703
|
+
continue;
|
|
13704
|
+
}
|
|
13705
|
+
const entry = leg.chainId === void 0 ? { ...e } : { ...e, chainId: leg.chainId };
|
|
13706
|
+
seen.set(id, { entry, legs: 1 });
|
|
13707
|
+
merged.push(entry);
|
|
13708
|
+
}
|
|
13709
|
+
if (page.hasMore && page.nextCursor) {
|
|
13710
|
+
nextCursorMap[fanoutKey(leg)] = page.nextCursor;
|
|
13711
|
+
hasMore = true;
|
|
13712
|
+
}
|
|
13713
|
+
}
|
|
13714
|
+
merged.sort((a, b) => {
|
|
13715
|
+
const dateDiff = new Date(b.date).getTime() - new Date(a.date).getTime();
|
|
13716
|
+
if (dateDiff !== 0) return dateDiff;
|
|
13717
|
+
if (a.agent !== b.agent) return a.agent < b.agent ? -1 : 1;
|
|
13718
|
+
const aChain = a.chainId ?? 0;
|
|
13719
|
+
const bChain = b.chainId ?? 0;
|
|
13720
|
+
if (aChain !== bChain) return aChain - bChain;
|
|
13721
|
+
const aTx = a.transactions?.[0]?.txHashes?.[0] ?? "";
|
|
13722
|
+
const bTx = b.transactions?.[0]?.txHashes?.[0] ?? "";
|
|
13723
|
+
if (aTx !== bTx) return aTx < bTx ? -1 : 1;
|
|
13724
|
+
if (a.action !== b.action) return a.action < b.action ? -1 : 1;
|
|
13725
|
+
return 0;
|
|
13726
|
+
});
|
|
13727
|
+
return {
|
|
13728
|
+
data: merged,
|
|
13729
|
+
hasMore,
|
|
13730
|
+
nextCursor: hasMore ? encodeFanoutCursor(nextCursorMap) : void 0
|
|
13731
|
+
};
|
|
13732
|
+
}
|
|
13733
|
+
|
|
13734
|
+
// src/lib/daily-earnings-merge.ts
|
|
13735
|
+
function mergeDailyEarnings(series) {
|
|
13736
|
+
const byAsset = /* @__PURE__ */ new Map();
|
|
13737
|
+
for (const s of series) {
|
|
13738
|
+
for (const { asset, points } of s.assets) {
|
|
13739
|
+
const byDate = byAsset.get(asset) ?? /* @__PURE__ */ new Map();
|
|
13740
|
+
for (const point of points) {
|
|
13741
|
+
byDate.set(point.date, (byDate.get(point.date) ?? 0) + point.amount);
|
|
13742
|
+
}
|
|
13743
|
+
byAsset.set(asset, byDate);
|
|
13744
|
+
}
|
|
13745
|
+
}
|
|
13746
|
+
return {
|
|
13747
|
+
walletAddress: series[0]?.walletAddress ?? "",
|
|
13748
|
+
// Names the first source's chain. On a fanned-out read the payload spans
|
|
13749
|
+
// several, so this is provenance rather than scope — `assets` is the part
|
|
13750
|
+
// that carries the merged figures.
|
|
13751
|
+
chainId: series[0]?.chainId ?? 0,
|
|
13752
|
+
assets: [...byAsset.entries()].map(([asset, byDate]) => ({
|
|
13753
|
+
asset,
|
|
13754
|
+
points: [...byDate.entries()].map(([date, amount]) => ({ date, amount })).sort((a, b) => a.date.localeCompare(b.date))
|
|
13755
|
+
})).sort((a, b) => a.asset.localeCompare(b.asset))
|
|
13756
|
+
};
|
|
13757
|
+
}
|
|
13758
|
+
|
|
12320
13759
|
// src/lib/swap/swap-api.ts
|
|
12321
13760
|
init_errors();
|
|
12322
13761
|
var FUSION_SECRET_SERVER_PUBLISH = 1;
|
|
@@ -12580,6 +14019,8 @@ var FALLBACK_WRAP_GAS = 50000n;
|
|
|
12580
14019
|
var APPROVE_GAS = 60000n;
|
|
12581
14020
|
var GAS_SAFETY = 2n;
|
|
12582
14021
|
var MIN_WALLET_GAS_PRICE = 3000000000n;
|
|
14022
|
+
var WRAP_WATCH_INTERVAL_MS = 4e3;
|
|
14023
|
+
var WRAP_PROMPT_TIMEOUT_MS = 5 * 60 * 1e3;
|
|
12583
14024
|
async function wrapNative(deps, options) {
|
|
12584
14025
|
const { chainId, wrapper, nativeSymbol, requested } = options;
|
|
12585
14026
|
const balance = await deps.readNativeBalance();
|
|
@@ -12637,16 +14078,90 @@ async function wrapNative(deps, options) {
|
|
|
12637
14078
|
}
|
|
12638
14079
|
);
|
|
12639
14080
|
}
|
|
14081
|
+
let baseline;
|
|
14082
|
+
if (deps.readWrappedBalance) {
|
|
14083
|
+
try {
|
|
14084
|
+
baseline = await deps.readWrappedBalance();
|
|
14085
|
+
} catch (error) {
|
|
14086
|
+
debugLog("owney-sdk", "wrap: balance read failed, not watching", {
|
|
14087
|
+
message: error instanceof Error ? error.message : String(error)
|
|
14088
|
+
});
|
|
14089
|
+
}
|
|
14090
|
+
}
|
|
12640
14091
|
await deps.ensureChain(chainId);
|
|
12641
14092
|
debugLog("owney-sdk", "wrap: sending deposit()", {
|
|
12642
14093
|
wrapper,
|
|
12643
14094
|
value: wrapped.toString()
|
|
12644
14095
|
});
|
|
12645
|
-
|
|
12646
|
-
|
|
12647
|
-
|
|
12648
|
-
|
|
12649
|
-
|
|
14096
|
+
let notified = false;
|
|
14097
|
+
const notify2 = (hash2) => {
|
|
14098
|
+
if (notified) return;
|
|
14099
|
+
notified = true;
|
|
14100
|
+
options.onSubmitted?.(hash2);
|
|
14101
|
+
};
|
|
14102
|
+
const outcome = await new Promise((resolve, reject) => {
|
|
14103
|
+
let done = false;
|
|
14104
|
+
let timer;
|
|
14105
|
+
const finish = (settle) => {
|
|
14106
|
+
if (done) return;
|
|
14107
|
+
done = true;
|
|
14108
|
+
clearTimeout(timer);
|
|
14109
|
+
settle();
|
|
14110
|
+
};
|
|
14111
|
+
timer = setTimeout(
|
|
14112
|
+
() => finish(
|
|
14113
|
+
() => reject(
|
|
14114
|
+
new OwneyError(
|
|
14115
|
+
"SWAP_WALLET_PROMPT_TIMEOUT",
|
|
14116
|
+
// Hedged on purpose: a wallet that never answered may still have
|
|
14117
|
+
// sent it, and wrapping again would wrap twice.
|
|
14118
|
+
`Your wallet didn't answer the request to wrap your ${nativeSymbol}. Check your wallet before trying again \u2014 if the wrap went through, your funds are there as wrapped ${nativeSymbol}.`,
|
|
14119
|
+
{ chainId, prompt: "wrap", timeoutMs: WRAP_PROMPT_TIMEOUT_MS }
|
|
14120
|
+
)
|
|
14121
|
+
)
|
|
14122
|
+
),
|
|
14123
|
+
WRAP_PROMPT_TIMEOUT_MS
|
|
14124
|
+
);
|
|
14125
|
+
deps.sendTransaction(
|
|
14126
|
+
{ to: wrapper, data: WRAP_SELECTOR, value: wrapped.toString() },
|
|
14127
|
+
(hash2) => {
|
|
14128
|
+
clearTimeout(timer);
|
|
14129
|
+
notify2(hash2);
|
|
14130
|
+
}
|
|
14131
|
+
).then(
|
|
14132
|
+
(txHash) => finish(() => resolve({ txHash })),
|
|
14133
|
+
(error) => finish(() => reject(error))
|
|
14134
|
+
);
|
|
14135
|
+
if (baseline !== void 0 && deps.readWrappedBalance) {
|
|
14136
|
+
const read2 = deps.readWrappedBalance;
|
|
14137
|
+
const target = baseline + wrapped;
|
|
14138
|
+
const sleep4 = deps.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms)));
|
|
14139
|
+
void (async () => {
|
|
14140
|
+
while (!done) {
|
|
14141
|
+
await sleep4(WRAP_WATCH_INTERVAL_MS);
|
|
14142
|
+
if (done) return;
|
|
14143
|
+
try {
|
|
14144
|
+
if (await read2() >= target) {
|
|
14145
|
+
debugLog(
|
|
14146
|
+
"owney-sdk",
|
|
14147
|
+
"wrap: landed on chain before the wallet answered"
|
|
14148
|
+
);
|
|
14149
|
+
finish(() => {
|
|
14150
|
+
notify2();
|
|
14151
|
+
resolve({});
|
|
14152
|
+
});
|
|
14153
|
+
return;
|
|
14154
|
+
}
|
|
14155
|
+
} catch {
|
|
14156
|
+
}
|
|
14157
|
+
}
|
|
14158
|
+
})();
|
|
14159
|
+
}
|
|
14160
|
+
});
|
|
14161
|
+
return {
|
|
14162
|
+
wrapped,
|
|
14163
|
+
...outcome.txHash ? { txHash: outcome.txHash } : {}
|
|
14164
|
+
};
|
|
12650
14165
|
}
|
|
12651
14166
|
function requireWrapper(quote) {
|
|
12652
14167
|
const wrapper = quote.wrappedNative;
|
|
@@ -12788,6 +14303,10 @@ var DEFAULT_POLL_MS2 = 5e3;
|
|
|
12788
14303
|
var MAX_BACKOFF_MS = 3e4;
|
|
12789
14304
|
var backoffFor = (failures, base7) => Math.min(base7 * 2 ** Math.min(failures, 5), MAX_BACKOFF_MS);
|
|
12790
14305
|
var DEFAULT_TIMEOUT_MS3 = 15 * 60 * 1e3;
|
|
14306
|
+
var NOT_FOUND_GRACE_MS = 2 * 60 * 1e3;
|
|
14307
|
+
function isNotFound(error) {
|
|
14308
|
+
return error instanceof OwneyError && error.details?.statusCode === 404;
|
|
14309
|
+
}
|
|
12791
14310
|
async function runFusionOrderInternal(deps, options) {
|
|
12792
14311
|
const {
|
|
12793
14312
|
orderHash,
|
|
@@ -12818,6 +14337,7 @@ async function runFusionOrderInternal(deps, options) {
|
|
|
12818
14337
|
assertTime();
|
|
12819
14338
|
};
|
|
12820
14339
|
let failures = 0;
|
|
14340
|
+
let notFoundSince;
|
|
12821
14341
|
const published = /* @__PURE__ */ new Set();
|
|
12822
14342
|
onStage?.("swapping");
|
|
12823
14343
|
for (; ; ) {
|
|
@@ -12853,7 +14373,20 @@ async function runFusionOrderInternal(deps, options) {
|
|
|
12853
14373
|
status = state.status;
|
|
12854
14374
|
partial ||= status === "partially-filled" || !!state.fills?.length;
|
|
12855
14375
|
failures = 0;
|
|
12856
|
-
|
|
14376
|
+
notFoundSince = void 0;
|
|
14377
|
+
} catch (error) {
|
|
14378
|
+
if (isNotFound(error)) {
|
|
14379
|
+
notFoundSince ??= deps.now();
|
|
14380
|
+
if (deps.now() - notFoundSince >= NOT_FOUND_GRACE_MS) {
|
|
14381
|
+
throw new OwneyError(
|
|
14382
|
+
"SWAP_ORDER_NOT_FOUND",
|
|
14383
|
+
"The swap provider has no record of this order, so nothing was exchanged.",
|
|
14384
|
+
{ orderHash }
|
|
14385
|
+
);
|
|
14386
|
+
}
|
|
14387
|
+
} else {
|
|
14388
|
+
notFoundSince = void 0;
|
|
14389
|
+
}
|
|
12857
14390
|
failures += 1;
|
|
12858
14391
|
await pause(backoffFor(failures, pollIntervalMs));
|
|
12859
14392
|
continue;
|
|
@@ -13126,7 +14659,7 @@ async function executeSwap(deps, options) {
|
|
|
13126
14659
|
});
|
|
13127
14660
|
const before = await deps.readTargetBalance();
|
|
13128
14661
|
debugLog("owney-sdk", "swap: target balance before", before.toString());
|
|
13129
|
-
const result = quote.rail === "classic" ? await runClassic(deps, options) : quote.rail === "fusion" ? await runSameChainFusion(deps, options, walletAddress) : await runFusion(deps, options, walletAddress);
|
|
14662
|
+
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);
|
|
13130
14663
|
const { arrived } = await awaitBalanceIncrease({
|
|
13131
14664
|
readBalance: () => deps.readTargetBalance(),
|
|
13132
14665
|
baseline: before,
|
|
@@ -13145,6 +14678,17 @@ async function executeSwap(deps, options) {
|
|
|
13145
14678
|
active = false;
|
|
13146
14679
|
}
|
|
13147
14680
|
}
|
|
14681
|
+
async function doubtVerdict(deps, error, before) {
|
|
14682
|
+
if (!(error instanceof OwneyError) || error.code !== "SWAP_ORDER_EXPIRED" && error.code !== "SWAP_ORDER_CANCELLED" || error.details?.outcome !== "not-submitted") throw error;
|
|
14683
|
+
const now = await deps.readTargetBalance().catch(() => before);
|
|
14684
|
+
if (now <= before) throw error;
|
|
14685
|
+
debugLog("owney-sdk", "swap: rail said no but the wallet received funds", { status: error.details?.status });
|
|
14686
|
+
throw new OwneyError(
|
|
14687
|
+
"SWAP_REQUEST_FAILED",
|
|
14688
|
+
"The swap's status says it did not fill, but funds arrived in your wallet since it started. Check your wallet before retrying.",
|
|
14689
|
+
{ ...error.details, settlementUnconfirmed: true, outcome: "submitted-unknown" }
|
|
14690
|
+
);
|
|
14691
|
+
}
|
|
13148
14692
|
async function runClassic(deps, options) {
|
|
13149
14693
|
const {
|
|
13150
14694
|
quote,
|
|
@@ -13169,8 +14713,8 @@ async function runClassic(deps, options) {
|
|
|
13169
14713
|
onStage?.("quoting");
|
|
13170
14714
|
debugLog("owney-sdk", "swap: fetching classic calldata");
|
|
13171
14715
|
let { tx } = await deps.api.swapTx(swapTxRequest);
|
|
13172
|
-
const
|
|
13173
|
-
if (!
|
|
14716
|
+
const isNative2 = BigInt(tx.value ?? "0") > 0n;
|
|
14717
|
+
if (!isNative2) {
|
|
13174
14718
|
const needed = amount;
|
|
13175
14719
|
const current = await deps.readAllowance(tx.to);
|
|
13176
14720
|
debugLog("owney-sdk", "swap: allowance", {
|
|
@@ -13394,7 +14938,7 @@ async function runFusion(deps, options, walletAddress) {
|
|
|
13394
14938
|
...onStage ? { onStage } : {}
|
|
13395
14939
|
});
|
|
13396
14940
|
} catch (error) {
|
|
13397
|
-
if (error instanceof OwneyError && error.code === "SWAP_ORDER_REFUNDED" && error.details?.outcome === "refunded") {
|
|
14941
|
+
if (error instanceof OwneyError && (error.code === "SWAP_ORDER_REFUNDED" && error.details?.outcome === "refunded" || error.code === "SWAP_ORDER_NOT_FOUND")) {
|
|
13398
14942
|
clearOrder(built.orderHash);
|
|
13399
14943
|
}
|
|
13400
14944
|
throw error;
|
|
@@ -13677,6 +15221,34 @@ function verifiedFee(payout) {
|
|
|
13677
15221
|
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;
|
|
13678
15222
|
}
|
|
13679
15223
|
|
|
15224
|
+
// src/lib/swap/swap.gas-check.ts
|
|
15225
|
+
init_errors();
|
|
15226
|
+
var CLASSIC_SWAP_GAS = 300000n;
|
|
15227
|
+
var APPROVE_GAS2 = 60000n;
|
|
15228
|
+
var isNative = (address) => address.toLowerCase().startsWith("0xeeee");
|
|
15229
|
+
async function swapGasShortfall(deps, quote) {
|
|
15230
|
+
if (quote.rail !== "classic" || isNative(quote.src.address)) return null;
|
|
15231
|
+
const gas = CLASSIC_SWAP_GAS + APPROVE_GAS2;
|
|
15232
|
+
const [balance, gasPrice] = await Promise.all([
|
|
15233
|
+
deps.readNativeBalance(),
|
|
15234
|
+
deps.getMaxFeePerGas()
|
|
15235
|
+
]);
|
|
15236
|
+
const required = gas * gasPrice;
|
|
15237
|
+
return balance < required ? { chainId: quote.src.chainId, balance, required } : null;
|
|
15238
|
+
}
|
|
15239
|
+
function swapGasError(shortfall, nativeSymbol) {
|
|
15240
|
+
return new OwneyError(
|
|
15241
|
+
"SWAP_INSUFFICIENT_GAS",
|
|
15242
|
+
`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.`,
|
|
15243
|
+
{
|
|
15244
|
+
chainId: shortfall.chainId,
|
|
15245
|
+
symbol: nativeSymbol,
|
|
15246
|
+
balance: shortfall.balance.toString(),
|
|
15247
|
+
required: shortfall.required.toString()
|
|
15248
|
+
}
|
|
15249
|
+
);
|
|
15250
|
+
}
|
|
15251
|
+
|
|
13680
15252
|
// src/lib/swap/swap.permit.ts
|
|
13681
15253
|
var import_viem20 = require("viem");
|
|
13682
15254
|
var PERMIT_ABI = (0, import_viem20.parseAbi)([
|
|
@@ -14143,9 +15715,40 @@ function aggregateApyHistory(agentApys) {
|
|
|
14143
15715
|
const total = points.reduce((sum, p) => sum + p.historicalBalance.amount, 0);
|
|
14144
15716
|
if (total <= 0 || !Number.isFinite(total)) return [];
|
|
14145
15717
|
const apy = points.reduce((sum, p) => sum + p.apy * (p.historicalBalance.amount / total), 0);
|
|
14146
|
-
|
|
15718
|
+
if (!Number.isFinite(apy)) return [];
|
|
15719
|
+
const incentives = aggregateIncentives(points, total);
|
|
15720
|
+
return [{ date, apy, ...incentives.length > 0 ? { incentives } : {} }];
|
|
14147
15721
|
});
|
|
14148
15722
|
}
|
|
15723
|
+
function incentiveKey(incentive) {
|
|
15724
|
+
return JSON.stringify([
|
|
15725
|
+
incentive.source,
|
|
15726
|
+
incentive.agentId,
|
|
15727
|
+
incentive.opportunityId,
|
|
15728
|
+
[...incentive.campaignIds].sort()
|
|
15729
|
+
]);
|
|
15730
|
+
}
|
|
15731
|
+
function aggregateIncentives(points, totalBalance) {
|
|
15732
|
+
const byProgram = /* @__PURE__ */ new Map();
|
|
15733
|
+
for (const point of points) {
|
|
15734
|
+
const weight = point.historicalBalance.amount / totalBalance;
|
|
15735
|
+
for (const incentive of point.incentives ?? []) {
|
|
15736
|
+
if (!Number.isFinite(incentive.apr) || !Number.isFinite(incentive.apyContribution)) continue;
|
|
15737
|
+
const key2 = incentiveKey(incentive);
|
|
15738
|
+
const existing = byProgram.get(key2);
|
|
15739
|
+
if (existing) {
|
|
15740
|
+
existing.apyContribution += incentive.apyContribution * weight;
|
|
15741
|
+
} else {
|
|
15742
|
+
byProgram.set(key2, {
|
|
15743
|
+
...incentive,
|
|
15744
|
+
campaignIds: [...incentive.campaignIds],
|
|
15745
|
+
apyContribution: incentive.apyContribution * weight
|
|
15746
|
+
});
|
|
15747
|
+
}
|
|
15748
|
+
}
|
|
15749
|
+
}
|
|
15750
|
+
return [...byProgram.values()];
|
|
15751
|
+
}
|
|
14149
15752
|
function aggregateApyByChainAndAsset(agentApys, agentBalances) {
|
|
14150
15753
|
const sums = {};
|
|
14151
15754
|
const weights = {};
|
|
@@ -14750,7 +16353,9 @@ async function execute(i, key2, plan) {
|
|
|
14750
16353
|
if (balance < total)
|
|
14751
16354
|
throw new OwneyError(
|
|
14752
16355
|
"DEPOSIT_INSUFFICIENT_BALANCE",
|
|
14753
|
-
"Insufficient token balance for this deposit."
|
|
16356
|
+
"Insufficient token balance for this deposit.",
|
|
16357
|
+
// What was seen: a swap's deposit retries once at a small shortfall (ROUT-618).
|
|
16358
|
+
{ token: i.token, chainId: i.chainId, balance: balance.toString(), amount: total.toString() }
|
|
14754
16359
|
);
|
|
14755
16360
|
if (allowance < total && !supportsSponsoredErc2612(i.chainId, i.token))
|
|
14756
16361
|
throw new OwneyError(
|
|
@@ -14785,15 +16390,20 @@ async function execute(i, key2, plan) {
|
|
|
14785
16390
|
tokenName,
|
|
14786
16391
|
tokenVersion
|
|
14787
16392
|
};
|
|
14788
|
-
const signature2 = await
|
|
14789
|
-
|
|
14790
|
-
|
|
14791
|
-
|
|
14792
|
-
|
|
14793
|
-
|
|
14794
|
-
|
|
16393
|
+
const signature2 = await signWithChainRetry(
|
|
16394
|
+
i.walletChain ?? i.pub,
|
|
16395
|
+
i.wallet,
|
|
16396
|
+
i.chainId,
|
|
16397
|
+
() => i.wallet.signTypedData({
|
|
16398
|
+
account: i.owner,
|
|
16399
|
+
...erc2612TypedData({
|
|
16400
|
+
chainId: i.chainId,
|
|
16401
|
+
token: i.token,
|
|
16402
|
+
owner: i.owner,
|
|
16403
|
+
permit: unsignedPermit
|
|
16404
|
+
})
|
|
14795
16405
|
})
|
|
14796
|
-
|
|
16406
|
+
);
|
|
14797
16407
|
erc2612Permit = { ...unsignedPermit, signature: signature2 };
|
|
14798
16408
|
}
|
|
14799
16409
|
const spender = await getSponsorRelayerAddress({
|
|
@@ -14810,10 +16420,15 @@ async function execute(i, key2, plan) {
|
|
|
14810
16420
|
deadline: (now + 900n).toString(),
|
|
14811
16421
|
...erc2612Permit ? { erc2612Permit } : {}
|
|
14812
16422
|
};
|
|
14813
|
-
const signature = await
|
|
14814
|
-
|
|
14815
|
-
|
|
14816
|
-
|
|
16423
|
+
const signature = await signWithChainRetry(
|
|
16424
|
+
i.walletChain ?? i.pub,
|
|
16425
|
+
i.wallet,
|
|
16426
|
+
i.chainId,
|
|
16427
|
+
() => i.wallet.signTypedData({
|
|
16428
|
+
account: i.owner,
|
|
16429
|
+
...batchTypedData(unsigned, spender)
|
|
16430
|
+
})
|
|
16431
|
+
);
|
|
14817
16432
|
i.onApproved?.();
|
|
14818
16433
|
return send({ ...unsigned, signature });
|
|
14819
16434
|
}
|
|
@@ -14842,6 +16457,7 @@ function makeSponsoredTokenCallback(deps) {
|
|
|
14842
16457
|
chainId,
|
|
14843
16458
|
transfers,
|
|
14844
16459
|
pub,
|
|
16460
|
+
walletChain,
|
|
14845
16461
|
wallet,
|
|
14846
16462
|
onApproved: deps.onApproved,
|
|
14847
16463
|
// Rest arguments keep the callbacks' arity: the flag appears only when set.
|
|
@@ -14937,6 +16553,123 @@ async function runAgentDepositBatch(chainId, legs, transfer) {
|
|
|
14937
16553
|
}
|
|
14938
16554
|
}
|
|
14939
16555
|
|
|
16556
|
+
// src/lib/walletconnect-switch.ts
|
|
16557
|
+
var WALLET_SWITCH_TIMEOUT_MS = 12e4;
|
|
16558
|
+
var HOLD_CHAIN_MS = 15e3;
|
|
16559
|
+
var MAX_RESENDS = 2;
|
|
16560
|
+
var holds = /* @__PURE__ */ new Map();
|
|
16561
|
+
function parseChainId(raw2) {
|
|
16562
|
+
if (typeof raw2 === "number") return raw2;
|
|
16563
|
+
if (typeof raw2 !== "string") return void 0;
|
|
16564
|
+
const ref = raw2.split(":").pop() ?? raw2;
|
|
16565
|
+
const id = ref.startsWith("0x") ? Number.parseInt(ref, 16) : Number(ref);
|
|
16566
|
+
return Number.isFinite(id) ? id : void 0;
|
|
16567
|
+
}
|
|
16568
|
+
function walletConnectCore(provider) {
|
|
16569
|
+
const p = provider;
|
|
16570
|
+
const core = p?.signer ?? p;
|
|
16571
|
+
if (typeof core?.client?.request !== "function" || typeof core.setDefaultChain !== "function" || typeof core.session?.topic !== "string") {
|
|
16572
|
+
return null;
|
|
16573
|
+
}
|
|
16574
|
+
const peer = core.session.peer?.metadata?.name ?? "";
|
|
16575
|
+
if (!/metamask/i.test(peer)) return null;
|
|
16576
|
+
return core;
|
|
16577
|
+
}
|
|
16578
|
+
async function switchWalletConnectChain(provider, chainId, timeoutMs = WALLET_SWITCH_TIMEOUT_MS) {
|
|
16579
|
+
const core = walletConnectCore(provider);
|
|
16580
|
+
if (!core) return false;
|
|
16581
|
+
holds.get(core.session.topic)?.();
|
|
16582
|
+
await requestSwitch(core, provider, chainId, timeoutMs);
|
|
16583
|
+
holdChain(core, provider, chainId);
|
|
16584
|
+
return true;
|
|
16585
|
+
}
|
|
16586
|
+
async function requestSwitch(core, provider, chainId, timeoutMs) {
|
|
16587
|
+
const current = Number(
|
|
16588
|
+
await provider.request({ method: "eth_chainId" })
|
|
16589
|
+
);
|
|
16590
|
+
const hexChainId = `0x${chainId.toString(16)}`;
|
|
16591
|
+
let timer;
|
|
16592
|
+
try {
|
|
16593
|
+
await Promise.race([
|
|
16594
|
+
core.client.request({
|
|
16595
|
+
topic: core.session.topic,
|
|
16596
|
+
chainId: `eip155:${current}`,
|
|
16597
|
+
request: {
|
|
16598
|
+
method: "wallet_switchEthereumChain",
|
|
16599
|
+
params: [{ chainId: hexChainId }]
|
|
16600
|
+
}
|
|
16601
|
+
}),
|
|
16602
|
+
new Promise((_, reject) => {
|
|
16603
|
+
timer = setTimeout(
|
|
16604
|
+
() => reject(
|
|
16605
|
+
new Error("The wallet did not answer the network switch in time")
|
|
16606
|
+
),
|
|
16607
|
+
timeoutMs
|
|
16608
|
+
);
|
|
16609
|
+
})
|
|
16610
|
+
]);
|
|
16611
|
+
} finally {
|
|
16612
|
+
clearTimeout(timer);
|
|
16613
|
+
}
|
|
16614
|
+
try {
|
|
16615
|
+
core.setDefaultChain(`eip155:${chainId}`);
|
|
16616
|
+
} catch {
|
|
16617
|
+
}
|
|
16618
|
+
}
|
|
16619
|
+
function holdChain(core, provider, chainId) {
|
|
16620
|
+
if (typeof core.on !== "function" || typeof core.removeListener !== "function") {
|
|
16621
|
+
return;
|
|
16622
|
+
}
|
|
16623
|
+
let resends = 0;
|
|
16624
|
+
const listener = (raw2) => {
|
|
16625
|
+
const reported = parseChainId(raw2);
|
|
16626
|
+
debugLog("wc-switch", "wallet reported chain", {
|
|
16627
|
+
reported,
|
|
16628
|
+
holding: chainId,
|
|
16629
|
+
resends
|
|
16630
|
+
});
|
|
16631
|
+
if (reported === void 0 || reported === chainId) return;
|
|
16632
|
+
if (resends >= MAX_RESENDS) return;
|
|
16633
|
+
resends += 1;
|
|
16634
|
+
void requestSwitch(core, provider, chainId, WALLET_SWITCH_TIMEOUT_MS).catch(
|
|
16635
|
+
(error) => debugLog("wc-switch", "re-switch failed", {
|
|
16636
|
+
error: error instanceof Error ? error.message : String(error)
|
|
16637
|
+
})
|
|
16638
|
+
);
|
|
16639
|
+
};
|
|
16640
|
+
const release = () => {
|
|
16641
|
+
clearTimeout(timer);
|
|
16642
|
+
core.removeListener?.("chainChanged", listener);
|
|
16643
|
+
if (holds.get(core.session.topic) === release) {
|
|
16644
|
+
holds.delete(core.session.topic);
|
|
16645
|
+
}
|
|
16646
|
+
};
|
|
16647
|
+
const timer = setTimeout(release, HOLD_CHAIN_MS);
|
|
16648
|
+
core.on("chainChanged", listener);
|
|
16649
|
+
holds.set(core.session.topic, release);
|
|
16650
|
+
}
|
|
16651
|
+
function withWalletConnectSwitch(provider) {
|
|
16652
|
+
if (!walletConnectCore(provider)) return provider;
|
|
16653
|
+
const target = provider;
|
|
16654
|
+
const request2 = async (args) => {
|
|
16655
|
+
if (args?.method !== "wallet_switchEthereumChain") {
|
|
16656
|
+
return target.request(args);
|
|
16657
|
+
}
|
|
16658
|
+
const [param] = args.params ?? [];
|
|
16659
|
+
const chainId = Number.parseInt(param?.chainId ?? "", 16);
|
|
16660
|
+
if (!Number.isFinite(chainId)) return target.request(args);
|
|
16661
|
+
await switchWalletConnectChain(target, chainId);
|
|
16662
|
+
return null;
|
|
16663
|
+
};
|
|
16664
|
+
return new Proxy(target, {
|
|
16665
|
+
get(obj, prop) {
|
|
16666
|
+
if (prop === "request") return request2;
|
|
16667
|
+
const value = Reflect.get(obj, prop, obj);
|
|
16668
|
+
return typeof value === "function" ? value.bind(obj) : value;
|
|
16669
|
+
}
|
|
16670
|
+
});
|
|
16671
|
+
}
|
|
16672
|
+
|
|
14940
16673
|
// src/lib/sponsored-calls-deposit.ts
|
|
14941
16674
|
var import_viem24 = require("viem");
|
|
14942
16675
|
init_errors();
|
|
@@ -15116,6 +16849,19 @@ function makeSponsoredCallsCallback(deps) {
|
|
|
15116
16849
|
var WALLET_CATCHUP_TIMEOUT_MS = 3e4;
|
|
15117
16850
|
var PERMIT2_ALLOWANCE_VERIFY_ATTEMPTS = 6;
|
|
15118
16851
|
var PERMIT2_ALLOWANCE_VERIFY_DELAY_MS = 250;
|
|
16852
|
+
function shortfallBalance(error, asked) {
|
|
16853
|
+
if (!(error instanceof OwneyError)) return void 0;
|
|
16854
|
+
if (error.code !== "DEPOSIT_INSUFFICIENT_BALANCE") return void 0;
|
|
16855
|
+
const seen = error.details?.balance;
|
|
16856
|
+
if (typeof seen !== "string") return void 0;
|
|
16857
|
+
const balance = BigInt(seen);
|
|
16858
|
+
if (balance <= 0n || balance >= asked) return void 0;
|
|
16859
|
+
return (asked - balance) * 100n <= asked ? balance : void 0;
|
|
16860
|
+
}
|
|
16861
|
+
function agentRunsOn(agent, chainId) {
|
|
16862
|
+
const chains = agent.supportedChainIds;
|
|
16863
|
+
return !chains || chains.includes(chainId);
|
|
16864
|
+
}
|
|
15119
16865
|
function encodeMultiAgentCursor(map) {
|
|
15120
16866
|
return Buffer.from(JSON.stringify(map), "utf8").toString("base64");
|
|
15121
16867
|
}
|
|
@@ -15195,6 +16941,14 @@ var OwneySDK = class {
|
|
|
15195
16941
|
* withdraw, but they are excluded from new deposits / activations.
|
|
15196
16942
|
*/
|
|
15197
16943
|
disabledAgents = /* @__PURE__ */ new Set();
|
|
16944
|
+
/**
|
|
16945
|
+
* Agents whose sign-in the user cancelled this session (the wallet rejected
|
|
16946
|
+
* the prompt), keyed by chain. Until the app ends the session they are read
|
|
16947
|
+
* from a saved sign-in only (`readStateFor`), so no read reopens the prompt
|
|
16948
|
+
* the user cancelled. A later successful activation of the agent removes
|
|
16949
|
+
* it, and `disconnect()` or a different wallet's `connect()` clears the map.
|
|
16950
|
+
*/
|
|
16951
|
+
declinedSignIns = /* @__PURE__ */ new Map();
|
|
15198
16952
|
state = null;
|
|
15199
16953
|
connectionRevision = 0;
|
|
15200
16954
|
disconnectingAgents = null;
|
|
@@ -15209,6 +16963,7 @@ var OwneySDK = class {
|
|
|
15209
16963
|
zyfaiRpcUrls;
|
|
15210
16964
|
yieldseekerApiBaseUrl;
|
|
15211
16965
|
yieldseekerSiweOrigin;
|
|
16966
|
+
userPoolCustomization = false;
|
|
15212
16967
|
routingApiBaseUrl;
|
|
15213
16968
|
referralSource;
|
|
15214
16969
|
ledger;
|
|
@@ -15229,6 +16984,8 @@ var OwneySDK = class {
|
|
|
15229
16984
|
* session started: true when it armed the refresh, false when its deadline
|
|
15230
16985
|
* had passed (it only dropped the cache and forced one snapshot read). */
|
|
15231
16986
|
recoveredFundingReads = /* @__PURE__ */ new Map();
|
|
16987
|
+
/** Confirmed deposits already announced to their agent (`depositConfirmed`), bounded. */
|
|
16988
|
+
announcedDeposits = /* @__PURE__ */ new Set();
|
|
15232
16989
|
fundingBalanceChecks = /* @__PURE__ */ new WeakMap();
|
|
15233
16990
|
activationChecks = /* @__PURE__ */ new Map();
|
|
15234
16991
|
// Protect the SDK entry point as well as the mini-app hook. This owns only
|
|
@@ -15259,6 +17016,7 @@ var OwneySDK = class {
|
|
|
15259
17016
|
this.routingApiBaseUrl = config.routingApiBaseUrl;
|
|
15260
17017
|
this.paymasterServiceUrl = config.paymasterServiceUrl;
|
|
15261
17018
|
this.referralSource = config.referralSource;
|
|
17019
|
+
this.userPoolCustomization = config.userPoolCustomization ?? false;
|
|
15262
17020
|
this.ledger = createFundingLedger({
|
|
15263
17021
|
apiKey: config.apiKey,
|
|
15264
17022
|
baseUrl: config.routingApiBaseUrl,
|
|
@@ -15483,10 +17241,15 @@ var OwneySDK = class {
|
|
|
15483
17241
|
}
|
|
15484
17242
|
const replacingOwner = this.state !== null && this.state.walletAddress.toLowerCase() !== walletAddress.toLowerCase();
|
|
15485
17243
|
this.clearConnectionState();
|
|
17244
|
+
if (replacingOwner) this.declinedSignIns.clear();
|
|
15486
17245
|
await (replacingOwner ? this.disconnectAgents() : this.disconnectingAgents);
|
|
15487
17246
|
if (revision !== this.connectionRevision)
|
|
15488
17247
|
throw new OwneyError("NOT_CONNECTED", "Wallet connection changed while connecting.");
|
|
15489
|
-
this.state = {
|
|
17248
|
+
this.state = {
|
|
17249
|
+
provider: withWalletConnectSwitch(provider),
|
|
17250
|
+
walletAddress,
|
|
17251
|
+
chainId: null
|
|
17252
|
+
};
|
|
15490
17253
|
}
|
|
15491
17254
|
/**
|
|
15492
17255
|
* Disconnect from all agents and clear connection state.
|
|
@@ -15495,6 +17258,7 @@ var OwneySDK = class {
|
|
|
15495
17258
|
async disconnect() {
|
|
15496
17259
|
++this.connectionRevision;
|
|
15497
17260
|
this.clearConnectionState();
|
|
17261
|
+
this.declinedSignIns.clear();
|
|
15498
17262
|
await this.disconnectAgents();
|
|
15499
17263
|
}
|
|
15500
17264
|
clearConnectionState() {
|
|
@@ -15524,6 +17288,44 @@ var OwneySDK = class {
|
|
|
15524
17288
|
isAgentDisabled(agentId) {
|
|
15525
17289
|
return this.disabledAgents.has(agentId);
|
|
15526
17290
|
}
|
|
17291
|
+
/**
|
|
17292
|
+
* True when `id` takes no new deposits on this chain and asset this
|
|
17293
|
+
* session: its adapter reports no agent for the slot.
|
|
17294
|
+
*/
|
|
17295
|
+
isAgentUnavailable(id, chainId, asset) {
|
|
17296
|
+
if (asset === void 0) return false;
|
|
17297
|
+
return this.state !== null && this.agents.get(id)?.isSlotUnavailable?.(this.state, chainId, asset) === true;
|
|
17298
|
+
}
|
|
17299
|
+
/**
|
|
17300
|
+
* The agents that take no new deposits on this chain and asset this
|
|
17301
|
+
* session, so the app can show them as unavailable: each agent whose
|
|
17302
|
+
* provider has no agent for this slot. They stay withdrawable.
|
|
17303
|
+
*/
|
|
17304
|
+
getUnavailableAgentIds(chainId, asset) {
|
|
17305
|
+
return [...this.agents.keys()].filter((id) => this.isAgentUnavailable(id, chainId, asset));
|
|
17306
|
+
}
|
|
17307
|
+
/**
|
|
17308
|
+
* The adapter reports no agent for this chain and asset this session (see
|
|
17309
|
+
* `IAgent.isSlotUnavailable`): there is nothing there to withdraw, so a
|
|
17310
|
+
* withdrawal without an explicit agent leaves it out instead of failing its
|
|
17311
|
+
* leg.
|
|
17312
|
+
*/
|
|
17313
|
+
hasNoAgentForSlot(agent, state, chainId, asset) {
|
|
17314
|
+
return agent?.isSlotUnavailable?.(state, chainId, asset) === true;
|
|
17315
|
+
}
|
|
17316
|
+
/**
|
|
17317
|
+
* The state an agent's reads use. An agent whose sign-in the user cancelled
|
|
17318
|
+
* on the connection chain this session is read from a saved sign-in only,
|
|
17319
|
+
* as `offChainPortfolioAgents` reads: a read that would need a wallet
|
|
17320
|
+
* prompt fails for that agent instead of reopening the prompt the user
|
|
17321
|
+
* cancelled. A later successful activation of the agent, or `disconnect()`,
|
|
17322
|
+
* lifts it.
|
|
17323
|
+
*/
|
|
17324
|
+
readStateFor(agentId, state) {
|
|
17325
|
+
const chainId = state.chainId;
|
|
17326
|
+
if (state.promptless === true || chainId === null) return state;
|
|
17327
|
+
return this.declinedSignIns.get(chainId)?.has(agentId) === true ? { ...state, promptless: true } : state;
|
|
17328
|
+
}
|
|
15527
17329
|
/**
|
|
15528
17330
|
* Check if the SDK has an active connection state.
|
|
15529
17331
|
* @returns `true` if `connect()` has been called and `disconnect()` has not
|
|
@@ -15719,6 +17521,35 @@ var OwneySDK = class {
|
|
|
15719
17521
|
}
|
|
15720
17522
|
return active;
|
|
15721
17523
|
}
|
|
17524
|
+
/**
|
|
17525
|
+
* Agents that do not run on the connection chain but can be read on their
|
|
17526
|
+
* own from a saved sign-in: Yieldseeker, Base-only, while the wallet sits on
|
|
17527
|
+
* Arbitrum or Ethereum. The whole-portfolio reads (ROUT-479) add them, under
|
|
17528
|
+
* a promptless state; with no saved sign-in they are left out, as before.
|
|
17529
|
+
*/
|
|
17530
|
+
offChainPortfolioAgents(state) {
|
|
17531
|
+
const connectionChain = state.chainId;
|
|
17532
|
+
if (connectionChain === null) return [];
|
|
17533
|
+
const active = this.getActiveAgents();
|
|
17534
|
+
const promptless = { ...state, promptless: true };
|
|
17535
|
+
return [...this.agents.values()].flatMap((agent) => {
|
|
17536
|
+
if (active.has(agent.id) || agentRunsOn(agent, connectionChain) || !agent.hasReadSession) return [];
|
|
17537
|
+
const chainIds = agent.supportedChainIds.filter((id) => agent.hasReadSession(promptless, id));
|
|
17538
|
+
return chainIds.length ? [{ agent, state: promptless, chainIds }] : [];
|
|
17539
|
+
});
|
|
17540
|
+
}
|
|
17541
|
+
/** Every agent a whole-portfolio read covers: the active ones on the
|
|
17542
|
+
* connection chain, then the off-chain ones on their own chain. */
|
|
17543
|
+
portfolioReads(state, chainId) {
|
|
17544
|
+
return [
|
|
17545
|
+
...this.activeReads(state, chainId),
|
|
17546
|
+
...this.offChainPortfolioAgents(state).map(({ agent, state: readState, chainIds }) => ({ id: agent.id, agent, state: readState, chainId: chainIds[0], offChain: true }))
|
|
17547
|
+
];
|
|
17548
|
+
}
|
|
17549
|
+
/** The active agents, each with the state its reads use (`readStateFor`). */
|
|
17550
|
+
activeReads(state, chainId) {
|
|
17551
|
+
return [...this.getActiveAgents()].map(([id, agent]) => ({ id, agent, state: this.readStateFor(id, state), chainId }));
|
|
17552
|
+
}
|
|
15722
17553
|
/**
|
|
15723
17554
|
* Read the org's agent policy once and reuse it. fetchOrgAgentConfig never
|
|
15724
17555
|
* throws — it degrades to null — so this cannot break activation.
|
|
@@ -15755,7 +17586,8 @@ var OwneySDK = class {
|
|
|
15755
17586
|
try {
|
|
15756
17587
|
const policy = await this.getOrgAgentConfig();
|
|
15757
17588
|
if (!policy) return;
|
|
15758
|
-
|
|
17589
|
+
const effective = orgPolicyForConnect(policy, this.userPoolCustomization);
|
|
17590
|
+
await agent.applyOrgPolicy(state, chainId, effective);
|
|
15759
17591
|
} catch (error) {
|
|
15760
17592
|
console.warn(
|
|
15761
17593
|
`[owney-sdk] applyOrgPolicy(${agent.id}) failed (non-fatal):`,
|
|
@@ -15841,7 +17673,7 @@ var OwneySDK = class {
|
|
|
15841
17673
|
*/
|
|
15842
17674
|
async getAvailableAgents(options = {}) {
|
|
15843
17675
|
await this.ensureAgentsInitialized();
|
|
15844
|
-
const { chainId, asset, includeDisabled = false } = options;
|
|
17676
|
+
const { chainId, asset, includeDisabled = false, includeUnavailable = false } = options;
|
|
15845
17677
|
const available = [];
|
|
15846
17678
|
for (const [id, agent] of this.agents) {
|
|
15847
17679
|
const isEnabled = !this.isAgentDisabled(id);
|
|
@@ -15857,6 +17689,9 @@ var OwneySDK = class {
|
|
|
15857
17689
|
continue;
|
|
15858
17690
|
}
|
|
15859
17691
|
}
|
|
17692
|
+
if (chainId !== void 0 && !includeUnavailable && !includeDisabled && this.isAgentUnavailable(id, chainId, asset)) {
|
|
17693
|
+
continue;
|
|
17694
|
+
}
|
|
15860
17695
|
available.push({
|
|
15861
17696
|
id,
|
|
15862
17697
|
isEnabled,
|
|
@@ -15876,8 +17711,17 @@ var OwneySDK = class {
|
|
|
15876
17711
|
* that support the given chainId (incompatible agents are silently skipped).
|
|
15877
17712
|
* If provided, ALL specified agents must support the chainId or the call
|
|
15878
17713
|
* throws before activating any agent.
|
|
17714
|
+
* @param options - Optional. `asset` limits setup to that asset;
|
|
17715
|
+
* `onAgentsSelected` fires once reads can start.
|
|
17716
|
+
* @throws Activation stops at the first agent that fails, and the caller
|
|
17717
|
+
* should end the session. `AGENT_ACTIVATION_PARTIAL_FAILURE` when an
|
|
17718
|
+
* earlier agent activated; `walletRejected` in its details means the user
|
|
17719
|
+
* rejected a signature. `AGENT_ACTIVATION_BLOCKED` when the agent can
|
|
17720
|
+
* never be readied (`details.permanent`). Otherwise the agent's own error
|
|
17721
|
+
* is thrown as is. Until it signs in, an agent whose signature the user
|
|
17722
|
+
* rejected is read from a saved sign-in only and opens no prompt.
|
|
15879
17723
|
*/
|
|
15880
|
-
async activateAgent(chainId, agentId,
|
|
17724
|
+
async activateAgent(chainId, agentId, options = {}) {
|
|
15881
17725
|
const state = this.requireState();
|
|
15882
17726
|
await this.ensureAgentsInitialized();
|
|
15883
17727
|
this.assertActivationSession(state);
|
|
@@ -15914,7 +17758,8 @@ var OwneySDK = class {
|
|
|
15914
17758
|
this.activeAgents.add(id);
|
|
15915
17759
|
}
|
|
15916
17760
|
state.chainId = chainId;
|
|
15917
|
-
|
|
17761
|
+
options.onAgentsSelected?.();
|
|
17762
|
+
await this.activateAgentsInTurn(agents, state, chainId, options.asset);
|
|
15918
17763
|
return;
|
|
15919
17764
|
}
|
|
15920
17765
|
const compatible = [...this.agents.values()].filter(
|
|
@@ -15932,10 +17777,11 @@ var OwneySDK = class {
|
|
|
15932
17777
|
this.activeAgents.add(agent.id);
|
|
15933
17778
|
}
|
|
15934
17779
|
state.chainId = chainId;
|
|
17780
|
+
options.onAgentsSelected?.();
|
|
15935
17781
|
const enabledCompatible = compatible.filter(
|
|
15936
17782
|
(agent) => !this.isAgentDisabled(agent.id)
|
|
15937
17783
|
);
|
|
15938
|
-
await this.activateAgentsInTurn(enabledCompatible, state, chainId, asset);
|
|
17784
|
+
await this.activateAgentsInTurn(enabledCompatible, state, chainId, options.asset);
|
|
15939
17785
|
}
|
|
15940
17786
|
assertActivationSession(state) {
|
|
15941
17787
|
if (this.state !== state) {
|
|
@@ -15955,12 +17801,17 @@ var OwneySDK = class {
|
|
|
15955
17801
|
* Serializing costs no real wall-clock: the user can only approve one prompt
|
|
15956
17802
|
* at a time anyway.
|
|
15957
17803
|
*
|
|
15958
|
-
* Stop at the first failure
|
|
15959
|
-
* agent's wallet prompt
|
|
15960
|
-
*
|
|
17804
|
+
* Stop at the first failure (2026-11-06): a connect needs every agent, so
|
|
17805
|
+
* no later agent's wallet prompt opens for a sign-in that already failed.
|
|
17806
|
+
* When an earlier agent activated, the partial failure reports it, and
|
|
17807
|
+
* `walletRejected` tells the app the user canceled; the app ends the
|
|
17808
|
+
* session either way. When none activated, the agent's own error is thrown.
|
|
17809
|
+
* A failure the provider marks `permanent` is thrown as
|
|
17810
|
+
* `AGENT_ACTIVATION_BLOCKED`.
|
|
15961
17811
|
*/
|
|
15962
17812
|
async activateAgentsInTurn(agents, state, chainId, asset) {
|
|
15963
17813
|
let firstError = null;
|
|
17814
|
+
let walletRejected = false;
|
|
15964
17815
|
const activatedAgentIds = [];
|
|
15965
17816
|
const failedAgents = [];
|
|
15966
17817
|
for (const agent of agents) {
|
|
@@ -15971,6 +17822,7 @@ var OwneySDK = class {
|
|
|
15971
17822
|
await this.applyOrgPolicyTo(agent, state, chainId);
|
|
15972
17823
|
this.assertActivationSession(state);
|
|
15973
17824
|
activatedAgentIds.push(agent.id);
|
|
17825
|
+
this.declinedSignIns.get(chainId)?.delete(agent.id);
|
|
15974
17826
|
} catch (error) {
|
|
15975
17827
|
this.assertActivationSession(state);
|
|
15976
17828
|
const message = error !== null && typeof error === "object" && "message" in error && typeof error.message === "string" ? error.message : typeof error === "string" ? error : "No activation error message was returned.";
|
|
@@ -15980,15 +17832,28 @@ var OwneySDK = class {
|
|
|
15980
17832
|
message,
|
|
15981
17833
|
...error instanceof OwneyError && error.details ? { details: error.details } : {}
|
|
15982
17834
|
});
|
|
15983
|
-
|
|
15984
|
-
|
|
15985
|
-
|
|
15986
|
-
|
|
17835
|
+
firstError = error;
|
|
17836
|
+
if (this.isUserRejectedWithdrawal(error)) {
|
|
17837
|
+
walletRejected = true;
|
|
17838
|
+
const declined = this.declinedSignIns.get(chainId) ?? /* @__PURE__ */ new Set();
|
|
17839
|
+
declined.add(agent.id);
|
|
17840
|
+
this.declinedSignIns.set(chainId, declined);
|
|
15987
17841
|
}
|
|
15988
17842
|
break;
|
|
15989
17843
|
}
|
|
15990
17844
|
}
|
|
15991
17845
|
if (firstError === null) return;
|
|
17846
|
+
if (failedAgents.some(({ details }) => details?.permanent === true)) {
|
|
17847
|
+
throw new OwneyError(
|
|
17848
|
+
"AGENT_ACTIVATION_BLOCKED",
|
|
17849
|
+
failedAgents.map(({ agentId, message }) => `${this.formatAgentName(agentId)} activation failed: ${message}`).join(" "),
|
|
17850
|
+
{
|
|
17851
|
+
activatedAgentIds,
|
|
17852
|
+
failedAgentIds: failedAgents.map(({ agentId }) => agentId),
|
|
17853
|
+
failures: failedAgents
|
|
17854
|
+
}
|
|
17855
|
+
);
|
|
17856
|
+
}
|
|
15992
17857
|
if (activatedAgentIds.length === 0) throw firstError;
|
|
15993
17858
|
const failedAgentIds = failedAgents.map(({ agentId }) => agentId);
|
|
15994
17859
|
const activeNames = activatedAgentIds.map(this.formatAgentName).join(", ");
|
|
@@ -15998,7 +17863,7 @@ var OwneySDK = class {
|
|
|
15998
17863
|
throw new OwneyError(
|
|
15999
17864
|
"AGENT_ACTIVATION_PARTIAL_FAILURE",
|
|
16000
17865
|
`${activeNames} activated. ${failureMessages}`,
|
|
16001
|
-
{ activatedAgentIds, failedAgentIds, failures: failedAgents }
|
|
17866
|
+
{ activatedAgentIds, failedAgentIds, failures: failedAgents, ...walletRejected ? { walletRejected: true } : {} }
|
|
16002
17867
|
);
|
|
16003
17868
|
}
|
|
16004
17869
|
/**
|
|
@@ -16013,6 +17878,10 @@ var OwneySDK = class {
|
|
|
16013
17878
|
* all shares into one signature; custom callbacks still run once per agent.
|
|
16014
17879
|
* @param options.agentId - Optional explicit target. Otherwise split equally,
|
|
16015
17880
|
* or fund remaining agents when a recovery deposit cannot meet every minimum.
|
|
17881
|
+
* @param options.excludeAgentIds - Agents that must receive nothing. The rest
|
|
17882
|
+
* split the whole amount under their own minimums. Throws
|
|
17883
|
+
* `ALL_AGENTS_EXCLUDED` when none is left or `agentId` is listed. Ignored
|
|
17884
|
+
* when resuming a signed batch.
|
|
16016
17885
|
* @returns {OwneyDepositResult} for a single agent, or {OwneyMultiDepositResult} with per-agent results
|
|
16017
17886
|
*/
|
|
16018
17887
|
async deposit(options) {
|
|
@@ -16041,6 +17910,7 @@ var OwneySDK = class {
|
|
|
16041
17910
|
const submitted = !!(evidence.txHash || evidence.userOpHash || evidence.callsId || evidence.depositSubmission === "started");
|
|
16042
17911
|
if (leg) ledgerOp?.leg(submitted ? { ...leg, rail: ledgerRail(evidence.agentId) } : leg);
|
|
16043
17912
|
if (leg?.status === "confirmed") this.ledgerProviderSamples(ledgerOp, evidence, "deposit");
|
|
17913
|
+
this.announceDepositConfirmed(state, chainId, evidence, ledgerOp);
|
|
16044
17914
|
} catch {
|
|
16045
17915
|
}
|
|
16046
17916
|
};
|
|
@@ -16074,15 +17944,18 @@ var OwneySDK = class {
|
|
|
16074
17944
|
return { agentResults: {} };
|
|
16075
17945
|
}
|
|
16076
17946
|
const state = this.requireState();
|
|
16077
|
-
const chainId = this.requireChainId();
|
|
17947
|
+
const chainId = options.chainId ?? this.requireChainId();
|
|
17948
|
+
const activatedChain = state.chainId;
|
|
17949
|
+
const excludeAgentIds = options.resumeTxHash || options.resumeSavedBatch ? void 0 : options.excludeAgentIds;
|
|
17950
|
+
this.assertDepositAgentsRemain(chainId, asset, agentId, excludeAgentIds);
|
|
16078
17951
|
let checkpointFailure;
|
|
16079
17952
|
let checkpointFailedEvidence = [];
|
|
16080
17953
|
const checkpoint2 = options.onBeforeSubmission ? async (evidence) => {
|
|
16081
17954
|
try {
|
|
16082
|
-
if (this.state !== state || state.chainId !==
|
|
17955
|
+
if (this.state !== state || state.chainId !== activatedChain) throw new Error("Wallet changed before deposit submission.");
|
|
16083
17956
|
const submitting = evidence.map((leg) => ({ ...leg, depositSubmission: "started" }));
|
|
16084
17957
|
await options.onBeforeSubmission(submitting);
|
|
16085
|
-
if (this.state !== state || state.chainId !==
|
|
17958
|
+
if (this.state !== state || state.chainId !== activatedChain) throw new Error("Wallet changed before deposit submission.");
|
|
16086
17959
|
submitting.forEach((leg) => notifyFunding(onProgress, leg));
|
|
16087
17960
|
} catch (cause) {
|
|
16088
17961
|
checkpointFailedEvidence = evidence;
|
|
@@ -16124,7 +17997,8 @@ var OwneySDK = class {
|
|
|
16124
17997
|
chainId,
|
|
16125
17998
|
token: ledgerToken?.address ?? "",
|
|
16126
17999
|
asset: asset.toLowerCase(),
|
|
16127
|
-
requestedAmountRaw: amount
|
|
18000
|
+
requestedAmountRaw: amount,
|
|
18001
|
+
...options.batchId === void 0 ? {} : { batchId: options.batchId }
|
|
16128
18002
|
});
|
|
16129
18003
|
} catch {
|
|
16130
18004
|
}
|
|
@@ -16150,7 +18024,7 @@ var OwneySDK = class {
|
|
|
16150
18024
|
const wallet = await (agent.getFundingWallet ? agent.getFundingWallet(state, chainId, asset) : agent.getUserProfile(state, chainId).then((profile) => profile.smartWallet)).catch(() => void 0);
|
|
16151
18025
|
return { agent, wallet };
|
|
16152
18026
|
}));
|
|
16153
|
-
if (this.state !== state || this.state.chainId !==
|
|
18027
|
+
if (this.state !== state || this.state.chainId !== activatedChain)
|
|
16154
18028
|
throw new OwneyError("NOT_CONNECTED", "Wallet changed while recovering the deposit.");
|
|
16155
18029
|
const usedAgents = /* @__PURE__ */ new Set();
|
|
16156
18030
|
const legs = pending2.transfers.map((transfer) => {
|
|
@@ -16170,11 +18044,11 @@ var OwneySDK = class {
|
|
|
16170
18044
|
const batchTransfer2 = getDepositBatchTransfer(effectiveCallback);
|
|
16171
18045
|
if (!batchTransfer2) throw invalid2();
|
|
16172
18046
|
const result = await runAgentDepositBatch(chainId, legs, batchTransfer2).catch((error) => {
|
|
16173
|
-
if (error instanceof OwneyError && error.code === "YIELDSEEKER_WALLET_UNVERIFIED")
|
|
18047
|
+
if (error instanceof OwneyError && (error.code === "YIELDSEEKER_WALLET_UNVERIFIED" || error.code === "YIELDSEEKER_AGENT_CLOSED" || error.details?.notSubmitted === true))
|
|
16174
18048
|
throw new OwneyError(
|
|
16175
18049
|
error.code,
|
|
16176
|
-
"We could not verify your Yieldseeker wallet on-chain, so the saved deposit was not re-sent. It may already have been submitted earlier.",
|
|
16177
|
-
{ ...error.details, notSubmitted: false, safeToFallback: false, resumeTxHash: options.resumeTxHash },
|
|
18050
|
+
error.code === "YIELDSEEKER_WALLET_UNVERIFIED" ? "We could not verify your Yieldseeker wallet on-chain, so the saved deposit was not re-sent. It may already have been submitted earlier." : "The saved deposit was not re-sent. It may already have been submitted earlier.",
|
|
18051
|
+
{ cause: error.message, ...error.details, notSubmitted: false, safeToFallback: false, resumeTxHash: options.resumeTxHash },
|
|
16178
18052
|
error.agentId
|
|
16179
18053
|
);
|
|
16180
18054
|
throw error;
|
|
@@ -16190,6 +18064,7 @@ var OwneySDK = class {
|
|
|
16190
18064
|
);
|
|
16191
18065
|
}
|
|
16192
18066
|
const agent = this.getAgent(agentId);
|
|
18067
|
+
this.validateChainSupport(agent, chainId);
|
|
16193
18068
|
this.validateAssetSupport(agent, chainId, asset);
|
|
16194
18069
|
await this.validateMinDepositAmount(agent, state, chainId, asset, amount);
|
|
16195
18070
|
return ledgerDone(await this.depositWithFallback(
|
|
@@ -16208,9 +18083,10 @@ var OwneySDK = class {
|
|
|
16208
18083
|
));
|
|
16209
18084
|
}
|
|
16210
18085
|
const totalAmount = BigInt(amount);
|
|
18086
|
+
this.validateChainHasAgents(chainId);
|
|
16211
18087
|
const eligibleAgents = this.getEligibleAgents(chainId, asset, {
|
|
16212
18088
|
excludeDisabled: true
|
|
16213
|
-
});
|
|
18089
|
+
}).filter((agent) => !excludeAgentIds?.includes(agent.id));
|
|
16214
18090
|
const prospectiveShare = totalAmount / BigInt(eligibleAgents.length);
|
|
16215
18091
|
const meetsEveryMinimum = eligibleAgents.every((agent) => prospectiveShare >= this.getMinDepositAmount(agent, chainId, asset));
|
|
16216
18092
|
const exemptFlags = meetsEveryMinimum ? eligibleAgents.map(() => false) : await Promise.all(eligibleAgents.map((agent) => this.hasExistingBalance(agent, state, chainId, asset, true)));
|
|
@@ -16358,7 +18234,7 @@ var OwneySDK = class {
|
|
|
16358
18234
|
}
|
|
16359
18235
|
try {
|
|
16360
18236
|
if (!depositCallback && appObserves && !options.resumeTxHash) {
|
|
16361
|
-
const ids = agentId ? [agentId] : this.getEligibleAgents(chainId, asset).map((agent) => agent.id);
|
|
18237
|
+
const ids = agentId ? [agentId] : this.getEligibleAgents(chainId, asset).filter((agent) => !excludeAgentIds?.includes(agent.id)).map((agent) => agent.id);
|
|
16362
18238
|
for (const id of ids) {
|
|
16363
18239
|
const evidence = [...prepared.values()].find((value) => value.agentId === id);
|
|
16364
18240
|
const rejected = error instanceof OwneyError && error.details?.notSubmitted === true;
|
|
@@ -16458,6 +18334,29 @@ var OwneySDK = class {
|
|
|
16458
18334
|
}
|
|
16459
18335
|
}
|
|
16460
18336
|
}
|
|
18337
|
+
/**
|
|
18338
|
+
* Refuses a new deposit that `excludeAgentIds` leaves with nobody to fund:
|
|
18339
|
+
* the explicit `agentId` is listed, or every agent that can take this asset
|
|
18340
|
+
* on this chain (and is not disabled) is. A no-op without a list, so a deposit
|
|
18341
|
+
* without exclusions is exactly as it was. Reads no provider.
|
|
18342
|
+
*/
|
|
18343
|
+
assertDepositAgentsRemain(chainId, asset, agentId, excludeAgentIds) {
|
|
18344
|
+
if (!excludeAgentIds?.length) return;
|
|
18345
|
+
const refuse = (message) => new OwneyError(
|
|
18346
|
+
"ALL_AGENTS_EXCLUDED",
|
|
18347
|
+
message,
|
|
18348
|
+
{ phase: "prepare", rejectedBeforeSubmission: true }
|
|
18349
|
+
);
|
|
18350
|
+
if (agentId) {
|
|
18351
|
+
if (excludeAgentIds.includes(agentId))
|
|
18352
|
+
throw refuse(`Agent "${agentId}" is excluded from this deposit. No deposit was submitted.`);
|
|
18353
|
+
return;
|
|
18354
|
+
}
|
|
18355
|
+
this.validateChainHasAgents(chainId);
|
|
18356
|
+
const remaining = this.getEligibleAgents(chainId, asset, { excludeDisabled: true }).filter((agent) => !excludeAgentIds.includes(agent.id));
|
|
18357
|
+
if (remaining.length === 0)
|
|
18358
|
+
throw refuse(`Every agent that can take ${asset} on chain ${chainId} is excluded from this deposit. No deposit was submitted.`);
|
|
18359
|
+
}
|
|
16461
18360
|
getMinDepositAmount(agent, chainId, asset) {
|
|
16462
18361
|
const chainAssets = agent.supportedAssets.find(
|
|
16463
18362
|
(sa) => sa.chainId === chainId
|
|
@@ -16564,6 +18463,41 @@ var OwneySDK = class {
|
|
|
16564
18463
|
return false;
|
|
16565
18464
|
}
|
|
16566
18465
|
}
|
|
18466
|
+
/**
|
|
18467
|
+
* Guard an explicitly requested chain against one agent's own list.
|
|
18468
|
+
*
|
|
18469
|
+
* Only reachable when the caller passes `chainId` — the activated chain has
|
|
18470
|
+
* already been checked by `activateAgent`. Kept separate from
|
|
18471
|
+
* `validateAssetSupport` so "this agent is not on Ethereum" does not arrive
|
|
18472
|
+
* worded as "this agent does not support USDC".
|
|
18473
|
+
*/
|
|
18474
|
+
validateChainSupport(agent, chainId) {
|
|
18475
|
+
if (!agent.supportedChainIds.includes(chainId)) {
|
|
18476
|
+
throw new AgentChainIncompatibleError(
|
|
18477
|
+
[{ agentId: agent.id, supportedChainIds: agent.supportedChainIds }],
|
|
18478
|
+
chainId
|
|
18479
|
+
);
|
|
18480
|
+
}
|
|
18481
|
+
}
|
|
18482
|
+
/**
|
|
18483
|
+
* Guard an explicitly requested chain before a fan-out.
|
|
18484
|
+
*
|
|
18485
|
+
* Without this the split simply produces no agents, and the caller is told
|
|
18486
|
+
* their amount "cannot activate every eligible agent" against a combined
|
|
18487
|
+
* minimum of 0 — an error about the amount when the chain is at fault.
|
|
18488
|
+
*/
|
|
18489
|
+
validateChainHasAgents(chainId) {
|
|
18490
|
+
const compatible = [...this.agents.values()].some(
|
|
18491
|
+
(agent) => agent.supportedChainIds.includes(chainId)
|
|
18492
|
+
);
|
|
18493
|
+
if (!compatible) {
|
|
18494
|
+
throw new OwneyError(
|
|
18495
|
+
"CHAIN_NO_COMPATIBLE_AGENTS",
|
|
18496
|
+
`No agents support chain ${chainId}.`,
|
|
18497
|
+
{ chainId }
|
|
18498
|
+
);
|
|
18499
|
+
}
|
|
18500
|
+
}
|
|
16567
18501
|
validateAssetSupport(agent, chainId, asset) {
|
|
16568
18502
|
const chainAssets = agent.supportedAssets.find(
|
|
16569
18503
|
(sa) => sa.chainId === chainId
|
|
@@ -16577,9 +18511,15 @@ var OwneySDK = class {
|
|
|
16577
18511
|
);
|
|
16578
18512
|
}
|
|
16579
18513
|
}
|
|
18514
|
+
/**
|
|
18515
|
+
* The agents that support this asset on this chain. `excludeDisabled` is for
|
|
18516
|
+
* new deposits: it also leaves out the agents unavailable for this slot this
|
|
18517
|
+
* session (see `getUnavailableAgentIds`). Without it, withdrawals and deposit
|
|
18518
|
+
* recovery still see every agent that may hold funds.
|
|
18519
|
+
*/
|
|
16580
18520
|
getEligibleAgents(chainId, asset, opts) {
|
|
16581
18521
|
const eligible = [...this.agents.values()].filter((agent) => {
|
|
16582
|
-
if (opts?.excludeDisabled && this.isAgentDisabled(agent.id)) {
|
|
18522
|
+
if (opts?.excludeDisabled && (this.isAgentDisabled(agent.id) || this.isAgentUnavailable(agent.id, chainId, asset))) {
|
|
16583
18523
|
return false;
|
|
16584
18524
|
}
|
|
16585
18525
|
const chainAssets = agent.supportedAssets.find(
|
|
@@ -16607,20 +18547,13 @@ var OwneySDK = class {
|
|
|
16607
18547
|
return approvalOrder || left.index - right.index;
|
|
16608
18548
|
}).map(({ agent }) => agent);
|
|
16609
18549
|
}
|
|
18550
|
+
/**
|
|
18551
|
+
* The user cancelled a wallet prompt, for any agent: see isWalletRejection.
|
|
18552
|
+
* That includes an agent error that kept the rejection only as text in
|
|
18553
|
+
* `details.cause`.
|
|
18554
|
+
*/
|
|
16610
18555
|
isUserRejectedWithdrawal(error) {
|
|
16611
|
-
|
|
16612
|
-
const seen = /* @__PURE__ */ new Set();
|
|
16613
|
-
while (current && typeof current === "object" && !seen.has(current)) {
|
|
16614
|
-
seen.add(current);
|
|
16615
|
-
const candidate = current;
|
|
16616
|
-
if (candidate.code === 4001 || candidate.code === "4001" || candidate.code === "ACTION_REJECTED") return true;
|
|
16617
|
-
const message = [candidate.message, candidate.shortMessage].filter((value) => typeof value === "string").join(" ");
|
|
16618
|
-
if (/user (?:rejected|denied)|rejected by user|request rejected/i.test(message)) {
|
|
16619
|
-
return true;
|
|
16620
|
-
}
|
|
16621
|
-
current = candidate.cause;
|
|
16622
|
-
}
|
|
16623
|
-
return false;
|
|
18556
|
+
return isWalletRejection(error);
|
|
16624
18557
|
}
|
|
16625
18558
|
captureReadScope(requestedChain) {
|
|
16626
18559
|
const original = this.requireState();
|
|
@@ -16721,6 +18654,7 @@ var OwneySDK = class {
|
|
|
16721
18654
|
if (isFullYieldseekerWithdrawal(transaction, { ...evidence, agentWallet }, token.address, receipt))
|
|
16722
18655
|
verified = inspectFundingReceipt(receipt, { ...evidence, agentWallet, intendedAmount: "MAX" }, token.address, direction);
|
|
16723
18656
|
}
|
|
18657
|
+
if (direction === "deposit") this.announceDepositConfirmed(state, chainId, verified);
|
|
16724
18658
|
const key2 = `${state.walletAddress.toLowerCase()}:${chainId}:${evidence.agentId}:${evidence.token}:${evidence.txHash}`;
|
|
16725
18659
|
if (options.refreshBalance !== false && (verified.transfer === "confirmed" || verified.transfer === "failed" && verified.confirmedAmount === "0") && !this.recoveredFundingReads.has(key2)) {
|
|
16726
18660
|
agent.invalidateFundingRead?.(state, chainId, evidence.token, options.balanceRefreshUntil, evidence.txHash);
|
|
@@ -16729,6 +18663,33 @@ var OwneySDK = class {
|
|
|
16729
18663
|
}
|
|
16730
18664
|
return verified;
|
|
16731
18665
|
}
|
|
18666
|
+
/**
|
|
18667
|
+
* Tells the agent, once per confirmed deposit transfer, that its deposit
|
|
18668
|
+
* landed (`IAgent.depositConfirmed`), and records the outcome on the
|
|
18669
|
+
* deposit's ledger operation when there is one. In the background: never
|
|
18670
|
+
* throws and never delays the deposit. A missed notice only leaves the
|
|
18671
|
+
* provider on its own schedule.
|
|
18672
|
+
*/
|
|
18673
|
+
announceDepositConfirmed(state, chainId, evidence, ledgerOp) {
|
|
18674
|
+
try {
|
|
18675
|
+
if (evidence.transfer !== "confirmed") return;
|
|
18676
|
+
const agent = this.agents.get(evidence.agentId);
|
|
18677
|
+
const movement = evidence.txHash ?? evidence.userOpHash ?? evidence.callsId;
|
|
18678
|
+
if (!agent?.depositConfirmed || !movement) return;
|
|
18679
|
+
const key2 = `${state.walletAddress.toLowerCase()}:${chainId}:${evidence.agentId}:${evidence.token}:${movement.toLowerCase()}`;
|
|
18680
|
+
if (this.announcedDeposits.has(key2)) return;
|
|
18681
|
+
this.announcedDeposits.add(key2);
|
|
18682
|
+
if (this.announcedDeposits.size > 256) this.announcedDeposits.delete(this.announcedDeposits.values().next().value);
|
|
18683
|
+
const legKey = `agent:${evidence.agentId}`;
|
|
18684
|
+
void Promise.resolve().then(() => agent.depositConfirmed(state, chainId, evidence)).then((notice) => notice, () => ({ notified: false, reason: "ERROR" })).then((notice) => {
|
|
18685
|
+
try {
|
|
18686
|
+
ledgerOp?.event?.("provider.deposit_notified", { legKey, ...notice });
|
|
18687
|
+
} catch {
|
|
18688
|
+
}
|
|
18689
|
+
});
|
|
18690
|
+
} catch {
|
|
18691
|
+
}
|
|
18692
|
+
}
|
|
16732
18693
|
noteFundingRefresh(key2, armed) {
|
|
16733
18694
|
this.recoveredFundingReads.delete(key2);
|
|
16734
18695
|
this.recoveredFundingReads.set(key2, armed);
|
|
@@ -17217,6 +19178,14 @@ var OwneySDK = class {
|
|
|
17217
19178
|
return hash2;
|
|
17218
19179
|
},
|
|
17219
19180
|
ensureChain: (id) => this.ensureSwapChain(id),
|
|
19181
|
+
// Over HTTP, so a wallet that broadcast the wrap without telling the
|
|
19182
|
+
// page cannot also hide that it landed (ROUT-726).
|
|
19183
|
+
readWrappedBalance: () => publicClient.readContract({
|
|
19184
|
+
address: wrapper.address,
|
|
19185
|
+
abi: ERC20_ALLOWANCE_ABI,
|
|
19186
|
+
functionName: "balanceOf",
|
|
19187
|
+
args: [walletAddress]
|
|
19188
|
+
}),
|
|
17220
19189
|
// Read through the same public client as every other sizing input, so
|
|
17221
19190
|
// a wallet sitting on the wrong chain cannot answer for this one.
|
|
17222
19191
|
readAllowance: (token, spender) => publicClient.readContract({
|
|
@@ -17299,6 +19268,19 @@ var OwneySDK = class {
|
|
|
17299
19268
|
chain: dstChain,
|
|
17300
19269
|
transport: swapReadTransport(quote.dst.chainId, this.zyfaiRpcUrls)
|
|
17301
19270
|
});
|
|
19271
|
+
const walletPublic = (0, import_viem25.createPublicClient)({
|
|
19272
|
+
chain: srcChain,
|
|
19273
|
+
transport: (0, import_viem25.custom)(provider)
|
|
19274
|
+
});
|
|
19275
|
+
const signOnSource = (payload) => signWithChainRetry(
|
|
19276
|
+
walletPublic,
|
|
19277
|
+
wallet,
|
|
19278
|
+
quote.src.chainId,
|
|
19279
|
+
() => wallet.signTypedData({
|
|
19280
|
+
account: state.walletAddress,
|
|
19281
|
+
...payload
|
|
19282
|
+
})
|
|
19283
|
+
);
|
|
17302
19284
|
return {
|
|
17303
19285
|
api: this.swapApi(),
|
|
17304
19286
|
// Native-aware, like readSourceBalance below. Native ETH is never a
|
|
@@ -17349,10 +19331,7 @@ var OwneySDK = class {
|
|
|
17349
19331
|
},
|
|
17350
19332
|
signTypedData: (typedData) => {
|
|
17351
19333
|
assertWallet();
|
|
17352
|
-
return
|
|
17353
|
-
account: state.walletAddress,
|
|
17354
|
-
...typedData
|
|
17355
|
-
});
|
|
19334
|
+
return signOnSource(typedData);
|
|
17356
19335
|
},
|
|
17357
19336
|
// Chain-bound like every other read here: the wallet provider's chain is
|
|
17358
19337
|
// not ours to rely on mid-swap.
|
|
@@ -17421,10 +19400,7 @@ var OwneySDK = class {
|
|
|
17421
19400
|
chainId: quote.src.chainId,
|
|
17422
19401
|
signTypedData: (payload) => {
|
|
17423
19402
|
assertWallet();
|
|
17424
|
-
return
|
|
17425
|
-
account: state.walletAddress,
|
|
17426
|
-
...payload
|
|
17427
|
-
});
|
|
19403
|
+
return signOnSource(payload);
|
|
17428
19404
|
}
|
|
17429
19405
|
}
|
|
17430
19406
|
),
|
|
@@ -17451,13 +19427,27 @@ var OwneySDK = class {
|
|
|
17451
19427
|
* would strand funds we might have been able to move.
|
|
17452
19428
|
*/
|
|
17453
19429
|
/** ERC20 balance of the connected wallet, read through the wallet's own node. */
|
|
19430
|
+
/**
|
|
19431
|
+
* A read client pinned to `chainId`, over HTTP rather than the wallet.
|
|
19432
|
+
*
|
|
19433
|
+
* The swap rail has read this way from the start, and the reason is written
|
|
19434
|
+
* out at `buildSwapDeps`: a provider-backed client reads from whatever chain
|
|
19435
|
+
* the WALLET is on, which after a cross-chain swap is the source chain, not
|
|
19436
|
+
* the one the funds landed on. The deposit's own reads did not, so a Permit2
|
|
19437
|
+
* check for WETH on Arbitrum went to Base — where that address is not a
|
|
19438
|
+
* contract at all, so viem got "0x" back and threw "The contract function
|
|
19439
|
+
* 'allowance' returned no data".
|
|
19440
|
+
*/
|
|
19441
|
+
chainReader(chainId) {
|
|
19442
|
+
return (0, import_viem25.createPublicClient)({
|
|
19443
|
+
chain: swapChain(chainId),
|
|
19444
|
+
transport: swapReadTransport(chainId, this.zyfaiRpcUrls)
|
|
19445
|
+
});
|
|
19446
|
+
}
|
|
17454
19447
|
async readTokenBalance(chainId, token) {
|
|
17455
19448
|
const state = this.requireState();
|
|
17456
19449
|
return readErc20Balance(
|
|
17457
|
-
(
|
|
17458
|
-
chain: swapChain(chainId),
|
|
17459
|
-
transport: (0, import_viem25.custom)(this.requireConnectedProvider())
|
|
17460
|
-
}),
|
|
19450
|
+
this.chainReader(chainId),
|
|
17461
19451
|
token,
|
|
17462
19452
|
state.walletAddress
|
|
17463
19453
|
);
|
|
@@ -17466,10 +19456,7 @@ var OwneySDK = class {
|
|
|
17466
19456
|
async readTokenPermit2Allowance(chainId, token) {
|
|
17467
19457
|
const state = this.requireState();
|
|
17468
19458
|
return readPermit2Allowance(
|
|
17469
|
-
(
|
|
17470
|
-
chain: swapChain(chainId),
|
|
17471
|
-
transport: (0, import_viem25.custom)(this.requireConnectedProvider())
|
|
17472
|
-
}),
|
|
19459
|
+
this.chainReader(chainId),
|
|
17473
19460
|
token,
|
|
17474
19461
|
state.walletAddress
|
|
17475
19462
|
);
|
|
@@ -17498,6 +19485,34 @@ var OwneySDK = class {
|
|
|
17498
19485
|
const balance = await this.readTokenBalance(chainId, token);
|
|
17499
19486
|
return (balance < received ? balance : received).toString();
|
|
17500
19487
|
}
|
|
19488
|
+
/**
|
|
19489
|
+
* Deposit a swap's output, retrying once at the balance the deposit saw.
|
|
19490
|
+
*
|
|
19491
|
+
* `settleSwapDepositAmount` approves and THEN reads, but the read and the
|
|
19492
|
+
* deposit's own pre-check can disagree: the approval is confirmed through
|
|
19493
|
+
* the wallet's node, the read goes to a pinned RPC, and gas paid in WETH
|
|
19494
|
+
* (MetaMask offers this to a wallet with no ETH) can land after either.
|
|
19495
|
+
* ROUT-618 failed that way with the settle step in place.
|
|
19496
|
+
*
|
|
19497
|
+
* The pre-check reports the balance it saw, and that is the authority, so
|
|
19498
|
+
* a shortfall is retried once at that figure. Only a small one: a node that
|
|
19499
|
+
* has not caught up can read near zero, and depositing that would leave the
|
|
19500
|
+
* rest of the swap stranded behind a "success".
|
|
19501
|
+
*/
|
|
19502
|
+
async depositSwapOutput(options) {
|
|
19503
|
+
const attempt = (amount) => this.deposit({ ...options, amount });
|
|
19504
|
+
try {
|
|
19505
|
+
return {
|
|
19506
|
+
deposit: await attempt(options.amount),
|
|
19507
|
+
deposited: options.amount
|
|
19508
|
+
};
|
|
19509
|
+
} catch (error) {
|
|
19510
|
+
const balance = shortfallBalance(error, BigInt(options.amount));
|
|
19511
|
+
if (balance === void 0) throw error;
|
|
19512
|
+
const deposited = balance.toString();
|
|
19513
|
+
return { deposit: await attempt(deposited), deposited };
|
|
19514
|
+
}
|
|
19515
|
+
}
|
|
17501
19516
|
async walletSeesBalance(chainId, token, amount) {
|
|
17502
19517
|
const provider = this.requireConnectedProvider();
|
|
17503
19518
|
const state = this.requireState();
|
|
@@ -17523,9 +19538,39 @@ var OwneySDK = class {
|
|
|
17523
19538
|
* Runs a quoted swap. A named seam rather than an inline `executeSwap` call
|
|
17524
19539
|
* so the deposit half of `swapAndDeposit` can be exercised on its own.
|
|
17525
19540
|
*/
|
|
17526
|
-
runSwap(quote, options, onTransactionHash) {
|
|
19541
|
+
async runSwap(quote, options, onTransactionHash) {
|
|
19542
|
+
await this.checkSwapGas(quote);
|
|
17527
19543
|
return executeSwap(this.buildSwapDeps(quote, options.assertCurrent, onTransactionHash), { quote, ...options });
|
|
17528
19544
|
}
|
|
19545
|
+
/**
|
|
19546
|
+
* Throws SWAP_INSUFFICIENT_GAS when the wallet cannot pay for this swap.
|
|
19547
|
+
*
|
|
19548
|
+
* Only the classic rail is ever refused: it is the one where the user sends
|
|
19549
|
+
* the transactions. Call it on a preview quote to warn BEFORE a withdrawal
|
|
19550
|
+
* moves anything — `withdrawAndSwap` repeats it on its own quote, but by
|
|
19551
|
+
* then the funds have already left the agent (ROUT-622).
|
|
19552
|
+
*/
|
|
19553
|
+
async checkSwapGas(quote) {
|
|
19554
|
+
const state = this.requireState();
|
|
19555
|
+
const chain2 = swapChain(quote.src.chainId);
|
|
19556
|
+
if (!chain2) return;
|
|
19557
|
+
const pub = (0, import_viem25.createPublicClient)({
|
|
19558
|
+
chain: chain2,
|
|
19559
|
+
transport: swapReadTransport(quote.src.chainId, this.zyfaiRpcUrls)
|
|
19560
|
+
});
|
|
19561
|
+
const shortfall = await swapGasShortfall(
|
|
19562
|
+
{
|
|
19563
|
+
readNativeBalance: () => pub.getBalance({ address: state.walletAddress }),
|
|
19564
|
+
// The 1559 ceiling, as the wrap reserve reads it.
|
|
19565
|
+
getMaxFeePerGas: async () => {
|
|
19566
|
+
const fees = await pub.estimateFeesPerGas();
|
|
19567
|
+
return fees.maxFeePerGas ?? pub.getGasPrice();
|
|
19568
|
+
}
|
|
19569
|
+
},
|
|
19570
|
+
quote
|
|
19571
|
+
);
|
|
19572
|
+
if (shortfall) throw swapGasError(shortfall, chain2.nativeCurrency.symbol);
|
|
19573
|
+
}
|
|
17529
19574
|
/**
|
|
17530
19575
|
* The half of the swap deps that only ever talks to the routing API.
|
|
17531
19576
|
*
|
|
@@ -17586,8 +19631,17 @@ var OwneySDK = class {
|
|
|
17586
19631
|
* second half of `swapAndDeposit` on its own. Cleared only once the deposit
|
|
17587
19632
|
* has actually gone through — a failure here leaves the record in place so it
|
|
17588
19633
|
* can be offered again rather than silently dropped.
|
|
19634
|
+
*
|
|
19635
|
+
* The record does not remember `excludeAgentIds`, on purpose: the caller must
|
|
19636
|
+
* pass the CURRENT list, because the user's choice may have changed since the
|
|
19637
|
+
* swap (a deposit reads it fresh each time). Without it, a record with no
|
|
19638
|
+
* `agentId` splits across every eligible agent. When the list leaves nobody to
|
|
19639
|
+
* fund (or names the record's own agent) it throws `ALL_AGENTS_EXCLUDED`
|
|
19640
|
+
* before the wallet is touched and keeps the record.
|
|
19641
|
+
*
|
|
19642
|
+
* @param options.excludeAgentIds - See `DepositOptions.excludeAgentIds`.
|
|
17589
19643
|
*/
|
|
17590
|
-
async completePendingDeposit(id) {
|
|
19644
|
+
async completePendingDeposit(id, options = {}) {
|
|
17591
19645
|
const entry = listPendingDeposits().find((p) => p.id === id);
|
|
17592
19646
|
if (!entry) {
|
|
17593
19647
|
throw new OwneyError(
|
|
@@ -17596,13 +19650,28 @@ var OwneySDK = class {
|
|
|
17596
19650
|
{ id }
|
|
17597
19651
|
);
|
|
17598
19652
|
}
|
|
19653
|
+
this.assertDepositAgentsRemain(
|
|
19654
|
+
entry.chainId,
|
|
19655
|
+
entry.symbol,
|
|
19656
|
+
entry.agentId,
|
|
19657
|
+
options.excludeAgentIds
|
|
19658
|
+
);
|
|
17599
19659
|
await this.ensureSwapChain(entry.chainId);
|
|
17600
|
-
const
|
|
17601
|
-
|
|
19660
|
+
const token = entry.symbol === "WETH" ? SPONSORED_WETH_BY_CHAIN[entry.chainId] : void 0;
|
|
19661
|
+
const amount = token ? await this.settleSwapDepositAmount(
|
|
19662
|
+
entry.chainId,
|
|
19663
|
+
token,
|
|
19664
|
+
entry.symbol,
|
|
19665
|
+
BigInt(entry.received)
|
|
19666
|
+
) : entry.received;
|
|
19667
|
+
const { deposit } = await this.depositSwapOutput({
|
|
19668
|
+
amount,
|
|
17602
19669
|
asset: entry.symbol,
|
|
17603
19670
|
...entry.agentId ? { agentId: entry.agentId } : {},
|
|
19671
|
+
...options.excludeAgentIds ? { excludeAgentIds: options.excludeAgentIds } : {},
|
|
17604
19672
|
// The swap's own funding-ledger operation; older records have none.
|
|
17605
|
-
...typeof entry.operationId === "string" ? { operationId: entry.operationId } : {}
|
|
19673
|
+
...typeof entry.operationId === "string" ? { operationId: entry.operationId } : {},
|
|
19674
|
+
...typeof entry.batchId === "string" ? { batchId: entry.batchId } : {}
|
|
17606
19675
|
});
|
|
17607
19676
|
clearPendingDeposit(entry.id);
|
|
17608
19677
|
return deposit;
|
|
@@ -17661,13 +19730,15 @@ var OwneySDK = class {
|
|
|
17661
19730
|
chainId: deposit.chainId,
|
|
17662
19731
|
createdAt: Date.now(),
|
|
17663
19732
|
...typeof deposit.agentId === "string" ? { agentId: deposit.agentId } : {},
|
|
17664
|
-
...typeof deposit.operationId === "string" ? { operationId: deposit.operationId } : {}
|
|
19733
|
+
...typeof deposit.operationId === "string" ? { operationId: deposit.operationId } : {},
|
|
19734
|
+
...typeof deposit.batchId === "string" ? { batchId: deposit.batchId } : {}
|
|
17665
19735
|
});
|
|
17666
19736
|
clearOrder(order.orderHash);
|
|
17667
19737
|
updateWithdrawSwap(order.orderHash, { status: "landed" });
|
|
17668
19738
|
return { orderHash: order.orderHash, status: "completed" };
|
|
17669
19739
|
} catch (error) {
|
|
17670
|
-
if (error instanceof OwneyError && error.code === "SWAP_ORDER_REFUNDED" && error.details?.outcome === "refunded"
|
|
19740
|
+
if (error instanceof OwneyError && (error.code === "SWAP_ORDER_REFUNDED" && error.details?.outcome === "refunded" || // The provider never accepted it: nothing was escrowed.
|
|
19741
|
+
error.code === "SWAP_ORDER_NOT_FOUND")) {
|
|
17671
19742
|
clearOrder(order.orderHash);
|
|
17672
19743
|
updateWithdrawSwap(order.orderHash, { status: "refunded" });
|
|
17673
19744
|
} else {
|
|
@@ -17826,6 +19897,7 @@ var OwneySDK = class {
|
|
|
17826
19897
|
async swapAndDeposit(options) {
|
|
17827
19898
|
const state = this.requireState();
|
|
17828
19899
|
options.assertCurrent?.();
|
|
19900
|
+
this.assertDepositAgentsRemain(options.to.chainId, options.to.symbol, options.agentId, options.excludeAgentIds);
|
|
17829
19901
|
if (options.agentId) {
|
|
17830
19902
|
this.validateAssetSupport(
|
|
17831
19903
|
this.getAgent(options.agentId),
|
|
@@ -17840,7 +19912,8 @@ var OwneySDK = class {
|
|
|
17840
19912
|
owner: state.walletAddress,
|
|
17841
19913
|
chainId: options.to.chainId,
|
|
17842
19914
|
token: SupportedAssets.find((value) => value.chainId === options.to.chainId && value.symbol === options.to.symbol)?.address ?? "",
|
|
17843
|
-
asset: options.to.symbol.toLowerCase()
|
|
19915
|
+
asset: options.to.symbol.toLowerCase(),
|
|
19916
|
+
...options.batchId === void 0 ? {} : { batchId: options.batchId }
|
|
17844
19917
|
});
|
|
17845
19918
|
const secretHandoff = this.secretHandoffFor(ledgerOp, ledgerInput);
|
|
17846
19919
|
try {
|
|
@@ -17878,7 +19951,8 @@ var OwneySDK = class {
|
|
|
17878
19951
|
symbol: options.to.symbol,
|
|
17879
19952
|
chainId: quote.dst.chainId,
|
|
17880
19953
|
...options.agentId ? { agentId: options.agentId } : {},
|
|
17881
|
-
...ledgerOp ? { operationId: ledgerOp.operationId } : {}
|
|
19954
|
+
...ledgerOp ? { operationId: ledgerOp.operationId } : {},
|
|
19955
|
+
...options.batchId === void 0 ? {} : { batchId: options.batchId }
|
|
17882
19956
|
},
|
|
17883
19957
|
...secretHandoff ? { secretHandoff } : {},
|
|
17884
19958
|
...ledgerOp ? { onOrderSubmitted: (orderHash) => {
|
|
@@ -17921,17 +19995,18 @@ var OwneySDK = class {
|
|
|
17921
19995
|
options.assertCurrent?.();
|
|
17922
19996
|
await options.onBeforeDeposit?.();
|
|
17923
19997
|
options.assertCurrent?.();
|
|
17924
|
-
const deposit = await this.
|
|
19998
|
+
const { deposit, deposited } = await this.depositSwapOutput({
|
|
17925
19999
|
amount,
|
|
17926
20000
|
asset: options.to.symbol,
|
|
17927
20001
|
...options.agentId ? { agentId: options.agentId } : {},
|
|
20002
|
+
...options.excludeAgentIds ? { excludeAgentIds: options.excludeAgentIds } : {},
|
|
17928
20003
|
...options.onDepositProgress ? { onProgress: options.onDepositProgress } : {},
|
|
17929
20004
|
...options.onBeforeDepositSubmission ? { onBeforeSubmission: options.onBeforeDepositSubmission } : {},
|
|
17930
20005
|
...options.assertCurrent ? { assertSubmissionCurrent: options.assertCurrent } : {},
|
|
17931
20006
|
...ledgerOp ? { operationId: ledgerOp.operationId } : {}
|
|
17932
20007
|
});
|
|
17933
20008
|
if (backgroundDepositId) clearPendingDeposit(backgroundDepositId);
|
|
17934
|
-
return this.ledgerSucceeded(ledgerOp, { swap, deposit, deposited
|
|
20009
|
+
return this.ledgerSucceeded(ledgerOp, { swap, deposit, deposited });
|
|
17935
20010
|
} catch (error) {
|
|
17936
20011
|
const pending2 = {
|
|
17937
20012
|
// Keyed by the order when there is one, so it replaces any record a
|
|
@@ -17943,7 +20018,11 @@ var OwneySDK = class {
|
|
|
17943
20018
|
...options.agentId ? { agentId: options.agentId } : {},
|
|
17944
20019
|
createdAt: Date.now()
|
|
17945
20020
|
};
|
|
17946
|
-
savePendingDeposit(
|
|
20021
|
+
savePendingDeposit({
|
|
20022
|
+
...pending2,
|
|
20023
|
+
...ledgerOp ? { operationId: ledgerOp.operationId } : {},
|
|
20024
|
+
...options.batchId === void 0 ? {} : { batchId: options.batchId }
|
|
20025
|
+
});
|
|
17947
20026
|
throw new OwneyError(
|
|
17948
20027
|
"SWAP_DEPOSIT_PENDING",
|
|
17949
20028
|
`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.`,
|
|
@@ -17993,7 +20072,8 @@ var OwneySDK = class {
|
|
|
17993
20072
|
token: asset.address,
|
|
17994
20073
|
asset: asset.symbol.toLowerCase(),
|
|
17995
20074
|
isMax: recovery.requested === void 0,
|
|
17996
|
-
...recovery.requested === void 0 ? {} : { requestedAmountRaw: recovery.requested }
|
|
20075
|
+
...recovery.requested === void 0 ? {} : { requestedAmountRaw: recovery.requested },
|
|
20076
|
+
...record2.batchId === void 0 ? {} : { batchId: record2.batchId }
|
|
17997
20077
|
});
|
|
17998
20078
|
} catch {
|
|
17999
20079
|
}
|
|
@@ -18148,6 +20228,7 @@ var OwneySDK = class {
|
|
|
18148
20228
|
let ledgerInput;
|
|
18149
20229
|
ledgerOp = this.openSwapLedger(() => {
|
|
18150
20230
|
const requestedRaw = saved ? saved.recovery.requested : options.amount === void 0 ? void 0 : (0, import_viem25.parseUnits)(options.amount, asset.decimals).toString();
|
|
20231
|
+
const batchId = saved?.batchId ?? options.batchId;
|
|
18151
20232
|
return ledgerInput = {
|
|
18152
20233
|
operationId: saved?.operationId ?? options.operationId,
|
|
18153
20234
|
kind: "withdraw_swap",
|
|
@@ -18156,7 +20237,8 @@ var OwneySDK = class {
|
|
|
18156
20237
|
token: asset.address,
|
|
18157
20238
|
asset: asset.symbol.toLowerCase(),
|
|
18158
20239
|
isMax: requestedRaw === void 0,
|
|
18159
|
-
...requestedRaw === void 0 ? {} : { requestedAmountRaw: requestedRaw }
|
|
20240
|
+
...requestedRaw === void 0 ? {} : { requestedAmountRaw: requestedRaw },
|
|
20241
|
+
...batchId === void 0 ? {} : { batchId }
|
|
18160
20242
|
};
|
|
18161
20243
|
});
|
|
18162
20244
|
const secretHandoff = this.secretHandoffFor(ledgerOp, ledgerInput);
|
|
@@ -18201,7 +20283,8 @@ var OwneySDK = class {
|
|
|
18201
20283
|
agentId: options.agentId,
|
|
18202
20284
|
evidence: {}
|
|
18203
20285
|
},
|
|
18204
|
-
...ledgerOp ? { operationId: ledgerOp.operationId } : {}
|
|
20286
|
+
...ledgerOp ? { operationId: ledgerOp.operationId } : {},
|
|
20287
|
+
...options.batchId === void 0 ? {} : { batchId: options.batchId }
|
|
18205
20288
|
};
|
|
18206
20289
|
if (ledgerOp && !record2.operationId) record2.operationId = ledgerOp.operationId;
|
|
18207
20290
|
hadDurableRecord = saveWithdrawSwap(record2);
|
|
@@ -18317,6 +20400,8 @@ var OwneySDK = class {
|
|
|
18317
20400
|
() => new OwneyError("SWAP_WALLET_PROMPT_TIMEOUT", "The wallet did not confirm its chain. No swap was submitted.", { outcome: "not-submitted" })
|
|
18318
20401
|
);
|
|
18319
20402
|
assertCurrent();
|
|
20403
|
+
await this.checkSwapGas(quote);
|
|
20404
|
+
assertCurrent();
|
|
18320
20405
|
const swap = await executeSwap(this.buildSwapDeps(quote, assertCurrent, (hash2) => {
|
|
18321
20406
|
record2.txHash = hash2;
|
|
18322
20407
|
saveWithdrawSwap(record2);
|
|
@@ -18446,7 +20531,7 @@ var OwneySDK = class {
|
|
|
18446
20531
|
{ phase: "prepare", rejectedBeforeSubmission: true }
|
|
18447
20532
|
);
|
|
18448
20533
|
const state = this.requireState();
|
|
18449
|
-
const chainId = this.requireChainId();
|
|
20534
|
+
const chainId = options.chainId ?? this.requireChainId();
|
|
18450
20535
|
const submissionKey = `${state.walletAddress.toLowerCase()}:${chainId}:${options.asset.toUpperCase()}`;
|
|
18451
20536
|
if (this.withdrawalSubmissions.has(submissionKey))
|
|
18452
20537
|
throw new OwneyError(
|
|
@@ -18454,7 +20539,7 @@ var OwneySDK = class {
|
|
|
18454
20539
|
"A withdrawal request is already running.",
|
|
18455
20540
|
{ chainId, asset: options.asset, phase: "prepare", rejectedBeforeSubmission: true }
|
|
18456
20541
|
);
|
|
18457
|
-
const ids = options.agentId ? [options.agentId] : this.getActiveAgentIds().filter((id) => !options.excludeAgentIds?.includes(id));
|
|
20542
|
+
const ids = options.agentId ? [options.agentId] : this.getActiveAgentIds().filter((id) => !options.excludeAgentIds?.includes(id) && !this.hasNoAgentForSlot(this.agents.get(id), state, chainId, options.asset));
|
|
18458
20543
|
const attempted = /* @__PURE__ */ new Set();
|
|
18459
20544
|
this.withdrawalSubmissions.add(submissionKey);
|
|
18460
20545
|
let ledgerOp;
|
|
@@ -18468,7 +20553,8 @@ var OwneySDK = class {
|
|
|
18468
20553
|
token: ledgerToken?.address ?? "",
|
|
18469
20554
|
asset: options.asset.toLowerCase(),
|
|
18470
20555
|
isMax: options.amount === void 0,
|
|
18471
|
-
...options.amount !== void 0 ? { requestedAmountRaw: BigInt(options.amount).toString() } : {}
|
|
20556
|
+
...options.amount !== void 0 ? { requestedAmountRaw: BigInt(options.amount).toString() } : {},
|
|
20557
|
+
...options.batchId === void 0 ? {} : { batchId: options.batchId }
|
|
18472
20558
|
});
|
|
18473
20559
|
} catch {
|
|
18474
20560
|
}
|
|
@@ -18793,6 +20879,7 @@ var OwneySDK = class {
|
|
|
18793
20879
|
}
|
|
18794
20880
|
async withdrawFromAgents(options, state, chainId, attempted, ledgerLeg, reservation, plannedLegs, settleLedger, serverLegs = /* @__PURE__ */ new Map()) {
|
|
18795
20881
|
const { asset, amount, agentId, onAgentResult } = options;
|
|
20882
|
+
const activatedChain = state.chainId;
|
|
18796
20883
|
const notifyAgentResult = (id, result) => {
|
|
18797
20884
|
try {
|
|
18798
20885
|
if (result.evidence) notifyFunding(options.onProgress, result.evidence);
|
|
@@ -18853,7 +20940,7 @@ var OwneySDK = class {
|
|
|
18853
20940
|
const plannedTask = serverLegs.get(agent.id);
|
|
18854
20941
|
const serverTask = plannedTask ? await plannedTask.answer : void 0;
|
|
18855
20942
|
if (serverTask) await settleLedger?.(3e3);
|
|
18856
|
-
if (this.state !== state || this.state.chainId !==
|
|
20943
|
+
if (this.state !== state || this.state.chainId !== activatedChain)
|
|
18857
20944
|
throw new OwneyError("NOT_CONNECTED", "Wallet connection changed before withdrawal submission.");
|
|
18858
20945
|
attempted.add(agent.id);
|
|
18859
20946
|
let evidence = {
|
|
@@ -18923,6 +21010,8 @@ var OwneySDK = class {
|
|
|
18923
21010
|
progress({ ...evidence, transfer: "failed", delivery: "failed" });
|
|
18924
21011
|
if (serverLegs.size && requested2 === void 0 && agent.withdrawalRequiresWalletApproval && error instanceof OwneyError && error.code === "WITHDRAW_INSUFFICIENT_BALANCE" && error.details?.available === "0" && evidence.transfer === "failed" && !evidence.txHash && !evidence.userOpHash && !evidence.callsId)
|
|
18925
21012
|
ledgerLeg?.(evidence, "WITHDRAW_INSUFFICIENT_BALANCE");
|
|
21013
|
+
else if (error instanceof OwneyError && /^[A-Z0-9_]{1,64}$/.test(error.code) && evidence.transfer === "failed" && !evidence.withdrawalRequest?.failure && !(requested2 === void 0 && error.code === "WITHDRAW_INSUFFICIENT_BALANCE"))
|
|
21014
|
+
ledgerLeg?.(evidence, error.code);
|
|
18926
21015
|
settled2({ settled: "threw", evidence });
|
|
18927
21016
|
throw error;
|
|
18928
21017
|
}
|
|
@@ -18938,6 +21027,7 @@ var OwneySDK = class {
|
|
|
18938
21027
|
}
|
|
18939
21028
|
if (agentId) {
|
|
18940
21029
|
const agent = this.getAgent(agentId);
|
|
21030
|
+
this.validateChainSupport(agent, chainId);
|
|
18941
21031
|
this.validateAssetSupport(agent, chainId, asset);
|
|
18942
21032
|
const result = await withFailureReporting(
|
|
18943
21033
|
this.apiKey,
|
|
@@ -19029,7 +21119,7 @@ var OwneySDK = class {
|
|
|
19029
21119
|
serverLegs.set(planned.agentId, leg);
|
|
19030
21120
|
}
|
|
19031
21121
|
};
|
|
19032
|
-
const eligibleAgents = this.getEligibleAgents(chainId, asset).filter((agent) => !options.excludeAgentIds?.includes(agent.id));
|
|
21122
|
+
const eligibleAgents = this.getEligibleAgents(chainId, asset).filter((agent) => !options.excludeAgentIds?.includes(agent.id) && !this.hasNoAgentForSlot(agent, state, chainId, asset));
|
|
19033
21123
|
const withdrawalAgents = this.orderAgentsForWithdrawal(eligibleAgents);
|
|
19034
21124
|
if (!amount) {
|
|
19035
21125
|
const results2 = {};
|
|
@@ -19161,7 +21251,7 @@ var OwneySDK = class {
|
|
|
19161
21251
|
const verified = await entry.agent.getWithdrawableBalance(state, chainId, token, minimumAmount);
|
|
19162
21252
|
if (typeof verified !== "bigint" || verified < 0n)
|
|
19163
21253
|
throw new OwneyError("WITHDRAW_BALANCE_UNAVAILABLE", "Invalid withdrawal balance proof.", {}, entry.agent.id);
|
|
19164
|
-
if (this.state !== state || this.state.walletAddress !== state.walletAddress || this.state.chainId !==
|
|
21254
|
+
if (this.state !== state || this.state.walletAddress !== state.walletAddress || this.state.chainId !== activatedChain)
|
|
19165
21255
|
throw new OwneyError("NOT_CONNECTED", "Account changed while planning withdrawal.");
|
|
19166
21256
|
entry.balance = verified;
|
|
19167
21257
|
const unavailableIndex = unavailableAgents.indexOf(entry.agent);
|
|
@@ -19176,7 +21266,7 @@ var OwneySDK = class {
|
|
|
19176
21266
|
};
|
|
19177
21267
|
}
|
|
19178
21268
|
}));
|
|
19179
|
-
if (this.state !== state || this.state.chainId !==
|
|
21269
|
+
if (this.state !== state || this.state.chainId !== activatedChain)
|
|
19180
21270
|
throw new OwneyError("NOT_CONNECTED", "Account changed while planning withdrawal.");
|
|
19181
21271
|
const unavailableAgentIds = unavailableAgents.map((agent) => agent.id);
|
|
19182
21272
|
const totalAvailable = balances.reduce((sum, x) => sum + x.balance, 0n);
|
|
@@ -19357,11 +21447,82 @@ var OwneySDK = class {
|
|
|
19357
21447
|
* @param agentId - Optional. Agent to query. Omit for aggregated balances.
|
|
19358
21448
|
* @returns {AgentBalance} for a single agent, or {OwneyBalances} with totalBalance and per-agent breakdown
|
|
19359
21449
|
*/
|
|
21450
|
+
/**
|
|
21451
|
+
* Withdraw every position the wallet holds, across chains and assets.
|
|
21452
|
+
*
|
|
21453
|
+
* `withdraw()` drains one asset on one chain, so this is N of those. It
|
|
21454
|
+
* deliberately does not stop at the first failure: the funds in the other
|
|
21455
|
+
* positions are just as withdrawable, and someone who asked for everything
|
|
21456
|
+
* is better served by three of four than by none. Each leg reports its own
|
|
21457
|
+
* outcome so the caller can name the ones that did not arrive; only a total
|
|
21458
|
+
* failure throws.
|
|
21459
|
+
*
|
|
21460
|
+
* @returns {OwneyWithdrawAllResult} one leg per position attempted.
|
|
21461
|
+
*/
|
|
21462
|
+
async withdrawAll() {
|
|
21463
|
+
this.requireState();
|
|
21464
|
+
const balances = await this.readBalances(void 0, false);
|
|
21465
|
+
const positions = /* @__PURE__ */ new Map();
|
|
21466
|
+
for (const agentBalance of Object.values(balances.agentBalances ?? {})) {
|
|
21467
|
+
for (const token of agentBalance.tokens ?? []) {
|
|
21468
|
+
if (!(Number(token.amount) > 0)) continue;
|
|
21469
|
+
const key2 = `${token.chainId}:${token.asset}`;
|
|
21470
|
+
const seen = positions.get(key2);
|
|
21471
|
+
if (seen) {
|
|
21472
|
+
seen.amount = String(Number(seen.amount) + Number(token.amount));
|
|
21473
|
+
continue;
|
|
21474
|
+
}
|
|
21475
|
+
positions.set(key2, {
|
|
21476
|
+
chainId: token.chainId,
|
|
21477
|
+
asset: token.asset,
|
|
21478
|
+
amount: token.amount
|
|
21479
|
+
});
|
|
21480
|
+
}
|
|
21481
|
+
}
|
|
21482
|
+
if (positions.size === 0) {
|
|
21483
|
+
throw new OwneyError(
|
|
21484
|
+
"WITHDRAW_NOTHING_TO_WITHDRAW",
|
|
21485
|
+
"There is nothing to withdraw."
|
|
21486
|
+
);
|
|
21487
|
+
}
|
|
21488
|
+
const legs = [];
|
|
21489
|
+
for (const position2 of positions.values()) {
|
|
21490
|
+
try {
|
|
21491
|
+
const result = await this.withdraw({
|
|
21492
|
+
asset: position2.asset,
|
|
21493
|
+
chainId: position2.chainId
|
|
21494
|
+
});
|
|
21495
|
+
legs.push({ ...position2, result });
|
|
21496
|
+
} catch (err) {
|
|
21497
|
+
console.error(
|
|
21498
|
+
`withdrawAll failed for ${position2.asset} on ${position2.chainId}:`,
|
|
21499
|
+
err
|
|
21500
|
+
);
|
|
21501
|
+
legs.push({
|
|
21502
|
+
...position2,
|
|
21503
|
+
error: err instanceof Error ? err.message : String(err)
|
|
21504
|
+
});
|
|
21505
|
+
}
|
|
21506
|
+
}
|
|
21507
|
+
if (legs.every((leg) => leg.error !== void 0)) {
|
|
21508
|
+
throw new OwneyError(
|
|
21509
|
+
"WITHDRAW_ALL_FAILED",
|
|
21510
|
+
"Failed to withdraw from every position.",
|
|
21511
|
+
{
|
|
21512
|
+
legErrors: Object.fromEntries(
|
|
21513
|
+
legs.map((leg) => [`${leg.asset}:${leg.chainId}`, leg.error])
|
|
21514
|
+
)
|
|
21515
|
+
}
|
|
21516
|
+
);
|
|
21517
|
+
}
|
|
21518
|
+
return { legs };
|
|
21519
|
+
}
|
|
19360
21520
|
async getBalances(agentId, options) {
|
|
19361
21521
|
if (agentId) {
|
|
19362
|
-
const { state, chainId, assertCurrent } = this.captureReadScope(options?.chainId);
|
|
21522
|
+
const { state: scope, chainId, assertCurrent } = this.captureReadScope(options?.chainId);
|
|
19363
21523
|
const asset = options?.asset;
|
|
19364
21524
|
const agent = this.getAgent(agentId);
|
|
21525
|
+
const state = this.readStateFor(agentId, scope);
|
|
19365
21526
|
const result = await this.readAgent(
|
|
19366
21527
|
agent,
|
|
19367
21528
|
"balances",
|
|
@@ -19374,7 +21535,11 @@ var OwneySDK = class {
|
|
|
19374
21535
|
balanceComposition: agent.balanceComposition ?? "tokens-include-positions"
|
|
19375
21536
|
};
|
|
19376
21537
|
}
|
|
19377
|
-
const
|
|
21538
|
+
const portfolio = options?.chainId === void 0 && options?.asset === void 0;
|
|
21539
|
+
return this.readBalances(options, portfolio);
|
|
21540
|
+
}
|
|
21541
|
+
async readBalances(options, portfolio) {
|
|
21542
|
+
const { balances, failures } = await this.readAggregatedBalances(options, portfolio);
|
|
19378
21543
|
if (Object.keys(balances.agentBalances).length === 0) {
|
|
19379
21544
|
throw new OwneyError(
|
|
19380
21545
|
"BALANCE_ALL_FAILED",
|
|
@@ -19385,21 +21550,27 @@ var OwneySDK = class {
|
|
|
19385
21550
|
return balances;
|
|
19386
21551
|
}
|
|
19387
21552
|
/** Preserve failure objects for withdrawal recovery without changing public balance results. */
|
|
19388
|
-
async readAggregatedBalances(options) {
|
|
21553
|
+
async readAggregatedBalances(options, portfolio = false) {
|
|
19389
21554
|
const { state, chainId, assertCurrent } = this.captureReadScope(options?.chainId);
|
|
19390
21555
|
const asset = options?.asset;
|
|
19391
|
-
const readBalance = (
|
|
19392
|
-
agent,
|
|
21556
|
+
const readBalance = (read2) => !read2.offChain ? this.readAgent(
|
|
21557
|
+
read2.agent,
|
|
19393
21558
|
"balances",
|
|
19394
|
-
() => asset ? agent.getBalances(state, chainId, asset) : agent.getBalances(state, chainId),
|
|
21559
|
+
() => asset ? read2.agent.getBalances(read2.state, chainId, asset) : read2.agent.getBalances(read2.state, chainId),
|
|
19395
21560
|
asset ? { asset } : null
|
|
21561
|
+
) : this.readAgent(
|
|
21562
|
+
read2.agent,
|
|
21563
|
+
"balances",
|
|
21564
|
+
() => read2.agent.getBalances(read2.state, read2.chainId),
|
|
21565
|
+
{ chainId: read2.chainId }
|
|
19396
21566
|
);
|
|
19397
21567
|
let totalBalance = 0;
|
|
19398
21568
|
const results = {};
|
|
19399
|
-
const entries =
|
|
21569
|
+
const entries = (portfolio ? this.portfolioReads(state, chainId) : this.activeReads(state, chainId)).map((read2) => [read2.id, read2]);
|
|
19400
21570
|
const balanceResults = await Promise.allSettled(
|
|
19401
|
-
entries.map(async ([id,
|
|
19402
|
-
const
|
|
21571
|
+
entries.map(async ([id, read2]) => {
|
|
21572
|
+
const { agent } = read2;
|
|
21573
|
+
const b = await readBalance(read2);
|
|
19403
21574
|
return [
|
|
19404
21575
|
id,
|
|
19405
21576
|
{
|
|
@@ -19450,16 +21621,21 @@ var OwneySDK = class {
|
|
|
19450
21621
|
const chainId = this.requireChainId();
|
|
19451
21622
|
if (agentId) {
|
|
19452
21623
|
const agent = this.getAgent(agentId);
|
|
21624
|
+
const readState = this.readStateFor(agentId, state);
|
|
19453
21625
|
return this.readAgent(
|
|
19454
21626
|
agent,
|
|
19455
21627
|
"earnings",
|
|
19456
|
-
() => agent.getEarnings(
|
|
21628
|
+
() => agent.getEarnings(readState, chainId)
|
|
19457
21629
|
);
|
|
19458
21630
|
}
|
|
19459
|
-
const entries = [...this.getActiveAgents().entries()];
|
|
19460
21631
|
return this.aggregateEarnings(
|
|
19461
|
-
|
|
19462
|
-
(
|
|
21632
|
+
this.portfolioReads(state, chainId),
|
|
21633
|
+
(read2) => this.readAgent(
|
|
21634
|
+
read2.agent,
|
|
21635
|
+
"earnings",
|
|
21636
|
+
() => read2.agent.getEarnings(read2.state, read2.chainId),
|
|
21637
|
+
read2.offChain ? { chainId: read2.chainId } : null
|
|
21638
|
+
)
|
|
19463
21639
|
);
|
|
19464
21640
|
}
|
|
19465
21641
|
/**
|
|
@@ -19469,23 +21645,24 @@ var OwneySDK = class {
|
|
|
19469
21645
|
async refreshEarnings(agentId) {
|
|
19470
21646
|
const state = this.requireState();
|
|
19471
21647
|
const chainId = this.requireChainId();
|
|
19472
|
-
const refreshAgent = (agent) => this.readAgent(
|
|
21648
|
+
const refreshAgent = ({ agent, state: readState, chainId: readChain, offChain }) => this.readAgent(
|
|
19473
21649
|
agent,
|
|
19474
21650
|
agent.refreshEarnings ? "refreshEarnings" : "earnings",
|
|
19475
|
-
() => agent.refreshEarnings?.(
|
|
21651
|
+
() => agent.refreshEarnings?.(readState, readChain) ?? agent.getEarnings(readState, readChain),
|
|
21652
|
+
offChain ? { chainId: readChain } : null
|
|
19476
21653
|
);
|
|
19477
|
-
if (agentId) return refreshAgent(this.getAgent(agentId));
|
|
19478
|
-
return this.aggregateEarnings(
|
|
21654
|
+
if (agentId) return refreshAgent({ agent: this.getAgent(agentId), state: this.readStateFor(agentId, state), chainId });
|
|
21655
|
+
return this.aggregateEarnings(this.portfolioReads(state, chainId), refreshAgent);
|
|
19479
21656
|
}
|
|
19480
21657
|
async aggregateEarnings(entries, read2) {
|
|
19481
|
-
const settled2 = await Promise.allSettled(entries.map(
|
|
21658
|
+
const settled2 = await Promise.allSettled(entries.map(read2));
|
|
19482
21659
|
const agentEarnings = {};
|
|
19483
21660
|
const agentErrors = {};
|
|
19484
21661
|
const agentRetryAt = {};
|
|
19485
21662
|
const failures = [];
|
|
19486
21663
|
let totalEarnings = 0;
|
|
19487
21664
|
for (let i = 0; i < settled2.length; i++) {
|
|
19488
|
-
const
|
|
21665
|
+
const { id } = entries[i];
|
|
19489
21666
|
const result = settled2[i];
|
|
19490
21667
|
if (result.status === "fulfilled") {
|
|
19491
21668
|
agentEarnings[id] = result.value;
|
|
@@ -19532,9 +21709,46 @@ var OwneySDK = class {
|
|
|
19532
21709
|
async getDailyEarnings({
|
|
19533
21710
|
agentId,
|
|
19534
21711
|
days,
|
|
19535
|
-
tokenSymbol
|
|
21712
|
+
tokenSymbol,
|
|
21713
|
+
chainIds
|
|
19536
21714
|
}) {
|
|
19537
21715
|
const state = this.requireState();
|
|
21716
|
+
if (chainIds?.length) {
|
|
21717
|
+
const agents = (agentId ? [this.getAgent(agentId)] : [...this.getActiveAgents().values()]).filter((agent) => agent.getDailyEarnings);
|
|
21718
|
+
const legs = [];
|
|
21719
|
+
for (const agent of agents) {
|
|
21720
|
+
for (const legChainId of chainIds) {
|
|
21721
|
+
if (agentRunsOn(agent, legChainId))
|
|
21722
|
+
legs.push({ agent, legChainId, legState: this.readStateFor(agent.id, state) });
|
|
21723
|
+
}
|
|
21724
|
+
}
|
|
21725
|
+
if (!agentId) {
|
|
21726
|
+
for (const extra of this.offChainPortfolioAgents(state)) {
|
|
21727
|
+
if (!extra.agent.getDailyEarnings) continue;
|
|
21728
|
+
for (const legChainId of chainIds) {
|
|
21729
|
+
if (extra.chainIds.includes(legChainId))
|
|
21730
|
+
legs.push({ agent: extra.agent, legChainId, legState: extra.state });
|
|
21731
|
+
}
|
|
21732
|
+
}
|
|
21733
|
+
}
|
|
21734
|
+
const settled3 = await Promise.allSettled(
|
|
21735
|
+
legs.map(
|
|
21736
|
+
({ agent, legChainId, legState }) => this.readAgent(
|
|
21737
|
+
agent,
|
|
21738
|
+
"dailyEarnings",
|
|
21739
|
+
() => agent.getDailyEarnings(legState, legChainId, days, tokenSymbol),
|
|
21740
|
+
// The leg's chain must be in the key: the read key otherwise names
|
|
21741
|
+
// only the CONNECTION chain, so every leg shared the first leg's
|
|
21742
|
+
// request and the sum counted that chain once per leg. (ROUT-561)
|
|
21743
|
+
{ days, tokenSymbol, chainId: legChainId }
|
|
21744
|
+
)
|
|
21745
|
+
)
|
|
21746
|
+
);
|
|
21747
|
+
const series2 = settled3.flatMap((result) => result.status === "fulfilled" ? [result.value] : []);
|
|
21748
|
+
const failure = settled3.find((result) => result.status === "rejected");
|
|
21749
|
+
if (!series2.length && failure?.status === "rejected") throw failure.reason;
|
|
21750
|
+
return mergeDailyEarnings(series2);
|
|
21751
|
+
}
|
|
19538
21752
|
const chainId = this.requireChainId();
|
|
19539
21753
|
if (agentId) {
|
|
19540
21754
|
const agent = this.getAgent(agentId);
|
|
@@ -19545,22 +21759,21 @@ var OwneySDK = class {
|
|
|
19545
21759
|
assets: []
|
|
19546
21760
|
};
|
|
19547
21761
|
}
|
|
21762
|
+
const readState = this.readStateFor(agentId, state);
|
|
19548
21763
|
return this.readAgent(
|
|
19549
21764
|
agent,
|
|
19550
21765
|
"dailyEarnings",
|
|
19551
|
-
() => agent.getDailyEarnings(
|
|
21766
|
+
() => agent.getDailyEarnings(readState, chainId, days, tokenSymbol),
|
|
19552
21767
|
{ days, tokenSymbol }
|
|
19553
21768
|
);
|
|
19554
21769
|
}
|
|
19555
|
-
const entries =
|
|
19556
|
-
([, agent]) => agent.getDailyEarnings
|
|
19557
|
-
);
|
|
21770
|
+
const entries = this.activeReads(state, chainId).filter(({ agent }) => agent.getDailyEarnings);
|
|
19558
21771
|
const settled2 = await Promise.allSettled(
|
|
19559
21772
|
entries.map(
|
|
19560
|
-
(
|
|
21773
|
+
({ agent, state: readState }) => this.readAgent(
|
|
19561
21774
|
agent,
|
|
19562
21775
|
"dailyEarnings",
|
|
19563
|
-
() => agent.getDailyEarnings(
|
|
21776
|
+
() => agent.getDailyEarnings(readState, chainId, days, tokenSymbol),
|
|
19564
21777
|
{ days, tokenSymbol }
|
|
19565
21778
|
)
|
|
19566
21779
|
)
|
|
@@ -19576,49 +21789,136 @@ var OwneySDK = class {
|
|
|
19576
21789
|
assets: aggregateDailyEarnings(series, tokenSymbol)
|
|
19577
21790
|
};
|
|
19578
21791
|
}
|
|
21792
|
+
/**
|
|
21793
|
+
* The deposit-time pool catalogue (ROUT-569): every protocol with its
|
|
21794
|
+
* selectable pools (name, APY, TVL, link) for `asset` under `strategy`.
|
|
21795
|
+
* Defaults to the zyfai agent, the only one with pool customization today.
|
|
21796
|
+
*/
|
|
21797
|
+
async getPoolCatalog(params) {
|
|
21798
|
+
await this.ensureAgentsInitialized();
|
|
21799
|
+
const agent = this.getAgent(params.agentId ?? "zyfai");
|
|
21800
|
+
if (!agent.getPoolCatalog) {
|
|
21801
|
+
throw new OwneyError(
|
|
21802
|
+
"POOL_CATALOG_UNSUPPORTED",
|
|
21803
|
+
`Agent ${agent.id} does not support pool customization`
|
|
21804
|
+
);
|
|
21805
|
+
}
|
|
21806
|
+
return agent.getPoolCatalog({
|
|
21807
|
+
asset: params.asset,
|
|
21808
|
+
strategy: params.strategy
|
|
21809
|
+
});
|
|
21810
|
+
}
|
|
21811
|
+
/**
|
|
21812
|
+
* Apply a user's deposit-time pool selection to their account (ROUT-569).
|
|
21813
|
+
* The request carries explicit pool choices plus the resulting strategy for
|
|
21814
|
+
* each asset reviewed in the deposit flow.
|
|
21815
|
+
*/
|
|
21816
|
+
async setPoolSelection(params) {
|
|
21817
|
+
await this.ensureAgentsInitialized();
|
|
21818
|
+
const agent = this.getAgent(params.agentId ?? "zyfai");
|
|
21819
|
+
if (!agent.setPoolSelection) {
|
|
21820
|
+
throw new OwneyError(
|
|
21821
|
+
"POOL_SELECTION_UNSUPPORTED",
|
|
21822
|
+
`Agent ${agent.id} does not support pool customization`
|
|
21823
|
+
);
|
|
21824
|
+
}
|
|
21825
|
+
await agent.setPoolSelection(params.selection, this.state ?? void 0);
|
|
21826
|
+
}
|
|
21827
|
+
/**
|
|
21828
|
+
* The pool selection saved on the user's account (ROUT-650), so the Pools
|
|
21829
|
+
* step can show what applies now rather than the defaults. `pairs` and
|
|
21830
|
+
* `assets` say which protocol/chain lists and strategies to read.
|
|
21831
|
+
*/
|
|
21832
|
+
async getPoolSelection(params) {
|
|
21833
|
+
const state = this.requireState();
|
|
21834
|
+
const chainId = this.requireChainId();
|
|
21835
|
+
await this.ensureAgentsInitialized();
|
|
21836
|
+
const agent = this.getAgent(params.agentId ?? "zyfai");
|
|
21837
|
+
if (!agent.getPoolSelection) {
|
|
21838
|
+
throw new OwneyError(
|
|
21839
|
+
"POOL_SELECTION_UNSUPPORTED",
|
|
21840
|
+
`Agent ${agent.id} does not support pool customization`
|
|
21841
|
+
);
|
|
21842
|
+
}
|
|
21843
|
+
return agent.getPoolSelection(state, chainId, {
|
|
21844
|
+
pairs: params.pairs,
|
|
21845
|
+
assets: params.assets
|
|
21846
|
+
});
|
|
21847
|
+
}
|
|
21848
|
+
/**
|
|
21849
|
+
* The agents a person can customize pools for: registered, enabled, and
|
|
21850
|
+
* able to list a pool catalogue. Waits for agent initialization, so an agent
|
|
21851
|
+
* the organization disabled is known and left out.
|
|
21852
|
+
*/
|
|
21853
|
+
async getPoolCustomizationAgents() {
|
|
21854
|
+
await this.ensureAgentsInitialized();
|
|
21855
|
+
return [...this.agents].filter(([id, agent]) => !this.isAgentDisabled(id) && typeof agent.getPoolCatalog === "function").map(([id]) => id).sort();
|
|
21856
|
+
}
|
|
19579
21857
|
async getAccountApy({
|
|
19580
21858
|
agentId,
|
|
19581
21859
|
days,
|
|
19582
|
-
tokenSymbol
|
|
21860
|
+
tokenSymbol,
|
|
21861
|
+
chainId: scope
|
|
19583
21862
|
}) {
|
|
19584
21863
|
const state = this.requireState();
|
|
19585
21864
|
const chainId = this.requireChainId();
|
|
21865
|
+
const scopeChainId = scope === "all" ? null : scope;
|
|
19586
21866
|
if (agentId) {
|
|
19587
21867
|
const agent = this.getAgent(agentId);
|
|
19588
|
-
|
|
21868
|
+
const readState = this.readStateFor(agentId, state);
|
|
21869
|
+
const accountApy = await this.readAgent(
|
|
19589
21870
|
agent,
|
|
19590
21871
|
"accountApy",
|
|
19591
|
-
() => agent.getAccountApy(
|
|
19592
|
-
{ days, tokenSymbol }
|
|
21872
|
+
() => agent.getAccountApy(readState, chainId, days, tokenSymbol, scopeChainId),
|
|
21873
|
+
{ days, tokenSymbol, scopeChainId }
|
|
21874
|
+
);
|
|
21875
|
+
return this.enrichApyHistory(
|
|
21876
|
+
accountApy,
|
|
21877
|
+
agentId,
|
|
21878
|
+
scopeChainId === null ? void 0 : scopeChainId ?? chainId,
|
|
21879
|
+
tokenSymbol
|
|
19593
21880
|
);
|
|
19594
21881
|
}
|
|
19595
|
-
const
|
|
19596
|
-
const
|
|
19597
|
-
|
|
19598
|
-
|
|
19599
|
-
|
|
19600
|
-
const apy = await this.readAgent(
|
|
21882
|
+
const entries = scopeChainId === void 0 ? this.activeReads(state, chainId) : this.portfolioReads(state, chainId).filter((read2) => !read2.offChain || scopeChainId === null || agentRunsOn(read2.agent, scopeChainId));
|
|
21883
|
+
const reads = await Promise.all(
|
|
21884
|
+
entries.map(async ({ id, agent, state: readState, chainId: readChain, offChain = false }) => {
|
|
21885
|
+
const pair = Promise.all([
|
|
21886
|
+
this.readAgent(
|
|
19601
21887
|
agent,
|
|
19602
21888
|
"accountApy",
|
|
19603
|
-
() => agent.getAccountApy(
|
|
19604
|
-
|
|
19605
|
-
|
|
19606
|
-
|
|
19607
|
-
|
|
19608
|
-
|
|
19609
|
-
|
|
19610
|
-
|
|
19611
|
-
|
|
19612
|
-
|
|
19613
|
-
|
|
19614
|
-
|
|
19615
|
-
|
|
19616
|
-
|
|
19617
|
-
|
|
19618
|
-
|
|
21889
|
+
() => agent.getAccountApy(
|
|
21890
|
+
readState,
|
|
21891
|
+
readChain,
|
|
21892
|
+
days,
|
|
21893
|
+
tokenSymbol,
|
|
21894
|
+
scopeChainId
|
|
21895
|
+
),
|
|
21896
|
+
offChain ? { days, tokenSymbol, scopeChainId, chainId: readChain } : { days, tokenSymbol, scopeChainId }
|
|
21897
|
+
),
|
|
21898
|
+
this.readAgent(
|
|
21899
|
+
agent,
|
|
21900
|
+
"balances",
|
|
21901
|
+
() => agent.getBalances(readState, readChain),
|
|
21902
|
+
offChain ? { chainId: readChain } : null
|
|
21903
|
+
).then((b) => balanceForApyScope(b, readChain, tokenSymbol))
|
|
21904
|
+
]);
|
|
21905
|
+
if (!offChain) return [id, ...await pair];
|
|
21906
|
+
return pair.then(([apy, balance]) => [id, apy, balance], (error) => {
|
|
21907
|
+
console.error(`[owney-sdk] APY fetch failed for agent "${id}" on chain ${readChain}:`, error);
|
|
21908
|
+
return null;
|
|
21909
|
+
});
|
|
21910
|
+
})
|
|
21911
|
+
);
|
|
21912
|
+
const apyResults = reads.flatMap((read2) => read2 ? [[read2[0], read2[1]]] : []);
|
|
21913
|
+
const balanceResults = reads.flatMap((read2) => read2 ? [[read2[0], read2[2]]] : []);
|
|
19619
21914
|
const results = {};
|
|
19620
21915
|
for (const [id, apy] of apyResults) {
|
|
19621
|
-
results[id] =
|
|
21916
|
+
results[id] = await this.enrichApyHistory(
|
|
21917
|
+
apy,
|
|
21918
|
+
id,
|
|
21919
|
+
scopeChainId === null ? void 0 : scopeChainId ?? chainId,
|
|
21920
|
+
tokenSymbol
|
|
21921
|
+
);
|
|
19622
21922
|
}
|
|
19623
21923
|
const balances = {};
|
|
19624
21924
|
for (const [id, bal] of balanceResults) {
|
|
@@ -19648,6 +21948,36 @@ var OwneySDK = class {
|
|
|
19648
21948
|
history
|
|
19649
21949
|
};
|
|
19650
21950
|
}
|
|
21951
|
+
async enrichApyHistory(accountApy, agentId, chainId, tokenSymbol) {
|
|
21952
|
+
const history = accountApy.history;
|
|
21953
|
+
if (agentId !== "zyfai" || chainId === void 0 || !tokenSymbol || !history?.length) return accountApy;
|
|
21954
|
+
const incentives = await fetchApyIncentives(
|
|
21955
|
+
this.apiKey,
|
|
21956
|
+
{
|
|
21957
|
+
walletAddress: accountApy.walletAddress,
|
|
21958
|
+
agentId,
|
|
21959
|
+
chainId,
|
|
21960
|
+
asset: tokenSymbol,
|
|
21961
|
+
from: history[0].date,
|
|
21962
|
+
to: history[history.length - 1].date
|
|
21963
|
+
},
|
|
21964
|
+
this.routingApiBaseUrl
|
|
21965
|
+
);
|
|
21966
|
+
if (incentives.length === 0) return accountApy;
|
|
21967
|
+
const byDate = /* @__PURE__ */ new Map();
|
|
21968
|
+
for (const { date, ...incentive } of incentives) {
|
|
21969
|
+
const entries = byDate.get(date) ?? [];
|
|
21970
|
+
entries.push(incentive);
|
|
21971
|
+
byDate.set(date, entries);
|
|
21972
|
+
}
|
|
21973
|
+
return {
|
|
21974
|
+
...accountApy,
|
|
21975
|
+
history: history.map((point) => {
|
|
21976
|
+
const pointIncentives = byDate.get(point.date);
|
|
21977
|
+
return pointIncentives?.length ? { ...point, incentives: pointIncentives } : point;
|
|
21978
|
+
})
|
|
21979
|
+
};
|
|
21980
|
+
}
|
|
19651
21981
|
/**
|
|
19652
21982
|
* Get transaction history for a specific agent, or all agents.
|
|
19653
21983
|
*
|
|
@@ -19666,11 +21996,61 @@ var OwneySDK = class {
|
|
|
19666
21996
|
* @returns {OwneyAgentHistory} `data` (up to `limit` entries), `hasMore`, `nextCursor`.
|
|
19667
21997
|
*/
|
|
19668
21998
|
async getHistory(options) {
|
|
21999
|
+
const { agentId, filters, chainIds } = options ?? {};
|
|
22000
|
+
if (chainIds?.length) {
|
|
22001
|
+
const state2 = this.requireState();
|
|
22002
|
+
const agents = agentId ? [this.getAgent(agentId)] : [...this.getActiveAgents().values()];
|
|
22003
|
+
const cursorMap2 = filters?.cursor ? decodeFanoutCursor(filters.cursor) : void 0;
|
|
22004
|
+
const legs = [];
|
|
22005
|
+
for (const agent of agents) {
|
|
22006
|
+
for (const legChainId of chainIds) {
|
|
22007
|
+
if (agentRunsOn(agent, legChainId))
|
|
22008
|
+
legs.push({ agentId: agent.id, chainId: legChainId, legState: this.readStateFor(agent.id, state2) });
|
|
22009
|
+
}
|
|
22010
|
+
}
|
|
22011
|
+
if (!agentId) {
|
|
22012
|
+
for (const extra of this.offChainPortfolioAgents(state2)) {
|
|
22013
|
+
for (const legChainId of chainIds) {
|
|
22014
|
+
if (extra.chainIds.includes(legChainId))
|
|
22015
|
+
legs.push({ agentId: extra.agent.id, chainId: legChainId, legState: extra.state });
|
|
22016
|
+
}
|
|
22017
|
+
}
|
|
22018
|
+
}
|
|
22019
|
+
const agentErrors2 = {};
|
|
22020
|
+
let firstFailure;
|
|
22021
|
+
const pages = await Promise.all(
|
|
22022
|
+
legs.map(async (leg) => {
|
|
22023
|
+
const legCursor = cursorMap2?.[fanoutKey(leg)];
|
|
22024
|
+
if (cursorMap2 && legCursor === void 0) {
|
|
22025
|
+
return { leg, page: null };
|
|
22026
|
+
}
|
|
22027
|
+
const legFilters = { ...filters, cursor: legCursor };
|
|
22028
|
+
const agent = this.getAgent(leg.agentId);
|
|
22029
|
+
try {
|
|
22030
|
+
const page = await this.readAgent(
|
|
22031
|
+
agent,
|
|
22032
|
+
"history",
|
|
22033
|
+
() => agent.getHistory(leg.legState, leg.chainId, legFilters),
|
|
22034
|
+
// Keyed per leg for the same reason as getDailyEarnings' fan-out.
|
|
22035
|
+
{ ...legFilters, chainId: leg.chainId }
|
|
22036
|
+
);
|
|
22037
|
+
return { leg, page };
|
|
22038
|
+
} catch (error) {
|
|
22039
|
+
firstFailure ??= error;
|
|
22040
|
+
agentErrors2[leg.agentId] = error instanceof Error ? error.message : String(error);
|
|
22041
|
+
return { leg, page: null };
|
|
22042
|
+
}
|
|
22043
|
+
})
|
|
22044
|
+
);
|
|
22045
|
+
if (firstFailure !== void 0 && pages.every(({ page }) => page === null)) throw firstFailure;
|
|
22046
|
+
const merged2 = mergeHistoryPages(pages);
|
|
22047
|
+
return Object.keys(agentErrors2).length ? { ...merged2, agentErrors: agentErrors2 } : merged2;
|
|
22048
|
+
}
|
|
19669
22049
|
const { state, chainId, assertCurrent } = this.captureReadScope(options?.chainId);
|
|
19670
|
-
const { agentId, filters } = options ?? {};
|
|
19671
22050
|
if (agentId) {
|
|
19672
22051
|
const agent = this.getAgent(agentId);
|
|
19673
|
-
const
|
|
22052
|
+
const readState = this.readStateFor(agentId, state);
|
|
22053
|
+
const page = await this.readAgent(agent, "history", () => agent.getHistory(readState, chainId, filters), filters);
|
|
19674
22054
|
assertCurrent();
|
|
19675
22055
|
return page;
|
|
19676
22056
|
}
|
|
@@ -19684,10 +22064,11 @@ var OwneySDK = class {
|
|
|
19684
22064
|
}
|
|
19685
22065
|
const agentFilters = { ...filters, cursor: agentCursor || void 0 };
|
|
19686
22066
|
try {
|
|
22067
|
+
const readState = this.readStateFor(agent.id, state);
|
|
19687
22068
|
const page = await this.readAgent(
|
|
19688
22069
|
agent,
|
|
19689
22070
|
"history",
|
|
19690
|
-
() => agent.getHistory(
|
|
22071
|
+
() => agent.getHistory(readState, chainId, agentFilters),
|
|
19691
22072
|
agentFilters
|
|
19692
22073
|
);
|
|
19693
22074
|
return { agentId: agent.id, page };
|
|
@@ -19745,20 +22126,20 @@ var OwneySDK = class {
|
|
|
19745
22126
|
const chainId = this.requireChainId();
|
|
19746
22127
|
if (agentId) {
|
|
19747
22128
|
const agent = this.getAgent(agentId);
|
|
22129
|
+
const readState = this.readStateFor(agentId, state);
|
|
19748
22130
|
return this.readAgent(
|
|
19749
22131
|
agent,
|
|
19750
22132
|
"profile",
|
|
19751
|
-
() => agent.getUserProfile(
|
|
22133
|
+
() => agent.getUserProfile(readState, chainId)
|
|
19752
22134
|
);
|
|
19753
22135
|
}
|
|
19754
22136
|
const results = {};
|
|
19755
|
-
const entries = [...this.getActiveAgents().entries()];
|
|
19756
22137
|
const profileResults = await Promise.all(
|
|
19757
|
-
|
|
22138
|
+
this.activeReads(state, chainId).map(async ({ id, agent, state: readState }) => {
|
|
19758
22139
|
const p = await this.readAgent(
|
|
19759
22140
|
agent,
|
|
19760
22141
|
"profile",
|
|
19761
|
-
() => agent.getUserProfile(
|
|
22142
|
+
() => agent.getUserProfile(readState, chainId)
|
|
19762
22143
|
);
|
|
19763
22144
|
return [id, p];
|
|
19764
22145
|
})
|
|
@@ -19968,10 +22349,11 @@ var OwneySDK = class {
|
|
|
19968
22349
|
const entries = [...activeAgents.entries()];
|
|
19969
22350
|
const balanceResults = await Promise.allSettled(
|
|
19970
22351
|
entries.map(async ([id, agent]) => {
|
|
22352
|
+
const readState = this.readStateFor(id, state);
|
|
19971
22353
|
const b = await this.readAgent(
|
|
19972
22354
|
agent,
|
|
19973
22355
|
"balances",
|
|
19974
|
-
() => agent.getBalances(
|
|
22356
|
+
() => agent.getBalances(readState, chainId)
|
|
19975
22357
|
);
|
|
19976
22358
|
return [id, b.positions ?? []];
|
|
19977
22359
|
})
|
|
@@ -20257,5 +22639,6 @@ function createOwneySIWX(config) {
|
|
|
20257
22639
|
saveWithdrawSwap,
|
|
20258
22640
|
setOwneyDebug,
|
|
20259
22641
|
subscribeWithdrawSwaps,
|
|
22642
|
+
switchWalletConnectChain,
|
|
20260
22643
|
updateWithdrawSwap
|
|
20261
22644
|
});
|