@owney/sdk 0.7.25-beta.3 → 0.7.26-beta.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +7 -9
- package/dist/index.cjs +1482 -2454
- package/dist/index.d.cts +414 -144
- package/dist/index.d.ts +414 -144
- package/dist/index.js +1485 -2473
- package/package.json +1 -1
package/dist/index.cjs
CHANGED
|
@@ -26,32 +26,12 @@ __export(index_exports, {
|
|
|
26
26
|
NotConnectedError: () => NotConnectedError,
|
|
27
27
|
OwneyError: () => OwneyError,
|
|
28
28
|
OwneySDK: () => OwneySDK,
|
|
29
|
-
YieldseekerAgent: () => YieldseekerAgent,
|
|
30
29
|
createOwneySIWX: () => createOwneySIWX,
|
|
30
|
+
listPendingSwaps: () => listOrders,
|
|
31
31
|
setOwneyDebug: () => setOwneyDebug
|
|
32
32
|
});
|
|
33
33
|
module.exports = __toCommonJS(index_exports);
|
|
34
34
|
|
|
35
|
-
// src/lib/deposit-batch-callback.ts
|
|
36
|
-
var batchCallbacks = /* @__PURE__ */ new WeakMap();
|
|
37
|
-
var getDepositBatchTransfer = (callback) => callback ? batchCallbacks.get(callback) : void 0;
|
|
38
|
-
function toBatchTransfer(to, amount, verification) {
|
|
39
|
-
return {
|
|
40
|
-
to,
|
|
41
|
-
amount,
|
|
42
|
-
...verification ? {
|
|
43
|
-
yieldseeker: {
|
|
44
|
-
signature: verification.signature,
|
|
45
|
-
userId: verification.userId,
|
|
46
|
-
agentId: verification.yieldseekerAgentId
|
|
47
|
-
}
|
|
48
|
-
} : {}
|
|
49
|
-
};
|
|
50
|
-
}
|
|
51
|
-
function registerDepositBatch(callback, transfer) {
|
|
52
|
-
batchCallbacks.set(callback, transfer);
|
|
53
|
-
}
|
|
54
|
-
|
|
55
35
|
// src/errors.ts
|
|
56
36
|
var OwneyError = class extends Error {
|
|
57
37
|
code;
|
|
@@ -331,18 +311,18 @@ function tokenDecimals(symbol, explicit) {
|
|
|
331
311
|
return explicit;
|
|
332
312
|
return DECIMALS_BY_SYMBOL[(symbol ?? "").toLowerCase()] ?? 6;
|
|
333
313
|
}
|
|
334
|
-
function mapDeposit(
|
|
314
|
+
function mapDeposit(raw) {
|
|
335
315
|
return {
|
|
336
|
-
txHash:
|
|
337
|
-
smartWallet:
|
|
338
|
-
amount:
|
|
316
|
+
txHash: raw.txHash,
|
|
317
|
+
smartWallet: raw.smartWallet,
|
|
318
|
+
amount: raw.amount
|
|
339
319
|
};
|
|
340
320
|
}
|
|
341
|
-
function mapWithdraw(
|
|
321
|
+
function mapWithdraw(raw) {
|
|
342
322
|
return {
|
|
343
|
-
txHash:
|
|
344
|
-
type:
|
|
345
|
-
amount:
|
|
323
|
+
txHash: raw.txHash,
|
|
324
|
+
type: raw.type,
|
|
325
|
+
amount: raw.amount
|
|
346
326
|
};
|
|
347
327
|
}
|
|
348
328
|
var CHAIN_ID_TO_NAME = {
|
|
@@ -361,10 +341,10 @@ function resolveChainId(chain) {
|
|
|
361
341
|
if (Number.isFinite(asNum) && asNum > 0) return asNum;
|
|
362
342
|
return NAME_TO_CHAIN_ID[chain.trim().toLowerCase()] ?? NaN;
|
|
363
343
|
}
|
|
364
|
-
function mapPendingAllocations(
|
|
365
|
-
if (!Array.isArray(
|
|
344
|
+
function mapPendingAllocations(raw) {
|
|
345
|
+
if (!Array.isArray(raw)) return void 0;
|
|
366
346
|
const pending = [];
|
|
367
|
-
for (const entry of
|
|
347
|
+
for (const entry of raw) {
|
|
368
348
|
if (typeof entry !== "object" || entry === null) continue;
|
|
369
349
|
const e = entry;
|
|
370
350
|
if (typeof e.chainId !== "number" || !Number.isFinite(e.chainId)) continue;
|
|
@@ -387,8 +367,8 @@ function mapPendingAllocations(raw2) {
|
|
|
387
367
|
}
|
|
388
368
|
return pending.length > 0 ? pending : void 0;
|
|
389
369
|
}
|
|
390
|
-
function mapBalances(
|
|
391
|
-
const portfolio =
|
|
370
|
+
function mapBalances(raw, _chainId, smartWallet) {
|
|
371
|
+
const portfolio = raw.portfolio;
|
|
392
372
|
const portfolioByChain = portfolio.portfolioByChain ?? {};
|
|
393
373
|
let totalBalance = 0;
|
|
394
374
|
const tokens = [];
|
|
@@ -457,8 +437,8 @@ function sumTokenValues(tokens) {
|
|
|
457
437
|
function sumTokenEarnings(tokens) {
|
|
458
438
|
return Object.values(tokens).reduce((sum, val) => sum + Number(val), 0);
|
|
459
439
|
}
|
|
460
|
-
function mapEarnings(
|
|
461
|
-
const totalEarningsByChain =
|
|
440
|
+
function mapEarnings(raw, smartWallet) {
|
|
441
|
+
const totalEarningsByChain = raw.data.totalEarningsByChainWithFee ?? raw.data.totalEarningsByChain ?? {};
|
|
462
442
|
const tokens = [];
|
|
463
443
|
for (const [chainIdKey, tokensBySymbol] of Object.entries(
|
|
464
444
|
totalEarningsByChain
|
|
@@ -477,15 +457,15 @@ function mapEarnings(raw2, smartWallet) {
|
|
|
477
457
|
return {
|
|
478
458
|
smartWallet,
|
|
479
459
|
lifetimeEarnings: sumTokenEarnings(
|
|
480
|
-
|
|
460
|
+
raw.data.totalEarningsByTokenWithFee ?? raw.data.totalEarningsByToken
|
|
481
461
|
),
|
|
482
462
|
tokens
|
|
483
463
|
};
|
|
484
464
|
}
|
|
485
|
-
function mapWeightedApyByChain(
|
|
486
|
-
if (!
|
|
465
|
+
function mapWeightedApyByChain(raw) {
|
|
466
|
+
if (!raw) return void 0;
|
|
487
467
|
const out = {};
|
|
488
|
-
for (const [chainKey, tokenApy] of Object.entries(
|
|
468
|
+
for (const [chainKey, tokenApy] of Object.entries(raw)) {
|
|
489
469
|
const chainId = Number(chainKey);
|
|
490
470
|
if (!SUPPORTED_CHAIN_IDS.includes(chainId)) continue;
|
|
491
471
|
const perAsset = {};
|
|
@@ -525,8 +505,8 @@ function rawPoolApyForChain(entry, chainId, tokenSymbol) {
|
|
|
525
505
|
}
|
|
526
506
|
return totalBalance > 0 ? weightedSum / totalBalance : null;
|
|
527
507
|
}
|
|
528
|
-
function mapApyHistory(
|
|
529
|
-
const history = Object.entries(
|
|
508
|
+
function mapApyHistory(raw, chainId, tokenSymbol) {
|
|
509
|
+
const history = Object.entries(raw.history ?? {}).map(([date, entry]) => ({
|
|
530
510
|
date,
|
|
531
511
|
apy: rawPoolApyForChain(entry, chainId, tokenSymbol),
|
|
532
512
|
// Provider position balances are treated as decimal amounts of the
|
|
@@ -542,9 +522,9 @@ function mapApyHistory(raw2, chainId, tokenSymbol) {
|
|
|
542
522
|
} : {}
|
|
543
523
|
})).filter((p) => p.apy !== null).sort((a, b) => a.date.localeCompare(b.date));
|
|
544
524
|
return {
|
|
545
|
-
walletAddress:
|
|
546
|
-
weightedApyAfterFee:
|
|
547
|
-
apyByChainAndAsset: mapWeightedApyByChain(
|
|
525
|
+
walletAddress: raw.walletAddress,
|
|
526
|
+
weightedApyAfterFee: raw.weightedApyAfterFee ? sumTokenValues(raw.weightedApyAfterFee) : void 0,
|
|
527
|
+
apyByChainAndAsset: mapWeightedApyByChain(raw.weightedApyAfterFeeByChain),
|
|
548
528
|
history
|
|
549
529
|
};
|
|
550
530
|
}
|
|
@@ -640,23 +620,23 @@ function mapEntries(rawEntries, chainId) {
|
|
|
640
620
|
};
|
|
641
621
|
});
|
|
642
622
|
}
|
|
643
|
-
function mapUserProfile(
|
|
623
|
+
function mapUserProfile(raw, userAddress) {
|
|
644
624
|
return {
|
|
645
625
|
address: userAddress,
|
|
646
|
-
smartWallet:
|
|
647
|
-
chains:
|
|
648
|
-
strategy:
|
|
649
|
-
hasActiveSessionKey:
|
|
650
|
-
protocols:
|
|
651
|
-
splitting:
|
|
652
|
-
minSplits:
|
|
626
|
+
smartWallet: raw.smartWallet || "",
|
|
627
|
+
chains: raw.chains || [],
|
|
628
|
+
strategy: raw.strategy,
|
|
629
|
+
hasActiveSessionKey: raw.hasActiveSessionKey || false,
|
|
630
|
+
protocols: raw.protocols || [],
|
|
631
|
+
splitting: raw.splitting,
|
|
632
|
+
minSplits: raw.minSplits
|
|
653
633
|
};
|
|
654
634
|
}
|
|
655
|
-
function mapApyByStrategy(
|
|
635
|
+
function mapApyByStrategy(raw) {
|
|
656
636
|
const apyPerAsset = {};
|
|
657
637
|
let apySum = 0;
|
|
658
638
|
let apyCount = 0;
|
|
659
|
-
for (const entry of
|
|
639
|
+
for (const entry of raw.data) {
|
|
660
640
|
const supported = SupportedAssets.find(
|
|
661
641
|
(asset) => asset.chainId === entry.chain_id && asset.symbol === entry.token_symbol
|
|
662
642
|
);
|
|
@@ -768,9 +748,9 @@ function netDeltaForSnapshot(entry, chainId, asset) {
|
|
|
768
748
|
debugLog("zyfai:earnings", "gross fallback for daily earnings", { gross });
|
|
769
749
|
return gross;
|
|
770
750
|
}
|
|
771
|
-
function mapDailyEarnings(
|
|
751
|
+
function mapDailyEarnings(raw, chainId, tokenSymbol) {
|
|
772
752
|
const wanted = tokenSymbol?.toUpperCase();
|
|
773
|
-
const snapshots = [...
|
|
753
|
+
const snapshots = [...raw.data ?? []].sort(
|
|
774
754
|
(a, b) => a.snapshot_date.localeCompare(b.snapshot_date)
|
|
775
755
|
);
|
|
776
756
|
const byAsset = /* @__PURE__ */ new Map();
|
|
@@ -785,7 +765,7 @@ function mapDailyEarnings(raw2, chainId, tokenSymbol) {
|
|
|
785
765
|
}
|
|
786
766
|
}
|
|
787
767
|
const assets = [...byAsset.entries()].map(([asset, series]) => ({ asset, points: series.points })).sort((a, b) => a.asset.localeCompare(b.asset));
|
|
788
|
-
return { walletAddress:
|
|
768
|
+
return { walletAddress: raw.walletAddress, chainId, assets };
|
|
789
769
|
}
|
|
790
770
|
|
|
791
771
|
// src/agents/zyfai/zyfai.withdraw-amount.ts
|
|
@@ -896,15 +876,15 @@ var readSession = (address, _chainId) => {
|
|
|
896
876
|
if (typeof window === "undefined") return null;
|
|
897
877
|
const key2 = buildKey(address);
|
|
898
878
|
const store = storage();
|
|
899
|
-
let
|
|
879
|
+
let raw = null;
|
|
900
880
|
try {
|
|
901
|
-
|
|
881
|
+
raw = store?.getItem(key2) ?? null;
|
|
902
882
|
} catch {
|
|
903
|
-
|
|
883
|
+
raw = null;
|
|
904
884
|
}
|
|
905
|
-
if (
|
|
885
|
+
if (raw) {
|
|
906
886
|
try {
|
|
907
|
-
const parsed = JSON.parse(
|
|
887
|
+
const parsed = JSON.parse(raw);
|
|
908
888
|
if (isFreshSession(parsed)) return parsed;
|
|
909
889
|
} catch {
|
|
910
890
|
}
|
|
@@ -1072,8 +1052,8 @@ function buildChainsByProtocol(protocols, dashboardChainIds) {
|
|
|
1072
1052
|
}
|
|
1073
1053
|
return result;
|
|
1074
1054
|
}
|
|
1075
|
-
function flattenAvailablePools(
|
|
1076
|
-
const byChain =
|
|
1055
|
+
function flattenAvailablePools(raw) {
|
|
1056
|
+
const byChain = raw ?? {};
|
|
1077
1057
|
const names = [];
|
|
1078
1058
|
for (const byToken of Object.values(byChain ?? {})) {
|
|
1079
1059
|
for (const entry of Object.values(byToken ?? {})) {
|
|
@@ -1576,8 +1556,8 @@ var ZyfaiAgent = class _ZyfaiAgent {
|
|
|
1576
1556
|
const poolResults = await Promise.all(
|
|
1577
1557
|
universe.map(async (protocol) => {
|
|
1578
1558
|
try {
|
|
1579
|
-
const
|
|
1580
|
-
return [protocol.id, flattenAvailablePools(
|
|
1559
|
+
const raw = await this.sdk.getAvailablePools(protocol.id, strategy);
|
|
1560
|
+
return [protocol.id, flattenAvailablePools(raw)];
|
|
1581
1561
|
} catch (error) {
|
|
1582
1562
|
console.warn(
|
|
1583
1563
|
`[zyfai] applyPoolPolicy: getAvailablePools(${protocol.id}) failed, skipping this protocol (non-fatal):`,
|
|
@@ -1643,14 +1623,14 @@ var ZyfaiAgent = class _ZyfaiAgent {
|
|
|
1643
1623
|
async readWalletState(ownerAddress) {
|
|
1644
1624
|
try {
|
|
1645
1625
|
const { portfolio } = await this.sdk.getPositions(ownerAddress);
|
|
1646
|
-
const
|
|
1626
|
+
const raw = portfolio;
|
|
1647
1627
|
debugLog("zyfai:onboard", "wallet state from getPositions", {
|
|
1648
|
-
predeployed:
|
|
1649
|
-
hasActiveSessionKey:
|
|
1628
|
+
predeployed: raw?.predeployed,
|
|
1629
|
+
hasActiveSessionKey: raw?.hasActiveSessionKey
|
|
1650
1630
|
});
|
|
1651
1631
|
return {
|
|
1652
|
-
predeployed:
|
|
1653
|
-
hasActiveSessionKey:
|
|
1632
|
+
predeployed: raw?.predeployed,
|
|
1633
|
+
hasActiveSessionKey: raw?.hasActiveSessionKey
|
|
1654
1634
|
};
|
|
1655
1635
|
} catch (error) {
|
|
1656
1636
|
console.warn(
|
|
@@ -1936,14 +1916,14 @@ var ZyfaiAgent = class _ZyfaiAgent {
|
|
|
1936
1916
|
return { txHash, smartWallet, amount };
|
|
1937
1917
|
}
|
|
1938
1918
|
await this.ensureWalletDeployed(this.getAddress(), validChainId);
|
|
1939
|
-
const
|
|
1919
|
+
const raw = await this.sdk.depositFunds(
|
|
1940
1920
|
this.getAddress(),
|
|
1941
1921
|
validChainId,
|
|
1942
1922
|
amount,
|
|
1943
1923
|
asset,
|
|
1944
1924
|
"aggressive"
|
|
1945
1925
|
);
|
|
1946
|
-
return mapDeposit(
|
|
1926
|
+
return mapDeposit(raw);
|
|
1947
1927
|
} catch (error) {
|
|
1948
1928
|
throw error;
|
|
1949
1929
|
}
|
|
@@ -1952,27 +1932,27 @@ var ZyfaiAgent = class _ZyfaiAgent {
|
|
|
1952
1932
|
async withdraw(state, chainId, token, amount) {
|
|
1953
1933
|
const validChainId = isValidChainId(chainId);
|
|
1954
1934
|
await this.ensureConnected(state, validChainId);
|
|
1955
|
-
const
|
|
1935
|
+
const raw = await this.sdk.withdrawFunds(
|
|
1956
1936
|
this.getAddress(),
|
|
1957
1937
|
validChainId,
|
|
1958
1938
|
amount,
|
|
1959
1939
|
token
|
|
1960
1940
|
);
|
|
1961
|
-
if (!
|
|
1941
|
+
if (!raw.success) {
|
|
1962
1942
|
throw new OwneyError(
|
|
1963
1943
|
"WITHDRAW_FAILED",
|
|
1964
|
-
|
|
1965
|
-
{ chainId: validChainId, token, amount, response:
|
|
1944
|
+
raw.message || "Zyfai withdraw failed.",
|
|
1945
|
+
{ chainId: validChainId, token, amount, response: raw },
|
|
1966
1946
|
this.id
|
|
1967
1947
|
);
|
|
1968
1948
|
}
|
|
1969
|
-
return mapWithdraw(
|
|
1949
|
+
return mapWithdraw(raw);
|
|
1970
1950
|
}
|
|
1971
1951
|
// --- IAgent: Portfolio reads ---
|
|
1972
1952
|
async getBalances(state, chainId) {
|
|
1973
1953
|
const { smartWallet, chainId: validChainId } = await this.resolveSmartWallet(state, chainId);
|
|
1974
|
-
const
|
|
1975
|
-
return mapBalances(
|
|
1954
|
+
const raw = await this.sdk.getPortfolio(this.getAddress());
|
|
1955
|
+
return mapBalances(raw, validChainId, smartWallet);
|
|
1976
1956
|
}
|
|
1977
1957
|
earningsKey(state, chainId, smartWallet) {
|
|
1978
1958
|
return JSON.stringify([
|
|
@@ -1985,11 +1965,11 @@ var ZyfaiAgent = class _ZyfaiAgent {
|
|
|
1985
1965
|
const existing = this.earningsReads.get(key2);
|
|
1986
1966
|
if (existing) return existing;
|
|
1987
1967
|
const generation = this.earningsGeneration;
|
|
1988
|
-
const pending = Promise.resolve().then(() => this.sdk.getOnchainEarnings(smartWallet)).then((
|
|
1968
|
+
const pending = Promise.resolve().then(() => this.sdk.getOnchainEarnings(smartWallet)).then((raw) => {
|
|
1989
1969
|
if (generation === this.earningsGeneration) {
|
|
1990
|
-
this.earningsSnapshot = { key: key2, raw
|
|
1970
|
+
this.earningsSnapshot = { key: key2, raw, at: Date.now() };
|
|
1991
1971
|
}
|
|
1992
|
-
return
|
|
1972
|
+
return raw;
|
|
1993
1973
|
}).finally(() => {
|
|
1994
1974
|
if (this.earningsReads.get(key2) === pending)
|
|
1995
1975
|
this.earningsReads.delete(key2);
|
|
@@ -1999,11 +1979,11 @@ var ZyfaiAgent = class _ZyfaiAgent {
|
|
|
1999
1979
|
}
|
|
2000
1980
|
async getEarnings(state, chainId) {
|
|
2001
1981
|
const { smartWallet } = await this.resolveSmartWallet(state, chainId);
|
|
2002
|
-
const
|
|
1982
|
+
const raw = await this.readEarnings(
|
|
2003
1983
|
this.earningsKey(state, chainId, smartWallet),
|
|
2004
1984
|
smartWallet
|
|
2005
1985
|
);
|
|
2006
|
-
return mapEarnings(
|
|
1986
|
+
return mapEarnings(raw, smartWallet);
|
|
2007
1987
|
}
|
|
2008
1988
|
async refreshEarnings(state, chainId) {
|
|
2009
1989
|
const { smartWallet } = await this.resolveSmartWallet(state, chainId);
|
|
@@ -2030,17 +2010,17 @@ var ZyfaiAgent = class _ZyfaiAgent {
|
|
|
2030
2010
|
}
|
|
2031
2011
|
async getAccountApy(state, chainId, days, tokenSymbol) {
|
|
2032
2012
|
const { smartWallet } = await this.resolveSmartWallet(state, chainId);
|
|
2033
|
-
const
|
|
2034
|
-
return mapApyHistory(
|
|
2013
|
+
const raw = await this.sdk.getDailyApyHistory(smartWallet, days);
|
|
2014
|
+
return mapApyHistory(raw, chainId, tokenSymbol);
|
|
2035
2015
|
}
|
|
2036
2016
|
async getDailyEarnings(state, chainId, days, tokenSymbol) {
|
|
2037
2017
|
const { smartWallet } = await this.resolveSmartWallet(state, chainId);
|
|
2038
2018
|
const start = new Date(Date.now() - (DayFilterMapping[days] + 1) * 864e5);
|
|
2039
|
-
const
|
|
2019
|
+
const raw = await this.sdk.getDailyEarnings(
|
|
2040
2020
|
smartWallet,
|
|
2041
2021
|
start.toISOString().slice(0, 10)
|
|
2042
2022
|
);
|
|
2043
|
-
return mapDailyEarnings(
|
|
2023
|
+
return mapDailyEarnings(raw, chainId, tokenSymbol);
|
|
2044
2024
|
}
|
|
2045
2025
|
/**
|
|
2046
2026
|
* Owney speaks asset symbols ("USDC" / "WETH"); Zyfai's history endpoint
|
|
@@ -2075,7 +2055,7 @@ var ZyfaiAgent = class _ZyfaiAgent {
|
|
|
2075
2055
|
const matched = [];
|
|
2076
2056
|
let backendExhausted = false;
|
|
2077
2057
|
for (let i = 0; i < MAX_BACKEND_CALLS && matched.length < limit; i++) {
|
|
2078
|
-
const
|
|
2058
|
+
const raw = await this.sdk.getHistory(smartWallet, validChainId, {
|
|
2079
2059
|
limit: backendPageSize,
|
|
2080
2060
|
offset,
|
|
2081
2061
|
fromDate: options?.fromDate,
|
|
@@ -2086,13 +2066,13 @@ var ZyfaiAgent = class _ZyfaiAgent {
|
|
|
2086
2066
|
// asset's rows and handing back a page that filters to nothing.
|
|
2087
2067
|
assetType
|
|
2088
2068
|
});
|
|
2089
|
-
|
|
2069
|
+
raw.data.forEach((entry, idx) => {
|
|
2090
2070
|
if (entry.chainId === validChainId) {
|
|
2091
2071
|
matched.push({ entry, rawIdx: offset + idx });
|
|
2092
2072
|
}
|
|
2093
2073
|
});
|
|
2094
|
-
offset +=
|
|
2095
|
-
if (
|
|
2074
|
+
offset += raw.data.length;
|
|
2075
|
+
if (raw.data.length < backendPageSize) {
|
|
2096
2076
|
backendExhausted = true;
|
|
2097
2077
|
break;
|
|
2098
2078
|
}
|
|
@@ -2114,18 +2094,18 @@ var ZyfaiAgent = class _ZyfaiAgent {
|
|
|
2114
2094
|
}
|
|
2115
2095
|
async getUserProfile(state, chainId) {
|
|
2116
2096
|
await this.connectAuth(state, chainId);
|
|
2117
|
-
const
|
|
2097
|
+
const raw = await this.sdk.getUserDetails();
|
|
2118
2098
|
debugLog("zyfai:profile", "getUserProfile \u2014 Zyfai reports", {
|
|
2119
2099
|
asset: "USDC (default \u2014 no asset passed)",
|
|
2120
|
-
splitting:
|
|
2121
|
-
minSplits:
|
|
2122
|
-
strategy:
|
|
2123
|
-
chains:
|
|
2124
|
-
protocolCount:
|
|
2125
|
-
hasActiveSessionKey:
|
|
2126
|
-
smartWallet:
|
|
2100
|
+
splitting: raw.splitting,
|
|
2101
|
+
minSplits: raw.minSplits,
|
|
2102
|
+
strategy: raw.strategy,
|
|
2103
|
+
chains: raw.chains,
|
|
2104
|
+
protocolCount: raw.protocols?.length,
|
|
2105
|
+
hasActiveSessionKey: raw.hasActiveSessionKey,
|
|
2106
|
+
smartWallet: raw.smartWallet
|
|
2127
2107
|
});
|
|
2128
|
-
return mapUserProfile(
|
|
2108
|
+
return mapUserProfile(raw, this.connectedAddress);
|
|
2129
2109
|
}
|
|
2130
2110
|
async ensureAutoSelectProtocols(state, chainId, asset) {
|
|
2131
2111
|
await this.connectAuth(state, chainId);
|
|
@@ -2144,20 +2124,80 @@ var ZyfaiAgent = class _ZyfaiAgent {
|
|
|
2144
2124
|
}
|
|
2145
2125
|
// --- IAgent: Discovery (no wallet required) ---
|
|
2146
2126
|
async getAgentApy(days, options) {
|
|
2147
|
-
const
|
|
2127
|
+
const raw = await this.sdk.getAPYPerStrategy(
|
|
2148
2128
|
false,
|
|
2149
2129
|
DayFilterMapping[days],
|
|
2150
2130
|
"aggressive",
|
|
2151
2131
|
options?.chainId,
|
|
2152
2132
|
options?.tokenSymbol
|
|
2153
2133
|
);
|
|
2154
|
-
return mapApyByStrategy(
|
|
2134
|
+
return mapApyByStrategy(raw);
|
|
2155
2135
|
}
|
|
2156
2136
|
};
|
|
2157
2137
|
|
|
2158
|
-
// src/
|
|
2159
|
-
var
|
|
2160
|
-
|
|
2138
|
+
// src/lib/routing-api.ts
|
|
2139
|
+
var ROUTING_API_BASE_URL = "https://owney-routing-api-243946518160.europe-west4.run.app";
|
|
2140
|
+
async function fetchOrgAgentConfig(apiKey, baseUrl = ROUTING_API_BASE_URL) {
|
|
2141
|
+
const url = `${baseUrl}/api/v1/agent/org-config`;
|
|
2142
|
+
try {
|
|
2143
|
+
const res = await fetch(url, {
|
|
2144
|
+
method: "GET",
|
|
2145
|
+
headers: {
|
|
2146
|
+
"Content-Type": "application/json",
|
|
2147
|
+
"x-owney-api-key": `${apiKey}`
|
|
2148
|
+
}
|
|
2149
|
+
});
|
|
2150
|
+
if (!res.ok) {
|
|
2151
|
+
if (res.status !== 404) {
|
|
2152
|
+
console.warn(
|
|
2153
|
+
`[owney-sdk] Could not read org agent config (${res.status}); leaving user profiles unchanged.`
|
|
2154
|
+
);
|
|
2155
|
+
}
|
|
2156
|
+
return null;
|
|
2157
|
+
}
|
|
2158
|
+
const json = await res.json();
|
|
2159
|
+
const policy = json.success ? json.data ?? null : null;
|
|
2160
|
+
debugLog(
|
|
2161
|
+
"owney-sdk",
|
|
2162
|
+
policy ? "org agent config: loaded" : "org agent config: none set by this partner \u2014 user profiles will be left as they are",
|
|
2163
|
+
policy ?? void 0
|
|
2164
|
+
);
|
|
2165
|
+
return policy;
|
|
2166
|
+
} catch (error) {
|
|
2167
|
+
console.warn(
|
|
2168
|
+
"[owney-sdk] Could not read org agent config (non-fatal):",
|
|
2169
|
+
error instanceof Error ? error.message : String(error)
|
|
2170
|
+
);
|
|
2171
|
+
return null;
|
|
2172
|
+
}
|
|
2173
|
+
}
|
|
2174
|
+
async function fetchAgentKeys(apiKey, baseUrl = ROUTING_API_BASE_URL) {
|
|
2175
|
+
const url = `${baseUrl}/api/v1/agent/keys`;
|
|
2176
|
+
const res = await fetch(url, {
|
|
2177
|
+
method: "GET",
|
|
2178
|
+
headers: {
|
|
2179
|
+
"Content-Type": "application/json",
|
|
2180
|
+
"x-owney-api-key": `${apiKey}`
|
|
2181
|
+
}
|
|
2182
|
+
});
|
|
2183
|
+
if (!res.ok) {
|
|
2184
|
+
const text = await res.text().catch(() => "");
|
|
2185
|
+
throw new OwneyError(
|
|
2186
|
+
"API_ROUTING_ERROR",
|
|
2187
|
+
`Routing API error ${res.status}: ${text}`,
|
|
2188
|
+
{ statusCode: res.status, responseBody: text }
|
|
2189
|
+
);
|
|
2190
|
+
}
|
|
2191
|
+
const json = await res.json();
|
|
2192
|
+
if (!json.success) {
|
|
2193
|
+
throw new OwneyError(
|
|
2194
|
+
"API_ROUTING_FAILED",
|
|
2195
|
+
`Routing API request failed: ${json.message}`,
|
|
2196
|
+
{ message: json.message }
|
|
2197
|
+
);
|
|
2198
|
+
}
|
|
2199
|
+
return json.data;
|
|
2200
|
+
}
|
|
2161
2201
|
|
|
2162
2202
|
// src/lib/chain-guard.ts
|
|
2163
2203
|
var CHAIN_NAMES = {
|
|
@@ -2194,132 +2234,167 @@ async function ensureWalletOnChain(pub, wallet, expected) {
|
|
|
2194
2234
|
}
|
|
2195
2235
|
}
|
|
2196
2236
|
|
|
2197
|
-
// src/lib/
|
|
2198
|
-
|
|
2199
|
-
|
|
2200
|
-
|
|
2201
|
-
|
|
2202
|
-
|
|
2203
|
-
|
|
2204
|
-
|
|
2205
|
-
|
|
2206
|
-
|
|
2207
|
-
|
|
2208
|
-
|
|
2209
|
-
|
|
2210
|
-
|
|
2211
|
-
|
|
2212
|
-
|
|
2213
|
-
|
|
2214
|
-
|
|
2215
|
-
|
|
2237
|
+
// src/lib/swap/swap-api.ts
|
|
2238
|
+
async function request(baseUrl, apiKey, path, init) {
|
|
2239
|
+
const url = `${baseUrl}/api/v1/swap${path}`;
|
|
2240
|
+
const res = await fetch(url, {
|
|
2241
|
+
method: init?.method ?? "GET",
|
|
2242
|
+
headers: {
|
|
2243
|
+
"Content-Type": "application/json",
|
|
2244
|
+
"x-owney-api-key": apiKey
|
|
2245
|
+
},
|
|
2246
|
+
...init ? { body: JSON.stringify(init.body) } : {}
|
|
2247
|
+
});
|
|
2248
|
+
if (!res.ok) {
|
|
2249
|
+
const text = await res.text().catch(() => "");
|
|
2250
|
+
if (res.status === 429) {
|
|
2251
|
+
throw new OwneyError(
|
|
2252
|
+
"SWAP_RATE_LIMITED",
|
|
2253
|
+
"Swap provider is rate limiting, retry shortly",
|
|
2254
|
+
{ statusCode: res.status }
|
|
2255
|
+
);
|
|
2256
|
+
}
|
|
2257
|
+
if (res.status === 403) {
|
|
2258
|
+
throw new OwneyError(
|
|
2259
|
+
"SWAP_DISABLED",
|
|
2260
|
+
"Swap is not enabled for this organization",
|
|
2261
|
+
{ statusCode: res.status }
|
|
2262
|
+
);
|
|
2263
|
+
}
|
|
2216
2264
|
throw new OwneyError(
|
|
2217
|
-
"
|
|
2218
|
-
`
|
|
2219
|
-
{
|
|
2265
|
+
"SWAP_REQUEST_FAILED",
|
|
2266
|
+
`Swap API error ${res.status}: ${text}`,
|
|
2267
|
+
{ statusCode: res.status, responseBody: text }
|
|
2220
2268
|
);
|
|
2221
2269
|
}
|
|
2222
|
-
const
|
|
2223
|
-
|
|
2224
|
-
try {
|
|
2225
|
-
parsed = JSON.parse(text);
|
|
2226
|
-
} catch {
|
|
2227
|
-
}
|
|
2228
|
-
if (!res.ok || !parsed?.success || typeof parsed.data?.intent !== "string" || typeof parsed.data.expiresAt !== "number") {
|
|
2270
|
+
const json = await res.json();
|
|
2271
|
+
if (!json.success) {
|
|
2229
2272
|
throw new OwneyError(
|
|
2230
|
-
"
|
|
2231
|
-
`
|
|
2232
|
-
{
|
|
2233
|
-
statusCode: res.status,
|
|
2234
|
-
responseBody: text.slice(0, 500),
|
|
2235
|
-
safeToFallback: true
|
|
2236
|
-
}
|
|
2273
|
+
"SWAP_REQUEST_FAILED",
|
|
2274
|
+
`Swap API request failed: ${json.message ?? "unknown error"}`,
|
|
2275
|
+
{ message: json.message }
|
|
2237
2276
|
);
|
|
2238
2277
|
}
|
|
2239
|
-
return
|
|
2278
|
+
return json.data;
|
|
2240
2279
|
}
|
|
2241
|
-
|
|
2242
|
-
|
|
2243
|
-
|
|
2244
|
-
|
|
2245
|
-
|
|
2246
|
-
|
|
2247
|
-
|
|
2248
|
-
|
|
2249
|
-
|
|
2250
|
-
|
|
2251
|
-
|
|
2252
|
-
|
|
2253
|
-
|
|
2254
|
-
|
|
2255
|
-
|
|
2256
|
-
|
|
2257
|
-
|
|
2258
|
-
|
|
2259
|
-
|
|
2260
|
-
|
|
2261
|
-
|
|
2262
|
-
|
|
2263
|
-
|
|
2264
|
-
|
|
2265
|
-
|
|
2266
|
-
|
|
2267
|
-
|
|
2268
|
-
|
|
2269
|
-
|
|
2270
|
-
|
|
2271
|
-
|
|
2280
|
+
function createSwapApi(baseUrl, apiKey) {
|
|
2281
|
+
return {
|
|
2282
|
+
/** Source assets the user may pay with, and each chain's deposit targets. */
|
|
2283
|
+
listTokens: () => request(baseUrl, apiKey, "/tokens"),
|
|
2284
|
+
/**
|
|
2285
|
+
* Search one chain's payable-with assets by name, symbol or address.
|
|
2286
|
+
*
|
|
2287
|
+
* Separate from `listTokens` on purpose: the full set is thousands of
|
|
2288
|
+
* tokens per chain, far too much to ship to a picker, so the short list
|
|
2289
|
+
* renders immediately and this reaches everything else on demand.
|
|
2290
|
+
*
|
|
2291
|
+
* Already filtered server-side to what a quote will accept, so anything
|
|
2292
|
+
* returned here can be paid with.
|
|
2293
|
+
*/
|
|
2294
|
+
searchTokens: (params) => request(
|
|
2295
|
+
baseUrl,
|
|
2296
|
+
apiKey,
|
|
2297
|
+
`/tokens/search?${new URLSearchParams({
|
|
2298
|
+
chainId: String(params.chainId),
|
|
2299
|
+
query: params.query,
|
|
2300
|
+
...params.limit === void 0 ? {} : { limit: String(params.limit) }
|
|
2301
|
+
}).toString()}`
|
|
2302
|
+
),
|
|
2303
|
+
/**
|
|
2304
|
+
* `walletAddress` is required even though the routing API could not infer
|
|
2305
|
+
* it: the Fusion+ quoter binds a quote to whoever will sign the order and
|
|
2306
|
+
* rejects the request without it.
|
|
2307
|
+
*/
|
|
2308
|
+
quote: (params) => request(baseUrl, apiKey, "/quote", {
|
|
2309
|
+
method: "POST",
|
|
2310
|
+
body: {
|
|
2311
|
+
srcChainId: params.from.chainId,
|
|
2312
|
+
srcSymbol: params.from.symbol,
|
|
2313
|
+
dstChainId: params.to.chainId,
|
|
2314
|
+
dstSymbol: params.to.symbol,
|
|
2315
|
+
amount: params.from.amount,
|
|
2316
|
+
walletAddress: params.walletAddress,
|
|
2317
|
+
...params.direction ? { direction: params.direction } : {}
|
|
2272
2318
|
}
|
|
2273
|
-
)
|
|
2274
|
-
|
|
2275
|
-
|
|
2276
|
-
|
|
2277
|
-
|
|
2278
|
-
|
|
2279
|
-
|
|
2280
|
-
|
|
2281
|
-
|
|
2282
|
-
|
|
2283
|
-
|
|
2284
|
-
|
|
2285
|
-
|
|
2286
|
-
"x-owney-api-key": input.apiKey
|
|
2287
|
-
},
|
|
2288
|
-
body: JSON.stringify(input.body)
|
|
2319
|
+
}),
|
|
2320
|
+
/** Ready-to-send calldata for a same-chain swap. */
|
|
2321
|
+
swapTx: (params) => request(baseUrl, apiKey, "/tx", {
|
|
2322
|
+
method: "POST",
|
|
2323
|
+
body: {
|
|
2324
|
+
srcChainId: params.from.chainId,
|
|
2325
|
+
srcSymbol: params.from.symbol,
|
|
2326
|
+
dstChainId: params.to.chainId,
|
|
2327
|
+
dstSymbol: params.to.symbol,
|
|
2328
|
+
amount: params.from.amount,
|
|
2329
|
+
walletAddress: params.walletAddress,
|
|
2330
|
+
slippage: params.slippage,
|
|
2331
|
+
...params.direction ? { direction: params.direction } : {}
|
|
2289
2332
|
}
|
|
2290
|
-
)
|
|
2291
|
-
|
|
2292
|
-
|
|
2293
|
-
|
|
2294
|
-
|
|
2295
|
-
|
|
2296
|
-
|
|
2297
|
-
|
|
2298
|
-
|
|
2299
|
-
|
|
2300
|
-
|
|
2301
|
-
|
|
2302
|
-
|
|
2303
|
-
|
|
2304
|
-
|
|
2305
|
-
|
|
2306
|
-
|
|
2333
|
+
}),
|
|
2334
|
+
/**
|
|
2335
|
+
* Builds a Fusion+ order server-side and returns EIP-712 typed data.
|
|
2336
|
+
*
|
|
2337
|
+
* Only HASHES go over the wire. The preimages never leave the browser —
|
|
2338
|
+
* see swap.secrets.
|
|
2339
|
+
*/
|
|
2340
|
+
buildOrder: (params) => request(baseUrl, apiKey, "/order/build", {
|
|
2341
|
+
method: "POST",
|
|
2342
|
+
body: {
|
|
2343
|
+
srcChainId: params.from.chainId,
|
|
2344
|
+
srcSymbol: params.from.symbol,
|
|
2345
|
+
dstChainId: params.to.chainId,
|
|
2346
|
+
dstSymbol: params.to.symbol,
|
|
2347
|
+
amount: params.from.amount,
|
|
2348
|
+
walletAddress: params.walletAddress,
|
|
2349
|
+
secretHashes: params.secretHashes,
|
|
2350
|
+
...params.direction ? { direction: params.direction } : {},
|
|
2351
|
+
...params.receiver ? { receiver: params.receiver } : {}
|
|
2307
2352
|
}
|
|
2308
|
-
)
|
|
2309
|
-
|
|
2310
|
-
|
|
2353
|
+
}),
|
|
2354
|
+
submitOrder: (body) => request(baseUrl, apiKey, "/order", { method: "POST", body }),
|
|
2355
|
+
/**
|
|
2356
|
+
* Only call once `readyForSecrets` reports the escrow deployed. Publishing
|
|
2357
|
+
* earlier hands a resolver the preimage while the user's funds are locked
|
|
2358
|
+
* and nothing has been posted on the destination chain.
|
|
2359
|
+
*/
|
|
2360
|
+
submitSecret: (orderHash, secret) => request(baseUrl, apiKey, "/order/secret", {
|
|
2361
|
+
method: "POST",
|
|
2362
|
+
body: { orderHash, secret }
|
|
2363
|
+
}),
|
|
2364
|
+
orderStatus: (orderHash) => request(baseUrl, apiKey, `/order/${orderHash}`),
|
|
2365
|
+
readyForSecrets: (orderHash) => request(
|
|
2366
|
+
baseUrl,
|
|
2367
|
+
apiKey,
|
|
2368
|
+
`/order/${orderHash}/ready-for-secrets`
|
|
2369
|
+
)
|
|
2370
|
+
};
|
|
2371
|
+
}
|
|
2372
|
+
|
|
2373
|
+
// src/lib/swap/swap.rpc.ts
|
|
2374
|
+
var import_viem2 = require("viem");
|
|
2375
|
+
var DEFAULT_RPC_URLS = {
|
|
2376
|
+
1: ["https://cloudflare-eth.com", "https://ethereum-rpc.publicnode.com"],
|
|
2377
|
+
8453: ["https://mainnet.base.org", "https://base-rpc.publicnode.com"],
|
|
2378
|
+
42161: [
|
|
2379
|
+
"https://arb1.arbitrum.io/rpc",
|
|
2380
|
+
"https://arbitrum-one-rpc.publicnode.com"
|
|
2381
|
+
]
|
|
2382
|
+
};
|
|
2383
|
+
function swapReadTransport(chainId, overrides) {
|
|
2384
|
+
const override = overrides?.[chainId];
|
|
2385
|
+
if (override) return (0, import_viem2.http)(override);
|
|
2386
|
+
const urls = DEFAULT_RPC_URLS[chainId];
|
|
2387
|
+
if (!urls || urls.length === 0) return (0, import_viem2.http)();
|
|
2388
|
+
return (0, import_viem2.fallback)(urls.map((url) => (0, import_viem2.http)(url)));
|
|
2389
|
+
}
|
|
2390
|
+
function receiptTimeoutMs(chainId) {
|
|
2391
|
+
return chainId === 1 ? 6e5 : 18e4;
|
|
2311
2392
|
}
|
|
2312
2393
|
|
|
2313
2394
|
// src/lib/permit2.ts
|
|
2314
2395
|
var import_viem3 = require("viem");
|
|
2315
2396
|
var PERMIT2_ADDRESS = "0x000000000022D473030F116dDEE9F6B43aC78BA3";
|
|
2316
2397
|
var MAX_UINT256 = 2n ** 256n - 1n;
|
|
2317
|
-
function permit2ApprovalAmount(requiredAmount) {
|
|
2318
|
-
if (requiredAmount <= 0n) {
|
|
2319
|
-
throw new Error("Permit2 approval requires a positive deposit amount");
|
|
2320
|
-
}
|
|
2321
|
-
return MAX_UINT256;
|
|
2322
|
-
}
|
|
2323
2398
|
var ERC20_ALLOWANCE_ABI = [
|
|
2324
2399
|
{
|
|
2325
2400
|
type: "function",
|
|
@@ -2349,6 +2424,29 @@ var ERC20_ALLOWANCE_ABI = [
|
|
|
2349
2424
|
outputs: [{ name: "", type: "uint256" }]
|
|
2350
2425
|
}
|
|
2351
2426
|
];
|
|
2427
|
+
function buildPermitTransferFromTypedData(input) {
|
|
2428
|
+
return {
|
|
2429
|
+
domain: {
|
|
2430
|
+
name: "Permit2",
|
|
2431
|
+
chainId: input.chainId,
|
|
2432
|
+
verifyingContract: PERMIT2_ADDRESS
|
|
2433
|
+
},
|
|
2434
|
+
types: {
|
|
2435
|
+
PermitTransferFrom: [
|
|
2436
|
+
{ name: "permitted", type: "TokenPermissions" },
|
|
2437
|
+
{ name: "spender", type: "address" },
|
|
2438
|
+
{ name: "nonce", type: "uint256" },
|
|
2439
|
+
{ name: "deadline", type: "uint256" }
|
|
2440
|
+
],
|
|
2441
|
+
TokenPermissions: [
|
|
2442
|
+
{ name: "token", type: "address" },
|
|
2443
|
+
{ name: "amount", type: "uint256" }
|
|
2444
|
+
]
|
|
2445
|
+
},
|
|
2446
|
+
primaryType: "PermitTransferFrom",
|
|
2447
|
+
message: input.message
|
|
2448
|
+
};
|
|
2449
|
+
}
|
|
2352
2450
|
function randomPermit2Nonce() {
|
|
2353
2451
|
const bytes = new Uint8Array(32);
|
|
2354
2452
|
globalThis.crypto.getRandomValues(bytes);
|
|
@@ -2371,39 +2469,122 @@ async function readErc20Balance(publicClient, token, owner) {
|
|
|
2371
2469
|
});
|
|
2372
2470
|
}
|
|
2373
2471
|
|
|
2374
|
-
// src/lib/
|
|
2375
|
-
var
|
|
2376
|
-
var
|
|
2377
|
-
function
|
|
2378
|
-
|
|
2472
|
+
// src/lib/swap/swap.secrets.ts
|
|
2473
|
+
var import_viem4 = require("viem");
|
|
2474
|
+
var SECRET_BYTES = 32;
|
|
2475
|
+
function randomBytes(length) {
|
|
2476
|
+
const bytes = new Uint8Array(length);
|
|
2477
|
+
const cryptoObj = typeof globalThis !== "undefined" ? globalThis.crypto : void 0;
|
|
2478
|
+
if (!cryptoObj?.getRandomValues) {
|
|
2479
|
+
throw new Error(
|
|
2480
|
+
"[owney-sdk] Secure randomness is unavailable, so a swap secret cannot be generated safely."
|
|
2481
|
+
);
|
|
2482
|
+
}
|
|
2483
|
+
cryptoObj.getRandomValues(bytes);
|
|
2484
|
+
return bytes;
|
|
2379
2485
|
}
|
|
2380
|
-
function
|
|
2381
|
-
|
|
2382
|
-
|
|
2383
|
-
|
|
2384
|
-
|
|
2385
|
-
|
|
2386
|
-
|
|
2387
|
-
|
|
2388
|
-
|
|
2389
|
-
|
|
2390
|
-
|
|
2391
|
-
|
|
2392
|
-
|
|
2486
|
+
function mintSecrets(count) {
|
|
2487
|
+
if (!Number.isInteger(count) || count < 1) {
|
|
2488
|
+
throw new Error(
|
|
2489
|
+
`[owney-sdk] A swap needs at least one secret, got ${String(count)}.`
|
|
2490
|
+
);
|
|
2491
|
+
}
|
|
2492
|
+
const secrets = [];
|
|
2493
|
+
const secretHashes = [];
|
|
2494
|
+
for (let i = 0; i < count; i++) {
|
|
2495
|
+
const secret = (0, import_viem4.toHex)(randomBytes(SECRET_BYTES));
|
|
2496
|
+
secrets.push(secret);
|
|
2497
|
+
secretHashes.push((0, import_viem4.keccak256)(secret));
|
|
2498
|
+
}
|
|
2499
|
+
return { secrets, secretHashes };
|
|
2393
2500
|
}
|
|
2394
2501
|
|
|
2395
|
-
// src/
|
|
2396
|
-
var
|
|
2397
|
-
|
|
2398
|
-
|
|
2399
|
-
|
|
2400
|
-
|
|
2401
|
-
var KEY_PREFIX2 = "owney.yieldseeker.session.v5";
|
|
2402
|
-
var INVALIDATED_KEY_PREFIXES = [
|
|
2403
|
-
"owney.yieldseeker.session",
|
|
2404
|
-
"owney.yieldseeker.session.v3",
|
|
2405
|
-
"owney.yieldseeker.session.v4"
|
|
2502
|
+
// src/lib/swap/swap.types.ts
|
|
2503
|
+
var SWAP_TERMINAL_STATUSES = [
|
|
2504
|
+
"executed",
|
|
2505
|
+
"expired",
|
|
2506
|
+
"cancelled",
|
|
2507
|
+
"refunded"
|
|
2406
2508
|
];
|
|
2509
|
+
var isSwapTerminal = (status) => SWAP_TERMINAL_STATUSES.includes(status);
|
|
2510
|
+
|
|
2511
|
+
// src/lib/swap/swap.order-runner.ts
|
|
2512
|
+
var DEFAULT_POLL_MS = 5e3;
|
|
2513
|
+
var MAX_BACKOFF_MS = 3e4;
|
|
2514
|
+
var backoffFor = (failures, base3) => Math.min(base3 * 2 ** Math.min(failures, 5), MAX_BACKOFF_MS);
|
|
2515
|
+
var DEFAULT_TIMEOUT_MS = 15 * 60 * 1e3;
|
|
2516
|
+
async function runFusionOrder(deps, options) {
|
|
2517
|
+
const {
|
|
2518
|
+
orderHash,
|
|
2519
|
+
secrets,
|
|
2520
|
+
onStage,
|
|
2521
|
+
pollIntervalMs = DEFAULT_POLL_MS,
|
|
2522
|
+
timeoutMs = DEFAULT_TIMEOUT_MS
|
|
2523
|
+
} = options;
|
|
2524
|
+
const deadline = deps.now() + timeoutMs;
|
|
2525
|
+
let failures = 0;
|
|
2526
|
+
const published = /* @__PURE__ */ new Set();
|
|
2527
|
+
onStage?.("swapping");
|
|
2528
|
+
for (; ; ) {
|
|
2529
|
+
if (deps.now() >= deadline) {
|
|
2530
|
+
throw new OwneyError(
|
|
2531
|
+
"SWAP_REQUEST_FAILED",
|
|
2532
|
+
"Timed out waiting for the swap to settle. It may still complete \u2014 check the order status before retrying.",
|
|
2533
|
+
{ orderHash }
|
|
2534
|
+
);
|
|
2535
|
+
}
|
|
2536
|
+
let ready;
|
|
2537
|
+
try {
|
|
2538
|
+
ready = await deps.readyForSecrets(orderHash);
|
|
2539
|
+
} catch {
|
|
2540
|
+
ready = {};
|
|
2541
|
+
}
|
|
2542
|
+
for (const fill of ready.fills ?? []) {
|
|
2543
|
+
if (published.has(fill.idx)) continue;
|
|
2544
|
+
const secret = secrets[fill.idx];
|
|
2545
|
+
if (secret === void 0) {
|
|
2546
|
+
throw new OwneyError(
|
|
2547
|
+
"SWAP_REQUEST_FAILED",
|
|
2548
|
+
`Swap needs a secret for fill ${fill.idx} that this session does not have. The order will refund once its timelock expires.`,
|
|
2549
|
+
{ orderHash, fillIndex: fill.idx }
|
|
2550
|
+
);
|
|
2551
|
+
}
|
|
2552
|
+
try {
|
|
2553
|
+
await deps.submitSecret(orderHash, secret);
|
|
2554
|
+
published.add(fill.idx);
|
|
2555
|
+
} catch {
|
|
2556
|
+
failures += 1;
|
|
2557
|
+
}
|
|
2558
|
+
}
|
|
2559
|
+
let status;
|
|
2560
|
+
try {
|
|
2561
|
+
({ status } = await deps.orderStatus(orderHash));
|
|
2562
|
+
failures = 0;
|
|
2563
|
+
} catch {
|
|
2564
|
+
failures += 1;
|
|
2565
|
+
await deps.sleep(backoffFor(failures, pollIntervalMs));
|
|
2566
|
+
continue;
|
|
2567
|
+
}
|
|
2568
|
+
if (status === "refunding") onStage?.("refunding");
|
|
2569
|
+
if (isSwapTerminal(status)) {
|
|
2570
|
+
if (status === "executed") {
|
|
2571
|
+
onStage?.("swapped");
|
|
2572
|
+
return { status, filled: true };
|
|
2573
|
+
}
|
|
2574
|
+
if (status === "refunded") onStage?.("refunded");
|
|
2575
|
+
throw new OwneyError(
|
|
2576
|
+
status === "refunded" ? "SWAP_ORDER_REFUNDED" : status === "cancelled" ? "SWAP_ORDER_CANCELLED" : "SWAP_ORDER_EXPIRED",
|
|
2577
|
+
status === "refunded" ? "The swap did not complete and your funds have been returned." : "The swap did not complete in time. Your funds will be returned once the timelock expires.",
|
|
2578
|
+
{ orderHash, status }
|
|
2579
|
+
);
|
|
2580
|
+
}
|
|
2581
|
+
await deps.sleep(pollIntervalMs);
|
|
2582
|
+
}
|
|
2583
|
+
}
|
|
2584
|
+
|
|
2585
|
+
// src/lib/swap/swap.secret-store.ts
|
|
2586
|
+
var KEY_PREFIX2 = "owney.swap.order";
|
|
2587
|
+
var MAX_AGE_MS = 24 * 60 * 60 * 1e3;
|
|
2407
2588
|
var storage2 = () => {
|
|
2408
2589
|
if (typeof window === "undefined") return null;
|
|
2409
2590
|
try {
|
|
@@ -2412,1649 +2593,287 @@ var storage2 = () => {
|
|
|
2412
2593
|
return null;
|
|
2413
2594
|
}
|
|
2414
2595
|
};
|
|
2415
|
-
var
|
|
2416
|
-
|
|
2417
|
-
|
|
2418
|
-
);
|
|
2419
|
-
var clearInvalidatedSessions = (store, address, chainId) => {
|
|
2420
|
-
for (const key2 of invalidatedKeys(address, chainId)) {
|
|
2421
|
-
memorySessions2.delete(key2);
|
|
2422
|
-
try {
|
|
2423
|
-
store?.removeItem(key2);
|
|
2424
|
-
} catch {
|
|
2425
|
-
}
|
|
2426
|
-
}
|
|
2427
|
-
};
|
|
2428
|
-
var memorySessions2 = /* @__PURE__ */ new Map();
|
|
2429
|
-
var isValidSession = (session) => {
|
|
2430
|
-
if (!session?.token) return false;
|
|
2596
|
+
var keyFor = (orderHash) => `${KEY_PREFIX2}.${orderHash}`;
|
|
2597
|
+
function saveOrder(order) {
|
|
2598
|
+
const store = storage2();
|
|
2599
|
+
if (!store) return;
|
|
2431
2600
|
try {
|
|
2432
|
-
|
|
2433
|
-
return typeof parsed.message === "string" && typeof parsed.signature === "string" && parsed.signature.startsWith("0x");
|
|
2601
|
+
store.setItem(keyFor(order.orderHash), JSON.stringify(order));
|
|
2434
2602
|
} catch {
|
|
2435
|
-
return false;
|
|
2436
2603
|
}
|
|
2437
|
-
}
|
|
2438
|
-
|
|
2439
|
-
if (typeof window === "undefined") return null;
|
|
2440
|
-
const key2 = buildKey2(address, chainId);
|
|
2604
|
+
}
|
|
2605
|
+
function clearOrder(orderHash) {
|
|
2441
2606
|
const store = storage2();
|
|
2442
|
-
|
|
2443
|
-
let raw2 = null;
|
|
2607
|
+
if (!store) return;
|
|
2444
2608
|
try {
|
|
2445
|
-
|
|
2609
|
+
store.removeItem(keyFor(orderHash));
|
|
2446
2610
|
} catch {
|
|
2447
|
-
raw2 = null;
|
|
2448
2611
|
}
|
|
2449
|
-
|
|
2450
|
-
|
|
2451
|
-
|
|
2452
|
-
|
|
2453
|
-
|
|
2454
|
-
|
|
2455
|
-
|
|
2456
|
-
|
|
2457
|
-
store
|
|
2458
|
-
|
|
2612
|
+
}
|
|
2613
|
+
function listOrders(now = Date.now()) {
|
|
2614
|
+
const store = storage2();
|
|
2615
|
+
if (!store) return [];
|
|
2616
|
+
const out = [];
|
|
2617
|
+
try {
|
|
2618
|
+
const keys = [];
|
|
2619
|
+
for (let i = 0; i < store.length; i++) {
|
|
2620
|
+
const key2 = store.key(i);
|
|
2621
|
+
if (key2?.startsWith(`${KEY_PREFIX2}.`)) keys.push(key2);
|
|
2459
2622
|
}
|
|
2460
|
-
|
|
2461
|
-
|
|
2462
|
-
|
|
2463
|
-
|
|
2464
|
-
|
|
2465
|
-
|
|
2466
|
-
|
|
2467
|
-
|
|
2468
|
-
|
|
2469
|
-
|
|
2470
|
-
|
|
2471
|
-
|
|
2472
|
-
|
|
2473
|
-
|
|
2474
|
-
try {
|
|
2475
|
-
store?.setItem(key2, JSON.stringify(session));
|
|
2476
|
-
} catch {
|
|
2477
|
-
}
|
|
2478
|
-
};
|
|
2479
|
-
var clearYieldseekerSession = (address, chainId) => {
|
|
2480
|
-
const key2 = buildKey2(address, chainId);
|
|
2481
|
-
memorySessions2.delete(key2);
|
|
2482
|
-
const store = storage2();
|
|
2483
|
-
clearInvalidatedSessions(store, address, chainId);
|
|
2484
|
-
try {
|
|
2485
|
-
store?.removeItem(key2);
|
|
2486
|
-
} catch {
|
|
2487
|
-
}
|
|
2488
|
-
};
|
|
2489
|
-
|
|
2490
|
-
// src/agents/yieldseeker/yieldseeker.auth.ts
|
|
2491
|
-
function resolveSiweOrigin(override) {
|
|
2492
|
-
const origin = override?.trim() || (typeof window !== "undefined" ? window.location?.origin : void 0);
|
|
2493
|
-
if (!origin || origin === "null") {
|
|
2494
|
-
throw new Error("Yieldseeker sign-in requires the requesting app's browser origin.");
|
|
2495
|
-
}
|
|
2496
|
-
const url = new URL(origin);
|
|
2497
|
-
if (url.protocol !== "https:" && url.protocol !== "http:") {
|
|
2498
|
-
throw new Error("Yieldseeker sign-in requires an HTTP or HTTPS app origin.");
|
|
2499
|
-
}
|
|
2500
|
-
if (url.username || url.password || url.pathname !== "/" || url.search || url.hash) {
|
|
2501
|
-
throw new Error("Yieldseeker SIWE override must be an origin without credentials, path, query, or fragment.");
|
|
2502
|
-
}
|
|
2503
|
-
return url;
|
|
2504
|
-
}
|
|
2505
|
-
function createYieldseekerSiweMessage(address, chainId, dependencies = {}) {
|
|
2506
|
-
const url = resolveSiweOrigin(dependencies.origin);
|
|
2507
|
-
return new import_siwe.SiweMessage({
|
|
2508
|
-
scheme: url.protocol.slice(0, -1),
|
|
2509
|
-
domain: url.host,
|
|
2510
|
-
address: (0, import_viem4.getAddress)(address),
|
|
2511
|
-
uri: url.origin,
|
|
2512
|
-
version: "1",
|
|
2513
|
-
chainId,
|
|
2514
|
-
nonce: (dependencies.nonce ?? import_siwe.generateNonce)(),
|
|
2515
|
-
issuedAt: (dependencies.now ?? (() => /* @__PURE__ */ new Date()))().toISOString()
|
|
2516
|
-
}).prepareMessage();
|
|
2517
|
-
}
|
|
2518
|
-
function encodeYieldseekerAuthToken(token) {
|
|
2519
|
-
const bytes = new TextEncoder().encode(JSON.stringify(token));
|
|
2520
|
-
let binary = "";
|
|
2521
|
-
for (const byte of bytes) binary += String.fromCharCode(byte);
|
|
2522
|
-
return btoa(binary);
|
|
2523
|
-
}
|
|
2524
|
-
var YieldseekerAuth = class {
|
|
2525
|
-
constructor(dependencies = {}) {
|
|
2526
|
-
this.dependencies = dependencies;
|
|
2527
|
-
}
|
|
2528
|
-
dependencies;
|
|
2529
|
-
tokens = /* @__PURE__ */ new Map();
|
|
2530
|
-
pending = /* @__PURE__ */ new Map();
|
|
2531
|
-
scopes = /* @__PURE__ */ new Map();
|
|
2532
|
-
key(state, chainId) {
|
|
2533
|
-
return `${state.walletAddress.toLowerCase()}:${chainId}:${resolveSiweOrigin(this.dependencies.origin).origin}`;
|
|
2534
|
-
}
|
|
2535
|
-
async getToken(state, chainId) {
|
|
2536
|
-
const key2 = this.key(state, chainId);
|
|
2537
|
-
const scope = { address: state.walletAddress, chainId };
|
|
2538
|
-
this.scopes.set(key2, scope);
|
|
2539
|
-
const cached = this.tokens.get(key2);
|
|
2540
|
-
if (cached) return cached;
|
|
2541
|
-
const persisted = readYieldseekerSession(scope.address, scope.chainId);
|
|
2542
|
-
if (persisted && this.matchesOrigin(persisted)) {
|
|
2543
|
-
this.tokens.set(key2, persisted);
|
|
2544
|
-
return persisted;
|
|
2545
|
-
}
|
|
2546
|
-
if (persisted) clearYieldseekerSession(scope.address, scope.chainId);
|
|
2547
|
-
const inFlight = this.pending.get(key2);
|
|
2548
|
-
if (inFlight) return inFlight;
|
|
2549
|
-
const request = this.sign(state, chainId).then((token) => {
|
|
2550
|
-
if (this.pending.get(key2) !== request) throw new Error("Wallet sign-in session changed. Please try again.");
|
|
2551
|
-
this.tokens.set(key2, token);
|
|
2552
|
-
writeYieldseekerSession(scope.address, scope.chainId, token);
|
|
2553
|
-
return token;
|
|
2554
|
-
});
|
|
2555
|
-
this.pending.set(key2, request);
|
|
2556
|
-
try {
|
|
2557
|
-
return await request;
|
|
2558
|
-
} finally {
|
|
2559
|
-
if (this.pending.get(key2) === request) this.pending.delete(key2);
|
|
2560
|
-
}
|
|
2561
|
-
}
|
|
2562
|
-
async refreshToken(state, chainId, rejectedToken) {
|
|
2563
|
-
const key2 = this.key(state, chainId);
|
|
2564
|
-
if (this.tokens.get(key2) === rejectedToken) {
|
|
2565
|
-
this.tokens.delete(key2);
|
|
2566
|
-
clearYieldseekerSession(state.walletAddress, chainId);
|
|
2567
|
-
}
|
|
2568
|
-
return this.getToken(state, chainId);
|
|
2569
|
-
}
|
|
2570
|
-
matchesOrigin(token) {
|
|
2571
|
-
try {
|
|
2572
|
-
const message = new import_siwe.SiweMessage(JSON.parse(atob(token)).message);
|
|
2573
|
-
const url = resolveSiweOrigin(this.dependencies.origin);
|
|
2574
|
-
return message.domain === url.host && message.uri === url.origin && message.scheme === url.protocol.slice(0, -1);
|
|
2575
|
-
} catch {
|
|
2576
|
-
return false;
|
|
2577
|
-
}
|
|
2578
|
-
}
|
|
2579
|
-
clear(state, chainId) {
|
|
2580
|
-
if (!state || chainId === void 0) {
|
|
2581
|
-
for (const scope of this.scopes.values()) {
|
|
2582
|
-
clearYieldseekerSession(scope.address, scope.chainId);
|
|
2623
|
+
for (const key2 of keys) {
|
|
2624
|
+
const raw = store.getItem(key2);
|
|
2625
|
+
if (!raw) continue;
|
|
2626
|
+
try {
|
|
2627
|
+
const parsed = JSON.parse(raw);
|
|
2628
|
+
if (now - parsed.createdAt > MAX_AGE_MS) {
|
|
2629
|
+
store.removeItem(key2);
|
|
2630
|
+
continue;
|
|
2631
|
+
}
|
|
2632
|
+
if (Array.isArray(parsed.secrets) && parsed.secrets.length > 0) {
|
|
2633
|
+
out.push(parsed);
|
|
2634
|
+
}
|
|
2635
|
+
} catch {
|
|
2636
|
+
store.removeItem(key2);
|
|
2583
2637
|
}
|
|
2584
|
-
this.tokens.clear();
|
|
2585
|
-
this.pending.clear();
|
|
2586
|
-
this.scopes.clear();
|
|
2587
|
-
return;
|
|
2588
2638
|
}
|
|
2589
|
-
const key2 = this.key(state, chainId);
|
|
2590
|
-
this.tokens.delete(key2);
|
|
2591
|
-
this.pending.delete(key2);
|
|
2592
|
-
this.scopes.delete(key2);
|
|
2593
|
-
clearYieldseekerSession(state.walletAddress, chainId);
|
|
2594
|
-
}
|
|
2595
|
-
async sign(state, chainId) {
|
|
2596
|
-
const account = (0, import_viem4.getAddress)(state.walletAddress);
|
|
2597
|
-
const publicClient = (0, import_viem4.createPublicClient)({
|
|
2598
|
-
chain: import_chains2.base,
|
|
2599
|
-
transport: (0, import_viem4.custom)(state.provider)
|
|
2600
|
-
});
|
|
2601
|
-
const walletClient = (0, import_viem4.createWalletClient)({
|
|
2602
|
-
account,
|
|
2603
|
-
chain: import_chains2.base,
|
|
2604
|
-
transport: (0, import_viem4.custom)(state.provider)
|
|
2605
|
-
});
|
|
2606
|
-
await ensureWalletOnChain(
|
|
2607
|
-
publicClient,
|
|
2608
|
-
walletClient,
|
|
2609
|
-
8453
|
|
2610
|
-
);
|
|
2611
|
-
const message = createYieldseekerSiweMessage(
|
|
2612
|
-
account,
|
|
2613
|
-
chainId,
|
|
2614
|
-
this.dependencies
|
|
2615
|
-
);
|
|
2616
|
-
const signature = await walletClient.signMessage({ account, message });
|
|
2617
|
-
return encodeYieldseekerAuthToken({ message, signature });
|
|
2618
|
-
}
|
|
2619
|
-
};
|
|
2620
|
-
|
|
2621
|
-
// src/agents/yieldseeker/yieldseeker.identity-cache.ts
|
|
2622
|
-
var KEY_PREFIX3 = "owney.yieldseeker.identity.v1";
|
|
2623
|
-
var YIELDSEEKER_IDENTITY_TTL_MS = 24 * 60 * 60 * 1e3;
|
|
2624
|
-
var memoryIdentities = /* @__PURE__ */ new Map();
|
|
2625
|
-
var storage3 = () => {
|
|
2626
|
-
if (typeof window === "undefined") return null;
|
|
2627
|
-
try {
|
|
2628
|
-
return window.localStorage;
|
|
2629
2639
|
} catch {
|
|
2630
|
-
return
|
|
2640
|
+
return out;
|
|
2631
2641
|
}
|
|
2632
|
-
|
|
2633
|
-
var keyFor = (walletAddress, chainId) => `${KEY_PREFIX3}:${walletAddress.toLowerCase()}:${chainId}`;
|
|
2634
|
-
function valid(value, walletAddress, chainId, now) {
|
|
2635
|
-
return Boolean(
|
|
2636
|
-
value && typeof value.userId === "string" && /^[a-zA-Z0-9_-]{1,128}$/.test(value.userId) && value.walletAddress.toLowerCase() === walletAddress.toLowerCase() && value.chainId === chainId && Number.isSafeInteger(value.expiresAt) && value.expiresAt > now
|
|
2637
|
-
);
|
|
2642
|
+
return out.sort((a, b) => b.createdAt - a.createdAt);
|
|
2638
2643
|
}
|
|
2639
|
-
function readYieldseekerIdentity(walletAddress, chainId, now = Date.now()) {
|
|
2640
|
-
if (typeof window === "undefined") return null;
|
|
2641
|
-
const key2 = keyFor(walletAddress, chainId);
|
|
2642
|
-
const store = storage3();
|
|
2643
|
-
let parsed = null;
|
|
2644
|
-
try {
|
|
2645
|
-
const raw2 = store?.getItem(key2);
|
|
2646
|
-
parsed = raw2 ? JSON.parse(raw2) : null;
|
|
2647
|
-
} catch {
|
|
2648
|
-
parsed = null;
|
|
2649
|
-
}
|
|
2650
|
-
const candidate = parsed ?? memoryIdentities.get(key2);
|
|
2651
|
-
if (valid(candidate, walletAddress, chainId, now)) {
|
|
2652
|
-
memoryIdentities.set(key2, candidate);
|
|
2653
|
-
return { userId: candidate.userId };
|
|
2654
|
-
}
|
|
2655
|
-
memoryIdentities.delete(key2);
|
|
2656
|
-
try {
|
|
2657
|
-
store?.removeItem(key2);
|
|
2658
|
-
} catch {
|
|
2659
|
-
}
|
|
2660
|
-
return null;
|
|
2661
|
-
}
|
|
2662
|
-
function writeYieldseekerIdentity(walletAddress, chainId, userId, now = Date.now()) {
|
|
2663
|
-
if (typeof window === "undefined") return;
|
|
2664
|
-
const identity = {
|
|
2665
|
-
userId,
|
|
2666
|
-
walletAddress,
|
|
2667
|
-
chainId,
|
|
2668
|
-
expiresAt: now + YIELDSEEKER_IDENTITY_TTL_MS
|
|
2669
|
-
};
|
|
2670
|
-
if (!valid(identity, walletAddress, chainId, now)) return;
|
|
2671
|
-
const key2 = keyFor(walletAddress, chainId);
|
|
2672
|
-
memoryIdentities.set(key2, identity);
|
|
2673
|
-
try {
|
|
2674
|
-
storage3()?.setItem(key2, JSON.stringify(identity));
|
|
2675
|
-
} catch {
|
|
2676
|
-
}
|
|
2677
|
-
}
|
|
2678
|
-
function clearYieldseekerIdentity(walletAddress, chainId) {
|
|
2679
|
-
const key2 = keyFor(walletAddress, chainId);
|
|
2680
|
-
memoryIdentities.delete(key2);
|
|
2681
|
-
try {
|
|
2682
|
-
storage3()?.removeItem(key2);
|
|
2683
|
-
} catch {
|
|
2684
|
-
}
|
|
2685
|
-
}
|
|
2686
|
-
|
|
2687
|
-
// src/agents/yieldseeker/yieldseeker.client.ts
|
|
2688
|
-
var DEFAULT_ROUTING_API_BASE_URL = "https://owney-routing-api-243946518160.europe-west4.run.app";
|
|
2689
|
-
function getYieldseekerProxyBaseUrl(routingApiBaseUrl = DEFAULT_ROUTING_API_BASE_URL) {
|
|
2690
|
-
return `${routingApiBaseUrl.replace(/\/$/, "")}/api/v1/agent/yieldseeker`;
|
|
2691
|
-
}
|
|
2692
|
-
var YIELDSEEKER_API_BASE_URL = getYieldseekerProxyBaseUrl();
|
|
2693
|
-
var YieldseekerApiError = class extends Error {
|
|
2694
|
-
constructor(status, providerCode, responseFields) {
|
|
2695
|
-
super(`Yieldseeker request failed (${status}): ${providerCode}`);
|
|
2696
|
-
this.status = status;
|
|
2697
|
-
this.providerCode = providerCode;
|
|
2698
|
-
this.responseFields = responseFields;
|
|
2699
|
-
this.name = "YieldseekerApiError";
|
|
2700
|
-
}
|
|
2701
|
-
status;
|
|
2702
|
-
providerCode;
|
|
2703
|
-
responseFields;
|
|
2704
|
-
get isAuthenticationError() {
|
|
2705
|
-
return this.status === 401 || this.status === 403;
|
|
2706
|
-
}
|
|
2707
|
-
};
|
|
2708
|
-
function providerError(body, fallback) {
|
|
2709
|
-
if (!body || typeof body !== "object") return { code: fallback };
|
|
2710
|
-
const record = body;
|
|
2711
|
-
return {
|
|
2712
|
-
code: typeof record.message === "string" ? record.message : fallback,
|
|
2713
|
-
fields: record.fields && typeof record.fields === "object" ? record.fields : void 0
|
|
2714
|
-
};
|
|
2715
|
-
}
|
|
2716
|
-
var YieldseekerApiClient = class {
|
|
2717
|
-
constructor(owneyApiKey, baseUrl = YIELDSEEKER_API_BASE_URL, fetchFn = fetch.bind(globalThis)) {
|
|
2718
|
-
this.owneyApiKey = owneyApiKey;
|
|
2719
|
-
this.baseUrl = baseUrl;
|
|
2720
|
-
this.fetchFn = fetchFn;
|
|
2721
|
-
}
|
|
2722
|
-
owneyApiKey;
|
|
2723
|
-
baseUrl;
|
|
2724
|
-
fetchFn;
|
|
2725
|
-
async request(path, options = {}) {
|
|
2726
|
-
const controller = new AbortController();
|
|
2727
|
-
const timer = setTimeout(
|
|
2728
|
-
() => controller.abort(),
|
|
2729
|
-
options.timeoutMs ?? 15e3
|
|
2730
|
-
);
|
|
2731
|
-
try {
|
|
2732
|
-
const response = await this.fetchFn(`${this.baseUrl}${path}`, {
|
|
2733
|
-
method: options.method ?? "GET",
|
|
2734
|
-
headers: {
|
|
2735
|
-
"Content-Type": "application/json",
|
|
2736
|
-
"x-owney-api-key": this.owneyApiKey,
|
|
2737
|
-
...options.signature ? { Authorization: `Signature ${options.signature}` } : {}
|
|
2738
|
-
},
|
|
2739
|
-
body: options.body ? JSON.stringify(options.body) : void 0,
|
|
2740
|
-
signal: controller.signal
|
|
2741
|
-
});
|
|
2742
|
-
const payload = await response.json().catch(() => null);
|
|
2743
|
-
if (!response.ok) {
|
|
2744
|
-
const error = providerError(payload, `HTTP_${response.status}`);
|
|
2745
|
-
throw new YieldseekerApiError(
|
|
2746
|
-
response.status,
|
|
2747
|
-
error.code,
|
|
2748
|
-
error.fields
|
|
2749
|
-
);
|
|
2750
|
-
}
|
|
2751
|
-
if (payload && typeof payload === "object" && payload.success === true && "data" in payload) {
|
|
2752
|
-
return payload.data;
|
|
2753
|
-
}
|
|
2754
|
-
return payload;
|
|
2755
|
-
} catch (error) {
|
|
2756
|
-
if (error instanceof YieldseekerApiError) throw error;
|
|
2757
|
-
if (error instanceof DOMException && error.name === "AbortError") {
|
|
2758
|
-
throw new YieldseekerApiError(408, "REQUEST_TIMEOUT");
|
|
2759
|
-
}
|
|
2760
|
-
throw new YieldseekerApiError(0, "NETWORK_ERROR", {
|
|
2761
|
-
cause: error instanceof Error ? error.message : String(error)
|
|
2762
|
-
});
|
|
2763
|
-
} finally {
|
|
2764
|
-
clearTimeout(timer);
|
|
2765
|
-
}
|
|
2766
|
-
}
|
|
2767
|
-
};
|
|
2768
2644
|
|
|
2769
|
-
// src/
|
|
2770
|
-
var
|
|
2771
|
-
|
|
2772
|
-
|
|
2773
|
-
|
|
2774
|
-
|
|
2775
|
-
|
|
2776
|
-
|
|
2777
|
-
|
|
2778
|
-
}
|
|
2779
|
-
|
|
2780
|
-
if (typeof value !== "number" && typeof value !== "string") return void 0;
|
|
2781
|
-
if (typeof value === "string" && value.trim() === "") return void 0;
|
|
2782
|
-
const factor = Number(value);
|
|
2783
|
-
return Number.isFinite(factor) && factor >= 0 ? factor : void 0;
|
|
2784
|
-
}
|
|
2785
|
-
function calculateSnapshotApy(snapshots, lookbackDays, now = Date.now()) {
|
|
2786
|
-
if (!Number.isFinite(lookbackDays) || lookbackDays <= 0 || !Number.isFinite(now)) {
|
|
2787
|
-
return void 0;
|
|
2788
|
-
}
|
|
2789
|
-
const points = snapshots.flatMap((snapshot) => {
|
|
2790
|
-
const time = snapshotTime(snapshot.date);
|
|
2791
|
-
return time !== void 0 && time <= now ? [{ snapshot, time }] : [];
|
|
2792
|
-
}).sort((a, b) => a.time - b.time);
|
|
2793
|
-
const end = points.at(-1);
|
|
2794
|
-
if (!end) return void 0;
|
|
2795
|
-
const cutoff = end.time - lookbackDays * DAY_MS;
|
|
2796
|
-
const start = points.find((point) => point.time >= cutoff);
|
|
2797
|
-
const actualDays = (end.time - start.time) / DAY_MS;
|
|
2798
|
-
if (actualDays <= 0) return void 0;
|
|
2799
|
-
const startFactor = returnFactor(start.snapshot.cumulativeReturnFactor);
|
|
2800
|
-
const endFactor = returnFactor(end.snapshot.cumulativeReturnFactor);
|
|
2801
|
-
if (startFactor === void 0 || startFactor === 0 || endFactor === void 0) {
|
|
2802
|
-
return void 0;
|
|
2803
|
-
}
|
|
2804
|
-
const periodReturn = endFactor / startFactor - 1;
|
|
2805
|
-
const apy = Math.pow(1 + periodReturn, 365 / actualDays) - 1;
|
|
2806
|
-
return Number.isFinite(apy) ? apy : void 0;
|
|
2807
|
-
}
|
|
2808
|
-
|
|
2809
|
-
// src/agents/yieldseeker/yieldseeker.types.ts
|
|
2810
|
-
var YIELDSEEKER_ASSET_METADATA = {
|
|
2811
|
-
USDC: {
|
|
2812
|
-
address: "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913",
|
|
2813
|
-
decimals: 6
|
|
2814
|
-
},
|
|
2815
|
-
WETH: {
|
|
2816
|
-
address: "0x4200000000000000000000000000000000000006",
|
|
2817
|
-
decimals: 18
|
|
2818
|
-
}
|
|
2819
|
-
};
|
|
2820
|
-
|
|
2821
|
-
// src/agents/yieldseeker/yieldseeker.mapper.ts
|
|
2822
|
-
function invalid(endpoint, detail) {
|
|
2823
|
-
throw new OwneyError(
|
|
2824
|
-
"AGENT_INVALID_RESPONSE",
|
|
2825
|
-
`Yieldseeker returned an invalid ${endpoint} response: ${detail}.`,
|
|
2826
|
-
{ endpoint, detail },
|
|
2827
|
-
"yieldseeker"
|
|
2828
|
-
);
|
|
2829
|
-
}
|
|
2830
|
-
function raw(value, endpoint) {
|
|
2831
|
-
if (typeof value !== "string" || !/^-?[0-9]+$/.test(value)) {
|
|
2832
|
-
return invalid(endpoint, "expected a base-10 integer string");
|
|
2833
|
-
}
|
|
2834
|
-
return BigInt(value);
|
|
2835
|
-
}
|
|
2836
|
-
function decimal(value, decimals, endpoint) {
|
|
2837
|
-
return (0, import_viem5.formatUnits)(raw(value, endpoint), decimals);
|
|
2838
|
-
}
|
|
2839
|
-
function usd(rawAmount, decimals, price) {
|
|
2840
|
-
return Number((0, import_viem5.formatUnits)(rawAmount, decimals)) * price;
|
|
2841
|
-
}
|
|
2842
|
-
function percent(value) {
|
|
2843
|
-
const result = Number(value);
|
|
2844
|
-
return Number.isFinite(result) ? result * 100 : 0;
|
|
2845
|
-
}
|
|
2846
|
-
var YIELDSEEKER_POSITIVE_YIELD_FEE_RATE = 0.1;
|
|
2847
|
-
function publicApyAfterYieldseekerFee(value) {
|
|
2848
|
-
const grossPercent = percent(value);
|
|
2849
|
-
if (grossPercent <= 0) return grossPercent;
|
|
2850
|
-
const netPercent = grossPercent * (1 - YIELDSEEKER_POSITIVE_YIELD_FEE_RATE);
|
|
2851
|
-
return Math.round(netPercent * 1e12) / 1e12;
|
|
2852
|
-
}
|
|
2853
|
-
function riskAdjustedApyForDays(option, days) {
|
|
2854
|
-
if (days === "7D") return option.riskAdjustedApy7dAverage;
|
|
2855
|
-
if (days === "30D") return option.riskAdjustedApy30dAverage;
|
|
2856
|
-
return (option.riskAdjustedApy7dAverage + option.riskAdjustedApy30dAverage) / 2;
|
|
2857
|
-
}
|
|
2858
|
-
function assetAddressValue(record, address) {
|
|
2859
|
-
const entry = Object.entries(record).find(
|
|
2860
|
-
([key2]) => key2.toLowerCase() === address.toLowerCase()
|
|
2861
|
-
);
|
|
2862
|
-
return entry?.[1] ?? "0";
|
|
2863
|
-
}
|
|
2864
|
-
function position(value, asset, baseAssetDecimals) {
|
|
2865
|
-
const option = value?.yieldOption;
|
|
2866
|
-
if (!option || typeof option.provider !== "string" || typeof option.name !== "string" || typeof option.address !== "string" || !(0, import_viem5.isAddress)(option.address)) {
|
|
2867
|
-
return invalid("yield positions", "missing vault metadata");
|
|
2868
|
-
}
|
|
2869
|
-
return {
|
|
2870
|
-
chain: "BASE",
|
|
2871
|
-
protocol: option.provider,
|
|
2872
|
-
protocolId: option.address,
|
|
2873
|
-
pool: option.name,
|
|
2874
|
-
asset,
|
|
2875
|
-
// `assetsRaw` is the ERC-4626 vault-share quantity, whose decimals can
|
|
2876
|
-
// differ from the underlying asset. Yieldseeker already converts it to
|
|
2877
|
-
// underlying base-asset units in `assetsBase`; pair that value with the
|
|
2878
|
-
// snapshot's corresponding `baseAssetDecimals` for display. Keep the raw
|
|
2879
|
-
// share quantity separately because withdraw-from-position expects it.
|
|
2880
|
-
amount: decimal(
|
|
2881
|
-
value.assetsBase,
|
|
2882
|
-
baseAssetDecimals,
|
|
2883
|
-
"yield positions"
|
|
2884
|
-
),
|
|
2885
|
-
amountRaw: String(value.assetsRaw),
|
|
2886
|
-
apy: percent(option.riskAdjustedApy),
|
|
2887
|
-
tvl: Number(option.totalDepositsUsd),
|
|
2888
|
-
liquidity: Number(option.withdrawableDepositsUsd)
|
|
2889
|
-
};
|
|
2890
|
-
}
|
|
2891
|
-
function mapYieldseekerBalances(contexts) {
|
|
2892
|
-
const tokens = [];
|
|
2893
|
-
const assetBalances = [];
|
|
2894
|
-
const positions = [];
|
|
2895
|
-
let totalUsd = 0;
|
|
2896
|
-
for (const context of contexts) {
|
|
2897
|
-
const metadata = YIELDSEEKER_ASSET_METADATA[context.asset];
|
|
2898
|
-
assetBalances.push({
|
|
2899
|
-
chain: "BASE",
|
|
2900
|
-
chainId: 8453,
|
|
2901
|
-
asset: context.asset,
|
|
2902
|
-
amount: decimal(context.snapshot.totalValueBase, context.snapshot.baseAssetDecimals, "snapshot")
|
|
2903
|
-
});
|
|
2904
|
-
const idle = assetAddressValue(
|
|
2905
|
-
context.snapshot.tokenBalances,
|
|
2906
|
-
metadata.address
|
|
2907
|
-
);
|
|
2908
|
-
tokens.push({
|
|
2909
|
-
chain: "BASE",
|
|
2910
|
-
chainId: 8453,
|
|
2911
|
-
asset: context.asset,
|
|
2912
|
-
amount: decimal(idle, metadata.decimals, "snapshot")
|
|
2913
|
-
});
|
|
2914
|
-
positions.push(
|
|
2915
|
-
...context.positions.map(
|
|
2916
|
-
(entry) => position(
|
|
2917
|
-
entry,
|
|
2918
|
-
context.asset,
|
|
2919
|
-
context.snapshot.baseAssetDecimals
|
|
2920
|
-
)
|
|
2921
|
-
)
|
|
2922
|
-
);
|
|
2923
|
-
totalUsd += usd(
|
|
2924
|
-
raw(context.snapshot.totalValueBase, "snapshot"),
|
|
2925
|
-
context.snapshot.baseAssetDecimals,
|
|
2926
|
-
context.snapshot.baseAssetPriceUsd
|
|
2927
|
-
);
|
|
2928
|
-
}
|
|
2929
|
-
return {
|
|
2930
|
-
...contexts.length === 1 ? { smartWallet: contexts[0].wallet.walletAddress } : {},
|
|
2931
|
-
totalBalance: String(totalUsd),
|
|
2932
|
-
totalBalanceAsset: "usdc",
|
|
2933
|
-
assetBalances,
|
|
2934
|
-
tokens,
|
|
2935
|
-
positions
|
|
2936
|
-
};
|
|
2645
|
+
// src/lib/swap/swap.executor.ts
|
|
2646
|
+
var DEFAULT_SLIPPAGE = 1;
|
|
2647
|
+
async function affordableAmount(deps, quoted) {
|
|
2648
|
+
const balance = await deps.readSourceBalance();
|
|
2649
|
+
if (balance >= quoted) return quoted;
|
|
2650
|
+
debugLog("owney-sdk", "swap: trimming to the current source balance", {
|
|
2651
|
+
quoted: quoted.toString(),
|
|
2652
|
+
balance: balance.toString(),
|
|
2653
|
+
short: (quoted - balance).toString()
|
|
2654
|
+
});
|
|
2655
|
+
return balance;
|
|
2937
2656
|
}
|
|
2938
|
-
function
|
|
2939
|
-
const
|
|
2940
|
-
|
|
2941
|
-
|
|
2942
|
-
|
|
2943
|
-
|
|
2944
|
-
|
|
2945
|
-
|
|
2946
|
-
|
|
2947
|
-
|
|
2948
|
-
|
|
2949
|
-
|
|
2950
|
-
|
|
2951
|
-
|
|
2952
|
-
|
|
2657
|
+
async function executeSwap(deps, options) {
|
|
2658
|
+
const { quote, walletAddress, onStage } = options;
|
|
2659
|
+
debugLog("owney-sdk", "swap: start", {
|
|
2660
|
+
rail: quote.rail,
|
|
2661
|
+
from: `${quote.src.amount} ${quote.src.symbol} on ${quote.src.chainId}`,
|
|
2662
|
+
to: `${quote.dst.symbol} on ${quote.dst.chainId}`,
|
|
2663
|
+
expected: quote.dst.amount,
|
|
2664
|
+
floor: quote.dstAmountMin
|
|
2665
|
+
});
|
|
2666
|
+
const before = await deps.readTargetBalance();
|
|
2667
|
+
debugLog("owney-sdk", "swap: target balance before", before.toString());
|
|
2668
|
+
const result = quote.rail === "classic" ? await runClassic(deps, options) : await runFusion(deps, options, walletAddress);
|
|
2669
|
+
const after = await deps.readTargetBalance();
|
|
2670
|
+
const received = after - before;
|
|
2671
|
+
debugLog("owney-sdk", "swap: target balance after", {
|
|
2672
|
+
after: after.toString(),
|
|
2673
|
+
received: received.toString()
|
|
2674
|
+
});
|
|
2675
|
+
if (received <= 0n) {
|
|
2676
|
+
throw new OwneyError(
|
|
2677
|
+
"SWAP_REQUEST_FAILED",
|
|
2678
|
+
"The swap completed but no funds arrived in the wallet. Check the transaction before retrying.",
|
|
2679
|
+
{ rail: quote.rail, ...result }
|
|
2953
2680
|
);
|
|
2954
2681
|
}
|
|
2955
|
-
return {
|
|
2956
|
-
smartWallet: contexts[0]?.wallet.walletAddress ?? "0x0000000000000000000000000000000000000000",
|
|
2957
|
-
lifetimeEarnings,
|
|
2958
|
-
tokens
|
|
2959
|
-
};
|
|
2960
|
-
}
|
|
2961
|
-
function apyForDays(context, days, now) {
|
|
2962
|
-
if (days === "7D") return percent(context.snapshot.apy7d);
|
|
2963
|
-
if (days === "30D") return percent(context.snapshot.apy30d);
|
|
2964
|
-
const apy = calculateSnapshotApy(context.historic?.dailyYieldSnapshots ?? [], 14, now);
|
|
2965
|
-
const apyPercent = apy === void 0 ? void 0 : apy * 100;
|
|
2966
|
-
return apyPercent !== void 0 && Number.isFinite(apyPercent) ? apyPercent : void 0;
|
|
2967
|
-
}
|
|
2968
|
-
function dailyApy(point) {
|
|
2969
|
-
const total = raw(point.totalValueBase, "historic position");
|
|
2970
|
-
const earned = raw(point.dailyYieldBase, "historic position");
|
|
2971
|
-
const principal = total - earned;
|
|
2972
|
-
if (principal <= 0n || earned === 0n) return 0;
|
|
2973
|
-
return Number(earned) / Number(principal) * 365 * 100;
|
|
2974
|
-
}
|
|
2975
|
-
function aggregateHistory(contexts, dayCount, now) {
|
|
2976
|
-
const today = new Date(now).toISOString().slice(0, 10);
|
|
2977
|
-
const cutoff = new Date(Date.parse(today) - (dayCount - 1) * 864e5).toISOString().slice(0, 10);
|
|
2978
|
-
const assets = new Set(contexts.map((context) => context.asset.toUpperCase()));
|
|
2979
|
-
const unit = assets.size === 1 ? [...assets][0] : "USD";
|
|
2980
|
-
const byDate = /* @__PURE__ */ new Map();
|
|
2981
|
-
for (const context of contexts) {
|
|
2982
|
-
const points = context.historic?.dailyYieldSnapshots ?? [];
|
|
2983
|
-
for (const point of points) {
|
|
2984
|
-
if (!/^\d{4}-\d{2}-\d{2}$/.test(point.date) || !Number.isFinite(Date.parse(point.date)) || point.date < cutoff || point.date > today) continue;
|
|
2985
|
-
const tokens = Number(decimal(point.totalValueBase, point.baseAssetDecimals, "historic position"));
|
|
2986
|
-
const amount = assets.size === 1 ? tokens : tokens * point.baseAssetPriceUsd;
|
|
2987
|
-
if (!Number.isFinite(amount) || amount < 0) {
|
|
2988
|
-
invalid("historic position", "expected a finite non-negative balance");
|
|
2989
|
-
}
|
|
2990
|
-
const current = byDate.get(point.date) ?? { weighted: 0, amount: 0 };
|
|
2991
|
-
current.weighted += dailyApy(point) * amount;
|
|
2992
|
-
current.amount += amount;
|
|
2993
|
-
byDate.set(point.date, current);
|
|
2994
|
-
}
|
|
2995
|
-
}
|
|
2996
|
-
return [...byDate.entries()].sort(([left], [right]) => left.localeCompare(right)).map(([date, value]) => ({
|
|
2997
|
-
date,
|
|
2998
|
-
apy: value.amount > 0 ? value.weighted / value.amount : 0,
|
|
2999
|
-
historicalBalance: { amount: value.amount, unit }
|
|
3000
|
-
}));
|
|
2682
|
+
return { received: received.toString(), ...result };
|
|
3001
2683
|
}
|
|
3002
|
-
function
|
|
3003
|
-
|
|
3004
|
-
|
|
3005
|
-
const byAsset = {};
|
|
3006
|
-
for (const context of contexts) {
|
|
3007
|
-
const valueUsd = usd(
|
|
3008
|
-
raw(context.snapshot.totalValueBase, "snapshot"),
|
|
3009
|
-
context.snapshot.baseAssetDecimals,
|
|
3010
|
-
context.snapshot.baseAssetPriceUsd
|
|
3011
|
-
);
|
|
3012
|
-
const apy = apyForDays(context, days, now);
|
|
3013
|
-
if (apy === void 0) continue;
|
|
3014
|
-
weighted += apy * valueUsd;
|
|
3015
|
-
totalUsd += valueUsd;
|
|
3016
|
-
byAsset[context.asset] = apy;
|
|
3017
|
-
}
|
|
3018
|
-
const dayCount = Number(days.slice(0, -1));
|
|
3019
|
-
return {
|
|
2684
|
+
async function runClassic(deps, options) {
|
|
2685
|
+
const {
|
|
2686
|
+
quote,
|
|
3020
2687
|
walletAddress,
|
|
3021
|
-
|
|
3022
|
-
|
|
3023
|
-
|
|
3024
|
-
};
|
|
3025
|
-
|
|
3026
|
-
|
|
3027
|
-
const
|
|
3028
|
-
|
|
3029
|
-
|
|
3030
|
-
|
|
3031
|
-
|
|
3032
|
-
|
|
3033
|
-
}
|
|
3034
|
-
|
|
3035
|
-
|
|
3036
|
-
|
|
3037
|
-
details.transactionHash,
|
|
3038
|
-
details.txHash,
|
|
3039
|
-
...Array.isArray(details.transactionHashes) ? details.transactionHashes : [],
|
|
3040
|
-
...Array.isArray(details.txHashes) ? details.txHashes : []
|
|
3041
|
-
];
|
|
3042
|
-
return values.filter(
|
|
3043
|
-
(value) => typeof value === "string" && /^0x[a-fA-F0-9]{64}$/.test(value)
|
|
3044
|
-
).filter((value, index, all) => all.indexOf(value) === index);
|
|
3045
|
-
}
|
|
3046
|
-
function actionEntry(action) {
|
|
3047
|
-
if (action.actionType.toLowerCase().includes("withdraw")) return void 0;
|
|
3048
|
-
return {
|
|
3049
|
-
agent: "yieldseeker",
|
|
3050
|
-
action: actionType(action.actionType),
|
|
3051
|
-
date: action.createdDate,
|
|
3052
|
-
oldApy: null,
|
|
3053
|
-
newApy: null,
|
|
3054
|
-
transactions: [
|
|
3055
|
-
{
|
|
3056
|
-
txHashes: transactionHashes(action.details),
|
|
3057
|
-
chainId: 8453
|
|
3058
|
-
}
|
|
3059
|
-
],
|
|
3060
|
-
rebalanceLog: []
|
|
3061
|
-
};
|
|
3062
|
-
}
|
|
3063
|
-
function depositDestination(context, movement) {
|
|
3064
|
-
const to = movement.toAddress.toLowerCase();
|
|
3065
|
-
const option = context.positions.find(({ yieldOption }) => yieldOption.chainId === movement.chainId && yieldOption.assetAddress.toLowerCase() === context.agent.assetAddress.toLowerCase() && yieldOption.address.toLowerCase() === to)?.yieldOption;
|
|
3066
|
-
if (option) return { protocol: option.provider || "Vault", pool: option.name, tokenSymbol: context.asset };
|
|
3067
|
-
const receipt = context.historic?.assets.find((asset) => asset.chainId === movement.chainId && !asset.isSpam && asset.address.toLowerCase() === to && asset.address.toLowerCase() !== context.agent.assetAddress.toLowerCase());
|
|
3068
|
-
const minted = receipt && context.historic?.movements.some((candidate) => candidate.chainId === movement.chainId && candidate.transactionHash.toLowerCase() === movement.transactionHash.toLowerCase() && candidate.assetAddress.toLowerCase() === receipt.address.toLowerCase() && candidate.fromAddress.toLowerCase() === "0x0000000000000000000000000000000000000000" && candidate.toAddress.toLowerCase() === context.wallet.walletAddress.toLowerCase() && raw(candidate.assetAmount, "historic position") > 0n);
|
|
3069
|
-
if (receipt && minted) return { protocol: "Vault", pool: receipt.name || receipt.symbol, tokenSymbol: context.asset };
|
|
3070
|
-
return void 0;
|
|
3071
|
-
}
|
|
3072
|
-
function movementEntry(movement, wallet, agent, asset, ownerAddress, vaultAddresses, destination) {
|
|
3073
|
-
const from = movement.fromAddress.toLowerCase();
|
|
3074
|
-
const to = movement.toAddress.toLowerCase();
|
|
3075
|
-
const owner = ownerAddress.toLowerCase();
|
|
3076
|
-
const agentWallet = wallet.walletAddress.toLowerCase();
|
|
3077
|
-
const baseAsset = agent.assetAddress.toLowerCase();
|
|
3078
|
-
if (movement.chainId !== agent.chainId || movement.assetAddress.toLowerCase() !== baseAsset) {
|
|
3079
|
-
return void 0;
|
|
3080
|
-
}
|
|
3081
|
-
let action;
|
|
3082
|
-
if (to === agentWallet && !vaultAddresses.has(from)) {
|
|
3083
|
-
action = "Top up";
|
|
3084
|
-
} else if (from === agentWallet && to === owner) {
|
|
3085
|
-
action = "Withdraw";
|
|
3086
|
-
} else if (from === agentWallet && destination) {
|
|
3087
|
-
action = "Deposit";
|
|
3088
|
-
}
|
|
3089
|
-
if (!action) return void 0;
|
|
3090
|
-
return {
|
|
3091
|
-
agent: "yieldseeker",
|
|
3092
|
-
action,
|
|
3093
|
-
...action === "Deposit" && destination ? { positions: [{
|
|
3094
|
-
...destination,
|
|
3095
|
-
amount: decimal(movement.assetAmount, YIELDSEEKER_ASSET_METADATA[asset].decimals, "historic position")
|
|
3096
|
-
}] } : {},
|
|
3097
|
-
date: movement.blockDate,
|
|
3098
|
-
oldApy: null,
|
|
3099
|
-
newApy: null,
|
|
3100
|
-
transactions: [
|
|
3101
|
-
{
|
|
3102
|
-
txHashes: [movement.transactionHash],
|
|
3103
|
-
chainId: agent.chainId,
|
|
3104
|
-
tokenSymbol: asset,
|
|
3105
|
-
amount: decimal(
|
|
3106
|
-
movement.assetAmount,
|
|
3107
|
-
YIELDSEEKER_ASSET_METADATA[asset].decimals,
|
|
3108
|
-
"historic position"
|
|
3109
|
-
)
|
|
3110
|
-
}
|
|
3111
|
-
],
|
|
3112
|
-
rebalanceLog: []
|
|
2688
|
+
slippage = DEFAULT_SLIPPAGE,
|
|
2689
|
+
direction,
|
|
2690
|
+
onStage
|
|
2691
|
+
} = options;
|
|
2692
|
+
const isNativeSource = quote.src.address.toLowerCase().startsWith("0xeeee");
|
|
2693
|
+
const amount = isNativeSource ? BigInt(quote.src.amount) : await affordableAmount(deps, BigInt(quote.src.amount));
|
|
2694
|
+
const swapTxRequest = {
|
|
2695
|
+
from: {
|
|
2696
|
+
chainId: quote.src.chainId,
|
|
2697
|
+
symbol: quote.src.symbol,
|
|
2698
|
+
amount: amount.toString()
|
|
2699
|
+
},
|
|
2700
|
+
to: { chainId: quote.dst.chainId, symbol: quote.dst.symbol },
|
|
2701
|
+
walletAddress,
|
|
2702
|
+
slippage,
|
|
2703
|
+
...direction ? { direction } : {}
|
|
3113
2704
|
};
|
|
3114
|
-
|
|
3115
|
-
|
|
3116
|
-
|
|
3117
|
-
|
|
3118
|
-
|
|
3119
|
-
|
|
3120
|
-
|
|
3121
|
-
|
|
3122
|
-
|
|
2705
|
+
onStage?.("quoting");
|
|
2706
|
+
debugLog("owney-sdk", "swap: fetching classic calldata");
|
|
2707
|
+
let { tx } = await deps.api.swapTx(swapTxRequest);
|
|
2708
|
+
const isNative = BigInt(tx.value ?? "0") > 0n;
|
|
2709
|
+
if (!isNative) {
|
|
2710
|
+
const needed = amount;
|
|
2711
|
+
const current = await deps.readAllowance(tx.to);
|
|
2712
|
+
debugLog("owney-sdk", "swap: allowance", {
|
|
2713
|
+
spender: tx.to,
|
|
2714
|
+
current: current.toString(),
|
|
2715
|
+
needed: needed.toString()
|
|
3123
2716
|
});
|
|
3124
|
-
|
|
3125
|
-
|
|
3126
|
-
|
|
3127
|
-
|
|
3128
|
-
|
|
3129
|
-
|
|
3130
|
-
|
|
3131
|
-
options.ownerAddress,
|
|
3132
|
-
options.vaultAddresses,
|
|
3133
|
-
depositDestination(context, movement)
|
|
3134
|
-
)
|
|
3135
|
-
),
|
|
3136
|
-
...(context.actions ?? []).map(actionEntry)
|
|
3137
|
-
].filter((entry) => entry !== void 0);
|
|
3138
|
-
});
|
|
3139
|
-
const grouped = /* @__PURE__ */ new Map();
|
|
3140
|
-
const ungrouped = [];
|
|
3141
|
-
for (const entry of entries) {
|
|
3142
|
-
const tx = entry.transactions[0];
|
|
3143
|
-
const hash = tx?.txHashes[0];
|
|
3144
|
-
if (!hash) {
|
|
3145
|
-
ungrouped.push(entry);
|
|
3146
|
-
continue;
|
|
3147
|
-
}
|
|
3148
|
-
const key2 = `${entry.agent}:${entry.action}:${tx.chainId}:${hash.toLowerCase()}`;
|
|
3149
|
-
const previous = grouped.get(key2);
|
|
3150
|
-
if (!previous) {
|
|
3151
|
-
grouped.set(key2, entry);
|
|
3152
|
-
continue;
|
|
3153
|
-
}
|
|
3154
|
-
if (entry.action === "Deposit" && entry.positions?.length) {
|
|
3155
|
-
if (!previous.positions?.length) {
|
|
3156
|
-
grouped.set(key2, entry);
|
|
3157
|
-
continue;
|
|
3158
|
-
}
|
|
3159
|
-
previous.positions.push(...entry.positions);
|
|
3160
|
-
previous.transactions.push(...entry.transactions);
|
|
3161
|
-
}
|
|
3162
|
-
}
|
|
3163
|
-
const filtered = [...grouped.values(), ...ungrouped].filter((entry) => (!options.fromDate || entry.date >= options.fromDate) && (!options.toDate || entry.date <= options.toDate)).sort((left, right) => right.date.localeCompare(left.date));
|
|
3164
|
-
return {
|
|
3165
|
-
data: filtered.slice(0, options.limit),
|
|
3166
|
-
// v1 returns the whole action/movement collection and defines no cursor.
|
|
3167
|
-
// Report a terminal page so callers never loop over the same prefix.
|
|
3168
|
-
hasMore: false
|
|
3169
|
-
};
|
|
3170
|
-
}
|
|
3171
|
-
function mapYieldseekerProfile(address, contexts) {
|
|
3172
|
-
const protocols = /* @__PURE__ */ new Set();
|
|
3173
|
-
for (const context of contexts) {
|
|
3174
|
-
for (const current of context.positions) {
|
|
3175
|
-
if (current.yieldOption?.provider) {
|
|
3176
|
-
protocols.add(String(current.yieldOption.provider));
|
|
3177
|
-
}
|
|
3178
|
-
}
|
|
3179
|
-
}
|
|
3180
|
-
return {
|
|
3181
|
-
address,
|
|
3182
|
-
smartWallet: contexts[0]?.wallet.walletAddress ?? "0x0000000000000000000000000000000000000000",
|
|
3183
|
-
chains: contexts.length > 0 ? [8453] : [],
|
|
3184
|
-
hasActiveSessionKey: contexts.some(
|
|
3185
|
-
(context) => context.wallet.initializedDate != null
|
|
3186
|
-
),
|
|
3187
|
-
protocols: [...protocols]
|
|
3188
|
-
};
|
|
3189
|
-
}
|
|
3190
|
-
function mapYieldseekerAgentApy(options, days) {
|
|
3191
|
-
const perAsset = {};
|
|
3192
|
-
const all = [];
|
|
3193
|
-
for (const entry of options) {
|
|
3194
|
-
const apys = entry.yieldOptions.map(
|
|
3195
|
-
(option) => publicApyAfterYieldseekerFee(riskAdjustedApyForDays(option, days))
|
|
3196
|
-
).filter(Number.isFinite);
|
|
3197
|
-
if (apys.length === 0) continue;
|
|
3198
|
-
const average = apys.reduce((sum, value) => sum + value, 0) / apys.length;
|
|
3199
|
-
perAsset[entry.asset] = average;
|
|
3200
|
-
all.push(average);
|
|
3201
|
-
}
|
|
3202
|
-
return {
|
|
3203
|
-
averageApy: all.length > 0 ? all.reduce((sum, value) => sum + value, 0) / all.length : 0,
|
|
3204
|
-
detailedApys: { apyPerAsset: { 8453: perAsset } }
|
|
3205
|
-
};
|
|
3206
|
-
}
|
|
3207
|
-
|
|
3208
|
-
// src/agents/yieldseeker/yieldseeker.agent.ts
|
|
3209
|
-
var OWNEY_AGENT_NAME = "owney";
|
|
3210
|
-
var YIELDSEEKER_USERNAME_PREFIX = "owney_";
|
|
3211
|
-
var YIELDSEEKER_USERNAME_RANDOM_LENGTH = 14;
|
|
3212
|
-
var YIELDSEEKER_USERNAME_CREATE_ATTEMPTS = 3;
|
|
3213
|
-
var YIELDSEEKER_YIELD_OPTIONS_CACHE_MS = 6e4;
|
|
3214
|
-
function generateYieldseekerUsername() {
|
|
3215
|
-
const suffix = globalThis.crypto.randomUUID().replaceAll("-", "").slice(0, YIELDSEEKER_USERNAME_RANDOM_LENGTH).toLowerCase();
|
|
3216
|
-
return `${YIELDSEEKER_USERNAME_PREFIX}${suffix}`;
|
|
3217
|
-
}
|
|
3218
|
-
function isUsernameConflict(error) {
|
|
3219
|
-
if (!(error instanceof YieldseekerApiError)) return false;
|
|
3220
|
-
const code = error.providerCode.toUpperCase();
|
|
3221
|
-
return code.includes("USERNAME") && (code.includes("TAKEN") || code.includes("EXIST") || code.includes("UNAVAILABLE") || code.includes("IN_USE"));
|
|
3222
|
-
}
|
|
3223
|
-
var YIELDSEEKER_AGENT_WALLET_ABI = [
|
|
3224
|
-
{
|
|
3225
|
-
type: "function",
|
|
3226
|
-
name: "withdrawAssetToUser",
|
|
3227
|
-
stateMutability: "nonpayable",
|
|
3228
|
-
inputs: [
|
|
3229
|
-
{ name: "recipient", type: "address" },
|
|
3230
|
-
{ name: "asset", type: "address" },
|
|
3231
|
-
{ name: "amount", type: "uint256" }
|
|
3232
|
-
],
|
|
3233
|
-
outputs: []
|
|
3234
|
-
},
|
|
3235
|
-
{
|
|
3236
|
-
type: "function",
|
|
3237
|
-
name: "withdrawAllAssetToUser",
|
|
3238
|
-
stateMutability: "nonpayable",
|
|
3239
|
-
inputs: [
|
|
3240
|
-
{ name: "recipient", type: "address" },
|
|
3241
|
-
{ name: "asset", type: "address" }
|
|
3242
|
-
],
|
|
3243
|
-
outputs: []
|
|
3244
|
-
}
|
|
3245
|
-
];
|
|
3246
|
-
function query(params) {
|
|
3247
|
-
const search = new URLSearchParams();
|
|
3248
|
-
for (const [key2, value] of Object.entries(params)) {
|
|
3249
|
-
if (value !== void 0) search.set(key2, String(value));
|
|
3250
|
-
}
|
|
3251
|
-
const encoded = search.toString();
|
|
3252
|
-
return encoded ? `?${encoded}` : "";
|
|
3253
|
-
}
|
|
3254
|
-
var YieldseekerAgent = class {
|
|
3255
|
-
id = "yieldseeker";
|
|
3256
|
-
balanceComposition = "tokens-plus-positions";
|
|
3257
|
-
supportedChainIds = [8453];
|
|
3258
|
-
supportedAssets = [
|
|
3259
|
-
{
|
|
3260
|
-
chainId: 8453,
|
|
3261
|
-
chain: "BASE",
|
|
3262
|
-
assets: [
|
|
3263
|
-
{ symbol: "USDC", minDepositAmount: "10000000" },
|
|
3264
|
-
{ symbol: "WETH", minDepositAmount: "1" }
|
|
3265
|
-
]
|
|
3266
|
-
}
|
|
3267
|
-
];
|
|
3268
|
-
api;
|
|
3269
|
-
auth;
|
|
3270
|
-
transactionExecutor;
|
|
3271
|
-
unwindReceiptWaiter;
|
|
3272
|
-
agentContexts = /* @__PURE__ */ new Map();
|
|
3273
|
-
users = /* @__PURE__ */ new Map();
|
|
3274
|
-
pendingAgents = /* @__PURE__ */ new Map();
|
|
3275
|
-
yieldOptions = /* @__PURE__ */ new Map();
|
|
3276
|
-
pendingYieldOptions = /* @__PURE__ */ new Map();
|
|
3277
|
-
constructor(owneyApiKey, options = {}) {
|
|
3278
|
-
this.api = new YieldseekerApiClient(
|
|
3279
|
-
owneyApiKey,
|
|
3280
|
-
options.baseUrl ?? getYieldseekerProxyBaseUrl(),
|
|
3281
|
-
options.fetchFn
|
|
3282
|
-
);
|
|
3283
|
-
this.auth = new YieldseekerAuth(options.auth);
|
|
3284
|
-
this.transactionExecutor = options.transactionExecutor;
|
|
3285
|
-
this.unwindReceiptWaiter = options.unwindReceiptWaiter;
|
|
3286
|
-
}
|
|
3287
|
-
async disconnect() {
|
|
3288
|
-
this.auth.clear();
|
|
3289
|
-
for (const key2 of this.users.keys()) {
|
|
3290
|
-
const [walletAddress, chainId] = key2.split(":");
|
|
3291
|
-
clearYieldseekerIdentity(walletAddress, Number(chainId));
|
|
3292
|
-
}
|
|
3293
|
-
this.users.clear();
|
|
3294
|
-
this.agentContexts.clear();
|
|
3295
|
-
this.pendingAgents.clear();
|
|
3296
|
-
}
|
|
3297
|
-
async activateAgent(state, chainId, asset) {
|
|
3298
|
-
this.assertChain(chainId);
|
|
3299
|
-
const targetAsset = asset ?? "USDC";
|
|
3300
|
-
this.assertAsset(targetAsset);
|
|
3301
|
-
await this.ensureAgent(state, chainId, targetAsset);
|
|
3302
|
-
}
|
|
3303
|
-
async deposit(state, chainId, amount, asset, depositCallback) {
|
|
3304
|
-
this.assertChain(chainId);
|
|
3305
|
-
this.assertAsset(asset);
|
|
3306
|
-
if (BigInt(amount) <= 0n) {
|
|
3307
|
-
throw new OwneyError(
|
|
3308
|
-
"DEPOSIT_AMOUNT_BELOW_MINIMUM",
|
|
3309
|
-
"Yieldseeker deposits must be greater than zero.",
|
|
3310
|
-
{ amount, minDepositAmount: "1" },
|
|
3311
|
-
this.id
|
|
3312
|
-
);
|
|
3313
|
-
}
|
|
3314
|
-
const context = await this.ensureAgent(state, chainId, asset);
|
|
3315
|
-
let txHash;
|
|
3316
|
-
try {
|
|
3317
|
-
if (depositCallback) {
|
|
3318
|
-
provideDepositVerificationContext(depositCallback, {
|
|
3319
|
-
agentId: "yieldseeker",
|
|
3320
|
-
signature: await this.auth.getToken(state, chainId),
|
|
3321
|
-
userId: context.user.userId,
|
|
3322
|
-
yieldseekerAgentId: context.agent.agentId
|
|
3323
|
-
});
|
|
3324
|
-
txHash = await depositCallback(
|
|
3325
|
-
context.wallet.walletAddress,
|
|
3326
|
-
chainId,
|
|
3327
|
-
amount
|
|
3328
|
-
);
|
|
3329
|
-
await this.waitForReceipt(state, chainId, txHash);
|
|
3330
|
-
} else {
|
|
3331
|
-
txHash = await this.submitTransaction(state, chainId, {
|
|
3332
|
-
from: (0, import_viem6.getAddress)(state.walletAddress),
|
|
3333
|
-
to: YIELDSEEKER_ASSET_METADATA[asset].address,
|
|
3334
|
-
data: (0, import_viem6.encodeFunctionData)({
|
|
3335
|
-
abi: import_viem6.erc20Abi,
|
|
3336
|
-
functionName: "transfer",
|
|
3337
|
-
args: [(0, import_viem6.getAddress)(context.wallet.walletAddress), BigInt(amount)]
|
|
3338
|
-
}),
|
|
3339
|
-
value: "0",
|
|
3340
|
-
chainId
|
|
3341
|
-
});
|
|
3342
|
-
}
|
|
3343
|
-
} finally {
|
|
3344
|
-
await this.refreshSnapshotAfterMovement(
|
|
3345
|
-
state,
|
|
3346
|
-
chainId,
|
|
3347
|
-
context,
|
|
3348
|
-
"deposit"
|
|
3349
|
-
);
|
|
3350
|
-
}
|
|
3351
|
-
return {
|
|
3352
|
-
txHash,
|
|
3353
|
-
smartWallet: context.wallet.walletAddress,
|
|
3354
|
-
amount
|
|
3355
|
-
};
|
|
3356
|
-
}
|
|
3357
|
-
async withdraw(state, chainId, asset, amount) {
|
|
3358
|
-
this.assertChain(chainId);
|
|
3359
|
-
this.assertAsset(asset);
|
|
3360
|
-
if (amount !== void 0 && BigInt(amount) <= 0n) {
|
|
3361
|
-
throw new OwneyError(
|
|
3362
|
-
"WITHDRAW_FAILED",
|
|
3363
|
-
"Yieldseeker withdrawals must be greater than zero.",
|
|
3364
|
-
{ amount },
|
|
3365
|
-
this.id
|
|
3366
|
-
);
|
|
3367
|
-
}
|
|
3368
|
-
const context = await this.findAgent(state, chainId, asset);
|
|
3369
|
-
if (!context) {
|
|
3370
|
-
throw new OwneyError(
|
|
3371
|
-
"WITHDRAW_INSUFFICIENT_BALANCE",
|
|
3372
|
-
`No Yieldseeker ${asset} agent exists for this wallet.`,
|
|
3373
|
-
{ asset, available: "0" },
|
|
3374
|
-
this.id
|
|
3375
|
-
);
|
|
3376
|
-
}
|
|
3377
|
-
try {
|
|
3378
|
-
const portfolio = await this.loadPortfolioContext(
|
|
3379
|
-
state,
|
|
3380
|
-
chainId,
|
|
3381
|
-
context
|
|
3382
|
-
);
|
|
3383
|
-
const metadata = YIELDSEEKER_ASSET_METADATA[asset];
|
|
3384
|
-
const idleEntry = Object.entries(portfolio.snapshot.tokenBalances).find(
|
|
3385
|
-
([address]) => address.toLowerCase() === metadata.address.toLowerCase()
|
|
3386
|
-
);
|
|
3387
|
-
const idle = BigInt(idleEntry?.[1] ?? "0");
|
|
3388
|
-
const deployed = portfolio.positions.reduce(
|
|
3389
|
-
(total, position2) => total + BigInt(position2.withdrawableAssetsRaw),
|
|
3390
|
-
0n
|
|
3391
|
-
);
|
|
3392
|
-
const totalAvailable = idle + deployed;
|
|
3393
|
-
const requested = amount === void 0 ? totalAvailable : BigInt(amount);
|
|
3394
|
-
if (requested > totalAvailable) {
|
|
3395
|
-
throw new OwneyError(
|
|
3396
|
-
"WITHDRAW_INSUFFICIENT_BALANCE",
|
|
3397
|
-
`Requested withdrawal "${requested}" exceeds available Yieldseeker balance "${totalAvailable}" for asset "${asset}".`,
|
|
3398
|
-
{
|
|
3399
|
-
asset,
|
|
3400
|
-
requested: requested.toString(),
|
|
3401
|
-
available: totalAvailable.toString()
|
|
3402
|
-
},
|
|
3403
|
-
this.id
|
|
3404
|
-
);
|
|
3405
|
-
}
|
|
3406
|
-
let remaining = requested > idle ? requested - idle : 0n;
|
|
3407
|
-
for (const position2 of portfolio.positions) {
|
|
3408
|
-
if (remaining === 0n) break;
|
|
3409
|
-
const available = BigInt(position2.withdrawableAssetsRaw);
|
|
3410
|
-
if (available <= 0n) continue;
|
|
3411
|
-
const assetsRaw = available < remaining ? available : remaining;
|
|
3412
|
-
const response = await this.walletRequest(
|
|
3413
|
-
state,
|
|
3414
|
-
chainId,
|
|
3415
|
-
this.agentPath(context, "withdraw-from-position"),
|
|
3416
|
-
{
|
|
3417
|
-
method: "POST",
|
|
3418
|
-
body: {
|
|
3419
|
-
chainId,
|
|
3420
|
-
vaultAddress: position2.yieldOption.address,
|
|
3421
|
-
assetsRaw: assetsRaw.toString()
|
|
3422
|
-
}
|
|
3423
|
-
}
|
|
3424
|
-
);
|
|
3425
|
-
if (!this.isTransactionHash(response?.transactionHash)) {
|
|
3426
|
-
throw this.invalidResponse("position withdrawal");
|
|
3427
|
-
}
|
|
3428
|
-
await this.waitForReceipt(state, chainId, response.transactionHash);
|
|
3429
|
-
remaining -= assetsRaw;
|
|
3430
|
-
}
|
|
3431
|
-
if (remaining > 0n) {
|
|
3432
|
-
throw this.invalidResponse("yield positions", {
|
|
3433
|
-
reason: "Withdrawable positions could not cover the request.",
|
|
3434
|
-
remaining: remaining.toString()
|
|
3435
|
-
});
|
|
3436
|
-
}
|
|
3437
|
-
const account = (0, import_viem6.getAddress)(state.walletAddress);
|
|
3438
|
-
const txHash = await this.submitTransaction(state, chainId, {
|
|
3439
|
-
from: account,
|
|
3440
|
-
to: (0, import_viem6.getAddress)(context.wallet.walletAddress),
|
|
3441
|
-
data: amount === void 0 ? (0, import_viem6.encodeFunctionData)({
|
|
3442
|
-
abi: YIELDSEEKER_AGENT_WALLET_ABI,
|
|
3443
|
-
functionName: "withdrawAllAssetToUser",
|
|
3444
|
-
args: [account, metadata.address]
|
|
3445
|
-
}) : (0, import_viem6.encodeFunctionData)({
|
|
3446
|
-
abi: YIELDSEEKER_AGENT_WALLET_ABI,
|
|
3447
|
-
functionName: "withdrawAssetToUser",
|
|
3448
|
-
args: [account, metadata.address, requested]
|
|
3449
|
-
}),
|
|
3450
|
-
value: "0",
|
|
3451
|
-
chainId
|
|
3452
|
-
});
|
|
3453
|
-
return {
|
|
3454
|
-
txHash,
|
|
3455
|
-
type: amount === void 0 ? "full" : "partial",
|
|
3456
|
-
amount: requested.toString()
|
|
3457
|
-
};
|
|
3458
|
-
} finally {
|
|
3459
|
-
await this.refreshSnapshotAfterMovement(
|
|
3460
|
-
state,
|
|
3461
|
-
chainId,
|
|
3462
|
-
context,
|
|
3463
|
-
"withdrawal"
|
|
3464
|
-
);
|
|
3465
|
-
}
|
|
3466
|
-
}
|
|
3467
|
-
async getBalances(state, chainId) {
|
|
3468
|
-
this.assertChain(chainId);
|
|
3469
|
-
return mapYieldseekerBalances(await this.loadPortfolio(state, chainId, {}));
|
|
3470
|
-
}
|
|
3471
|
-
async getEarnings(state, chainId) {
|
|
3472
|
-
this.assertChain(chainId);
|
|
3473
|
-
return mapYieldseekerEarnings(await this.loadPortfolio(state, chainId, {}));
|
|
3474
|
-
}
|
|
3475
|
-
async getAccountApy(state, chainId, days, tokenSymbol) {
|
|
3476
|
-
this.assertChain(chainId);
|
|
3477
|
-
const asset = tokenSymbol?.toUpperCase();
|
|
3478
|
-
if (asset !== void 0) this.assertAsset(asset);
|
|
3479
|
-
const contexts = await this.loadPortfolio(state, chainId, {
|
|
3480
|
-
...asset ? { asset } : {},
|
|
3481
|
-
historic: true
|
|
3482
|
-
});
|
|
3483
|
-
return mapYieldseekerApy(state.walletAddress, contexts, days);
|
|
3484
|
-
}
|
|
3485
|
-
async getHistory(state, chainId, options) {
|
|
3486
|
-
this.assertChain(chainId);
|
|
3487
|
-
const asset = options?.tokenSymbol?.toUpperCase();
|
|
3488
|
-
if (asset !== void 0) this.assertAsset(asset);
|
|
3489
|
-
const contexts = await this.loadPortfolio(state, chainId, {
|
|
3490
|
-
...asset ? { asset } : {},
|
|
3491
|
-
historic: true,
|
|
3492
|
-
actions: true
|
|
3493
|
-
});
|
|
3494
|
-
const catalog = await Promise.all(
|
|
3495
|
-
[...new Set(contexts.map((context) => context.asset))].map(
|
|
3496
|
-
(contextAsset) => this.loadYieldOptions(contextAsset)
|
|
3497
|
-
)
|
|
3498
|
-
);
|
|
3499
|
-
const vaultAddresses = new Set(
|
|
3500
|
-
catalog.flat().filter(
|
|
3501
|
-
(yieldOption) => yieldOption.chainId === chainId && (0, import_viem6.isAddress)(yieldOption.address)
|
|
3502
|
-
).map((yieldOption) => yieldOption.address.toLowerCase())
|
|
3503
|
-
);
|
|
3504
|
-
return mapYieldseekerHistory(contexts, {
|
|
3505
|
-
limit: options?.limit ?? 10,
|
|
3506
|
-
ownerAddress: state.walletAddress,
|
|
3507
|
-
vaultAddresses,
|
|
3508
|
-
...options?.fromDate ? { fromDate: options.fromDate } : {},
|
|
3509
|
-
...options?.toDate ? { toDate: options.toDate } : {}
|
|
3510
|
-
});
|
|
3511
|
-
}
|
|
3512
|
-
async getUserProfile(state, chainId) {
|
|
3513
|
-
this.assertChain(chainId);
|
|
3514
|
-
return mapYieldseekerProfile(
|
|
3515
|
-
state.walletAddress,
|
|
3516
|
-
await this.loadPortfolio(state, chainId, {})
|
|
3517
|
-
);
|
|
3518
|
-
}
|
|
3519
|
-
async getAgentApy(days, options) {
|
|
3520
|
-
this.assertOptionalChain(options?.chainId);
|
|
3521
|
-
const requested = options?.tokenSymbol?.toUpperCase();
|
|
3522
|
-
if (requested !== void 0) this.assertAsset(requested);
|
|
3523
|
-
const assets = requested ? [requested] : ["USDC", "WETH"];
|
|
3524
|
-
const values = await Promise.all(
|
|
3525
|
-
assets.map(async (asset) => {
|
|
3526
|
-
return { asset, yieldOptions: await this.loadYieldOptions(asset) };
|
|
3527
|
-
})
|
|
3528
|
-
);
|
|
3529
|
-
return mapYieldseekerAgentApy(values, days);
|
|
3530
|
-
}
|
|
3531
|
-
async loadYieldOptions(asset) {
|
|
3532
|
-
const cached = this.yieldOptions.get(asset);
|
|
3533
|
-
if (cached && cached.expiresAt > Date.now()) return cached.value;
|
|
3534
|
-
const pending = this.pendingYieldOptions.get(asset);
|
|
3535
|
-
if (pending) return pending;
|
|
3536
|
-
const metadata = YIELDSEEKER_ASSET_METADATA[asset];
|
|
3537
|
-
const request = this.api.request(
|
|
3538
|
-
`/chains/8453/assets/${metadata.address}/yield-options`
|
|
3539
|
-
).then((response) => {
|
|
3540
|
-
if (!Array.isArray(response?.yieldOptions)) {
|
|
3541
|
-
throw this.invalidResponse("yield options");
|
|
3542
|
-
}
|
|
3543
|
-
this.yieldOptions.set(asset, {
|
|
3544
|
-
expiresAt: Date.now() + YIELDSEEKER_YIELD_OPTIONS_CACHE_MS,
|
|
3545
|
-
value: response.yieldOptions
|
|
3546
|
-
});
|
|
3547
|
-
return response.yieldOptions;
|
|
3548
|
-
}).finally(() => this.pendingYieldOptions.delete(asset));
|
|
3549
|
-
this.pendingYieldOptions.set(asset, request);
|
|
3550
|
-
return request;
|
|
3551
|
-
}
|
|
3552
|
-
userKey(state, chainId) {
|
|
3553
|
-
return `${state.walletAddress.toLowerCase()}:${chainId}`;
|
|
3554
|
-
}
|
|
3555
|
-
contextKey(state, chainId, asset) {
|
|
3556
|
-
return `${this.userKey(state, chainId)}:${asset}`;
|
|
3557
|
-
}
|
|
3558
|
-
async resolveUser(state, chainId) {
|
|
3559
|
-
const key2 = this.userKey(state, chainId);
|
|
3560
|
-
const inMemory = this.users.get(key2);
|
|
3561
|
-
if (inMemory) return inMemory;
|
|
3562
|
-
const persisted = readYieldseekerIdentity(state.walletAddress, chainId);
|
|
3563
|
-
if (persisted) {
|
|
3564
|
-
this.users.set(key2, persisted);
|
|
3565
|
-
return persisted;
|
|
3566
|
-
}
|
|
3567
|
-
const walletAddress = (0, import_viem6.getAddress)(state.walletAddress);
|
|
3568
|
-
let user = null;
|
|
3569
|
-
try {
|
|
3570
|
-
const login = await this.providerRequest(
|
|
3571
|
-
state,
|
|
3572
|
-
chainId,
|
|
3573
|
-
"/users/login-with-wallet",
|
|
3574
|
-
{ method: "POST", body: { walletAddress } }
|
|
3575
|
-
);
|
|
3576
|
-
user = login?.user ?? null;
|
|
3577
|
-
if (!user) {
|
|
3578
|
-
throw this.invalidResponse("wallet login", {
|
|
3579
|
-
reason: "A successful login returned no user."
|
|
3580
|
-
});
|
|
3581
|
-
}
|
|
3582
|
-
} catch (error) {
|
|
3583
|
-
if (!(error instanceof YieldseekerApiError) || error.providerCode !== "NO_USER") {
|
|
3584
|
-
if (error instanceof OwneyError) throw error;
|
|
3585
|
-
throw this.mapApiError(error);
|
|
3586
|
-
}
|
|
3587
|
-
let created;
|
|
3588
|
-
for (let attempt = 0; attempt < YIELDSEEKER_USERNAME_CREATE_ATTEMPTS; attempt += 1) {
|
|
3589
|
-
try {
|
|
3590
|
-
created = await this.providerRequest(
|
|
3591
|
-
state,
|
|
3592
|
-
chainId,
|
|
3593
|
-
"/users",
|
|
3594
|
-
{
|
|
3595
|
-
method: "POST",
|
|
3596
|
-
body: {
|
|
3597
|
-
walletAddress,
|
|
3598
|
-
username: generateYieldseekerUsername()
|
|
3599
|
-
}
|
|
3600
|
-
}
|
|
3601
|
-
);
|
|
3602
|
-
break;
|
|
3603
|
-
} catch (createError) {
|
|
3604
|
-
const canRetry = isUsernameConflict(createError) && attempt + 1 < YIELDSEEKER_USERNAME_CREATE_ATTEMPTS;
|
|
3605
|
-
if (canRetry) continue;
|
|
3606
|
-
throw this.mapApiError(createError);
|
|
3607
|
-
}
|
|
3608
|
-
}
|
|
3609
|
-
user = created?.user ?? null;
|
|
3610
|
-
}
|
|
3611
|
-
if (!user || !/^[a-zA-Z0-9_-]{1,128}$/.test(user.userId)) {
|
|
3612
|
-
throw this.invalidResponse("wallet identity");
|
|
3613
|
-
}
|
|
3614
|
-
const resolved = { userId: user.userId };
|
|
3615
|
-
this.users.set(key2, resolved);
|
|
3616
|
-
writeYieldseekerIdentity(state.walletAddress, chainId, resolved.userId);
|
|
3617
|
-
return resolved;
|
|
3618
|
-
}
|
|
3619
|
-
forgetUser(state, chainId) {
|
|
3620
|
-
this.users.delete(this.userKey(state, chainId));
|
|
3621
|
-
clearYieldseekerIdentity(state.walletAddress, chainId);
|
|
3622
|
-
}
|
|
3623
|
-
async ensureAgent(state, chainId, asset) {
|
|
3624
|
-
const key2 = this.contextKey(state, chainId, asset);
|
|
3625
|
-
const cached = this.agentContexts.get(key2);
|
|
3626
|
-
if (cached) return cached;
|
|
3627
|
-
const pending = this.pendingAgents.get(key2);
|
|
3628
|
-
if (pending) return pending;
|
|
3629
|
-
const request = this.resolveAgent(state, chainId, asset, true).then(
|
|
3630
|
-
async (context) => {
|
|
3631
|
-
if (!context) throw this.invalidResponse("agent creation");
|
|
3632
|
-
await this.deployAgent(state, chainId, context);
|
|
3633
|
-
this.agentContexts.set(key2, context);
|
|
3634
|
-
return context;
|
|
3635
|
-
}
|
|
3636
|
-
);
|
|
3637
|
-
this.pendingAgents.set(key2, request);
|
|
3638
|
-
try {
|
|
3639
|
-
return await request;
|
|
3640
|
-
} finally {
|
|
3641
|
-
this.pendingAgents.delete(key2);
|
|
3642
|
-
}
|
|
3643
|
-
}
|
|
3644
|
-
async findAgent(state, chainId, asset) {
|
|
3645
|
-
const key2 = this.contextKey(state, chainId, asset);
|
|
3646
|
-
const cached = this.agentContexts.get(key2);
|
|
3647
|
-
if (cached) return cached;
|
|
3648
|
-
const context = await this.resolveAgent(state, chainId, asset, false);
|
|
3649
|
-
if (context) this.agentContexts.set(key2, context);
|
|
3650
|
-
return context;
|
|
3651
|
-
}
|
|
3652
|
-
async resolveAgent(state, chainId, asset, createIfMissing) {
|
|
3653
|
-
const user = await this.resolveUser(state, chainId);
|
|
3654
|
-
const response = await this.walletRequest(
|
|
3655
|
-
state,
|
|
3656
|
-
chainId,
|
|
3657
|
-
`/users/${user.userId}/agents`
|
|
3658
|
-
);
|
|
3659
|
-
if (!Array.isArray(response?.agents)) {
|
|
3660
|
-
throw this.invalidResponse("agent list");
|
|
3661
|
-
}
|
|
3662
|
-
const metadata = YIELDSEEKER_ASSET_METADATA[asset];
|
|
3663
|
-
let agent = response.agents.find(
|
|
3664
|
-
(candidate) => this.isOwneyAgent(candidate) && candidate.chainId === chainId && candidate.type === "vault" && candidate.assetAddress.toLowerCase() === metadata.address.toLowerCase()
|
|
3665
|
-
);
|
|
3666
|
-
if (!agent && createIfMissing) {
|
|
3667
|
-
const created = await this.walletRequest(
|
|
3668
|
-
state,
|
|
3669
|
-
chainId,
|
|
3670
|
-
`/users/${user.userId}/agents`,
|
|
3671
|
-
{
|
|
3672
|
-
method: "POST",
|
|
3673
|
-
body: {
|
|
3674
|
-
name: OWNEY_AGENT_NAME,
|
|
3675
|
-
emoji: "\u{1F989}",
|
|
3676
|
-
chainId,
|
|
3677
|
-
assetAddress: metadata.address,
|
|
3678
|
-
type: "vault",
|
|
3679
|
-
rulePreset: null
|
|
3680
|
-
}
|
|
3681
|
-
}
|
|
3682
|
-
);
|
|
3683
|
-
agent = created?.agent;
|
|
3684
|
-
}
|
|
3685
|
-
if (!agent) return null;
|
|
3686
|
-
this.assertAgent(agent);
|
|
3687
|
-
const walletResponse = await this.walletRequest(
|
|
3688
|
-
state,
|
|
3689
|
-
chainId,
|
|
3690
|
-
`/users/${user.userId}/agents/${agent.agentId}/wallet`
|
|
3691
|
-
);
|
|
3692
|
-
if (!walletResponse?.agentWallet || !(0, import_viem6.isAddress)(walletResponse.agentWallet.walletAddress)) {
|
|
3693
|
-
throw this.invalidResponse("agent wallet");
|
|
3694
|
-
}
|
|
3695
|
-
return { user, agent, wallet: walletResponse.agentWallet, asset };
|
|
3696
|
-
}
|
|
3697
|
-
async loadPortfolio(state, chainId, options) {
|
|
3698
|
-
const user = await this.resolveUser(state, chainId);
|
|
3699
|
-
const response = await this.walletRequest(
|
|
3700
|
-
state,
|
|
3701
|
-
chainId,
|
|
3702
|
-
`/users/${user.userId}/agents`
|
|
3703
|
-
);
|
|
3704
|
-
if (!Array.isArray(response?.agents)) {
|
|
3705
|
-
throw this.invalidResponse("agent list");
|
|
3706
|
-
}
|
|
3707
|
-
const contexts = [];
|
|
3708
|
-
for (const agent of response.agents) {
|
|
3709
|
-
const asset = this.assetForAgent(agent);
|
|
3710
|
-
if (!this.isOwneyAgent(agent) || !asset || agent.chainId !== chainId || agent.type !== "vault" || options.asset && options.asset !== asset) {
|
|
3711
|
-
continue;
|
|
3712
|
-
}
|
|
3713
|
-
this.assertAgent(agent);
|
|
3714
|
-
const walletResponse = await this.walletRequest(
|
|
3715
|
-
state,
|
|
3716
|
-
chainId,
|
|
3717
|
-
`/users/${user.userId}/agents/${agent.agentId}/wallet`
|
|
3718
|
-
);
|
|
3719
|
-
if (!walletResponse?.agentWallet || !(0, import_viem6.isAddress)(walletResponse.agentWallet.walletAddress)) {
|
|
3720
|
-
throw this.invalidResponse("agent wallet");
|
|
3721
|
-
}
|
|
3722
|
-
const context = {
|
|
3723
|
-
user,
|
|
3724
|
-
agent,
|
|
3725
|
-
wallet: walletResponse.agentWallet,
|
|
3726
|
-
asset
|
|
3727
|
-
};
|
|
3728
|
-
this.agentContexts.set(this.contextKey(state, chainId, asset), context);
|
|
3729
|
-
contexts.push(context);
|
|
3730
|
-
}
|
|
3731
|
-
return Promise.all(
|
|
3732
|
-
contexts.map(
|
|
3733
|
-
(context) => this.loadPortfolioContext(state, chainId, context, options)
|
|
3734
|
-
)
|
|
3735
|
-
);
|
|
3736
|
-
}
|
|
3737
|
-
async loadPortfolioContext(state, chainId, context, options = {}) {
|
|
3738
|
-
const [snapshot, positions, historic, actions] = await Promise.all([
|
|
3739
|
-
this.walletRequest(
|
|
3740
|
-
state,
|
|
3741
|
-
chainId,
|
|
3742
|
-
`${this.agentPath(context, "snapshot")}${query({
|
|
3743
|
-
shouldOnlyUseRecentValue: true,
|
|
3744
|
-
shouldAllowStaleOnError: true
|
|
3745
|
-
})}`
|
|
3746
|
-
),
|
|
3747
|
-
this.walletRequest(
|
|
3748
|
-
state,
|
|
3749
|
-
chainId,
|
|
3750
|
-
this.agentPath(context, "yield-positions")
|
|
3751
|
-
),
|
|
3752
|
-
options.historic ? this.walletRequest(
|
|
3753
|
-
state,
|
|
3754
|
-
chainId,
|
|
3755
|
-
this.agentPath(context, "wallet/historic-position")
|
|
3756
|
-
) : Promise.resolve(void 0),
|
|
3757
|
-
options.actions ? this.walletRequest(
|
|
3758
|
-
state,
|
|
3759
|
-
chainId,
|
|
3760
|
-
this.agentPath(context, "actions")
|
|
3761
|
-
) : Promise.resolve(void 0)
|
|
3762
|
-
]);
|
|
3763
|
-
if (!snapshot?.agentSnapshot) {
|
|
3764
|
-
throw this.invalidResponse("agent snapshot");
|
|
3765
|
-
}
|
|
3766
|
-
if (!Array.isArray(positions?.yieldPositions)) {
|
|
3767
|
-
throw this.invalidResponse("yield positions");
|
|
3768
|
-
}
|
|
3769
|
-
return {
|
|
3770
|
-
...context,
|
|
3771
|
-
snapshot: snapshot.agentSnapshot,
|
|
3772
|
-
positions: positions.yieldPositions,
|
|
3773
|
-
...historic?.position ? { historic: historic.position } : {},
|
|
3774
|
-
...actions?.actions ? { actions: actions.actions } : {}
|
|
3775
|
-
};
|
|
3776
|
-
}
|
|
3777
|
-
async deployAgent(state, chainId, context) {
|
|
3778
|
-
if (context.wallet.initializedDate != null) return;
|
|
3779
|
-
const walletAddress = context.wallet.walletAddress.toLowerCase();
|
|
3780
|
-
const deployed = await this.walletRequest(
|
|
3781
|
-
state,
|
|
3782
|
-
chainId,
|
|
3783
|
-
this.agentPath(context, "deploy"),
|
|
3784
|
-
{ method: "POST", body: {} }
|
|
3785
|
-
);
|
|
3786
|
-
if (!deployed?.agentWallet || !(0, import_viem6.isAddress)(deployed.agentWallet.walletAddress) || deployed.agentWallet.walletAddress.toLowerCase() !== walletAddress) {
|
|
3787
|
-
throw this.invalidResponse("agent deployment", {
|
|
3788
|
-
reason: "Deploy did not return the expected Agent Wallet."
|
|
3789
|
-
});
|
|
3790
|
-
}
|
|
3791
|
-
context.wallet = deployed.agentWallet;
|
|
3792
|
-
}
|
|
3793
|
-
async refreshSnapshotAfterMovement(state, chainId, context, movement) {
|
|
3794
|
-
try {
|
|
3795
|
-
const response = await this.walletRequest(
|
|
3796
|
-
state,
|
|
3797
|
-
chainId,
|
|
3798
|
-
`${this.agentPath(context, "snapshot")}${query({
|
|
3799
|
-
shouldForceRefresh: true
|
|
3800
|
-
})}`
|
|
3801
|
-
);
|
|
3802
|
-
if (!response?.agentSnapshot) {
|
|
3803
|
-
throw this.invalidResponse("agent snapshot refresh");
|
|
3804
|
-
}
|
|
3805
|
-
} catch (error) {
|
|
3806
|
-
console.warn(
|
|
3807
|
-
`[owney-sdk] Yieldseeker ${movement} snapshot refresh failed:`,
|
|
3808
|
-
error
|
|
3809
|
-
);
|
|
3810
|
-
}
|
|
3811
|
-
}
|
|
3812
|
-
agentPath(context, suffix) {
|
|
3813
|
-
return `/users/${context.user.userId}/agents/${context.agent.agentId}/${suffix}`;
|
|
3814
|
-
}
|
|
3815
|
-
async walletRequest(state, chainId, path, options = {}) {
|
|
3816
|
-
try {
|
|
3817
|
-
return await this.providerRequest(state, chainId, path, options);
|
|
3818
|
-
} catch (error) {
|
|
3819
|
-
throw this.mapApiError(error);
|
|
3820
|
-
}
|
|
3821
|
-
}
|
|
3822
|
-
async providerRequest(state, chainId, path, options = {}) {
|
|
3823
|
-
this.assertChain(chainId);
|
|
3824
|
-
const request = (signature2) => this.api.request(path, {
|
|
3825
|
-
...options,
|
|
3826
|
-
signature: signature2
|
|
3827
|
-
});
|
|
3828
|
-
let signature = await this.auth.getToken(state, chainId);
|
|
3829
|
-
try {
|
|
3830
|
-
return await request(signature);
|
|
3831
|
-
} catch (error) {
|
|
3832
|
-
if (!(error instanceof YieldseekerApiError)) throw error;
|
|
3833
|
-
if (error.providerCode === "NO_USER") throw error;
|
|
3834
|
-
if (!error.isAuthenticationError) throw error;
|
|
3835
|
-
signature = await this.auth.refreshToken(state, chainId, signature);
|
|
3836
|
-
try {
|
|
3837
|
-
return await request(signature);
|
|
3838
|
-
} catch (retryError) {
|
|
3839
|
-
if (retryError instanceof YieldseekerApiError && retryError.isAuthenticationError) {
|
|
3840
|
-
this.forgetUser(state, chainId);
|
|
3841
|
-
}
|
|
3842
|
-
throw retryError;
|
|
3843
|
-
}
|
|
3844
|
-
}
|
|
3845
|
-
}
|
|
3846
|
-
mapApiError(error) {
|
|
3847
|
-
if (!(error instanceof YieldseekerApiError)) {
|
|
3848
|
-
return new OwneyError(
|
|
3849
|
-
"AGENT_API_ERROR",
|
|
3850
|
-
"Yieldseeker request failed.",
|
|
3851
|
-
{ cause: error instanceof Error ? error.message : String(error) },
|
|
3852
|
-
this.id
|
|
3853
|
-
);
|
|
3854
|
-
}
|
|
3855
|
-
const code = error.isAuthenticationError ? "AGENT_AUTH_FAILED" : error.providerCode === "REQUEST_TIMEOUT" ? "AGENT_TIMEOUT" : "AGENT_API_ERROR";
|
|
3856
|
-
return new OwneyError(
|
|
3857
|
-
code,
|
|
3858
|
-
`Yieldseeker request failed: ${error.providerCode}.`,
|
|
3859
|
-
{
|
|
3860
|
-
statusCode: error.status,
|
|
3861
|
-
providerCode: error.providerCode,
|
|
3862
|
-
...error.responseFields ? { fields: error.responseFields } : {}
|
|
3863
|
-
},
|
|
3864
|
-
this.id
|
|
3865
|
-
);
|
|
3866
|
-
}
|
|
3867
|
-
async submitTransaction(state, chainId, transaction) {
|
|
3868
|
-
if (this.transactionExecutor) {
|
|
3869
|
-
return this.transactionExecutor(state, chainId, transaction);
|
|
3870
|
-
}
|
|
3871
|
-
this.assertTransaction(transaction, state, chainId);
|
|
3872
|
-
const account = (0, import_viem6.getAddress)(state.walletAddress);
|
|
3873
|
-
const walletClient = (0, import_viem6.createWalletClient)({
|
|
3874
|
-
account,
|
|
3875
|
-
chain: import_chains3.base,
|
|
3876
|
-
transport: (0, import_viem6.custom)(state.provider)
|
|
3877
|
-
});
|
|
3878
|
-
const publicClient = (0, import_viem6.createPublicClient)({
|
|
3879
|
-
chain: import_chains3.base,
|
|
3880
|
-
transport: (0, import_viem6.custom)(state.provider)
|
|
3881
|
-
});
|
|
3882
|
-
await ensureWalletOnChain(
|
|
3883
|
-
publicClient,
|
|
3884
|
-
walletClient,
|
|
3885
|
-
8453
|
|
3886
|
-
);
|
|
3887
|
-
const hash = await walletClient.sendTransaction({
|
|
3888
|
-
account,
|
|
3889
|
-
chain: import_chains3.base,
|
|
3890
|
-
to: (0, import_viem6.getAddress)(transaction.to),
|
|
3891
|
-
data: transaction.data,
|
|
3892
|
-
value: BigInt(transaction.value)
|
|
3893
|
-
});
|
|
3894
|
-
const receipt = await publicClient.waitForTransactionReceipt({
|
|
3895
|
-
hash,
|
|
3896
|
-
confirmations: 1
|
|
3897
|
-
});
|
|
3898
|
-
if (receipt.status !== "success") {
|
|
3899
|
-
throw new OwneyError(
|
|
3900
|
-
"AGENT_TRANSACTION_REVERTED",
|
|
3901
|
-
`Yieldseeker transaction reverted (${hash}).`,
|
|
3902
|
-
{ transactionHash: hash },
|
|
3903
|
-
this.id
|
|
3904
|
-
);
|
|
3905
|
-
}
|
|
3906
|
-
return hash;
|
|
3907
|
-
}
|
|
3908
|
-
async waitForReceipt(state, chainId, transactionHash) {
|
|
3909
|
-
if (this.unwindReceiptWaiter) {
|
|
3910
|
-
await this.unwindReceiptWaiter(state, chainId, transactionHash);
|
|
3911
|
-
return;
|
|
3912
|
-
}
|
|
3913
|
-
const publicClient = (0, import_viem6.createPublicClient)({
|
|
3914
|
-
chain: import_chains3.base,
|
|
3915
|
-
transport: (0, import_viem6.custom)(state.provider)
|
|
3916
|
-
});
|
|
3917
|
-
const receipt = await publicClient.waitForTransactionReceipt({
|
|
3918
|
-
hash: transactionHash,
|
|
3919
|
-
confirmations: 1
|
|
3920
|
-
});
|
|
3921
|
-
if (receipt.status !== "success") {
|
|
3922
|
-
throw new OwneyError(
|
|
3923
|
-
"AGENT_TRANSACTION_REVERTED",
|
|
3924
|
-
`Yieldseeker transaction reverted (${transactionHash}).`,
|
|
3925
|
-
{ transactionHash },
|
|
3926
|
-
this.id
|
|
3927
|
-
);
|
|
3928
|
-
}
|
|
3929
|
-
}
|
|
3930
|
-
assertTransaction(transaction, state, chainId) {
|
|
3931
|
-
if (!transaction || typeof transaction.from !== "string" || !(0, import_viem6.isAddress)(transaction.from) || typeof transaction.to !== "string" || !(0, import_viem6.isAddress)(transaction.to) || typeof transaction.data !== "string" || !/^0x[a-fA-F0-9]*$/.test(transaction.data) || typeof transaction.value !== "string" || !/^[0-9]+$/.test(transaction.value) || transaction.chainId !== chainId || (0, import_viem6.getAddress)(transaction.from) !== (0, import_viem6.getAddress)(state.walletAddress)) {
|
|
3932
|
-
throw this.invalidResponse("transaction");
|
|
3933
|
-
}
|
|
3934
|
-
}
|
|
3935
|
-
assertAgent(agent) {
|
|
3936
|
-
if (typeof agent.agentId !== "string" || typeof agent.assetAddress !== "string" || !(0, import_viem6.isAddress)(agent.assetAddress) || agent.chainId !== 8453) {
|
|
3937
|
-
throw this.invalidResponse("agent");
|
|
3938
|
-
}
|
|
3939
|
-
}
|
|
3940
|
-
isOwneyAgent(agent) {
|
|
3941
|
-
return typeof agent.name === "string" && agent.name.trim().toLowerCase() === OWNEY_AGENT_NAME;
|
|
3942
|
-
}
|
|
3943
|
-
assetForAgent(agent) {
|
|
3944
|
-
for (const asset of ["USDC", "WETH"]) {
|
|
3945
|
-
if (agent.assetAddress.toLowerCase() === YIELDSEEKER_ASSET_METADATA[asset].address.toLowerCase()) {
|
|
3946
|
-
return asset;
|
|
3947
|
-
}
|
|
3948
|
-
}
|
|
3949
|
-
return null;
|
|
3950
|
-
}
|
|
3951
|
-
isTransactionHash(value) {
|
|
3952
|
-
return typeof value === "string" && /^0x[a-fA-F0-9]{64}$/.test(value);
|
|
3953
|
-
}
|
|
3954
|
-
assertChain(chainId) {
|
|
3955
|
-
if (chainId !== 8453) {
|
|
3956
|
-
throw new OwneyError(
|
|
3957
|
-
"CHAIN_UNSUPPORTED",
|
|
3958
|
-
`Yieldseeker does not support chain ${chainId}.`,
|
|
3959
|
-
{ chainId, supportedChainIds: [8453] },
|
|
3960
|
-
this.id
|
|
3961
|
-
);
|
|
3962
|
-
}
|
|
3963
|
-
}
|
|
3964
|
-
assertOptionalChain(chainId) {
|
|
3965
|
-
if (chainId !== void 0) this.assertChain(chainId);
|
|
3966
|
-
}
|
|
3967
|
-
assertAsset(asset) {
|
|
3968
|
-
if (asset !== "USDC" && asset !== "WETH") {
|
|
3969
|
-
throw new OwneyError(
|
|
3970
|
-
"ASSET_UNSUPPORTED",
|
|
3971
|
-
`Yieldseeker does not support asset ${asset} in the Owney rollout.`,
|
|
3972
|
-
{
|
|
3973
|
-
asset,
|
|
3974
|
-
supportedAssets: ["USDC", "WETH"],
|
|
3975
|
-
providerAlsoAdvertises: ["cbBTC"]
|
|
3976
|
-
},
|
|
3977
|
-
this.id
|
|
2717
|
+
if (current < needed) {
|
|
2718
|
+
onStage?.("approving");
|
|
2719
|
+
await deps.ensureChain(quote.src.chainId);
|
|
2720
|
+
await deps.approve(tx.to, MAX_UINT256);
|
|
2721
|
+
debugLog(
|
|
2722
|
+
"owney-sdk",
|
|
2723
|
+
"swap: re-fetching classic calldata after approval"
|
|
3978
2724
|
);
|
|
2725
|
+
({ tx } = await deps.api.swapTx(swapTxRequest));
|
|
3979
2726
|
}
|
|
3980
2727
|
}
|
|
3981
|
-
|
|
3982
|
-
|
|
3983
|
-
|
|
3984
|
-
|
|
3985
|
-
|
|
3986
|
-
|
|
3987
|
-
|
|
2728
|
+
onStage?.("signing");
|
|
2729
|
+
await deps.ensureChain(quote.src.chainId);
|
|
2730
|
+
debugLog("owney-sdk", "swap: sending classic swap tx", { to: tx.to });
|
|
2731
|
+
const txHash = await deps.sendTransaction({
|
|
2732
|
+
to: tx.to,
|
|
2733
|
+
data: tx.data,
|
|
2734
|
+
value: tx.value ?? "0"
|
|
2735
|
+
});
|
|
2736
|
+
onStage?.("swapped");
|
|
2737
|
+
return { txHash };
|
|
2738
|
+
}
|
|
2739
|
+
async function runFusion(deps, options, walletAddress) {
|
|
2740
|
+
const { quote, direction, onStage } = options;
|
|
2741
|
+
const isNativeSource = quote.src.address.toLowerCase().startsWith("0xeeee");
|
|
2742
|
+
const amount = isNativeSource ? BigInt(quote.src.amount) : await affordableAmount(deps, BigInt(quote.src.amount));
|
|
2743
|
+
if (quote.spender && !isNativeSource) {
|
|
2744
|
+
const needed = amount;
|
|
2745
|
+
const current = await deps.readAllowance(quote.spender);
|
|
2746
|
+
debugLog("owney-sdk", "swap: fusion allowance", {
|
|
2747
|
+
spender: quote.spender,
|
|
2748
|
+
current: current.toString(),
|
|
2749
|
+
needed: needed.toString()
|
|
2750
|
+
});
|
|
2751
|
+
if (current < needed) {
|
|
2752
|
+
onStage?.("approving");
|
|
2753
|
+
await deps.ensureChain(quote.src.chainId);
|
|
2754
|
+
await deps.approve(quote.spender, MAX_UINT256);
|
|
2755
|
+
debugLog("owney-sdk", "swap: approved limit order protocol");
|
|
2756
|
+
}
|
|
3988
2757
|
}
|
|
3989
|
-
};
|
|
3990
|
-
|
|
3991
|
-
|
|
3992
|
-
|
|
3993
|
-
|
|
3994
|
-
const
|
|
2758
|
+
const { secrets, secretHashes } = mintSecrets(quote.secretsCount ?? 1);
|
|
2759
|
+
onStage?.("quoting");
|
|
2760
|
+
debugLog("owney-sdk", "swap: building fusion order", {
|
|
2761
|
+
secrets: secretHashes.length
|
|
2762
|
+
});
|
|
2763
|
+
const built = await deps.api.buildOrder({
|
|
2764
|
+
from: {
|
|
2765
|
+
chainId: quote.src.chainId,
|
|
2766
|
+
symbol: quote.src.symbol,
|
|
2767
|
+
// The trimmed amount — the order is re-quoted at this size server-side.
|
|
2768
|
+
amount: amount.toString()
|
|
2769
|
+
},
|
|
2770
|
+
to: { chainId: quote.dst.chainId, symbol: quote.dst.symbol },
|
|
2771
|
+
walletAddress,
|
|
2772
|
+
secretHashes,
|
|
2773
|
+
...direction ? { direction } : {}
|
|
2774
|
+
});
|
|
2775
|
+
saveOrder({
|
|
2776
|
+
orderHash: built.orderHash,
|
|
2777
|
+
secrets,
|
|
2778
|
+
srcChainId: quote.src.chainId,
|
|
2779
|
+
srcSymbol: quote.src.symbol,
|
|
2780
|
+
dstChainId: quote.dst.chainId,
|
|
2781
|
+
dstSymbol: quote.dst.symbol,
|
|
2782
|
+
amount: amount.toString(),
|
|
2783
|
+
createdAt: Date.now()
|
|
2784
|
+
});
|
|
2785
|
+
debugLog("owney-sdk", "swap: order built", { orderHash: built.orderHash });
|
|
2786
|
+
onStage?.("signing");
|
|
2787
|
+
await deps.ensureChain(quote.src.chainId);
|
|
2788
|
+
debugLog("owney-sdk", "swap: awaiting signature in wallet", {
|
|
2789
|
+
signingOnChain: quote.src.chainId
|
|
2790
|
+
});
|
|
2791
|
+
const signature = await deps.signTypedData(built.typedData);
|
|
2792
|
+
debugLog("owney-sdk", "swap: signed, submitting to relayer");
|
|
2793
|
+
await deps.api.submitOrder({
|
|
2794
|
+
srcChainId: quote.src.chainId,
|
|
2795
|
+
// The ORDER STRUCT, not the typed-data envelope we just signed. Sending
|
|
2796
|
+
// the envelope here gets a bare 500 from the relayer.
|
|
2797
|
+
order: built.order,
|
|
2798
|
+
signature,
|
|
2799
|
+
quoteId: built.quoteId,
|
|
2800
|
+
// Single-fill orders must NOT carry secretHashes — the relayer rejects
|
|
2801
|
+
// them with SECRET_HASHES_NOT_REQUIRED. The one hash is already inside the
|
|
2802
|
+
// order's hashlock, so repeating it here is redundant, and only a
|
|
2803
|
+
// multi-fill order (a Merkle tree of hashes) needs them listed.
|
|
2804
|
+
...secretHashes.length > 1 ? { secretHashes } : {},
|
|
2805
|
+
...built.extension ? { extension: built.extension } : {}
|
|
2806
|
+
});
|
|
2807
|
+
debugLog("owney-sdk", "swap: order submitted, polling escrows");
|
|
3995
2808
|
try {
|
|
3996
|
-
|
|
3997
|
-
|
|
3998
|
-
|
|
3999
|
-
|
|
4000
|
-
"x-owney-api-key": `${apiKey}`
|
|
4001
|
-
}
|
|
2809
|
+
await runFusionOrder(deps.runner, {
|
|
2810
|
+
orderHash: built.orderHash,
|
|
2811
|
+
secrets,
|
|
2812
|
+
...onStage ? { onStage } : {}
|
|
4002
2813
|
});
|
|
4003
|
-
if (!res.ok) {
|
|
4004
|
-
if (res.status !== 404) {
|
|
4005
|
-
console.warn(
|
|
4006
|
-
`[owney-sdk] Could not read org agent config (${res.status}); leaving user profiles unchanged.`
|
|
4007
|
-
);
|
|
4008
|
-
}
|
|
4009
|
-
return null;
|
|
4010
|
-
}
|
|
4011
|
-
const json = await res.json();
|
|
4012
|
-
const policy = json.success ? json.data ?? null : null;
|
|
4013
|
-
debugLog(
|
|
4014
|
-
"owney-sdk",
|
|
4015
|
-
policy ? "org agent config: loaded" : "org agent config: none set by this partner \u2014 user profiles will be left as they are",
|
|
4016
|
-
policy ?? void 0
|
|
4017
|
-
);
|
|
4018
|
-
return policy;
|
|
4019
2814
|
} catch (error) {
|
|
4020
|
-
|
|
4021
|
-
|
|
4022
|
-
|
|
4023
|
-
|
|
4024
|
-
return null;
|
|
2815
|
+
if (error instanceof OwneyError && (error.code === "SWAP_ORDER_REFUNDED" || error.code === "SWAP_ORDER_CANCELLED")) {
|
|
2816
|
+
clearOrder(built.orderHash);
|
|
2817
|
+
}
|
|
2818
|
+
throw error;
|
|
4025
2819
|
}
|
|
2820
|
+
clearOrder(built.orderHash);
|
|
2821
|
+
return { orderHash: built.orderHash };
|
|
4026
2822
|
}
|
|
4027
|
-
|
|
4028
|
-
|
|
4029
|
-
|
|
4030
|
-
|
|
4031
|
-
|
|
4032
|
-
|
|
4033
|
-
|
|
4034
|
-
|
|
2823
|
+
|
|
2824
|
+
// src/lib/swap/swap.arrival.ts
|
|
2825
|
+
var DEFAULT_TIMEOUT_MS2 = 18e4;
|
|
2826
|
+
var DEFAULT_POLL_MS2 = 4e3;
|
|
2827
|
+
var sleep = (ms) => new Promise((r) => setTimeout(r, ms));
|
|
2828
|
+
async function awaitWithdrawalArrival(options) {
|
|
2829
|
+
const {
|
|
2830
|
+
readBalance,
|
|
2831
|
+
baseline,
|
|
2832
|
+
timeoutMs = DEFAULT_TIMEOUT_MS2,
|
|
2833
|
+
pollMs = DEFAULT_POLL_MS2
|
|
2834
|
+
} = options;
|
|
2835
|
+
const deadline = Date.now() + timeoutMs;
|
|
2836
|
+
debugLog("owney-sdk", "withdraw: waiting for funds to land", {
|
|
2837
|
+
baseline: baseline.toString(),
|
|
2838
|
+
timeoutMs
|
|
4035
2839
|
});
|
|
4036
|
-
|
|
4037
|
-
|
|
4038
|
-
|
|
4039
|
-
|
|
4040
|
-
|
|
4041
|
-
|
|
4042
|
-
|
|
4043
|
-
|
|
4044
|
-
|
|
4045
|
-
|
|
4046
|
-
|
|
4047
|
-
|
|
4048
|
-
|
|
4049
|
-
|
|
4050
|
-
|
|
2840
|
+
let lastError;
|
|
2841
|
+
for (; ; ) {
|
|
2842
|
+
try {
|
|
2843
|
+
const balance = await readBalance();
|
|
2844
|
+
if (balance > baseline) {
|
|
2845
|
+
const arrived = balance - baseline;
|
|
2846
|
+
debugLog("owney-sdk", "withdraw: funds landed", {
|
|
2847
|
+
arrived: arrived.toString()
|
|
2848
|
+
});
|
|
2849
|
+
return arrived;
|
|
2850
|
+
}
|
|
2851
|
+
} catch (error) {
|
|
2852
|
+
lastError = error;
|
|
2853
|
+
debugLog("owney-sdk", "withdraw: balance read failed, retrying", {
|
|
2854
|
+
message: error instanceof Error ? error.message : String(error)
|
|
2855
|
+
});
|
|
2856
|
+
}
|
|
2857
|
+
if (Date.now() >= deadline) {
|
|
2858
|
+
throw new OwneyError(
|
|
2859
|
+
"WITHDRAW_ARRIVAL_TIMEOUT",
|
|
2860
|
+
"The withdrawal was accepted but the funds had not arrived in time to swap them. They are on their way to your wallet in the original asset.",
|
|
2861
|
+
{
|
|
2862
|
+
baseline: baseline.toString(),
|
|
2863
|
+
waitedMs: timeoutMs,
|
|
2864
|
+
...lastError ? {
|
|
2865
|
+
lastReadError: lastError instanceof Error ? lastError.message : String(lastError)
|
|
2866
|
+
} : {}
|
|
2867
|
+
}
|
|
2868
|
+
);
|
|
2869
|
+
}
|
|
2870
|
+
await sleep(pollMs);
|
|
4051
2871
|
}
|
|
4052
|
-
return json.data;
|
|
4053
2872
|
}
|
|
4054
2873
|
|
|
4055
2874
|
// src/lib/health-report.ts
|
|
4056
|
-
var
|
|
4057
|
-
async function reportAgentFailure(apiKey, agentType, errorCode, baseUrl =
|
|
2875
|
+
var ROUTING_API_BASE_URL2 = "https://owney-routing-api-243946518160.europe-west4.run.app";
|
|
2876
|
+
async function reportAgentFailure(apiKey, agentType, errorCode, baseUrl = ROUTING_API_BASE_URL2) {
|
|
4058
2877
|
try {
|
|
4059
2878
|
await fetch(`${baseUrl}/api/v1/agent/health-report`, {
|
|
4060
2879
|
method: "POST",
|
|
@@ -4086,7 +2905,7 @@ async function withFailureReporting(apiKey, agentType, fn, baseUrl) {
|
|
|
4086
2905
|
}
|
|
4087
2906
|
|
|
4088
2907
|
// src/lib/helpers/withdraw-helper.ts
|
|
4089
|
-
var
|
|
2908
|
+
var import_viem5 = require("viem");
|
|
4090
2909
|
function projectAgentBalancesForAsset(agents, aggregated, chainId, asset, decimals) {
|
|
4091
2910
|
const target = asset.toUpperCase();
|
|
4092
2911
|
return agents.map((agent) => {
|
|
@@ -4094,29 +2913,8 @@ function projectAgentBalancesForAsset(agents, aggregated, chainId, asset, decima
|
|
|
4094
2913
|
const tokenBalance = agentBalance?.tokens.find(
|
|
4095
2914
|
(t) => t.chainId === chainId && t.asset.toUpperCase() === target
|
|
4096
2915
|
);
|
|
4097
|
-
|
|
4098
|
-
|
|
4099
|
-
const chainNameById = {
|
|
4100
|
-
1: "ETHEREUM",
|
|
4101
|
-
8453: "BASE",
|
|
4102
|
-
42161: "ARBITRUM"
|
|
4103
|
-
};
|
|
4104
|
-
const targetChain = chainNameById[chainId];
|
|
4105
|
-
for (const position2 of agentBalance?.positions ?? []) {
|
|
4106
|
-
const positionChain = position2.chain.trim().toUpperCase();
|
|
4107
|
-
const matchesChain = positionChain === String(chainId) || targetChain !== void 0 && positionChain === targetChain;
|
|
4108
|
-
if (!matchesChain || position2.asset.toUpperCase() !== target) continue;
|
|
4109
|
-
if (position2.amountRaw !== void 0) {
|
|
4110
|
-
try {
|
|
4111
|
-
balance += BigInt(position2.amountRaw);
|
|
4112
|
-
continue;
|
|
4113
|
-
} catch {
|
|
4114
|
-
}
|
|
4115
|
-
}
|
|
4116
|
-
balance += (0, import_viem7.parseUnits)(position2.amount, decimals);
|
|
4117
|
-
}
|
|
4118
|
-
}
|
|
4119
|
-
return { agent, balance };
|
|
2916
|
+
if (!tokenBalance) return { agent, balance: 0n };
|
|
2917
|
+
return { agent, balance: (0, import_viem5.parseUnits)(tokenBalance.amount, decimals) };
|
|
4120
2918
|
});
|
|
4121
2919
|
}
|
|
4122
2920
|
function planProportionalShares(balances, requested, totalAvailable) {
|
|
@@ -4142,9 +2940,7 @@ function planProportionalShares(balances, requested, totalAvailable) {
|
|
|
4142
2940
|
return plans;
|
|
4143
2941
|
}
|
|
4144
2942
|
function planDisabledDrain(disabled, requested) {
|
|
4145
|
-
const sorted = [...disabled].filter((d) => d.balance > 0n).sort(
|
|
4146
|
-
(a, b) => b.balance > a.balance ? 1 : b.balance < a.balance ? -1 : 0
|
|
4147
|
-
);
|
|
2943
|
+
const sorted = [...disabled].filter((d) => d.balance > 0n).sort((a, b) => b.balance > a.balance ? 1 : b.balance < a.balance ? -1 : 0);
|
|
4148
2944
|
const plans = [];
|
|
4149
2945
|
let remaining = requested;
|
|
4150
2946
|
for (const { agent, balance } of sorted) {
|
|
@@ -4195,13 +2991,6 @@ function balanceForApyScope(balance, chainId, tokenSymbol) {
|
|
|
4195
2991
|
return Number.isFinite(total) && total > 0 ? total : 0;
|
|
4196
2992
|
}
|
|
4197
2993
|
const normalizedToken = tokenSymbol.toUpperCase();
|
|
4198
|
-
const snapshots = balance.assetBalances?.filter(
|
|
4199
|
-
(token) => Number(token.chainId) === chainId && String(token.asset).toUpperCase() === normalizedToken
|
|
4200
|
-
);
|
|
4201
|
-
if (snapshots?.length) {
|
|
4202
|
-
const amount = snapshots.reduce((sum, token) => sum + Number(token.amount), 0);
|
|
4203
|
-
if (Number.isFinite(amount)) return Math.max(0, amount);
|
|
4204
|
-
}
|
|
4205
2994
|
return balance.tokens.reduce((total, token) => {
|
|
4206
2995
|
if (Number(token.chainId) !== chainId || String(token.asset).toUpperCase() !== normalizedToken) {
|
|
4207
2996
|
return total;
|
|
@@ -4272,305 +3061,325 @@ function aggregateApyByChainAndAsset(agentApys, agentBalances) {
|
|
|
4272
3061
|
}
|
|
4273
3062
|
|
|
4274
3063
|
// src/client.ts
|
|
4275
|
-
var import_viem11 = require("viem");
|
|
4276
|
-
var import_chains4 = require("viem/chains");
|
|
4277
|
-
|
|
4278
|
-
// src/lib/sponsored-token-batch.ts
|
|
4279
|
-
var import_viem9 = require("viem");
|
|
4280
|
-
|
|
4281
|
-
// src/lib/permit2-batch.ts
|
|
4282
3064
|
var import_viem8 = require("viem");
|
|
4283
|
-
var
|
|
4284
|
-
|
|
4285
|
-
|
|
4286
|
-
|
|
4287
|
-
|
|
4288
|
-
|
|
4289
|
-
|
|
4290
|
-
|
|
4291
|
-
|
|
4292
|
-
Deposit: [{ name: "recipients", type: "address[]" }],
|
|
4293
|
-
TokenPermissions: [
|
|
4294
|
-
{ name: "token", type: "address" },
|
|
4295
|
-
{ name: "amount", type: "uint256" }
|
|
4296
|
-
]
|
|
4297
|
-
};
|
|
4298
|
-
var PERMIT2_BATCH_ABI = (0, import_viem8.parseAbi)([
|
|
4299
|
-
"struct TokenPermissions { address token; uint256 amount; }",
|
|
4300
|
-
"struct PermitBatchTransferFrom { TokenPermissions[] permitted; uint256 nonce; uint256 deadline; }",
|
|
4301
|
-
"struct SignatureTransferDetails { address to; uint256 requestedAmount; }",
|
|
4302
|
-
"function permitWitnessTransferFrom(PermitBatchTransferFrom permit,SignatureTransferDetails[] transferDetails,address owner,bytes32 witness,string witnessTypeString,bytes signature)",
|
|
4303
|
-
"function nonceBitmap(address owner,uint256 wordPos) view returns (uint256)"
|
|
4304
|
-
]);
|
|
4305
|
-
function batchPermit(b) {
|
|
4306
|
-
return {
|
|
4307
|
-
permitted: b.transfers.map((t) => ({
|
|
4308
|
-
token: b.token,
|
|
4309
|
-
amount: BigInt(t.amount)
|
|
4310
|
-
})),
|
|
4311
|
-
nonce: BigInt(b.nonce),
|
|
4312
|
-
deadline: BigInt(b.deadline)
|
|
4313
|
-
};
|
|
4314
|
-
}
|
|
4315
|
-
function batchTypedData(b, spender) {
|
|
3065
|
+
var import_chains2 = require("viem/chains");
|
|
3066
|
+
|
|
3067
|
+
// src/lib/transfer-auth.ts
|
|
3068
|
+
var import_viem6 = require("viem");
|
|
3069
|
+
var ERC20_META_ABI = [
|
|
3070
|
+
{ type: "function", name: "name", stateMutability: "view", inputs: [], outputs: [{ name: "", type: "string" }] },
|
|
3071
|
+
{ type: "function", name: "version", stateMutability: "view", inputs: [], outputs: [{ name: "", type: "string" }] }
|
|
3072
|
+
];
|
|
3073
|
+
function buildTransferWithAuthorizationTypedData(input) {
|
|
4316
3074
|
return {
|
|
4317
|
-
domain: {
|
|
4318
|
-
|
|
4319
|
-
|
|
4320
|
-
|
|
3075
|
+
domain: { name: input.tokenName, version: input.tokenVersion, chainId: input.chainId, verifyingContract: input.token },
|
|
3076
|
+
types: {
|
|
3077
|
+
TransferWithAuthorization: [
|
|
3078
|
+
{ name: "from", type: "address" },
|
|
3079
|
+
{ name: "to", type: "address" },
|
|
3080
|
+
{ name: "value", type: "uint256" },
|
|
3081
|
+
{ name: "validAfter", type: "uint256" },
|
|
3082
|
+
{ name: "validBefore", type: "uint256" },
|
|
3083
|
+
{ name: "nonce", type: "bytes32" }
|
|
3084
|
+
]
|
|
4321
3085
|
},
|
|
4322
|
-
|
|
4323
|
-
|
|
4324
|
-
message: {
|
|
4325
|
-
...batchPermit(b),
|
|
4326
|
-
spender,
|
|
4327
|
-
witness: { recipients: b.transfers.map((t) => t.to) }
|
|
4328
|
-
}
|
|
3086
|
+
primaryType: "TransferWithAuthorization",
|
|
3087
|
+
message: input.message
|
|
4329
3088
|
};
|
|
4330
3089
|
}
|
|
4331
|
-
|
|
4332
|
-
|
|
4333
|
-
|
|
4334
|
-
|
|
4335
|
-
|
|
4336
|
-
|
|
4337
|
-
to: t.to.toLowerCase(),
|
|
4338
|
-
amount: BigInt(t.amount).toString()
|
|
4339
|
-
}))
|
|
4340
|
-
);
|
|
4341
|
-
function read(key2) {
|
|
4342
|
-
return typeof window === "undefined" ? memory.get(key2) : window.localStorage.getItem(key2);
|
|
4343
|
-
}
|
|
4344
|
-
function save(key2, body) {
|
|
4345
|
-
const value = JSON.stringify({
|
|
4346
|
-
...body,
|
|
4347
|
-
transfers: body.transfers.map(({ to, amount }) => ({ to, amount }))
|
|
4348
|
-
});
|
|
4349
|
-
if (typeof window === "undefined") memory.set(key2, value);
|
|
4350
|
-
else window.localStorage.setItem(key2, value);
|
|
3090
|
+
async function readTokenMeta(publicClient, token) {
|
|
3091
|
+
const [tokenName, tokenVersion] = await Promise.all([
|
|
3092
|
+
publicClient.readContract({ address: token, abi: ERC20_META_ABI, functionName: "name" }),
|
|
3093
|
+
publicClient.readContract({ address: token, abi: ERC20_META_ABI, functionName: "version" }).catch(() => "2")
|
|
3094
|
+
]);
|
|
3095
|
+
return { tokenName, tokenVersion };
|
|
4351
3096
|
}
|
|
4352
|
-
function
|
|
4353
|
-
|
|
4354
|
-
|
|
3097
|
+
function randomAuthNonce() {
|
|
3098
|
+
const bytes = new Uint8Array(32);
|
|
3099
|
+
globalThis.crypto.getRandomValues(bytes);
|
|
3100
|
+
return (0, import_viem6.bytesToHex)(bytes);
|
|
4355
3101
|
}
|
|
4356
|
-
|
|
4357
|
-
|
|
4358
|
-
|
|
4359
|
-
|
|
4360
|
-
|
|
4361
|
-
|
|
4362
|
-
|
|
4363
|
-
|
|
4364
|
-
|
|
4365
|
-
|
|
4366
|
-
|
|
4367
|
-
|
|
3102
|
+
|
|
3103
|
+
// src/lib/sponsor-client.ts
|
|
3104
|
+
var ROUTING_API_BASE_URL3 = "https://owney-routing-api-243946518160.europe-west4.run.app";
|
|
3105
|
+
async function postSponsorTransferAuth(input) {
|
|
3106
|
+
const base3 = input.baseUrl ?? ROUTING_API_BASE_URL3;
|
|
3107
|
+
let res;
|
|
3108
|
+
try {
|
|
3109
|
+
res = await fetch(`${base3}/api/v1/sponsor/erc20-transfer-auth`, {
|
|
3110
|
+
method: "POST",
|
|
3111
|
+
headers: {
|
|
3112
|
+
"content-type": "application/json",
|
|
3113
|
+
"x-owney-api-key": input.apiKey
|
|
3114
|
+
},
|
|
3115
|
+
body: JSON.stringify(input.body)
|
|
3116
|
+
});
|
|
3117
|
+
} catch (networkError) {
|
|
3118
|
+
throw new OwneyError(
|
|
3119
|
+
"SPONSOR_REQUEST_FAILED",
|
|
3120
|
+
`Sponsor API network error: ${networkError instanceof Error ? networkError.message : String(networkError)}`,
|
|
3121
|
+
{ cause: String(networkError) }
|
|
3122
|
+
);
|
|
3123
|
+
}
|
|
3124
|
+
const text = await res.text();
|
|
3125
|
+
let parsed = null;
|
|
3126
|
+
try {
|
|
3127
|
+
parsed = JSON.parse(text);
|
|
3128
|
+
} catch {
|
|
3129
|
+
}
|
|
3130
|
+
if (!res.ok || !parsed?.success || !parsed.data) {
|
|
3131
|
+
throw new OwneyError(
|
|
3132
|
+
"SPONSOR_REQUEST_FAILED",
|
|
3133
|
+
`Sponsor API error ${res.status}: ${parsed?.message ?? text.slice(0, 500)}`,
|
|
3134
|
+
{
|
|
3135
|
+
statusCode: res.status,
|
|
3136
|
+
responseBody: text.slice(0, 500),
|
|
3137
|
+
// 503 SPONSOR_UNAVAILABLE = relayer out of gas; the tx was rejected
|
|
3138
|
+
// before broadcast, so it is safe to fall back to a user-paid deposit.
|
|
3139
|
+
safeToFallback: res.status === 503
|
|
3140
|
+
}
|
|
3141
|
+
);
|
|
4368
3142
|
}
|
|
4369
|
-
|
|
4370
|
-
inflight.set(key2, { plan, promise });
|
|
4371
|
-
return promise;
|
|
3143
|
+
return parsed.data;
|
|
4372
3144
|
}
|
|
4373
|
-
async function
|
|
4374
|
-
|
|
4375
|
-
|
|
4376
|
-
|
|
4377
|
-
|
|
4378
|
-
|
|
4379
|
-
|
|
4380
|
-
|
|
4381
|
-
|
|
4382
|
-
|
|
4383
|
-
|
|
4384
|
-
|
|
4385
|
-
|
|
4386
|
-
|
|
4387
|
-
|
|
4388
|
-
|
|
4389
|
-
|
|
4390
|
-
|
|
4391
|
-
|
|
4392
|
-
|
|
4393
|
-
|
|
4394
|
-
|
|
4395
|
-
|
|
4396
|
-
|
|
3145
|
+
async function postSponsorPermit2Transfer(input) {
|
|
3146
|
+
const base3 = input.baseUrl ?? ROUTING_API_BASE_URL3;
|
|
3147
|
+
let res;
|
|
3148
|
+
try {
|
|
3149
|
+
res = await fetch(`${base3}/api/v1/sponsor/permit2-transfer`, {
|
|
3150
|
+
method: "POST",
|
|
3151
|
+
headers: {
|
|
3152
|
+
"content-type": "application/json",
|
|
3153
|
+
"x-owney-api-key": input.apiKey
|
|
3154
|
+
},
|
|
3155
|
+
body: JSON.stringify(input.body)
|
|
3156
|
+
});
|
|
3157
|
+
} catch (networkError) {
|
|
3158
|
+
throw new OwneyError(
|
|
3159
|
+
"SPONSOR_REQUEST_FAILED",
|
|
3160
|
+
`Sponsor API network error: ${networkError instanceof Error ? networkError.message : String(networkError)}`,
|
|
3161
|
+
{ cause: String(networkError), safeToFallback: false }
|
|
3162
|
+
);
|
|
3163
|
+
}
|
|
3164
|
+
const text = await res.text();
|
|
3165
|
+
let parsed = null;
|
|
3166
|
+
try {
|
|
3167
|
+
parsed = JSON.parse(text);
|
|
3168
|
+
} catch {
|
|
3169
|
+
}
|
|
3170
|
+
if (!res.ok || !parsed?.success || !parsed.data) {
|
|
3171
|
+
throw new OwneyError(
|
|
3172
|
+
"SPONSOR_REQUEST_FAILED",
|
|
3173
|
+
`Sponsor API error ${res.status}: ${parsed?.message ?? text.slice(0, 500)}`,
|
|
3174
|
+
{
|
|
3175
|
+
statusCode: res.status,
|
|
3176
|
+
responseBody: text.slice(0, 500),
|
|
3177
|
+
safeToFallback: res.status >= 400 && res.status < 500 || res.status === 503
|
|
4397
3178
|
}
|
|
4398
|
-
|
|
4399
|
-
apiKey: i.apiKey,
|
|
4400
|
-
baseUrl: i.baseUrl,
|
|
4401
|
-
body
|
|
4402
|
-
});
|
|
4403
|
-
if (result.txHash !== (0, import_viem9.keccak256)(body.serializedTransaction))
|
|
4404
|
-
throw new Error(
|
|
4405
|
-
"Sponsorship receipt does not match the pending transaction."
|
|
4406
|
-
);
|
|
4407
|
-
clear(key2);
|
|
4408
|
-
return result.txHash;
|
|
4409
|
-
} catch (error) {
|
|
4410
|
-
if (!body.serializedTransaction || error instanceof OwneyError && error.details?.notSubmitted === true)
|
|
4411
|
-
clear(key2);
|
|
4412
|
-
throw error;
|
|
4413
|
-
}
|
|
4414
|
-
};
|
|
4415
|
-
const saved = read(key2);
|
|
4416
|
-
if (saved) {
|
|
4417
|
-
const previous = JSON.parse(saved);
|
|
4418
|
-
if (previous.chainId !== i.chainId || !(0, import_viem9.isAddressEqual)(previous.from, i.owner) || !(0, import_viem9.isAddressEqual)(previous.token, i.token) || planOf(previous.transfers) !== plan)
|
|
4419
|
-
throw new Error(
|
|
4420
|
-
"Retry the previous token deposit and agent split first to reconcile its status."
|
|
4421
|
-
);
|
|
4422
|
-
i.onApproved?.();
|
|
4423
|
-
return send({ ...previous, transfers: i.transfers });
|
|
3179
|
+
);
|
|
4424
3180
|
}
|
|
4425
|
-
|
|
4426
|
-
|
|
4427
|
-
|
|
4428
|
-
|
|
4429
|
-
|
|
4430
|
-
|
|
3181
|
+
return parsed.data;
|
|
3182
|
+
}
|
|
3183
|
+
async function getSponsorRelayerAddress(input) {
|
|
3184
|
+
const base3 = input.baseUrl ?? ROUTING_API_BASE_URL3;
|
|
3185
|
+
let res;
|
|
3186
|
+
try {
|
|
3187
|
+
res = await fetch(
|
|
3188
|
+
`${base3}/api/v1/sponsor/relayer-address?chainId=${input.chainId}`,
|
|
3189
|
+
{
|
|
3190
|
+
headers: { "x-owney-api-key": input.apiKey }
|
|
3191
|
+
}
|
|
3192
|
+
);
|
|
3193
|
+
} catch (networkError) {
|
|
4431
3194
|
throw new OwneyError(
|
|
4432
|
-
"
|
|
4433
|
-
|
|
3195
|
+
"SPONSOR_REQUEST_FAILED",
|
|
3196
|
+
`Sponsor API network error: ${networkError instanceof Error ? networkError.message : String(networkError)}`,
|
|
3197
|
+
{ cause: String(networkError), safeToFallback: true }
|
|
4434
3198
|
);
|
|
4435
|
-
|
|
3199
|
+
}
|
|
3200
|
+
const text = await res.text();
|
|
3201
|
+
let parsed = null;
|
|
3202
|
+
try {
|
|
3203
|
+
parsed = JSON.parse(text);
|
|
3204
|
+
} catch {
|
|
3205
|
+
}
|
|
3206
|
+
if (!res.ok || !parsed?.success || !parsed.data?.relayer) {
|
|
4436
3207
|
throw new OwneyError(
|
|
4437
|
-
"
|
|
4438
|
-
|
|
3208
|
+
"SPONSOR_REQUEST_FAILED",
|
|
3209
|
+
`Sponsor API error ${res.status}: ${parsed?.message ?? text.slice(0, 500)}`,
|
|
3210
|
+
{
|
|
3211
|
+
statusCode: res.status,
|
|
3212
|
+
responseBody: text.slice(0, 500),
|
|
3213
|
+
safeToFallback: true
|
|
3214
|
+
}
|
|
4439
3215
|
);
|
|
4440
|
-
|
|
4441
|
-
|
|
4442
|
-
|
|
4443
|
-
|
|
4444
|
-
|
|
4445
|
-
|
|
4446
|
-
|
|
4447
|
-
|
|
4448
|
-
|
|
4449
|
-
|
|
4450
|
-
|
|
4451
|
-
|
|
4452
|
-
|
|
3216
|
+
}
|
|
3217
|
+
return parsed.data.relayer;
|
|
3218
|
+
}
|
|
3219
|
+
|
|
3220
|
+
// src/lib/sponsored-deposit.ts
|
|
3221
|
+
var AUTH_WINDOW_SECONDS = 15 * 60;
|
|
3222
|
+
function makeSponsoredDepositCallback(deps) {
|
|
3223
|
+
const post = deps.httpPost ?? postSponsorTransferAuth;
|
|
3224
|
+
return async (smartWallet, chainId, amount) => {
|
|
3225
|
+
const cid = chainId;
|
|
3226
|
+
const token = deps.tokenAddressByChain[cid];
|
|
3227
|
+
if (!token) {
|
|
3228
|
+
throw new OwneyError(
|
|
3229
|
+
"CHAIN_UNSUPPORTED",
|
|
3230
|
+
`No sponsored token configured for chain ${chainId}`
|
|
3231
|
+
);
|
|
3232
|
+
}
|
|
3233
|
+
const pub = deps.getPublicClient(cid);
|
|
3234
|
+
const wallet = deps.getWalletClient(cid);
|
|
3235
|
+
await ensureWalletOnChain(pub, wallet, cid);
|
|
3236
|
+
try {
|
|
3237
|
+
const balance = await readErc20Balance(pub, token, deps.ownerAddress);
|
|
3238
|
+
if (balance < BigInt(amount)) {
|
|
3239
|
+
throw new OwneyError(
|
|
3240
|
+
"DEPOSIT_INSUFFICIENT_BALANCE",
|
|
3241
|
+
"Insufficient balance for this deposit.",
|
|
3242
|
+
{ token, chainId: cid, balance: balance.toString(), amount }
|
|
3243
|
+
);
|
|
3244
|
+
}
|
|
3245
|
+
} catch (err) {
|
|
3246
|
+
if (err instanceof OwneyError) throw err;
|
|
3247
|
+
console.warn(
|
|
3248
|
+
"[owney-sdk] Deposit balance pre-check failed (non-fatal):",
|
|
3249
|
+
err instanceof Error ? err.message : String(err)
|
|
3250
|
+
);
|
|
3251
|
+
}
|
|
3252
|
+
const { tokenName, tokenVersion } = await readTokenMeta(pub, token);
|
|
3253
|
+
const validAfter = 0n;
|
|
3254
|
+
const validBefore = BigInt(
|
|
3255
|
+
Math.floor(Date.now() / 1e3) + AUTH_WINDOW_SECONDS
|
|
3256
|
+
);
|
|
3257
|
+
const nonce = randomAuthNonce();
|
|
3258
|
+
const typedData = buildTransferWithAuthorizationTypedData({
|
|
3259
|
+
token,
|
|
3260
|
+
chainId: cid,
|
|
3261
|
+
tokenName,
|
|
3262
|
+
tokenVersion,
|
|
3263
|
+
message: {
|
|
3264
|
+
from: deps.ownerAddress,
|
|
3265
|
+
to: smartWallet,
|
|
3266
|
+
value: BigInt(amount),
|
|
3267
|
+
validAfter,
|
|
3268
|
+
validBefore,
|
|
3269
|
+
nonce
|
|
3270
|
+
}
|
|
3271
|
+
});
|
|
3272
|
+
const authSignature = await wallet.signTypedData({
|
|
3273
|
+
account: deps.ownerAddress,
|
|
3274
|
+
...typedData
|
|
3275
|
+
});
|
|
3276
|
+
deps.onApproved?.();
|
|
3277
|
+
const result = await post({
|
|
3278
|
+
baseUrl: deps.baseUrl,
|
|
3279
|
+
apiKey: deps.apiKey,
|
|
3280
|
+
body: {
|
|
3281
|
+
chainId: cid,
|
|
3282
|
+
token,
|
|
3283
|
+
from: deps.ownerAddress,
|
|
3284
|
+
to: smartWallet,
|
|
3285
|
+
value: amount,
|
|
3286
|
+
validAfter: validAfter.toString(),
|
|
3287
|
+
validBefore: validBefore.toString(),
|
|
3288
|
+
nonce,
|
|
3289
|
+
authSignature,
|
|
3290
|
+
tokenName,
|
|
3291
|
+
tokenVersion
|
|
3292
|
+
}
|
|
3293
|
+
});
|
|
3294
|
+
return result.txHash;
|
|
4453
3295
|
};
|
|
4454
|
-
const signature = await i.wallet.signTypedData({
|
|
4455
|
-
account: i.owner,
|
|
4456
|
-
...batchTypedData(unsigned, relayer)
|
|
4457
|
-
});
|
|
4458
|
-
i.onApproved?.();
|
|
4459
|
-
return send({ ...unsigned, signature });
|
|
4460
3296
|
}
|
|
4461
3297
|
|
|
4462
|
-
// src/lib/sponsored-
|
|
4463
|
-
|
|
4464
|
-
|
|
4465
|
-
|
|
3298
|
+
// src/lib/sponsored-weth-deposit.ts
|
|
3299
|
+
var PERMIT_WINDOW_SECONDS = 15 * 60;
|
|
3300
|
+
function makeSponsoredWethCallback(deps) {
|
|
3301
|
+
const get = deps.httpGet ?? getSponsorRelayerAddress;
|
|
3302
|
+
const post = deps.httpPost ?? postSponsorPermit2Transfer;
|
|
3303
|
+
return async (smartWallet, chainId, amount) => {
|
|
3304
|
+
const cid = chainId;
|
|
3305
|
+
const token = deps.tokenAddressByChain[cid];
|
|
3306
|
+
if (!token) {
|
|
4466
3307
|
throw new OwneyError(
|
|
4467
3308
|
"CHAIN_UNSUPPORTED",
|
|
4468
|
-
`No sponsored
|
|
3309
|
+
`No sponsored WETH configured for chain ${chainId}`
|
|
3310
|
+
);
|
|
3311
|
+
}
|
|
3312
|
+
const amountWei = BigInt(amount);
|
|
3313
|
+
const pub = deps.getPublicClient(cid);
|
|
3314
|
+
const wallet = deps.getWalletClient(cid);
|
|
3315
|
+
await ensureWalletOnChain(pub, wallet, cid);
|
|
3316
|
+
try {
|
|
3317
|
+
const balance = await readErc20Balance(pub, token, deps.ownerAddress);
|
|
3318
|
+
if (balance < amountWei) {
|
|
3319
|
+
throw new OwneyError(
|
|
3320
|
+
"DEPOSIT_INSUFFICIENT_BALANCE",
|
|
3321
|
+
"Insufficient WETH balance for this deposit.",
|
|
3322
|
+
{ token, chainId: cid, balance: balance.toString(), amount }
|
|
3323
|
+
);
|
|
3324
|
+
}
|
|
3325
|
+
} catch (err) {
|
|
3326
|
+
if (err instanceof OwneyError) throw err;
|
|
3327
|
+
console.warn(
|
|
3328
|
+
"[owney-sdk] WETH balance pre-check failed (non-fatal):",
|
|
3329
|
+
err instanceof Error ? err.message : String(err)
|
|
4469
3330
|
);
|
|
4470
|
-
|
|
4471
|
-
|
|
3331
|
+
}
|
|
3332
|
+
const allowance = await readPermit2Allowance(pub, token, deps.ownerAddress);
|
|
3333
|
+
if (allowance < amountWei) {
|
|
4472
3334
|
throw new OwneyError(
|
|
4473
|
-
"
|
|
4474
|
-
|
|
3335
|
+
"PERMIT2_APPROVAL_REQUIRED",
|
|
3336
|
+
"WETH gasless deposits need a one-time Permit2 approval; call approvePermit2() first",
|
|
3337
|
+
{ token, chainId: cid, allowance: allowance.toString(), amount }
|
|
4475
3338
|
);
|
|
4476
|
-
|
|
4477
|
-
await
|
|
4478
|
-
|
|
3339
|
+
}
|
|
3340
|
+
const relayer = await get({
|
|
3341
|
+
baseUrl: deps.baseUrl,
|
|
4479
3342
|
apiKey: deps.apiKey,
|
|
3343
|
+
chainId: cid
|
|
3344
|
+
});
|
|
3345
|
+
const nonce = randomPermit2Nonce();
|
|
3346
|
+
const deadline = BigInt(
|
|
3347
|
+
Math.floor(Date.now() / 1e3) + PERMIT_WINDOW_SECONDS
|
|
3348
|
+
);
|
|
3349
|
+
const typedData = buildPermitTransferFromTypedData({
|
|
3350
|
+
chainId: cid,
|
|
3351
|
+
message: {
|
|
3352
|
+
permitted: { token, amount: amountWei },
|
|
3353
|
+
spender: relayer,
|
|
3354
|
+
nonce,
|
|
3355
|
+
deadline
|
|
3356
|
+
}
|
|
3357
|
+
});
|
|
3358
|
+
const signature = await wallet.signTypedData({
|
|
3359
|
+
account: deps.ownerAddress,
|
|
3360
|
+
...typedData
|
|
3361
|
+
});
|
|
3362
|
+
deps.onApproved?.();
|
|
3363
|
+
const result = await post({
|
|
4480
3364
|
baseUrl: deps.baseUrl,
|
|
4481
|
-
|
|
4482
|
-
|
|
4483
|
-
|
|
4484
|
-
|
|
4485
|
-
|
|
4486
|
-
|
|
4487
|
-
|
|
3365
|
+
apiKey: deps.apiKey,
|
|
3366
|
+
body: {
|
|
3367
|
+
chainId: cid,
|
|
3368
|
+
token,
|
|
3369
|
+
from: deps.ownerAddress,
|
|
3370
|
+
to: smartWallet,
|
|
3371
|
+
amount,
|
|
3372
|
+
nonce: nonce.toString(),
|
|
3373
|
+
deadline: deadline.toString(),
|
|
3374
|
+
signature
|
|
3375
|
+
}
|
|
4488
3376
|
});
|
|
3377
|
+
return result.txHash;
|
|
4489
3378
|
};
|
|
4490
|
-
const callback = makeVerificationAwareDepositCallback(
|
|
4491
|
-
(to, chainId, amount, verification) => batch(chainId, [toBatchTransfer(to, amount, verification)])
|
|
4492
|
-
);
|
|
4493
|
-
registerDepositBatch(callback, batch);
|
|
4494
|
-
return callback;
|
|
4495
|
-
}
|
|
4496
|
-
|
|
4497
|
-
// src/lib/agent-deposit-batch.ts
|
|
4498
|
-
function deferred() {
|
|
4499
|
-
let resolve, reject;
|
|
4500
|
-
const promise = new Promise((yes, no) => {
|
|
4501
|
-
resolve = yes;
|
|
4502
|
-
reject = no;
|
|
4503
|
-
});
|
|
4504
|
-
void promise.catch(() => {
|
|
4505
|
-
});
|
|
4506
|
-
return { promise, resolve, reject };
|
|
4507
|
-
}
|
|
4508
|
-
async function runAgentDepositBatch(chainId, legs, transfer) {
|
|
4509
|
-
const funding = deferred();
|
|
4510
|
-
const tasks = [];
|
|
4511
|
-
const transfers = [];
|
|
4512
|
-
try {
|
|
4513
|
-
for (const leg of legs) {
|
|
4514
|
-
const ready = deferred();
|
|
4515
|
-
let entered = false;
|
|
4516
|
-
const callback = makeVerificationAwareDepositCallback(
|
|
4517
|
-
(to, cid, amount, verification) => {
|
|
4518
|
-
if (entered || cid !== chainId || BigInt(amount) !== BigInt(leg.amount)) {
|
|
4519
|
-
const error = new Error(
|
|
4520
|
-
"Agent changed its prepared deposit share."
|
|
4521
|
-
);
|
|
4522
|
-
ready.reject(error);
|
|
4523
|
-
throw error;
|
|
4524
|
-
}
|
|
4525
|
-
entered = true;
|
|
4526
|
-
ready.resolve(toBatchTransfer(to, amount, verification));
|
|
4527
|
-
return funding.promise;
|
|
4528
|
-
}
|
|
4529
|
-
);
|
|
4530
|
-
const task = Promise.resolve().then(() => leg.run(callback));
|
|
4531
|
-
tasks.push(task);
|
|
4532
|
-
void task.then(
|
|
4533
|
-
() => {
|
|
4534
|
-
if (!entered)
|
|
4535
|
-
ready.reject(
|
|
4536
|
-
new Error("Agent did not prepare a deposit transfer.")
|
|
4537
|
-
);
|
|
4538
|
-
},
|
|
4539
|
-
(error) => ready.reject(error)
|
|
4540
|
-
);
|
|
4541
|
-
transfers.push(await ready.promise);
|
|
4542
|
-
}
|
|
4543
|
-
const txHash = await transfer(chainId, transfers);
|
|
4544
|
-
funding.resolve(txHash);
|
|
4545
|
-
const settled = await Promise.allSettled(tasks);
|
|
4546
|
-
const agentResults = {};
|
|
4547
|
-
const failures = [];
|
|
4548
|
-
for (const [index, result] of settled.entries()) {
|
|
4549
|
-
if (result.status === "fulfilled")
|
|
4550
|
-
agentResults[legs[index].id] = result.value;
|
|
4551
|
-
else failures.push(legs[index].id);
|
|
4552
|
-
}
|
|
4553
|
-
if (failures.length)
|
|
4554
|
-
throw new OwneyError(
|
|
4555
|
-
"DEPOSIT_PARTIAL_FAILURE",
|
|
4556
|
-
"The deposit was sent to all agents, but some agent updates could not be confirmed. Check activity before depositing again.",
|
|
4557
|
-
{
|
|
4558
|
-
txHash,
|
|
4559
|
-
fundsSubmitted: true,
|
|
4560
|
-
agentResults,
|
|
4561
|
-
failedAgentIds: failures
|
|
4562
|
-
}
|
|
4563
|
-
);
|
|
4564
|
-
return { agentResults };
|
|
4565
|
-
} catch (error) {
|
|
4566
|
-
funding.reject(error);
|
|
4567
|
-
await Promise.allSettled(tasks);
|
|
4568
|
-
throw error;
|
|
4569
|
-
}
|
|
4570
3379
|
}
|
|
4571
3380
|
|
|
4572
3381
|
// src/lib/sponsored-calls-deposit.ts
|
|
4573
|
-
var
|
|
3382
|
+
var import_viem7 = require("viem");
|
|
4574
3383
|
var DEFAULT_POLL_INTERVAL_MS = 1500;
|
|
4575
3384
|
var DEFAULT_MAX_POLLS = 30;
|
|
4576
3385
|
async function paymasterSupported(provider, owner, chainId) {
|
|
@@ -4578,7 +3387,7 @@ async function paymasterSupported(provider, owner, chainId) {
|
|
|
4578
3387
|
method: "wallet_getCapabilities",
|
|
4579
3388
|
params: [owner]
|
|
4580
3389
|
});
|
|
4581
|
-
const forChain = caps?.[(0,
|
|
3390
|
+
const forChain = caps?.[(0, import_viem7.toHex)(chainId)] ?? caps?.[String(chainId)];
|
|
4582
3391
|
return Boolean(forChain?.paymasterService?.supported);
|
|
4583
3392
|
}
|
|
4584
3393
|
function makeSponsoredCallsCallback(deps) {
|
|
@@ -4596,7 +3405,7 @@ function makeSponsoredCallsCallback(deps) {
|
|
|
4596
3405
|
}
|
|
4597
3406
|
return new URL(configured, origin).toString();
|
|
4598
3407
|
};
|
|
4599
|
-
|
|
3408
|
+
return async (smartWallet, chainId, amount) => {
|
|
4600
3409
|
const cid = chainId;
|
|
4601
3410
|
const token = deps.tokenAddressByChain[cid];
|
|
4602
3411
|
if (!token) {
|
|
@@ -4612,53 +3421,22 @@ function makeSponsoredCallsCallback(deps) {
|
|
|
4612
3421
|
{ chainId }
|
|
4613
3422
|
);
|
|
4614
3423
|
}
|
|
4615
|
-
const
|
|
4616
|
-
|
|
4617
|
-
|
|
4618
|
-
|
|
4619
|
-
|
|
4620
|
-
functionName: "transfer",
|
|
4621
|
-
args: [transfer.to, BigInt(transfer.amount)]
|
|
4622
|
-
})
|
|
4623
|
-
}));
|
|
4624
|
-
let paymasterUrl = absolutePaymasterUrl();
|
|
4625
|
-
for (const transfer of transfers) {
|
|
4626
|
-
const verification = transfer.yieldseeker;
|
|
4627
|
-
if (!verification) continue;
|
|
4628
|
-
if (chainId !== 8453)
|
|
4629
|
-
throw new OwneyError(
|
|
4630
|
-
"CHAIN_UNSUPPORTED",
|
|
4631
|
-
`Yieldseeker sponsorship is not available on chain ${chainId}.`
|
|
4632
|
-
);
|
|
4633
|
-
const { intent } = await postPaymasterIntent({
|
|
4634
|
-
baseUrl: deps.routingApiBaseUrl,
|
|
4635
|
-
apiKey: deps.apiKey,
|
|
4636
|
-
yieldseekerSignature: verification.signature,
|
|
4637
|
-
body: {
|
|
4638
|
-
chainId,
|
|
4639
|
-
token,
|
|
4640
|
-
from: deps.ownerAddress,
|
|
4641
|
-
to: transfer.to,
|
|
4642
|
-
amount: transfer.amount,
|
|
4643
|
-
yieldseekerUserId: verification.userId,
|
|
4644
|
-
yieldseekerAgentId: verification.agentId
|
|
4645
|
-
}
|
|
4646
|
-
});
|
|
4647
|
-
const url = new URL(paymasterUrl);
|
|
4648
|
-
url.searchParams.append("owneyIntent", intent);
|
|
4649
|
-
paymasterUrl = url.toString();
|
|
4650
|
-
}
|
|
3424
|
+
const data = (0, import_viem7.encodeFunctionData)({
|
|
3425
|
+
abi: import_viem7.erc20Abi,
|
|
3426
|
+
functionName: "transfer",
|
|
3427
|
+
args: [smartWallet, BigInt(amount)]
|
|
3428
|
+
});
|
|
4651
3429
|
const sendResult = await deps.provider.request({
|
|
4652
3430
|
method: "wallet_sendCalls",
|
|
4653
3431
|
params: [
|
|
4654
3432
|
{
|
|
4655
3433
|
version: "2.0.0",
|
|
4656
3434
|
from: deps.ownerAddress,
|
|
4657
|
-
chainId: (0,
|
|
4658
|
-
atomicRequired:
|
|
4659
|
-
calls,
|
|
3435
|
+
chainId: (0, import_viem7.toHex)(chainId),
|
|
3436
|
+
atomicRequired: false,
|
|
3437
|
+
calls: [{ to: token, value: "0x0", data }],
|
|
4660
3438
|
capabilities: {
|
|
4661
|
-
paymasterService: { url:
|
|
3439
|
+
paymasterService: { url: absolutePaymasterUrl() }
|
|
4662
3440
|
}
|
|
4663
3441
|
}
|
|
4664
3442
|
]
|
|
@@ -4678,24 +3456,7 @@ function makeSponsoredCallsCallback(deps) {
|
|
|
4678
3456
|
params: [callsId]
|
|
4679
3457
|
});
|
|
4680
3458
|
const txHash = status?.receipts?.[0]?.transactionHash;
|
|
4681
|
-
if (
|
|
4682
|
-
throw new OwneyError(
|
|
4683
|
-
"SPONSOR_REQUEST_FAILED",
|
|
4684
|
-
"The sponsored deposit did not complete successfully.",
|
|
4685
|
-
{ chainId, callsId, safeToFallback: false }
|
|
4686
|
-
);
|
|
4687
|
-
}
|
|
4688
|
-
if (txHash && (transfers.length === 1 || status?.status === 200 || status?.status === "CONFIRMED")) {
|
|
4689
|
-
if (status?.receipts?.some(
|
|
4690
|
-
(receipt) => receipt.transactionHash !== txHash
|
|
4691
|
-
))
|
|
4692
|
-
throw new OwneyError(
|
|
4693
|
-
"SPONSORED_CALLS_NO_RECEIPT",
|
|
4694
|
-
"The wallet returned multiple transactions for an atomic deposit. Check activity before trying again.",
|
|
4695
|
-
{ chainId, callsId }
|
|
4696
|
-
);
|
|
4697
|
-
return txHash;
|
|
4698
|
-
}
|
|
3459
|
+
if (txHash) return txHash;
|
|
4699
3460
|
if (pollIntervalMs > 0) {
|
|
4700
3461
|
await new Promise((resolve) => setTimeout(resolve, pollIntervalMs));
|
|
4701
3462
|
}
|
|
@@ -4706,11 +3467,6 @@ function makeSponsoredCallsCallback(deps) {
|
|
|
4706
3467
|
{ chainId, callsId }
|
|
4707
3468
|
);
|
|
4708
3469
|
};
|
|
4709
|
-
const callback = makeVerificationAwareDepositCallback(
|
|
4710
|
-
(to, chainId, amount, verification) => batch(chainId, [toBatchTransfer(to, amount, verification)])
|
|
4711
|
-
);
|
|
4712
|
-
registerDepositBatch(callback, batch);
|
|
4713
|
-
return callback;
|
|
4714
3470
|
}
|
|
4715
3471
|
|
|
4716
3472
|
// src/client.ts
|
|
@@ -4740,20 +3496,15 @@ var SPONSORED_USDC_BY_CHAIN = {
|
|
|
4740
3496
|
1: "0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48"
|
|
4741
3497
|
};
|
|
4742
3498
|
var VIEM_CHAIN2 = {
|
|
4743
|
-
8453:
|
|
4744
|
-
42161:
|
|
4745
|
-
1:
|
|
3499
|
+
8453: import_chains2.base,
|
|
3500
|
+
42161: import_chains2.arbitrum,
|
|
3501
|
+
1: import_chains2.mainnet
|
|
4746
3502
|
};
|
|
4747
3503
|
var SPONSORED_WETH_BY_CHAIN = {
|
|
4748
3504
|
8453: "0x4200000000000000000000000000000000000006",
|
|
4749
3505
|
42161: "0x82aF49447D8a07e3bd95BD0d56f35241523fBab1",
|
|
4750
3506
|
1: "0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2"
|
|
4751
3507
|
};
|
|
4752
|
-
var SPONSORED_TOKENS_BY_ASSET = { USDC: SPONSORED_USDC_BY_CHAIN, WETH: SPONSORED_WETH_BY_CHAIN };
|
|
4753
|
-
function sponsoredTokensFor(asset) {
|
|
4754
|
-
if (!Object.prototype.hasOwnProperty.call(SPONSORED_TOKENS_BY_ASSET, asset)) throw new OwneyError("ASSET_UNSUPPORTED", `No sponsored token configured for ${asset}`);
|
|
4755
|
-
return SPONSORED_TOKENS_BY_ASSET[asset];
|
|
4756
|
-
}
|
|
4757
3508
|
function shouldFallbackToUserPaid(error, asset, appCallback) {
|
|
4758
3509
|
return (asset === "WETH" || asset === "USDC") && appCallback === void 0 && error instanceof OwneyError && error.code === "SPONSOR_REQUEST_FAILED" && error.details?.safeToFallback === true;
|
|
4759
3510
|
}
|
|
@@ -4775,8 +3526,6 @@ var OwneySDK = class {
|
|
|
4775
3526
|
orgAgentConfig;
|
|
4776
3527
|
orgAgentConfigPromise = null;
|
|
4777
3528
|
zyfaiRpcUrls;
|
|
4778
|
-
yieldseekerApiBaseUrl;
|
|
4779
|
-
yieldseekerSiweOrigin;
|
|
4780
3529
|
routingApiBaseUrl;
|
|
4781
3530
|
referralSource;
|
|
4782
3531
|
cachedSponsoredCallback = null;
|
|
@@ -4799,8 +3548,6 @@ var OwneySDK = class {
|
|
|
4799
3548
|
this.apiKey = config.apiKey;
|
|
4800
3549
|
if (config.debug) setOwneyDebug(true);
|
|
4801
3550
|
this.zyfaiRpcUrls = config.zyfaiRpcUrls;
|
|
4802
|
-
this.yieldseekerApiBaseUrl = config.yieldseekerApiBaseUrl;
|
|
4803
|
-
this.yieldseekerSiweOrigin = config.yieldseekerSiweOrigin;
|
|
4804
3551
|
this.routingApiBaseUrl = config.routingApiBaseUrl;
|
|
4805
3552
|
this.paymasterServiceUrl = config.paymasterServiceUrl;
|
|
4806
3553
|
this.referralSource = config.referralSource;
|
|
@@ -4834,7 +3581,6 @@ var OwneySDK = class {
|
|
|
4834
3581
|
* After calling this, `connect()` must be called again before using agent methods.
|
|
4835
3582
|
*/
|
|
4836
3583
|
async disconnect() {
|
|
4837
|
-
this.state = null;
|
|
4838
3584
|
for (const agent of this.agents.values()) {
|
|
4839
3585
|
await agent.disconnect();
|
|
4840
3586
|
}
|
|
@@ -4888,13 +3634,18 @@ var OwneySDK = class {
|
|
|
4888
3634
|
}
|
|
4889
3635
|
return this.state.provider;
|
|
4890
3636
|
}
|
|
4891
|
-
/**
|
|
3637
|
+
/**
|
|
3638
|
+
* Lazily builds (and caches) the default EIP-3009 sponsored deposit callback
|
|
3639
|
+
* used when the caller omits `depositCallback`. Wraps the connected EIP-1193
|
|
3640
|
+
* provider with viem `custom(provider)` to read token meta and sign the
|
|
3641
|
+
* `TransferWithAuthorization`, then POSTs to the sponsor API.
|
|
3642
|
+
*/
|
|
4892
3643
|
getDefaultSponsoredCallback(onApproved) {
|
|
4893
3644
|
if (!onApproved && this.cachedSponsoredCallback)
|
|
4894
3645
|
return this.cachedSponsoredCallback;
|
|
4895
3646
|
const provider = this.requireConnectedProvider();
|
|
4896
3647
|
const owner = this.state.walletAddress;
|
|
4897
|
-
const callback =
|
|
3648
|
+
const callback = makeSponsoredDepositCallback({
|
|
4898
3649
|
apiKey: this.apiKey,
|
|
4899
3650
|
baseUrl: this.routingApiBaseUrl,
|
|
4900
3651
|
ownerAddress: owner,
|
|
@@ -4903,32 +3654,35 @@ var OwneySDK = class {
|
|
|
4903
3654
|
// Casts work around viem's chain-narrowed Client vs the generic
|
|
4904
3655
|
// PublicClient/WalletClient param types — structurally identical at
|
|
4905
3656
|
// runtime, but the two share a name TS treats as unrelated.
|
|
4906
|
-
getPublicClient: (cid) => (0,
|
|
3657
|
+
getPublicClient: (cid) => (0, import_viem8.createPublicClient)({
|
|
4907
3658
|
chain: VIEM_CHAIN2[cid],
|
|
4908
|
-
transport: (0,
|
|
3659
|
+
transport: (0, import_viem8.custom)(provider)
|
|
4909
3660
|
}),
|
|
4910
|
-
getWalletClient: (cid) => (0,
|
|
3661
|
+
getWalletClient: (cid) => (0, import_viem8.createWalletClient)({
|
|
4911
3662
|
account: owner,
|
|
4912
3663
|
chain: VIEM_CHAIN2[cid],
|
|
4913
|
-
transport: (0,
|
|
3664
|
+
transport: (0, import_viem8.custom)(provider)
|
|
4914
3665
|
})
|
|
4915
3666
|
});
|
|
4916
3667
|
if (!onApproved) this.cachedSponsoredCallback = callback;
|
|
4917
3668
|
return callback;
|
|
4918
3669
|
}
|
|
4919
|
-
/**
|
|
3670
|
+
/**
|
|
3671
|
+
* Lazily builds (and caches) the default Permit2 sponsored WETH deposit
|
|
3672
|
+
* callback used when the caller omits `depositCallback` for a WETH
|
|
3673
|
+
* deposit. Mirrors `getDefaultSponsoredCallback()` but signs a Permit2
|
|
3674
|
+
* `PermitTransferFrom` instead of an EIP-3009 authorization.
|
|
3675
|
+
*/
|
|
4920
3676
|
getDefaultSponsoredCallsCallback(asset, onApproved) {
|
|
4921
3677
|
const cached = this.cachedSponsoredCallsCallbacks.get(asset);
|
|
4922
3678
|
if (!onApproved && cached) return cached;
|
|
4923
3679
|
const provider = this.requireConnectedProvider();
|
|
4924
3680
|
const callback = makeSponsoredCallsCallback({
|
|
4925
|
-
apiKey: this.apiKey,
|
|
4926
|
-
routingApiBaseUrl: this.routingApiBaseUrl,
|
|
4927
3681
|
provider,
|
|
4928
3682
|
ownerAddress: this.state.walletAddress,
|
|
4929
3683
|
paymasterServiceUrl: this.paymasterServiceUrl,
|
|
4930
3684
|
onApproved,
|
|
4931
|
-
tokenAddressByChain:
|
|
3685
|
+
tokenAddressByChain: asset === "WETH" ? SPONSORED_WETH_BY_CHAIN : SPONSORED_USDC_BY_CHAIN
|
|
4932
3686
|
});
|
|
4933
3687
|
if (!onApproved) this.cachedSponsoredCallsCallbacks.set(asset, callback);
|
|
4934
3688
|
return callback;
|
|
@@ -4937,14 +3691,14 @@ var OwneySDK = class {
|
|
|
4937
3691
|
* Lazily builds (and caches) the default Permit2 sponsored WETH deposit
|
|
4938
3692
|
* callback used when the caller omits `depositCallback` for a WETH deposit.
|
|
4939
3693
|
* Mirrors `getDefaultSponsoredCallback()` but signs a Permit2
|
|
4940
|
-
*
|
|
3694
|
+
* `PermitTransferFrom` instead of an EIP-3009 authorization.
|
|
4941
3695
|
*/
|
|
4942
3696
|
getDefaultWethSponsoredCallback(onApproved) {
|
|
4943
3697
|
if (!onApproved && this.cachedWethSponsoredCallback)
|
|
4944
3698
|
return this.cachedWethSponsoredCallback;
|
|
4945
3699
|
const provider = this.requireConnectedProvider();
|
|
4946
3700
|
const owner = this.state.walletAddress;
|
|
4947
|
-
const callback =
|
|
3701
|
+
const callback = makeSponsoredWethCallback({
|
|
4948
3702
|
apiKey: this.apiKey,
|
|
4949
3703
|
baseUrl: this.routingApiBaseUrl,
|
|
4950
3704
|
ownerAddress: owner,
|
|
@@ -4953,14 +3707,14 @@ var OwneySDK = class {
|
|
|
4953
3707
|
// Casts work around viem's chain-narrowed Client vs the generic
|
|
4954
3708
|
// PublicClient/WalletClient param types — structurally identical at
|
|
4955
3709
|
// runtime, but the two share a name TS treats as unrelated.
|
|
4956
|
-
getPublicClient: (cid) => (0,
|
|
3710
|
+
getPublicClient: (cid) => (0, import_viem8.createPublicClient)({
|
|
4957
3711
|
chain: VIEM_CHAIN2[cid],
|
|
4958
|
-
transport: (0,
|
|
3712
|
+
transport: (0, import_viem8.custom)(provider)
|
|
4959
3713
|
}),
|
|
4960
|
-
getWalletClient: (cid) => (0,
|
|
3714
|
+
getWalletClient: (cid) => (0, import_viem8.createWalletClient)({
|
|
4961
3715
|
account: owner,
|
|
4962
3716
|
chain: VIEM_CHAIN2[cid],
|
|
4963
|
-
transport: (0,
|
|
3717
|
+
transport: (0, import_viem8.custom)(provider)
|
|
4964
3718
|
})
|
|
4965
3719
|
});
|
|
4966
3720
|
if (!onApproved) this.cachedWethSponsoredCallback = callback;
|
|
@@ -5034,14 +3788,7 @@ var OwneySDK = class {
|
|
|
5034
3788
|
this.routingApiBaseUrl
|
|
5035
3789
|
);
|
|
5036
3790
|
this.disabledAgents.clear();
|
|
5037
|
-
for (const {
|
|
5038
|
-
key: key2,
|
|
5039
|
-
agent_type,
|
|
5040
|
-
is_enabled,
|
|
5041
|
-
is_configured
|
|
5042
|
-
} of agentKeys) {
|
|
5043
|
-
const configured = is_configured ?? Boolean(key2);
|
|
5044
|
-
if (!configured) continue;
|
|
3791
|
+
for (const { key: key2, agent_type, is_enabled } of agentKeys) {
|
|
5045
3792
|
const agent = this.createAgent(agent_type, key2);
|
|
5046
3793
|
if (!agent) continue;
|
|
5047
3794
|
this.agents.set(agent_type, agent);
|
|
@@ -5065,15 +3812,8 @@ var OwneySDK = class {
|
|
|
5065
3812
|
}
|
|
5066
3813
|
createAgent(agentId, key2) {
|
|
5067
3814
|
if (agentId === "zyfai") {
|
|
5068
|
-
if (!key2) return null;
|
|
5069
3815
|
return new ZyfaiAgent(key2, this.zyfaiRpcUrls, this.referralSource);
|
|
5070
3816
|
}
|
|
5071
|
-
if (agentId === "yieldseeker") {
|
|
5072
|
-
return new YieldseekerAgent(this.apiKey, {
|
|
5073
|
-
auth: { origin: this.yieldseekerSiweOrigin },
|
|
5074
|
-
baseUrl: this.yieldseekerApiBaseUrl ?? getYieldseekerProxyBaseUrl(this.routingApiBaseUrl)
|
|
5075
|
-
});
|
|
5076
|
-
}
|
|
5077
3817
|
return null;
|
|
5078
3818
|
}
|
|
5079
3819
|
/**
|
|
@@ -5118,10 +3858,9 @@ var OwneySDK = class {
|
|
|
5118
3858
|
* If provided, ALL specified agents must support the chainId or the call
|
|
5119
3859
|
* throws before activating any agent.
|
|
5120
3860
|
*/
|
|
5121
|
-
async activateAgent(chainId, agentId
|
|
3861
|
+
async activateAgent(chainId, agentId) {
|
|
5122
3862
|
const state = this.requireState();
|
|
5123
3863
|
await this.ensureAgentsInitialized();
|
|
5124
|
-
this.assertActivationSession(state);
|
|
5125
3864
|
if (agentId !== void 0) {
|
|
5126
3865
|
if (agentId.length === 0) {
|
|
5127
3866
|
throw new OwneyError(
|
|
@@ -5155,7 +3894,7 @@ var OwneySDK = class {
|
|
|
5155
3894
|
this.activeAgents.add(id);
|
|
5156
3895
|
}
|
|
5157
3896
|
state.chainId = chainId;
|
|
5158
|
-
await this.activateAgentsInTurn(agents, state, chainId
|
|
3897
|
+
await this.activateAgentsInTurn(agents, state, chainId);
|
|
5159
3898
|
return;
|
|
5160
3899
|
}
|
|
5161
3900
|
const compatible = [...this.agents.values()].filter(
|
|
@@ -5176,12 +3915,7 @@ var OwneySDK = class {
|
|
|
5176
3915
|
const enabledCompatible = compatible.filter(
|
|
5177
3916
|
(agent) => !this.isAgentDisabled(agent.id)
|
|
5178
3917
|
);
|
|
5179
|
-
await this.activateAgentsInTurn(enabledCompatible, state, chainId
|
|
5180
|
-
}
|
|
5181
|
-
assertActivationSession(state) {
|
|
5182
|
-
if (this.state !== state) {
|
|
5183
|
-
throw new OwneyError("NOT_CONNECTED", "Wallet connection changed. Please try again.");
|
|
5184
|
-
}
|
|
3918
|
+
await this.activateAgentsInTurn(enabledCompatible, state, chainId);
|
|
5185
3919
|
}
|
|
5186
3920
|
/**
|
|
5187
3921
|
* Activate agents ONE AT A TIME, each followed by its org policy.
|
|
@@ -5196,51 +3930,26 @@ var OwneySDK = class {
|
|
|
5196
3930
|
* Serializing costs no real wall-clock: the user can only approve one prompt
|
|
5197
3931
|
* at a time anyway.
|
|
5198
3932
|
*
|
|
5199
|
-
*
|
|
5200
|
-
*
|
|
5201
|
-
*
|
|
3933
|
+
* Every agent is attempted even if an earlier one fails, so one declined
|
|
3934
|
+
* signature can't deny the remaining agents their turn. The first failure is
|
|
3935
|
+
* rethrown (matching the previous `Promise.all` rejection) once all agents
|
|
3936
|
+
* have had a chance to activate.
|
|
5202
3937
|
*/
|
|
5203
|
-
async activateAgentsInTurn(agents, state, chainId
|
|
3938
|
+
async activateAgentsInTurn(agents, state, chainId) {
|
|
5204
3939
|
let firstError = null;
|
|
5205
|
-
const activatedAgentIds = [];
|
|
5206
|
-
const failedAgents = [];
|
|
5207
3940
|
for (const agent of agents) {
|
|
5208
|
-
this.assertActivationSession(state);
|
|
5209
3941
|
try {
|
|
5210
|
-
await agent.activateAgent(state, chainId
|
|
5211
|
-
this.assertActivationSession(state);
|
|
3942
|
+
await agent.activateAgent(state, chainId);
|
|
5212
3943
|
await this.applyOrgPolicyTo(agent, state, chainId);
|
|
5213
|
-
this.assertActivationSession(state);
|
|
5214
|
-
activatedAgentIds.push(agent.id);
|
|
5215
3944
|
} catch (error) {
|
|
5216
|
-
this.assertActivationSession(state);
|
|
5217
|
-
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.";
|
|
5218
|
-
failedAgents.push({
|
|
5219
|
-
agentId: agent.id,
|
|
5220
|
-
code: error instanceof OwneyError ? error.code : void 0,
|
|
5221
|
-
message,
|
|
5222
|
-
...error instanceof OwneyError && error.details ? { details: error.details } : {}
|
|
5223
|
-
});
|
|
5224
3945
|
if (firstError === null) {
|
|
5225
3946
|
firstError = error;
|
|
5226
3947
|
} else {
|
|
5227
3948
|
console.error(`activateAgent(${agent.id}) failed:`, error);
|
|
5228
3949
|
}
|
|
5229
|
-
break;
|
|
5230
3950
|
}
|
|
5231
3951
|
}
|
|
5232
|
-
if (firstError
|
|
5233
|
-
if (activatedAgentIds.length === 0) throw firstError;
|
|
5234
|
-
const failedAgentIds = failedAgents.map(({ agentId }) => agentId);
|
|
5235
|
-
const activeNames = activatedAgentIds.map(this.formatAgentName).join(", ");
|
|
5236
|
-
const failureMessages = failedAgents.map(
|
|
5237
|
-
({ agentId, message }) => `${this.formatAgentName(agentId)} activation failed: ${message}`
|
|
5238
|
-
).join(" ");
|
|
5239
|
-
throw new OwneyError(
|
|
5240
|
-
"AGENT_ACTIVATION_PARTIAL_FAILURE",
|
|
5241
|
-
`${activeNames} activated. ${failureMessages}`,
|
|
5242
|
-
{ activatedAgentIds, failedAgentIds, failures: failedAgents }
|
|
5243
|
-
);
|
|
3952
|
+
if (firstError !== null) throw firstError;
|
|
5244
3953
|
}
|
|
5245
3954
|
/**
|
|
5246
3955
|
* Deposit into a specific agent, or distribute across all eligible agents.
|
|
@@ -5250,8 +3959,7 @@ var OwneySDK = class {
|
|
|
5250
3959
|
* @param options.asset - Asset symbol to deposit (e.g. "USDC")
|
|
5251
3960
|
* @param options.depositCallback - Callback that performs the token transfer and returns a tx hash.
|
|
5252
3961
|
* When agentId is omitted, this callback is invoked once per eligible agent with that agent's
|
|
5253
|
-
* split amount and smart wallet address
|
|
5254
|
-
* all shares into one signature; custom callbacks still run once per agent.
|
|
3962
|
+
* split amount and smart wallet address — expect multiple wallet prompts.
|
|
5255
3963
|
* @param options.agentId - Optional explicit target. Otherwise split equally,
|
|
5256
3964
|
* or fund remaining agents when a recovery deposit cannot meet every minimum.
|
|
5257
3965
|
* @returns {OwneyDepositResult} for a single agent, or {OwneyMultiDepositResult} with per-agent results
|
|
@@ -5336,39 +4044,6 @@ var OwneySDK = class {
|
|
|
5336
4044
|
}
|
|
5337
4045
|
);
|
|
5338
4046
|
}
|
|
5339
|
-
const batchTransfer = getDepositBatchTransfer(effectiveCallback);
|
|
5340
|
-
if (!depositCallback && batchTransfer) {
|
|
5341
|
-
return runAgentDepositBatch(
|
|
5342
|
-
chainId,
|
|
5343
|
-
agentAmounts.map(({ agent, amount: amount2 }) => ({
|
|
5344
|
-
id: agent.id,
|
|
5345
|
-
amount: amount2,
|
|
5346
|
-
run: (callback) => withFailureReporting(
|
|
5347
|
-
this.apiKey,
|
|
5348
|
-
agent.id,
|
|
5349
|
-
() => agent.deposit(state, chainId, amount2, asset, callback),
|
|
5350
|
-
this.routingApiBaseUrl
|
|
5351
|
-
)
|
|
5352
|
-
})),
|
|
5353
|
-
async (cid, transfers) => {
|
|
5354
|
-
try {
|
|
5355
|
-
return await batchTransfer(cid, transfers);
|
|
5356
|
-
} catch (error) {
|
|
5357
|
-
if (!(error instanceof OwneyError) || error.code !== "PERMIT2_APPROVAL_REQUIRED")
|
|
5358
|
-
throw error;
|
|
5359
|
-
const requiredAmount = transfers.reduce(
|
|
5360
|
-
(sum, transfer) => sum + BigInt(transfer.amount),
|
|
5361
|
-
0n
|
|
5362
|
-
);
|
|
5363
|
-
await this.approvePermit2(
|
|
5364
|
-
asset,
|
|
5365
|
-
requiredAmount
|
|
5366
|
-
);
|
|
5367
|
-
return batchTransfer(cid, transfers);
|
|
5368
|
-
}
|
|
5369
|
-
}
|
|
5370
|
-
);
|
|
5371
|
-
}
|
|
5372
4047
|
const agentResults = {};
|
|
5373
4048
|
for (const [
|
|
5374
4049
|
index,
|
|
@@ -5408,7 +4083,7 @@ var OwneySDK = class {
|
|
|
5408
4083
|
*
|
|
5409
4084
|
* 1. Missing Permit2 allowance: when the app did not supply its own
|
|
5410
4085
|
* callback and the attempt fails with `PERMIT2_APPROVAL_REQUIRED` on a
|
|
5411
|
-
*
|
|
4086
|
+
* WETH deposit, this is the wallet's first gasless WETH deposit. We send
|
|
5412
4087
|
* the one-time (user-paid) Permit2 approval via `approvePermit2()` and
|
|
5413
4088
|
* retry the SAME sponsored attempt once. Bounded to one approval attempt
|
|
5414
4089
|
* per call so a wallet/agent that keeps reporting the allowance as
|
|
@@ -5445,15 +4120,12 @@ var OwneySDK = class {
|
|
|
5445
4120
|
try {
|
|
5446
4121
|
return await attempt(effectiveCallback);
|
|
5447
4122
|
} catch (error) {
|
|
5448
|
-
if (!approvalAttempted && appCallback === void 0 &&
|
|
4123
|
+
if (!approvalAttempted && appCallback === void 0 && asset === "WETH" && error instanceof OwneyError && error.code === "PERMIT2_APPROVAL_REQUIRED") {
|
|
5449
4124
|
approvalAttempted = true;
|
|
5450
4125
|
console.warn(
|
|
5451
|
-
"[owney-sdk] First
|
|
5452
|
-
);
|
|
5453
|
-
await this.approvePermit2(
|
|
5454
|
-
asset,
|
|
5455
|
-
BigInt(amount)
|
|
4126
|
+
"[owney-sdk] First WETH deposit: sending one-time Permit2 approval..."
|
|
5456
4127
|
);
|
|
4128
|
+
await this.approvePermit2();
|
|
5457
4129
|
continue;
|
|
5458
4130
|
}
|
|
5459
4131
|
if (!shouldFallbackToUserPaid(error, asset, appCallback)) throw error;
|
|
@@ -5491,10 +4163,10 @@ var OwneySDK = class {
|
|
|
5491
4163
|
agent,
|
|
5492
4164
|
amount: i === agents.length - 1 ? perAgent + remainder : perAgent
|
|
5493
4165
|
}));
|
|
5494
|
-
const
|
|
4166
|
+
const valid = splits.filter(
|
|
5495
4167
|
(s) => s.amount > 0n && (exempt.has(s.agent.id) || s.amount >= this.getMinDepositAmount(s.agent, chainId, asset))
|
|
5496
4168
|
);
|
|
5497
|
-
if (
|
|
4169
|
+
if (valid.length === agents.length) {
|
|
5498
4170
|
return splits.map((s) => ({ agent: s.agent, amount: String(s.amount) }));
|
|
5499
4171
|
}
|
|
5500
4172
|
const targets = agentsRequiringActivation.length > 0 ? agentsRequiringActivation : agents;
|
|
@@ -5513,11 +4185,6 @@ var OwneySDK = class {
|
|
|
5513
4185
|
)
|
|
5514
4186
|
}));
|
|
5515
4187
|
}
|
|
5516
|
-
formatAgentName(agentId) {
|
|
5517
|
-
if (agentId === "zyfai") return "Zyfai";
|
|
5518
|
-
if (agentId === "yieldseeker") return "Yieldseeker";
|
|
5519
|
-
return agentId;
|
|
5520
|
-
}
|
|
5521
4188
|
async validateMinDepositAmount(agent, state, chainId, asset, amount) {
|
|
5522
4189
|
const minDepositAmount = this.getMinDepositAmount(agent, chainId, asset);
|
|
5523
4190
|
const parsedAmount = BigInt(amount);
|
|
@@ -5549,12 +4216,12 @@ var OwneySDK = class {
|
|
|
5549
4216
|
(t) => t.chainId === chainId && t.asset.toLowerCase() === target
|
|
5550
4217
|
);
|
|
5551
4218
|
const targetChainName = agent.supportedAssets.find((entry) => entry.chainId === chainId)?.chain?.trim().toUpperCase();
|
|
5552
|
-
const
|
|
4219
|
+
const position = (balance.positions ?? []).find((p) => {
|
|
5553
4220
|
const positionChain = p.chain.trim().toUpperCase();
|
|
5554
4221
|
const matchesChain = positionChain === String(chainId) || targetChainName !== void 0 && positionChain === targetChainName;
|
|
5555
4222
|
return matchesChain && p.asset.toLowerCase() === target && Number(p.amount) > 0;
|
|
5556
4223
|
});
|
|
5557
|
-
return !!token && Number(token.amount) > 0 || !!
|
|
4224
|
+
return !!token && Number(token.amount) > 0 || !!position;
|
|
5558
4225
|
} catch (error) {
|
|
5559
4226
|
if (requireReliableRead) {
|
|
5560
4227
|
throw new OwneyError(
|
|
@@ -5600,6 +4267,354 @@ var OwneySDK = class {
|
|
|
5600
4267
|
return eligible;
|
|
5601
4268
|
}
|
|
5602
4269
|
// --- Fund operations ---
|
|
4270
|
+
// --- Swap to yield (ROUT-242) ---
|
|
4271
|
+
/** Lazily built so an app that never swaps pays nothing for it. */
|
|
4272
|
+
swapApiClient;
|
|
4273
|
+
swapApi() {
|
|
4274
|
+
this.swapApiClient ??= createSwapApi(
|
|
4275
|
+
this.routingApiBaseUrl ?? ROUTING_API_BASE_URL,
|
|
4276
|
+
this.apiKey
|
|
4277
|
+
);
|
|
4278
|
+
return this.swapApiClient;
|
|
4279
|
+
}
|
|
4280
|
+
/**
|
|
4281
|
+
* Put the wallet on `chainId`, or fail with something actionable.
|
|
4282
|
+
*
|
|
4283
|
+
* Reuses the same guard the deposit rail uses, which re-reads the chain after
|
|
4284
|
+
* switching — some wallets resolve wallet_switchEthereumChain before the
|
|
4285
|
+
* network has actually changed.
|
|
4286
|
+
*/
|
|
4287
|
+
async ensureSwapChain(chainId) {
|
|
4288
|
+
const provider = this.requireConnectedProvider();
|
|
4289
|
+
const state = this.requireState();
|
|
4290
|
+
const chain = VIEM_CHAIN2[chainId];
|
|
4291
|
+
if (!chain) {
|
|
4292
|
+
throw new OwneyError(
|
|
4293
|
+
"CHAIN_UNSUPPORTED",
|
|
4294
|
+
`Chain ${chainId} is not supported`,
|
|
4295
|
+
{ chainId }
|
|
4296
|
+
);
|
|
4297
|
+
}
|
|
4298
|
+
await ensureWalletOnChain(
|
|
4299
|
+
(0, import_viem8.createPublicClient)({ chain, transport: (0, import_viem8.custom)(provider) }),
|
|
4300
|
+
(0, import_viem8.createWalletClient)({
|
|
4301
|
+
account: state.walletAddress,
|
|
4302
|
+
chain,
|
|
4303
|
+
transport: (0, import_viem8.custom)(provider)
|
|
4304
|
+
}),
|
|
4305
|
+
chainId
|
|
4306
|
+
);
|
|
4307
|
+
}
|
|
4308
|
+
/**
|
|
4309
|
+
* Binds the executor's abstract deps to this client's wallet.
|
|
4310
|
+
*
|
|
4311
|
+
* Kept as a builder rather than baked into the executor so the whole swap
|
|
4312
|
+
* flow stays testable without a provider — the executor never imports viem.
|
|
4313
|
+
*/
|
|
4314
|
+
buildSwapDeps(quote) {
|
|
4315
|
+
const state = this.requireState();
|
|
4316
|
+
const provider = this.requireConnectedProvider();
|
|
4317
|
+
const srcChain = VIEM_CHAIN2[quote.src.chainId];
|
|
4318
|
+
const dstChain = VIEM_CHAIN2[quote.dst.chainId];
|
|
4319
|
+
const wallet = (0, import_viem8.createWalletClient)({
|
|
4320
|
+
account: state.walletAddress,
|
|
4321
|
+
chain: srcChain,
|
|
4322
|
+
transport: (0, import_viem8.custom)(provider)
|
|
4323
|
+
});
|
|
4324
|
+
const srcPublic = (0, import_viem8.createPublicClient)({
|
|
4325
|
+
chain: srcChain,
|
|
4326
|
+
transport: swapReadTransport(quote.src.chainId, this.zyfaiRpcUrls)
|
|
4327
|
+
});
|
|
4328
|
+
const dstPublic = (0, import_viem8.createPublicClient)({
|
|
4329
|
+
chain: dstChain,
|
|
4330
|
+
transport: swapReadTransport(quote.dst.chainId, this.zyfaiRpcUrls)
|
|
4331
|
+
});
|
|
4332
|
+
return {
|
|
4333
|
+
api: this.swapApi(),
|
|
4334
|
+
// Native-aware, like readSourceBalance below. Native ETH is never a
|
|
4335
|
+
// DEPOSIT target, so this only ever mattered once withdrawal shipped —
|
|
4336
|
+
// and there it is the headline case. balanceOf() on the 0xEeee sentinel
|
|
4337
|
+
// reverts, which would have read as "the swap landed nothing".
|
|
4338
|
+
readTargetBalance: async () => {
|
|
4339
|
+
const dst = quote.dst.address;
|
|
4340
|
+
if (dst.toLowerCase().startsWith("0xeeee")) {
|
|
4341
|
+
return dstPublic.getBalance({ address: state.walletAddress });
|
|
4342
|
+
}
|
|
4343
|
+
return dstPublic.readContract({
|
|
4344
|
+
address: dst,
|
|
4345
|
+
abi: import_viem8.erc20Abi,
|
|
4346
|
+
functionName: "balanceOf",
|
|
4347
|
+
args: [state.walletAddress]
|
|
4348
|
+
});
|
|
4349
|
+
},
|
|
4350
|
+
sendTransaction: async (tx) => {
|
|
4351
|
+
const hash = await wallet.sendTransaction({
|
|
4352
|
+
to: tx.to,
|
|
4353
|
+
data: tx.data,
|
|
4354
|
+
value: BigInt(tx.value || "0"),
|
|
4355
|
+
account: state.walletAddress,
|
|
4356
|
+
chain: srcChain
|
|
4357
|
+
});
|
|
4358
|
+
const receipt = await srcPublic.waitForTransactionReceipt({
|
|
4359
|
+
timeout: receiptTimeoutMs(quote.src.chainId),
|
|
4360
|
+
hash,
|
|
4361
|
+
confirmations: 1
|
|
4362
|
+
});
|
|
4363
|
+
if (receipt.status !== "success") {
|
|
4364
|
+
throw new OwneyError(
|
|
4365
|
+
"SWAP_REQUEST_FAILED",
|
|
4366
|
+
`Swap transaction reverted (tx ${hash})`,
|
|
4367
|
+
{ hash }
|
|
4368
|
+
);
|
|
4369
|
+
}
|
|
4370
|
+
return hash;
|
|
4371
|
+
},
|
|
4372
|
+
signTypedData: (typedData) => wallet.signTypedData({
|
|
4373
|
+
account: state.walletAddress,
|
|
4374
|
+
...typedData
|
|
4375
|
+
}),
|
|
4376
|
+
// Chain-bound like every other read here: the wallet provider's chain is
|
|
4377
|
+
// not ours to rely on mid-swap.
|
|
4378
|
+
readSourceBalance: async () => {
|
|
4379
|
+
const src = quote.src.address;
|
|
4380
|
+
if (src.toLowerCase().startsWith("0xeeee")) {
|
|
4381
|
+
return srcPublic.getBalance({ address: state.walletAddress });
|
|
4382
|
+
}
|
|
4383
|
+
return srcPublic.readContract({
|
|
4384
|
+
address: src,
|
|
4385
|
+
abi: ERC20_ALLOWANCE_ABI,
|
|
4386
|
+
functionName: "balanceOf",
|
|
4387
|
+
args: [state.walletAddress]
|
|
4388
|
+
});
|
|
4389
|
+
},
|
|
4390
|
+
readAllowance: (spender) => srcPublic.readContract({
|
|
4391
|
+
address: quote.src.address,
|
|
4392
|
+
abi: ERC20_ALLOWANCE_ABI,
|
|
4393
|
+
functionName: "allowance",
|
|
4394
|
+
args: [state.walletAddress, spender]
|
|
4395
|
+
}),
|
|
4396
|
+
approve: async (spender, amount) => {
|
|
4397
|
+
const hash = await wallet.writeContract({
|
|
4398
|
+
address: quote.src.address,
|
|
4399
|
+
abi: ERC20_ALLOWANCE_ABI,
|
|
4400
|
+
functionName: "approve",
|
|
4401
|
+
args: [spender, amount],
|
|
4402
|
+
account: state.walletAddress,
|
|
4403
|
+
chain: srcChain
|
|
4404
|
+
});
|
|
4405
|
+
await srcPublic.waitForTransactionReceipt({
|
|
4406
|
+
hash,
|
|
4407
|
+
confirmations: 1,
|
|
4408
|
+
timeout: receiptTimeoutMs(quote.src.chainId)
|
|
4409
|
+
});
|
|
4410
|
+
return hash;
|
|
4411
|
+
},
|
|
4412
|
+
ensureChain: (chainId) => this.ensureSwapChain(chainId),
|
|
4413
|
+
runner: {
|
|
4414
|
+
readyForSecrets: (h) => this.swapApi().readyForSecrets(h),
|
|
4415
|
+
submitSecret: (h, secret) => this.swapApi().submitSecret(h, secret),
|
|
4416
|
+
orderStatus: (h) => this.swapApi().orderStatus(h),
|
|
4417
|
+
sleep: (ms) => new Promise((resolve) => setTimeout(resolve, ms)),
|
|
4418
|
+
now: () => Date.now()
|
|
4419
|
+
}
|
|
4420
|
+
};
|
|
4421
|
+
}
|
|
4422
|
+
/**
|
|
4423
|
+
* Assets the user may pay with, and what each chain deposits into.
|
|
4424
|
+
*
|
|
4425
|
+
* The source list is deliberately wider than the deposit list: it includes
|
|
4426
|
+
* native ETH and USDT, which Owney never holds but users often do.
|
|
4427
|
+
*/
|
|
4428
|
+
async getSwapTokens() {
|
|
4429
|
+
return this.swapApi().listTokens();
|
|
4430
|
+
}
|
|
4431
|
+
/**
|
|
4432
|
+
* Search the assets a user may pay with on one chain.
|
|
4433
|
+
*
|
|
4434
|
+
* `getSwapTokens` returns the short list worth rendering unprompted. This
|
|
4435
|
+
* reaches everything else the routing API will accept — thousands per chain
|
|
4436
|
+
* once the wider allowlist is enabled, which is why it is a query rather
|
|
4437
|
+
* than a download.
|
|
4438
|
+
*
|
|
4439
|
+
* Results are filtered server-side to what a quote will accept, so anything
|
|
4440
|
+
* returned can be paid with. They are NOT ranked by trustworthiness: several
|
|
4441
|
+
* tokens can share a ticker, and `providers` (how many token lists carry the
|
|
4442
|
+
* address) is the only usable signal for telling them apart. Surface it.
|
|
4443
|
+
*
|
|
4444
|
+
* Returns nothing for a blank query rather than asking for the whole list.
|
|
4445
|
+
*/
|
|
4446
|
+
async searchSwapTokens(params) {
|
|
4447
|
+
const query = params.query.trim();
|
|
4448
|
+
if (!query) return { tokens: [] };
|
|
4449
|
+
return this.swapApi().searchTokens({
|
|
4450
|
+
chainId: params.chainId,
|
|
4451
|
+
query,
|
|
4452
|
+
...params.limit === void 0 ? {} : { limit: params.limit }
|
|
4453
|
+
});
|
|
4454
|
+
}
|
|
4455
|
+
/**
|
|
4456
|
+
* Price a swap without committing to it.
|
|
4457
|
+
*
|
|
4458
|
+
* `dstAmountMin` is the number to validate against a deposit minimum —
|
|
4459
|
+
* `dst.amount` is an estimate that a decaying auction or slippage can undercut,
|
|
4460
|
+
* and a swap landing below the floor leaves the user swapped but not
|
|
4461
|
+
* deposited.
|
|
4462
|
+
*/
|
|
4463
|
+
async getSwapQuote(params) {
|
|
4464
|
+
const state = this.requireState();
|
|
4465
|
+
return this.swapApi().quote({
|
|
4466
|
+
...params,
|
|
4467
|
+
walletAddress: state.walletAddress
|
|
4468
|
+
});
|
|
4469
|
+
}
|
|
4470
|
+
/**
|
|
4471
|
+
* Swap an asset the user holds into a deposit asset, then deposit it.
|
|
4472
|
+
*
|
|
4473
|
+
* Kept separate from `deposit()` rather than bolted on as an option: the
|
|
4474
|
+
* return shape differs, the staging callback is meaningless on the plain
|
|
4475
|
+
* path, and integrators who never swap should not have to reason about any
|
|
4476
|
+
* of it.
|
|
4477
|
+
*
|
|
4478
|
+
* The deposit runs on the MEASURED arrival, not the quote. A quote is an
|
|
4479
|
+
* estimate, so depositing the quoted figure would either strand dust or try
|
|
4480
|
+
* to move funds that never came.
|
|
4481
|
+
*
|
|
4482
|
+
* Failure modes differ in a way callers must respect. A same-chain swap is
|
|
4483
|
+
* atomic — if it fails, nothing moved. A cross-chain swap escrows the user's
|
|
4484
|
+
* funds first, so SWAP_ORDER_EXPIRED / REFUNDED / CANCELLED all mean the
|
|
4485
|
+
* money left the wallet. Only the former can honestly say "nothing has left
|
|
4486
|
+
* your wallet".
|
|
4487
|
+
*/
|
|
4488
|
+
async swapAndDeposit(options) {
|
|
4489
|
+
const state = this.requireState();
|
|
4490
|
+
const api = this.swapApi();
|
|
4491
|
+
const quote = await api.quote({
|
|
4492
|
+
from: options.from,
|
|
4493
|
+
to: options.to,
|
|
4494
|
+
walletAddress: state.walletAddress
|
|
4495
|
+
});
|
|
4496
|
+
await this.ensureSwapChain(quote.src.chainId);
|
|
4497
|
+
const swap = await executeSwap(this.buildSwapDeps(quote), {
|
|
4498
|
+
quote,
|
|
4499
|
+
walletAddress: state.walletAddress,
|
|
4500
|
+
...options.slippage === void 0 ? {} : { slippage: options.slippage },
|
|
4501
|
+
...options.onSwapProgress ? { onStage: options.onSwapProgress } : {}
|
|
4502
|
+
});
|
|
4503
|
+
options.onSwapProgress?.("depositing");
|
|
4504
|
+
await this.ensureSwapChain(quote.dst.chainId);
|
|
4505
|
+
const deposit = await this.deposit({
|
|
4506
|
+
amount: swap.received,
|
|
4507
|
+
asset: options.to.symbol,
|
|
4508
|
+
...options.agentId ? { agentId: options.agentId } : {}
|
|
4509
|
+
});
|
|
4510
|
+
return { swap, deposit };
|
|
4511
|
+
}
|
|
4512
|
+
/**
|
|
4513
|
+
* Withdraw from an agent and swap the proceeds into whatever the user wants
|
|
4514
|
+
* to hold, delivered to their own wallet.
|
|
4515
|
+
*
|
|
4516
|
+
* The mirror of `swapAndDeposit()`, with one structural difference that
|
|
4517
|
+
* drives the whole implementation: a deposit swap starts from funds already
|
|
4518
|
+
* sitting in the wallet, but a withdrawal has to wait for them. The agent's
|
|
4519
|
+
* provider acknowledges a withdrawal and *then* queues the on-chain transfer
|
|
4520
|
+
* to the EOA, so `withdraw()` resolving means "accepted", not "arrived".
|
|
4521
|
+
* Quoting before the tokens land would size the swap against a balance that
|
|
4522
|
+
* is not there yet.
|
|
4523
|
+
*
|
|
4524
|
+
* The swap is therefore sized from the MEASURED arrival, exactly as the
|
|
4525
|
+
* deposit path sizes its deposit from the measured swap output. On a full
|
|
4526
|
+
* withdrawal there is no other number available — "MAX" has no figure until
|
|
4527
|
+
* the agent picks one.
|
|
4528
|
+
*
|
|
4529
|
+
* **Failure here is not symmetrical with the deposit path.** A failed
|
|
4530
|
+
* deposit-swap leaves the user holding what they started with. A failed
|
|
4531
|
+
* withdrawal-swap leaves them holding the AGENT'S asset in their own wallet:
|
|
4532
|
+
* the money is out, safe, and in the wrong denomination. Both
|
|
4533
|
+
* `WITHDRAW_ARRIVAL_TIMEOUT` and `WITHDRAW_SWAP_FAILED` carry `withdrawn` for
|
|
4534
|
+
* that reason — the UI has to tell the user where their money actually is,
|
|
4535
|
+
* and must never present either as a lost withdrawal.
|
|
4536
|
+
*/
|
|
4537
|
+
async withdrawAndSwap(options) {
|
|
4538
|
+
const state = this.requireState();
|
|
4539
|
+
const activeChainId = this.requireChainId();
|
|
4540
|
+
if (options.from.chainId !== activeChainId) {
|
|
4541
|
+
throw new OwneyError(
|
|
4542
|
+
"CHAIN_MISMATCH",
|
|
4543
|
+
`Cannot withdraw from chain ${options.from.chainId} while the active chain is ${activeChainId}. Activate on that chain first.`,
|
|
4544
|
+
{ requested: options.from.chainId, active: activeChainId }
|
|
4545
|
+
);
|
|
4546
|
+
}
|
|
4547
|
+
const asset = SupportedAssets.find(
|
|
4548
|
+
(a) => a.chainId === options.from.chainId && a.symbol === options.from.symbol.toUpperCase()
|
|
4549
|
+
);
|
|
4550
|
+
if (!asset) {
|
|
4551
|
+
throw new OwneyError(
|
|
4552
|
+
"WITHDRAW_NO_PERMITTED_TOKENS",
|
|
4553
|
+
`${options.from.symbol} on chain ${options.from.chainId} is not an asset Owney holds`,
|
|
4554
|
+
{ ...options.from }
|
|
4555
|
+
);
|
|
4556
|
+
}
|
|
4557
|
+
const srcChain = VIEM_CHAIN2[options.from.chainId];
|
|
4558
|
+
const srcPublic = (0, import_viem8.createPublicClient)({
|
|
4559
|
+
chain: srcChain,
|
|
4560
|
+
transport: swapReadTransport(options.from.chainId, this.zyfaiRpcUrls)
|
|
4561
|
+
});
|
|
4562
|
+
const readWalletBalance = () => srcPublic.readContract({
|
|
4563
|
+
address: asset.address,
|
|
4564
|
+
abi: import_viem8.erc20Abi,
|
|
4565
|
+
functionName: "balanceOf",
|
|
4566
|
+
args: [state.walletAddress]
|
|
4567
|
+
});
|
|
4568
|
+
const baseline = await readWalletBalance();
|
|
4569
|
+
debugLog("owney-sdk", "withdrawAndSwap: baseline", {
|
|
4570
|
+
asset: `${asset.symbol}@${asset.chainId}`,
|
|
4571
|
+
baseline: baseline.toString()
|
|
4572
|
+
});
|
|
4573
|
+
options.onSwapProgress?.("withdrawing");
|
|
4574
|
+
const withdraw = await this.withdraw({
|
|
4575
|
+
asset: options.from.symbol,
|
|
4576
|
+
...options.amount === void 0 ? {} : { amount: options.amount },
|
|
4577
|
+
...options.agentId ? { agentId: options.agentId } : {}
|
|
4578
|
+
});
|
|
4579
|
+
const arrived = await awaitWithdrawalArrival({
|
|
4580
|
+
readBalance: readWalletBalance,
|
|
4581
|
+
baseline,
|
|
4582
|
+
...options.arrivalTimeoutMs === void 0 ? {} : { timeoutMs: options.arrivalTimeoutMs }
|
|
4583
|
+
});
|
|
4584
|
+
const withdrawn = arrived.toString();
|
|
4585
|
+
options.onSwapProgress?.("withdrawn");
|
|
4586
|
+
try {
|
|
4587
|
+
const quote = await this.swapApi().quote({
|
|
4588
|
+
from: { ...options.from, amount: withdrawn },
|
|
4589
|
+
to: options.to,
|
|
4590
|
+
direction: "withdraw",
|
|
4591
|
+
walletAddress: state.walletAddress
|
|
4592
|
+
});
|
|
4593
|
+
await this.ensureSwapChain(quote.src.chainId);
|
|
4594
|
+
const swap = await executeSwap(this.buildSwapDeps(quote), {
|
|
4595
|
+
quote,
|
|
4596
|
+
walletAddress: state.walletAddress,
|
|
4597
|
+
direction: "withdraw",
|
|
4598
|
+
...options.slippage === void 0 ? {} : { slippage: options.slippage },
|
|
4599
|
+
...options.onSwapProgress ? { onStage: options.onSwapProgress } : {}
|
|
4600
|
+
});
|
|
4601
|
+
return { withdraw, withdrawn, swap };
|
|
4602
|
+
} catch (error) {
|
|
4603
|
+
throw new OwneyError(
|
|
4604
|
+
"WITHDRAW_SWAP_FAILED",
|
|
4605
|
+
`Withdrew ${withdrawn} ${asset.symbol} to your wallet, but the swap to ${options.to.symbol} did not complete. The funds are in your wallet as ${asset.symbol}.`,
|
|
4606
|
+
{
|
|
4607
|
+
withdrawn,
|
|
4608
|
+
asset: asset.symbol,
|
|
4609
|
+
chainId: asset.chainId,
|
|
4610
|
+
intendedSymbol: options.to.symbol,
|
|
4611
|
+
intendedChainId: options.to.chainId,
|
|
4612
|
+
cause: error instanceof Error ? error.message : String(error),
|
|
4613
|
+
...error instanceof OwneyError ? { causeCode: error.code } : {}
|
|
4614
|
+
}
|
|
4615
|
+
);
|
|
4616
|
+
}
|
|
4617
|
+
}
|
|
5603
4618
|
/**
|
|
5604
4619
|
* Withdraw funds from a specific agent, or all agents that support the active chain+asset if agentId is omitted.
|
|
5605
4620
|
* Validates that the asset is supported by the target agent(s) on the active chain.
|
|
@@ -5669,10 +4684,6 @@ var OwneySDK = class {
|
|
|
5669
4684
|
}
|
|
5670
4685
|
const requested = BigInt(amount);
|
|
5671
4686
|
const aggregated = await this.getBalances();
|
|
5672
|
-
const unavailableAgents = eligibleAgents.filter(
|
|
5673
|
-
(agent) => !(agent.id in aggregated.agentBalances)
|
|
5674
|
-
);
|
|
5675
|
-
const unavailableAgentIds = unavailableAgents.map((agent) => agent.id);
|
|
5676
4687
|
const balances = projectAgentBalancesForAsset(
|
|
5677
4688
|
eligibleAgents,
|
|
5678
4689
|
aggregated.agentBalances,
|
|
@@ -5681,18 +4692,7 @@ var OwneySDK = class {
|
|
|
5681
4692
|
assetInfo.decimals
|
|
5682
4693
|
);
|
|
5683
4694
|
const totalAvailable = balances.reduce((sum, x) => sum + x.balance, 0n);
|
|
5684
|
-
if (totalAvailable
|
|
5685
|
-
throw new OwneyError(
|
|
5686
|
-
"WITHDRAW_BALANCE_UNAVAILABLE",
|
|
5687
|
-
`Cannot safely plan the withdrawal because balance data is unavailable for: ${unavailableAgentIds.join(", ")}.`,
|
|
5688
|
-
{
|
|
5689
|
-
asset,
|
|
5690
|
-
unavailableAgents: unavailableAgentIds,
|
|
5691
|
-
agentErrors: aggregated.agentErrors
|
|
5692
|
-
}
|
|
5693
|
-
);
|
|
5694
|
-
}
|
|
5695
|
-
if (totalAvailable < requested && unavailableAgents.length === 0) {
|
|
4695
|
+
if (totalAvailable < requested) {
|
|
5696
4696
|
throw new OwneyError(
|
|
5697
4697
|
"WITHDRAW_INSUFFICIENT_BALANCE",
|
|
5698
4698
|
`Requested withdrawal "${amount}" exceeds available balance "${totalAvailable.toString()}" for asset "${asset}".`,
|
|
@@ -5703,7 +4703,6 @@ var OwneySDK = class {
|
|
|
5703
4703
|
}
|
|
5704
4704
|
);
|
|
5705
4705
|
}
|
|
5706
|
-
const plannedTarget = totalAvailable < requested ? totalAvailable : requested;
|
|
5707
4706
|
const disabledBalances = balances.filter(
|
|
5708
4707
|
(b) => this.isAgentDisabled(b.agent.id)
|
|
5709
4708
|
);
|
|
@@ -5712,7 +4711,7 @@ var OwneySDK = class {
|
|
|
5712
4711
|
);
|
|
5713
4712
|
const { plans: disabledPlans, remaining: afterDrain } = planDisabledDrain(
|
|
5714
4713
|
disabledBalances,
|
|
5715
|
-
|
|
4714
|
+
requested
|
|
5716
4715
|
);
|
|
5717
4716
|
const enabledTotal = enabledBalances.reduce((s, b) => s + b.balance, 0n);
|
|
5718
4717
|
const enabledPlans = afterDrain > 0n ? planProportionalShares(enabledBalances, afterDrain, enabledTotal) : enabledBalances.map(({ agent, balance }) => ({
|
|
@@ -5722,9 +4721,7 @@ var OwneySDK = class {
|
|
|
5722
4721
|
}));
|
|
5723
4722
|
const plans = [...disabledPlans, ...enabledPlans];
|
|
5724
4723
|
const results = {};
|
|
5725
|
-
const agentErrors = {
|
|
5726
|
-
...aggregated.agentErrors ?? {}
|
|
5727
|
-
};
|
|
4724
|
+
const agentErrors = {};
|
|
5728
4725
|
for (let i = 0; i < plans.length; i++) {
|
|
5729
4726
|
const p = plans[i];
|
|
5730
4727
|
if (p.planned === 0n) continue;
|
|
@@ -5771,8 +4768,7 @@ var OwneySDK = class {
|
|
|
5771
4768
|
requested: amount,
|
|
5772
4769
|
withdrawn: withdrawn.toString(),
|
|
5773
4770
|
partialResults: results,
|
|
5774
|
-
agentErrors
|
|
5775
|
-
...unavailableAgentIds.length > 0 ? { unavailableAgents: unavailableAgentIds } : {}
|
|
4771
|
+
agentErrors
|
|
5776
4772
|
}
|
|
5777
4773
|
);
|
|
5778
4774
|
}
|
|
@@ -5789,25 +4785,24 @@ var OwneySDK = class {
|
|
|
5789
4785
|
const chainId = this.requireChainId();
|
|
5790
4786
|
if (agentId) {
|
|
5791
4787
|
const agent = this.getAgent(agentId);
|
|
5792
|
-
const result = await this.readAgent(
|
|
5793
|
-
|
|
5794
|
-
|
|
5795
|
-
|
|
5796
|
-
|
|
4788
|
+
const result = await this.readAgent(
|
|
4789
|
+
agent,
|
|
4790
|
+
"balances",
|
|
4791
|
+
() => agent.getBalances(state, chainId)
|
|
4792
|
+
);
|
|
4793
|
+
return result;
|
|
5797
4794
|
}
|
|
5798
4795
|
let totalBalance = 0;
|
|
5799
4796
|
const results = {};
|
|
5800
4797
|
const entries = [...this.getActiveAgents().entries()];
|
|
5801
4798
|
const balanceResults = await Promise.allSettled(
|
|
5802
4799
|
entries.map(async ([id, agent]) => {
|
|
5803
|
-
const b = await this.readAgent(
|
|
5804
|
-
|
|
5805
|
-
|
|
5806
|
-
|
|
5807
|
-
|
|
5808
|
-
|
|
5809
|
-
}
|
|
5810
|
-
];
|
|
4800
|
+
const b = await this.readAgent(
|
|
4801
|
+
agent,
|
|
4802
|
+
"balances",
|
|
4803
|
+
() => agent.getBalances(state, chainId)
|
|
4804
|
+
);
|
|
4805
|
+
return [id, b];
|
|
5811
4806
|
})
|
|
5812
4807
|
);
|
|
5813
4808
|
let successCount = 0;
|
|
@@ -5827,9 +4822,9 @@ var OwneySDK = class {
|
|
|
5827
4822
|
const reason = settledResult.reason;
|
|
5828
4823
|
agentFailures.push(reason);
|
|
5829
4824
|
const retryDelay = rateLimitDelay(reason);
|
|
5830
|
-
if (retryDelay !== void 0)
|
|
4825
|
+
if (retryDelay !== void 0)
|
|
4826
|
+
agentRetryAt[agentId2] = Date.now() + retryDelay;
|
|
5831
4827
|
agentErrors[agentId2] = reason instanceof Error ? reason.message : String(reason);
|
|
5832
|
-
console.error(`[owney-sdk] Balance fetch failed for agent "${agentId2}":`, reason);
|
|
5833
4828
|
}
|
|
5834
4829
|
if (successCount === 0) {
|
|
5835
4830
|
throw new OwneyError(
|
|
@@ -5855,14 +4850,22 @@ var OwneySDK = class {
|
|
|
5855
4850
|
const chainId = this.requireChainId();
|
|
5856
4851
|
if (agentId) {
|
|
5857
4852
|
const agent = this.getAgent(agentId);
|
|
5858
|
-
return this.readAgent(
|
|
4853
|
+
return this.readAgent(
|
|
4854
|
+
agent,
|
|
4855
|
+
"earnings",
|
|
4856
|
+
() => agent.getEarnings(state, chainId)
|
|
4857
|
+
);
|
|
5859
4858
|
}
|
|
5860
4859
|
let totalEarnings = 0;
|
|
5861
4860
|
const results = {};
|
|
5862
4861
|
const entries = [...this.getActiveAgents().entries()];
|
|
5863
4862
|
const earningsResults = await Promise.all(
|
|
5864
4863
|
entries.map(async ([id, agent]) => {
|
|
5865
|
-
const e = await this.readAgent(
|
|
4864
|
+
const e = await this.readAgent(
|
|
4865
|
+
agent,
|
|
4866
|
+
"earnings",
|
|
4867
|
+
() => agent.getEarnings(state, chainId)
|
|
4868
|
+
);
|
|
5866
4869
|
return [id, e];
|
|
5867
4870
|
})
|
|
5868
4871
|
);
|
|
@@ -6007,11 +5010,12 @@ var OwneySDK = class {
|
|
|
6007
5010
|
),
|
|
6008
5011
|
Promise.all(
|
|
6009
5012
|
entries.map(async ([id, agent]) => {
|
|
6010
|
-
const b = await this.readAgent(
|
|
6011
|
-
|
|
6012
|
-
|
|
6013
|
-
|
|
6014
|
-
|
|
5013
|
+
const b = await this.readAgent(
|
|
5014
|
+
agent,
|
|
5015
|
+
"balances",
|
|
5016
|
+
() => agent.getBalances(state, chainId)
|
|
5017
|
+
);
|
|
5018
|
+
return [id, balanceForApyScope(b, chainId, tokenSymbol)];
|
|
6015
5019
|
})
|
|
6016
5020
|
)
|
|
6017
5021
|
]);
|
|
@@ -6070,7 +5074,12 @@ var OwneySDK = class {
|
|
|
6070
5074
|
const { agentId, filters } = options ?? {};
|
|
6071
5075
|
if (agentId) {
|
|
6072
5076
|
const agent = this.getAgent(agentId);
|
|
6073
|
-
return this.readAgent(
|
|
5077
|
+
return this.readAgent(
|
|
5078
|
+
agent,
|
|
5079
|
+
"history",
|
|
5080
|
+
() => agent.getHistory(state, chainId, filters),
|
|
5081
|
+
filters
|
|
5082
|
+
);
|
|
6074
5083
|
}
|
|
6075
5084
|
const activeAgents = [...this.getActiveAgents().values()];
|
|
6076
5085
|
const cursorMap = filters?.cursor ? decodeMultiAgentCursor(filters.cursor) : {};
|
|
@@ -6127,13 +5136,21 @@ var OwneySDK = class {
|
|
|
6127
5136
|
const chainId = this.requireChainId();
|
|
6128
5137
|
if (agentId) {
|
|
6129
5138
|
const agent = this.getAgent(agentId);
|
|
6130
|
-
return this.readAgent(
|
|
5139
|
+
return this.readAgent(
|
|
5140
|
+
agent,
|
|
5141
|
+
"profile",
|
|
5142
|
+
() => agent.getUserProfile(state, chainId)
|
|
5143
|
+
);
|
|
6131
5144
|
}
|
|
6132
5145
|
const results = {};
|
|
6133
5146
|
const entries = [...this.getActiveAgents().entries()];
|
|
6134
5147
|
const profileResults = await Promise.all(
|
|
6135
5148
|
entries.map(async ([id, agent]) => {
|
|
6136
|
-
const p = await this.readAgent(
|
|
5149
|
+
const p = await this.readAgent(
|
|
5150
|
+
agent,
|
|
5151
|
+
"profile",
|
|
5152
|
+
() => agent.getUserProfile(state, chainId)
|
|
5153
|
+
);
|
|
6137
5154
|
return [id, p];
|
|
6138
5155
|
})
|
|
6139
5156
|
);
|
|
@@ -6172,44 +5189,43 @@ var OwneySDK = class {
|
|
|
6172
5189
|
return pending;
|
|
6173
5190
|
}
|
|
6174
5191
|
/**
|
|
6175
|
-
*
|
|
6176
|
-
*
|
|
6177
|
-
*
|
|
6178
|
-
*
|
|
6179
|
-
*
|
|
6180
|
-
* @param requiredAmount Raw base-unit amount the pending deposit must cover.
|
|
5192
|
+
* One-time, user-paid approval of Permit2 on the sponsored WETH token for
|
|
5193
|
+
* the active chain. Required once per wallet per chain before gasless WETH
|
|
5194
|
+
* deposits; afterwards deposit() is signature-only. Resolves only after the
|
|
5195
|
+
* approval transaction is mined (1 confirmation), so a subsequent deposit()
|
|
5196
|
+
* will see the new allowance; throws if the transaction reverted.
|
|
6181
5197
|
* @returns the approval transaction hash.
|
|
6182
5198
|
*/
|
|
6183
|
-
async approvePermit2(asset = "WETH"
|
|
5199
|
+
async approvePermit2(asset = "WETH") {
|
|
5200
|
+
void asset;
|
|
6184
5201
|
const state = this.requireState();
|
|
6185
5202
|
const chainId = this.requireChainId();
|
|
6186
|
-
this.
|
|
6187
|
-
const token =
|
|
5203
|
+
this.validateAssetSupport(this.getAgent("zyfai"), chainId, "WETH");
|
|
5204
|
+
const token = SPONSORED_WETH_BY_CHAIN[chainId];
|
|
6188
5205
|
if (!token) {
|
|
6189
5206
|
throw new OwneyError(
|
|
6190
5207
|
"CHAIN_UNSUPPORTED",
|
|
6191
|
-
`No sponsored
|
|
5208
|
+
`No sponsored WETH on chain ${chainId}`
|
|
6192
5209
|
);
|
|
6193
5210
|
}
|
|
6194
5211
|
const provider = this.requireConnectedProvider();
|
|
6195
|
-
const
|
|
6196
|
-
chain: VIEM_CHAIN2[chainId],
|
|
6197
|
-
transport: (0, import_viem11.custom)(provider)
|
|
6198
|
-
});
|
|
6199
|
-
const approvalAmount = permit2ApprovalAmount(requiredAmount);
|
|
6200
|
-
const wallet = (0, import_viem11.createWalletClient)({
|
|
5212
|
+
const wallet = (0, import_viem8.createWalletClient)({
|
|
6201
5213
|
account: state.walletAddress,
|
|
6202
5214
|
chain: VIEM_CHAIN2[chainId],
|
|
6203
|
-
transport: (0,
|
|
5215
|
+
transport: (0, import_viem8.custom)(provider)
|
|
6204
5216
|
});
|
|
6205
5217
|
const hash = await wallet.writeContract({
|
|
6206
5218
|
address: token,
|
|
6207
5219
|
abi: ERC20_ALLOWANCE_ABI,
|
|
6208
5220
|
functionName: "approve",
|
|
6209
|
-
args: [PERMIT2_ADDRESS,
|
|
5221
|
+
args: [PERMIT2_ADDRESS, MAX_UINT256],
|
|
6210
5222
|
account: state.walletAddress,
|
|
6211
5223
|
chain: VIEM_CHAIN2[chainId]
|
|
6212
5224
|
});
|
|
5225
|
+
const publicClient = (0, import_viem8.createPublicClient)({
|
|
5226
|
+
chain: VIEM_CHAIN2[chainId],
|
|
5227
|
+
transport: (0, import_viem8.custom)(provider)
|
|
5228
|
+
});
|
|
6213
5229
|
const receipt = await publicClient.waitForTransactionReceipt({
|
|
6214
5230
|
hash,
|
|
6215
5231
|
confirmations: 1
|
|
@@ -6242,15 +5258,23 @@ var OwneySDK = class {
|
|
|
6242
5258
|
const agentOptions = { tokenSymbol, chainId };
|
|
6243
5259
|
if (agentId) {
|
|
6244
5260
|
const agent = this.getAgent(agentId);
|
|
6245
|
-
return this.readAgent(
|
|
5261
|
+
return this.readAgent(
|
|
5262
|
+
agent,
|
|
5263
|
+
"agentApy",
|
|
5264
|
+
() => agent.getAgentApy(days, agentOptions),
|
|
5265
|
+
{ days, ...agentOptions }
|
|
5266
|
+
);
|
|
6246
5267
|
}
|
|
6247
5268
|
const results = {};
|
|
6248
|
-
const agentEntries = [...this.agents.entries()]
|
|
6249
|
-
([id]) => !this.isAgentDisabled(id)
|
|
6250
|
-
);
|
|
5269
|
+
const agentEntries = [...this.agents.entries()];
|
|
6251
5270
|
const apyResults = await Promise.all(
|
|
6252
5271
|
agentEntries.map(async ([id, agent]) => {
|
|
6253
|
-
const apy = await this.readAgent(
|
|
5272
|
+
const apy = await this.readAgent(
|
|
5273
|
+
agent,
|
|
5274
|
+
"agentApy",
|
|
5275
|
+
() => agent.getAgentApy(days, agentOptions),
|
|
5276
|
+
{ days, ...agentOptions }
|
|
5277
|
+
);
|
|
6254
5278
|
return [id, apy];
|
|
6255
5279
|
})
|
|
6256
5280
|
);
|
|
@@ -6277,7 +5301,11 @@ var OwneySDK = class {
|
|
|
6277
5301
|
const entries = [...activeAgents.entries()];
|
|
6278
5302
|
const balanceResults = await Promise.allSettled(
|
|
6279
5303
|
entries.map(async ([id, agent]) => {
|
|
6280
|
-
const b = await this.readAgent(
|
|
5304
|
+
const b = await this.readAgent(
|
|
5305
|
+
agent,
|
|
5306
|
+
"balances",
|
|
5307
|
+
() => agent.getBalances(state, chainId)
|
|
5308
|
+
);
|
|
6281
5309
|
return [id, b.positions ?? []];
|
|
6282
5310
|
})
|
|
6283
5311
|
);
|
|
@@ -6322,13 +5350,13 @@ var OwneySDK = class {
|
|
|
6322
5350
|
};
|
|
6323
5351
|
|
|
6324
5352
|
// src/agents/zyfai/zyfai.siwx.ts
|
|
6325
|
-
var
|
|
6326
|
-
var
|
|
5353
|
+
var import_viem9 = require("viem");
|
|
5354
|
+
var import_siwe = require("siwe");
|
|
6327
5355
|
var import_sdk2 = require("@zyfai/sdk");
|
|
6328
5356
|
|
|
6329
5357
|
// src/agents/zyfai/zyfai.siwx-cache.ts
|
|
6330
|
-
var
|
|
6331
|
-
var
|
|
5358
|
+
var KEY_PREFIX3 = "owney.siwx.session";
|
|
5359
|
+
var storage3 = () => {
|
|
6332
5360
|
if (typeof window === "undefined") return null;
|
|
6333
5361
|
try {
|
|
6334
5362
|
return window.localStorage;
|
|
@@ -6336,8 +5364,8 @@ var storage4 = () => {
|
|
|
6336
5364
|
return null;
|
|
6337
5365
|
}
|
|
6338
5366
|
};
|
|
6339
|
-
var
|
|
6340
|
-
var legacyKeyPrefix2 = (address) => `${
|
|
5367
|
+
var buildKey2 = (address) => `${KEY_PREFIX3}:${address.toLowerCase()}`;
|
|
5368
|
+
var legacyKeyPrefix2 = (address) => `${KEY_PREFIX3}:${address.toLowerCase()}:`;
|
|
6341
5369
|
var memorySiwxSessions = /* @__PURE__ */ new Map();
|
|
6342
5370
|
var readLegacySiwxSession = (store, address) => {
|
|
6343
5371
|
if (!store) return null;
|
|
@@ -6368,17 +5396,17 @@ var readLegacySiwxSession = (store, address) => {
|
|
|
6368
5396
|
};
|
|
6369
5397
|
var readSiwxSession = (address, chainId) => {
|
|
6370
5398
|
if (typeof window === "undefined") return null;
|
|
6371
|
-
const key2 =
|
|
6372
|
-
const store =
|
|
6373
|
-
let
|
|
5399
|
+
const key2 = buildKey2(address);
|
|
5400
|
+
const store = storage3();
|
|
5401
|
+
let raw = null;
|
|
6374
5402
|
try {
|
|
6375
|
-
|
|
5403
|
+
raw = store?.getItem(key2) ?? null;
|
|
6376
5404
|
} catch {
|
|
6377
|
-
|
|
5405
|
+
raw = null;
|
|
6378
5406
|
}
|
|
6379
|
-
if (
|
|
5407
|
+
if (raw) {
|
|
6380
5408
|
try {
|
|
6381
|
-
return JSON.parse(
|
|
5409
|
+
return JSON.parse(raw);
|
|
6382
5410
|
} catch {
|
|
6383
5411
|
memorySiwxSessions.delete(key2);
|
|
6384
5412
|
try {
|
|
@@ -6397,18 +5425,18 @@ var readSiwxSession = (address, chainId) => {
|
|
|
6397
5425
|
};
|
|
6398
5426
|
var writeSiwxSession = (address, _chainId, session) => {
|
|
6399
5427
|
if (typeof window === "undefined") return;
|
|
6400
|
-
const key2 =
|
|
5428
|
+
const key2 = buildKey2(address);
|
|
6401
5429
|
memorySiwxSessions.set(key2, session);
|
|
6402
|
-
const store =
|
|
5430
|
+
const store = storage3();
|
|
6403
5431
|
try {
|
|
6404
5432
|
store?.setItem(key2, JSON.stringify(session));
|
|
6405
5433
|
} catch {
|
|
6406
5434
|
}
|
|
6407
5435
|
};
|
|
6408
5436
|
var clearSiwxSession = (address, _chainId) => {
|
|
6409
|
-
const key2 =
|
|
5437
|
+
const key2 = buildKey2(address);
|
|
6410
5438
|
memorySiwxSessions.delete(key2);
|
|
6411
|
-
const store =
|
|
5439
|
+
const store = storage3();
|
|
6412
5440
|
try {
|
|
6413
5441
|
store?.removeItem(key2);
|
|
6414
5442
|
} catch {
|
|
@@ -6448,8 +5476,8 @@ function buildSIWXConfig(deps) {
|
|
|
6448
5476
|
statement: STATEMENT,
|
|
6449
5477
|
issuedAt,
|
|
6450
5478
|
toString() {
|
|
6451
|
-
return new
|
|
6452
|
-
address: (0,
|
|
5479
|
+
return new import_siwe.SiweMessage({
|
|
5480
|
+
address: (0, import_viem9.getAddress)(accountAddress),
|
|
6453
5481
|
chainId: numericChainId(chainId),
|
|
6454
5482
|
domain,
|
|
6455
5483
|
uri,
|
|
@@ -6491,7 +5519,7 @@ function buildSIWXConfig(deps) {
|
|
|
6491
5519
|
const persistSession = async (session) => {
|
|
6492
5520
|
const address = session.data.accountAddress;
|
|
6493
5521
|
const id = numericChainId(session.data.chainId);
|
|
6494
|
-
const message = new
|
|
5522
|
+
const message = new import_siwe.SiweMessage(session.message);
|
|
6495
5523
|
const login = await post("/auth/login", {
|
|
6496
5524
|
message,
|
|
6497
5525
|
signature: session.signature,
|
|
@@ -6527,9 +5555,9 @@ function buildSIWXConfig(deps) {
|
|
|
6527
5555
|
}
|
|
6528
5556
|
function createOwneySIWX(config) {
|
|
6529
5557
|
const zyfai = new import_sdk2.ZyfaiSDK({ apiKey: config.apiKey });
|
|
6530
|
-
const
|
|
5558
|
+
const http4 = zyfai.httpClient;
|
|
6531
5559
|
return buildSIWXConfig({
|
|
6532
|
-
post: (url, data) =>
|
|
5560
|
+
post: (url, data) => http4.post(url, data),
|
|
6533
5561
|
referralSource: config.referralSource
|
|
6534
5562
|
});
|
|
6535
5563
|
}
|
|
@@ -6541,7 +5569,7 @@ function createOwneySIWX(config) {
|
|
|
6541
5569
|
NotConnectedError,
|
|
6542
5570
|
OwneyError,
|
|
6543
5571
|
OwneySDK,
|
|
6544
|
-
YieldseekerAgent,
|
|
6545
5572
|
createOwneySIWX,
|
|
5573
|
+
listPendingSwaps,
|
|
6546
5574
|
setOwneyDebug
|
|
6547
5575
|
});
|