@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.js
CHANGED
|
@@ -1,23 +1,3 @@
|
|
|
1
|
-
// src/lib/deposit-batch-callback.ts
|
|
2
|
-
var batchCallbacks = /* @__PURE__ */ new WeakMap();
|
|
3
|
-
var getDepositBatchTransfer = (callback) => callback ? batchCallbacks.get(callback) : void 0;
|
|
4
|
-
function toBatchTransfer(to, amount, verification) {
|
|
5
|
-
return {
|
|
6
|
-
to,
|
|
7
|
-
amount,
|
|
8
|
-
...verification ? {
|
|
9
|
-
yieldseeker: {
|
|
10
|
-
signature: verification.signature,
|
|
11
|
-
userId: verification.userId,
|
|
12
|
-
agentId: verification.yieldseekerAgentId
|
|
13
|
-
}
|
|
14
|
-
} : {}
|
|
15
|
-
};
|
|
16
|
-
}
|
|
17
|
-
function registerDepositBatch(callback, transfer) {
|
|
18
|
-
batchCallbacks.set(callback, transfer);
|
|
19
|
-
}
|
|
20
|
-
|
|
21
1
|
// src/errors.ts
|
|
22
2
|
var OwneyError = class extends Error {
|
|
23
3
|
code;
|
|
@@ -297,18 +277,18 @@ function tokenDecimals(symbol, explicit) {
|
|
|
297
277
|
return explicit;
|
|
298
278
|
return DECIMALS_BY_SYMBOL[(symbol ?? "").toLowerCase()] ?? 6;
|
|
299
279
|
}
|
|
300
|
-
function mapDeposit(
|
|
280
|
+
function mapDeposit(raw) {
|
|
301
281
|
return {
|
|
302
|
-
txHash:
|
|
303
|
-
smartWallet:
|
|
304
|
-
amount:
|
|
282
|
+
txHash: raw.txHash,
|
|
283
|
+
smartWallet: raw.smartWallet,
|
|
284
|
+
amount: raw.amount
|
|
305
285
|
};
|
|
306
286
|
}
|
|
307
|
-
function mapWithdraw(
|
|
287
|
+
function mapWithdraw(raw) {
|
|
308
288
|
return {
|
|
309
|
-
txHash:
|
|
310
|
-
type:
|
|
311
|
-
amount:
|
|
289
|
+
txHash: raw.txHash,
|
|
290
|
+
type: raw.type,
|
|
291
|
+
amount: raw.amount
|
|
312
292
|
};
|
|
313
293
|
}
|
|
314
294
|
var CHAIN_ID_TO_NAME = {
|
|
@@ -327,10 +307,10 @@ function resolveChainId(chain) {
|
|
|
327
307
|
if (Number.isFinite(asNum) && asNum > 0) return asNum;
|
|
328
308
|
return NAME_TO_CHAIN_ID[chain.trim().toLowerCase()] ?? NaN;
|
|
329
309
|
}
|
|
330
|
-
function mapPendingAllocations(
|
|
331
|
-
if (!Array.isArray(
|
|
310
|
+
function mapPendingAllocations(raw) {
|
|
311
|
+
if (!Array.isArray(raw)) return void 0;
|
|
332
312
|
const pending = [];
|
|
333
|
-
for (const entry of
|
|
313
|
+
for (const entry of raw) {
|
|
334
314
|
if (typeof entry !== "object" || entry === null) continue;
|
|
335
315
|
const e = entry;
|
|
336
316
|
if (typeof e.chainId !== "number" || !Number.isFinite(e.chainId)) continue;
|
|
@@ -353,8 +333,8 @@ function mapPendingAllocations(raw2) {
|
|
|
353
333
|
}
|
|
354
334
|
return pending.length > 0 ? pending : void 0;
|
|
355
335
|
}
|
|
356
|
-
function mapBalances(
|
|
357
|
-
const portfolio =
|
|
336
|
+
function mapBalances(raw, _chainId, smartWallet) {
|
|
337
|
+
const portfolio = raw.portfolio;
|
|
358
338
|
const portfolioByChain = portfolio.portfolioByChain ?? {};
|
|
359
339
|
let totalBalance = 0;
|
|
360
340
|
const tokens = [];
|
|
@@ -423,8 +403,8 @@ function sumTokenValues(tokens) {
|
|
|
423
403
|
function sumTokenEarnings(tokens) {
|
|
424
404
|
return Object.values(tokens).reduce((sum, val) => sum + Number(val), 0);
|
|
425
405
|
}
|
|
426
|
-
function mapEarnings(
|
|
427
|
-
const totalEarningsByChain =
|
|
406
|
+
function mapEarnings(raw, smartWallet) {
|
|
407
|
+
const totalEarningsByChain = raw.data.totalEarningsByChainWithFee ?? raw.data.totalEarningsByChain ?? {};
|
|
428
408
|
const tokens = [];
|
|
429
409
|
for (const [chainIdKey, tokensBySymbol] of Object.entries(
|
|
430
410
|
totalEarningsByChain
|
|
@@ -443,15 +423,15 @@ function mapEarnings(raw2, smartWallet) {
|
|
|
443
423
|
return {
|
|
444
424
|
smartWallet,
|
|
445
425
|
lifetimeEarnings: sumTokenEarnings(
|
|
446
|
-
|
|
426
|
+
raw.data.totalEarningsByTokenWithFee ?? raw.data.totalEarningsByToken
|
|
447
427
|
),
|
|
448
428
|
tokens
|
|
449
429
|
};
|
|
450
430
|
}
|
|
451
|
-
function mapWeightedApyByChain(
|
|
452
|
-
if (!
|
|
431
|
+
function mapWeightedApyByChain(raw) {
|
|
432
|
+
if (!raw) return void 0;
|
|
453
433
|
const out = {};
|
|
454
|
-
for (const [chainKey, tokenApy] of Object.entries(
|
|
434
|
+
for (const [chainKey, tokenApy] of Object.entries(raw)) {
|
|
455
435
|
const chainId = Number(chainKey);
|
|
456
436
|
if (!SUPPORTED_CHAIN_IDS.includes(chainId)) continue;
|
|
457
437
|
const perAsset = {};
|
|
@@ -491,8 +471,8 @@ function rawPoolApyForChain(entry, chainId, tokenSymbol) {
|
|
|
491
471
|
}
|
|
492
472
|
return totalBalance > 0 ? weightedSum / totalBalance : null;
|
|
493
473
|
}
|
|
494
|
-
function mapApyHistory(
|
|
495
|
-
const history = Object.entries(
|
|
474
|
+
function mapApyHistory(raw, chainId, tokenSymbol) {
|
|
475
|
+
const history = Object.entries(raw.history ?? {}).map(([date, entry]) => ({
|
|
496
476
|
date,
|
|
497
477
|
apy: rawPoolApyForChain(entry, chainId, tokenSymbol),
|
|
498
478
|
// Provider position balances are treated as decimal amounts of the
|
|
@@ -508,9 +488,9 @@ function mapApyHistory(raw2, chainId, tokenSymbol) {
|
|
|
508
488
|
} : {}
|
|
509
489
|
})).filter((p) => p.apy !== null).sort((a, b) => a.date.localeCompare(b.date));
|
|
510
490
|
return {
|
|
511
|
-
walletAddress:
|
|
512
|
-
weightedApyAfterFee:
|
|
513
|
-
apyByChainAndAsset: mapWeightedApyByChain(
|
|
491
|
+
walletAddress: raw.walletAddress,
|
|
492
|
+
weightedApyAfterFee: raw.weightedApyAfterFee ? sumTokenValues(raw.weightedApyAfterFee) : void 0,
|
|
493
|
+
apyByChainAndAsset: mapWeightedApyByChain(raw.weightedApyAfterFeeByChain),
|
|
514
494
|
history
|
|
515
495
|
};
|
|
516
496
|
}
|
|
@@ -606,23 +586,23 @@ function mapEntries(rawEntries, chainId) {
|
|
|
606
586
|
};
|
|
607
587
|
});
|
|
608
588
|
}
|
|
609
|
-
function mapUserProfile(
|
|
589
|
+
function mapUserProfile(raw, userAddress) {
|
|
610
590
|
return {
|
|
611
591
|
address: userAddress,
|
|
612
|
-
smartWallet:
|
|
613
|
-
chains:
|
|
614
|
-
strategy:
|
|
615
|
-
hasActiveSessionKey:
|
|
616
|
-
protocols:
|
|
617
|
-
splitting:
|
|
618
|
-
minSplits:
|
|
592
|
+
smartWallet: raw.smartWallet || "",
|
|
593
|
+
chains: raw.chains || [],
|
|
594
|
+
strategy: raw.strategy,
|
|
595
|
+
hasActiveSessionKey: raw.hasActiveSessionKey || false,
|
|
596
|
+
protocols: raw.protocols || [],
|
|
597
|
+
splitting: raw.splitting,
|
|
598
|
+
minSplits: raw.minSplits
|
|
619
599
|
};
|
|
620
600
|
}
|
|
621
|
-
function mapApyByStrategy(
|
|
601
|
+
function mapApyByStrategy(raw) {
|
|
622
602
|
const apyPerAsset = {};
|
|
623
603
|
let apySum = 0;
|
|
624
604
|
let apyCount = 0;
|
|
625
|
-
for (const entry of
|
|
605
|
+
for (const entry of raw.data) {
|
|
626
606
|
const supported = SupportedAssets.find(
|
|
627
607
|
(asset) => asset.chainId === entry.chain_id && asset.symbol === entry.token_symbol
|
|
628
608
|
);
|
|
@@ -734,9 +714,9 @@ function netDeltaForSnapshot(entry, chainId, asset) {
|
|
|
734
714
|
debugLog("zyfai:earnings", "gross fallback for daily earnings", { gross });
|
|
735
715
|
return gross;
|
|
736
716
|
}
|
|
737
|
-
function mapDailyEarnings(
|
|
717
|
+
function mapDailyEarnings(raw, chainId, tokenSymbol) {
|
|
738
718
|
const wanted = tokenSymbol?.toUpperCase();
|
|
739
|
-
const snapshots = [...
|
|
719
|
+
const snapshots = [...raw.data ?? []].sort(
|
|
740
720
|
(a, b) => a.snapshot_date.localeCompare(b.snapshot_date)
|
|
741
721
|
);
|
|
742
722
|
const byAsset = /* @__PURE__ */ new Map();
|
|
@@ -751,7 +731,7 @@ function mapDailyEarnings(raw2, chainId, tokenSymbol) {
|
|
|
751
731
|
}
|
|
752
732
|
}
|
|
753
733
|
const assets = [...byAsset.entries()].map(([asset, series]) => ({ asset, points: series.points })).sort((a, b) => a.asset.localeCompare(b.asset));
|
|
754
|
-
return { walletAddress:
|
|
734
|
+
return { walletAddress: raw.walletAddress, chainId, assets };
|
|
755
735
|
}
|
|
756
736
|
|
|
757
737
|
// src/agents/zyfai/zyfai.withdraw-amount.ts
|
|
@@ -862,15 +842,15 @@ var readSession = (address, _chainId) => {
|
|
|
862
842
|
if (typeof window === "undefined") return null;
|
|
863
843
|
const key2 = buildKey(address);
|
|
864
844
|
const store = storage();
|
|
865
|
-
let
|
|
845
|
+
let raw = null;
|
|
866
846
|
try {
|
|
867
|
-
|
|
847
|
+
raw = store?.getItem(key2) ?? null;
|
|
868
848
|
} catch {
|
|
869
|
-
|
|
849
|
+
raw = null;
|
|
870
850
|
}
|
|
871
|
-
if (
|
|
851
|
+
if (raw) {
|
|
872
852
|
try {
|
|
873
|
-
const parsed = JSON.parse(
|
|
853
|
+
const parsed = JSON.parse(raw);
|
|
874
854
|
if (isFreshSession(parsed)) return parsed;
|
|
875
855
|
} catch {
|
|
876
856
|
}
|
|
@@ -1038,8 +1018,8 @@ function buildChainsByProtocol(protocols, dashboardChainIds) {
|
|
|
1038
1018
|
}
|
|
1039
1019
|
return result;
|
|
1040
1020
|
}
|
|
1041
|
-
function flattenAvailablePools(
|
|
1042
|
-
const byChain =
|
|
1021
|
+
function flattenAvailablePools(raw) {
|
|
1022
|
+
const byChain = raw ?? {};
|
|
1043
1023
|
const names = [];
|
|
1044
1024
|
for (const byToken of Object.values(byChain ?? {})) {
|
|
1045
1025
|
for (const entry of Object.values(byToken ?? {})) {
|
|
@@ -1542,8 +1522,8 @@ var ZyfaiAgent = class _ZyfaiAgent {
|
|
|
1542
1522
|
const poolResults = await Promise.all(
|
|
1543
1523
|
universe.map(async (protocol) => {
|
|
1544
1524
|
try {
|
|
1545
|
-
const
|
|
1546
|
-
return [protocol.id, flattenAvailablePools(
|
|
1525
|
+
const raw = await this.sdk.getAvailablePools(protocol.id, strategy);
|
|
1526
|
+
return [protocol.id, flattenAvailablePools(raw)];
|
|
1547
1527
|
} catch (error) {
|
|
1548
1528
|
console.warn(
|
|
1549
1529
|
`[zyfai] applyPoolPolicy: getAvailablePools(${protocol.id}) failed, skipping this protocol (non-fatal):`,
|
|
@@ -1609,14 +1589,14 @@ var ZyfaiAgent = class _ZyfaiAgent {
|
|
|
1609
1589
|
async readWalletState(ownerAddress) {
|
|
1610
1590
|
try {
|
|
1611
1591
|
const { portfolio } = await this.sdk.getPositions(ownerAddress);
|
|
1612
|
-
const
|
|
1592
|
+
const raw = portfolio;
|
|
1613
1593
|
debugLog("zyfai:onboard", "wallet state from getPositions", {
|
|
1614
|
-
predeployed:
|
|
1615
|
-
hasActiveSessionKey:
|
|
1594
|
+
predeployed: raw?.predeployed,
|
|
1595
|
+
hasActiveSessionKey: raw?.hasActiveSessionKey
|
|
1616
1596
|
});
|
|
1617
1597
|
return {
|
|
1618
|
-
predeployed:
|
|
1619
|
-
hasActiveSessionKey:
|
|
1598
|
+
predeployed: raw?.predeployed,
|
|
1599
|
+
hasActiveSessionKey: raw?.hasActiveSessionKey
|
|
1620
1600
|
};
|
|
1621
1601
|
} catch (error) {
|
|
1622
1602
|
console.warn(
|
|
@@ -1902,14 +1882,14 @@ var ZyfaiAgent = class _ZyfaiAgent {
|
|
|
1902
1882
|
return { txHash, smartWallet, amount };
|
|
1903
1883
|
}
|
|
1904
1884
|
await this.ensureWalletDeployed(this.getAddress(), validChainId);
|
|
1905
|
-
const
|
|
1885
|
+
const raw = await this.sdk.depositFunds(
|
|
1906
1886
|
this.getAddress(),
|
|
1907
1887
|
validChainId,
|
|
1908
1888
|
amount,
|
|
1909
1889
|
asset,
|
|
1910
1890
|
"aggressive"
|
|
1911
1891
|
);
|
|
1912
|
-
return mapDeposit(
|
|
1892
|
+
return mapDeposit(raw);
|
|
1913
1893
|
} catch (error) {
|
|
1914
1894
|
throw error;
|
|
1915
1895
|
}
|
|
@@ -1918,27 +1898,27 @@ var ZyfaiAgent = class _ZyfaiAgent {
|
|
|
1918
1898
|
async withdraw(state, chainId, token, amount) {
|
|
1919
1899
|
const validChainId = isValidChainId(chainId);
|
|
1920
1900
|
await this.ensureConnected(state, validChainId);
|
|
1921
|
-
const
|
|
1901
|
+
const raw = await this.sdk.withdrawFunds(
|
|
1922
1902
|
this.getAddress(),
|
|
1923
1903
|
validChainId,
|
|
1924
1904
|
amount,
|
|
1925
1905
|
token
|
|
1926
1906
|
);
|
|
1927
|
-
if (!
|
|
1907
|
+
if (!raw.success) {
|
|
1928
1908
|
throw new OwneyError(
|
|
1929
1909
|
"WITHDRAW_FAILED",
|
|
1930
|
-
|
|
1931
|
-
{ chainId: validChainId, token, amount, response:
|
|
1910
|
+
raw.message || "Zyfai withdraw failed.",
|
|
1911
|
+
{ chainId: validChainId, token, amount, response: raw },
|
|
1932
1912
|
this.id
|
|
1933
1913
|
);
|
|
1934
1914
|
}
|
|
1935
|
-
return mapWithdraw(
|
|
1915
|
+
return mapWithdraw(raw);
|
|
1936
1916
|
}
|
|
1937
1917
|
// --- IAgent: Portfolio reads ---
|
|
1938
1918
|
async getBalances(state, chainId) {
|
|
1939
1919
|
const { smartWallet, chainId: validChainId } = await this.resolveSmartWallet(state, chainId);
|
|
1940
|
-
const
|
|
1941
|
-
return mapBalances(
|
|
1920
|
+
const raw = await this.sdk.getPortfolio(this.getAddress());
|
|
1921
|
+
return mapBalances(raw, validChainId, smartWallet);
|
|
1942
1922
|
}
|
|
1943
1923
|
earningsKey(state, chainId, smartWallet) {
|
|
1944
1924
|
return JSON.stringify([
|
|
@@ -1951,11 +1931,11 @@ var ZyfaiAgent = class _ZyfaiAgent {
|
|
|
1951
1931
|
const existing = this.earningsReads.get(key2);
|
|
1952
1932
|
if (existing) return existing;
|
|
1953
1933
|
const generation = this.earningsGeneration;
|
|
1954
|
-
const pending = Promise.resolve().then(() => this.sdk.getOnchainEarnings(smartWallet)).then((
|
|
1934
|
+
const pending = Promise.resolve().then(() => this.sdk.getOnchainEarnings(smartWallet)).then((raw) => {
|
|
1955
1935
|
if (generation === this.earningsGeneration) {
|
|
1956
|
-
this.earningsSnapshot = { key: key2, raw
|
|
1936
|
+
this.earningsSnapshot = { key: key2, raw, at: Date.now() };
|
|
1957
1937
|
}
|
|
1958
|
-
return
|
|
1938
|
+
return raw;
|
|
1959
1939
|
}).finally(() => {
|
|
1960
1940
|
if (this.earningsReads.get(key2) === pending)
|
|
1961
1941
|
this.earningsReads.delete(key2);
|
|
@@ -1965,11 +1945,11 @@ var ZyfaiAgent = class _ZyfaiAgent {
|
|
|
1965
1945
|
}
|
|
1966
1946
|
async getEarnings(state, chainId) {
|
|
1967
1947
|
const { smartWallet } = await this.resolveSmartWallet(state, chainId);
|
|
1968
|
-
const
|
|
1948
|
+
const raw = await this.readEarnings(
|
|
1969
1949
|
this.earningsKey(state, chainId, smartWallet),
|
|
1970
1950
|
smartWallet
|
|
1971
1951
|
);
|
|
1972
|
-
return mapEarnings(
|
|
1952
|
+
return mapEarnings(raw, smartWallet);
|
|
1973
1953
|
}
|
|
1974
1954
|
async refreshEarnings(state, chainId) {
|
|
1975
1955
|
const { smartWallet } = await this.resolveSmartWallet(state, chainId);
|
|
@@ -1996,17 +1976,17 @@ var ZyfaiAgent = class _ZyfaiAgent {
|
|
|
1996
1976
|
}
|
|
1997
1977
|
async getAccountApy(state, chainId, days, tokenSymbol) {
|
|
1998
1978
|
const { smartWallet } = await this.resolveSmartWallet(state, chainId);
|
|
1999
|
-
const
|
|
2000
|
-
return mapApyHistory(
|
|
1979
|
+
const raw = await this.sdk.getDailyApyHistory(smartWallet, days);
|
|
1980
|
+
return mapApyHistory(raw, chainId, tokenSymbol);
|
|
2001
1981
|
}
|
|
2002
1982
|
async getDailyEarnings(state, chainId, days, tokenSymbol) {
|
|
2003
1983
|
const { smartWallet } = await this.resolveSmartWallet(state, chainId);
|
|
2004
1984
|
const start = new Date(Date.now() - (DayFilterMapping[days] + 1) * 864e5);
|
|
2005
|
-
const
|
|
1985
|
+
const raw = await this.sdk.getDailyEarnings(
|
|
2006
1986
|
smartWallet,
|
|
2007
1987
|
start.toISOString().slice(0, 10)
|
|
2008
1988
|
);
|
|
2009
|
-
return mapDailyEarnings(
|
|
1989
|
+
return mapDailyEarnings(raw, chainId, tokenSymbol);
|
|
2010
1990
|
}
|
|
2011
1991
|
/**
|
|
2012
1992
|
* Owney speaks asset symbols ("USDC" / "WETH"); Zyfai's history endpoint
|
|
@@ -2041,7 +2021,7 @@ var ZyfaiAgent = class _ZyfaiAgent {
|
|
|
2041
2021
|
const matched = [];
|
|
2042
2022
|
let backendExhausted = false;
|
|
2043
2023
|
for (let i = 0; i < MAX_BACKEND_CALLS && matched.length < limit; i++) {
|
|
2044
|
-
const
|
|
2024
|
+
const raw = await this.sdk.getHistory(smartWallet, validChainId, {
|
|
2045
2025
|
limit: backendPageSize,
|
|
2046
2026
|
offset,
|
|
2047
2027
|
fromDate: options?.fromDate,
|
|
@@ -2052,13 +2032,13 @@ var ZyfaiAgent = class _ZyfaiAgent {
|
|
|
2052
2032
|
// asset's rows and handing back a page that filters to nothing.
|
|
2053
2033
|
assetType
|
|
2054
2034
|
});
|
|
2055
|
-
|
|
2035
|
+
raw.data.forEach((entry, idx) => {
|
|
2056
2036
|
if (entry.chainId === validChainId) {
|
|
2057
2037
|
matched.push({ entry, rawIdx: offset + idx });
|
|
2058
2038
|
}
|
|
2059
2039
|
});
|
|
2060
|
-
offset +=
|
|
2061
|
-
if (
|
|
2040
|
+
offset += raw.data.length;
|
|
2041
|
+
if (raw.data.length < backendPageSize) {
|
|
2062
2042
|
backendExhausted = true;
|
|
2063
2043
|
break;
|
|
2064
2044
|
}
|
|
@@ -2080,18 +2060,18 @@ var ZyfaiAgent = class _ZyfaiAgent {
|
|
|
2080
2060
|
}
|
|
2081
2061
|
async getUserProfile(state, chainId) {
|
|
2082
2062
|
await this.connectAuth(state, chainId);
|
|
2083
|
-
const
|
|
2063
|
+
const raw = await this.sdk.getUserDetails();
|
|
2084
2064
|
debugLog("zyfai:profile", "getUserProfile \u2014 Zyfai reports", {
|
|
2085
2065
|
asset: "USDC (default \u2014 no asset passed)",
|
|
2086
|
-
splitting:
|
|
2087
|
-
minSplits:
|
|
2088
|
-
strategy:
|
|
2089
|
-
chains:
|
|
2090
|
-
protocolCount:
|
|
2091
|
-
hasActiveSessionKey:
|
|
2092
|
-
smartWallet:
|
|
2066
|
+
splitting: raw.splitting,
|
|
2067
|
+
minSplits: raw.minSplits,
|
|
2068
|
+
strategy: raw.strategy,
|
|
2069
|
+
chains: raw.chains,
|
|
2070
|
+
protocolCount: raw.protocols?.length,
|
|
2071
|
+
hasActiveSessionKey: raw.hasActiveSessionKey,
|
|
2072
|
+
smartWallet: raw.smartWallet
|
|
2093
2073
|
});
|
|
2094
|
-
return mapUserProfile(
|
|
2074
|
+
return mapUserProfile(raw, this.connectedAddress);
|
|
2095
2075
|
}
|
|
2096
2076
|
async ensureAutoSelectProtocols(state, chainId, asset) {
|
|
2097
2077
|
await this.connectAuth(state, chainId);
|
|
@@ -2110,28 +2090,80 @@ var ZyfaiAgent = class _ZyfaiAgent {
|
|
|
2110
2090
|
}
|
|
2111
2091
|
// --- IAgent: Discovery (no wallet required) ---
|
|
2112
2092
|
async getAgentApy(days, options) {
|
|
2113
|
-
const
|
|
2093
|
+
const raw = await this.sdk.getAPYPerStrategy(
|
|
2114
2094
|
false,
|
|
2115
2095
|
DayFilterMapping[days],
|
|
2116
2096
|
"aggressive",
|
|
2117
2097
|
options?.chainId,
|
|
2118
2098
|
options?.tokenSymbol
|
|
2119
2099
|
);
|
|
2120
|
-
return mapApyByStrategy(
|
|
2100
|
+
return mapApyByStrategy(raw);
|
|
2121
2101
|
}
|
|
2122
2102
|
};
|
|
2123
2103
|
|
|
2124
|
-
// src/
|
|
2125
|
-
|
|
2126
|
-
|
|
2127
|
-
|
|
2128
|
-
|
|
2129
|
-
|
|
2130
|
-
|
|
2131
|
-
|
|
2132
|
-
|
|
2133
|
-
|
|
2134
|
-
|
|
2104
|
+
// src/lib/routing-api.ts
|
|
2105
|
+
var ROUTING_API_BASE_URL = "https://owney-routing-api-243946518160.europe-west4.run.app";
|
|
2106
|
+
async function fetchOrgAgentConfig(apiKey, baseUrl = ROUTING_API_BASE_URL) {
|
|
2107
|
+
const url = `${baseUrl}/api/v1/agent/org-config`;
|
|
2108
|
+
try {
|
|
2109
|
+
const res = await fetch(url, {
|
|
2110
|
+
method: "GET",
|
|
2111
|
+
headers: {
|
|
2112
|
+
"Content-Type": "application/json",
|
|
2113
|
+
"x-owney-api-key": `${apiKey}`
|
|
2114
|
+
}
|
|
2115
|
+
});
|
|
2116
|
+
if (!res.ok) {
|
|
2117
|
+
if (res.status !== 404) {
|
|
2118
|
+
console.warn(
|
|
2119
|
+
`[owney-sdk] Could not read org agent config (${res.status}); leaving user profiles unchanged.`
|
|
2120
|
+
);
|
|
2121
|
+
}
|
|
2122
|
+
return null;
|
|
2123
|
+
}
|
|
2124
|
+
const json = await res.json();
|
|
2125
|
+
const policy = json.success ? json.data ?? null : null;
|
|
2126
|
+
debugLog(
|
|
2127
|
+
"owney-sdk",
|
|
2128
|
+
policy ? "org agent config: loaded" : "org agent config: none set by this partner \u2014 user profiles will be left as they are",
|
|
2129
|
+
policy ?? void 0
|
|
2130
|
+
);
|
|
2131
|
+
return policy;
|
|
2132
|
+
} catch (error) {
|
|
2133
|
+
console.warn(
|
|
2134
|
+
"[owney-sdk] Could not read org agent config (non-fatal):",
|
|
2135
|
+
error instanceof Error ? error.message : String(error)
|
|
2136
|
+
);
|
|
2137
|
+
return null;
|
|
2138
|
+
}
|
|
2139
|
+
}
|
|
2140
|
+
async function fetchAgentKeys(apiKey, baseUrl = ROUTING_API_BASE_URL) {
|
|
2141
|
+
const url = `${baseUrl}/api/v1/agent/keys`;
|
|
2142
|
+
const res = await fetch(url, {
|
|
2143
|
+
method: "GET",
|
|
2144
|
+
headers: {
|
|
2145
|
+
"Content-Type": "application/json",
|
|
2146
|
+
"x-owney-api-key": `${apiKey}`
|
|
2147
|
+
}
|
|
2148
|
+
});
|
|
2149
|
+
if (!res.ok) {
|
|
2150
|
+
const text = await res.text().catch(() => "");
|
|
2151
|
+
throw new OwneyError(
|
|
2152
|
+
"API_ROUTING_ERROR",
|
|
2153
|
+
`Routing API error ${res.status}: ${text}`,
|
|
2154
|
+
{ statusCode: res.status, responseBody: text }
|
|
2155
|
+
);
|
|
2156
|
+
}
|
|
2157
|
+
const json = await res.json();
|
|
2158
|
+
if (!json.success) {
|
|
2159
|
+
throw new OwneyError(
|
|
2160
|
+
"API_ROUTING_FAILED",
|
|
2161
|
+
`Routing API request failed: ${json.message}`,
|
|
2162
|
+
{ message: json.message }
|
|
2163
|
+
);
|
|
2164
|
+
}
|
|
2165
|
+
return json.data;
|
|
2166
|
+
}
|
|
2135
2167
|
|
|
2136
2168
|
// src/lib/chain-guard.ts
|
|
2137
2169
|
var CHAIN_NAMES = {
|
|
@@ -2168,132 +2200,167 @@ async function ensureWalletOnChain(pub, wallet, expected) {
|
|
|
2168
2200
|
}
|
|
2169
2201
|
}
|
|
2170
2202
|
|
|
2171
|
-
// src/lib/
|
|
2172
|
-
|
|
2173
|
-
|
|
2174
|
-
|
|
2175
|
-
|
|
2176
|
-
|
|
2177
|
-
|
|
2178
|
-
|
|
2179
|
-
|
|
2180
|
-
|
|
2181
|
-
|
|
2182
|
-
|
|
2183
|
-
|
|
2184
|
-
|
|
2185
|
-
|
|
2186
|
-
|
|
2187
|
-
|
|
2188
|
-
|
|
2189
|
-
|
|
2203
|
+
// src/lib/swap/swap-api.ts
|
|
2204
|
+
async function request(baseUrl, apiKey, path, init) {
|
|
2205
|
+
const url = `${baseUrl}/api/v1/swap${path}`;
|
|
2206
|
+
const res = await fetch(url, {
|
|
2207
|
+
method: init?.method ?? "GET",
|
|
2208
|
+
headers: {
|
|
2209
|
+
"Content-Type": "application/json",
|
|
2210
|
+
"x-owney-api-key": apiKey
|
|
2211
|
+
},
|
|
2212
|
+
...init ? { body: JSON.stringify(init.body) } : {}
|
|
2213
|
+
});
|
|
2214
|
+
if (!res.ok) {
|
|
2215
|
+
const text = await res.text().catch(() => "");
|
|
2216
|
+
if (res.status === 429) {
|
|
2217
|
+
throw new OwneyError(
|
|
2218
|
+
"SWAP_RATE_LIMITED",
|
|
2219
|
+
"Swap provider is rate limiting, retry shortly",
|
|
2220
|
+
{ statusCode: res.status }
|
|
2221
|
+
);
|
|
2222
|
+
}
|
|
2223
|
+
if (res.status === 403) {
|
|
2224
|
+
throw new OwneyError(
|
|
2225
|
+
"SWAP_DISABLED",
|
|
2226
|
+
"Swap is not enabled for this organization",
|
|
2227
|
+
{ statusCode: res.status }
|
|
2228
|
+
);
|
|
2229
|
+
}
|
|
2190
2230
|
throw new OwneyError(
|
|
2191
|
-
"
|
|
2192
|
-
`
|
|
2193
|
-
{
|
|
2231
|
+
"SWAP_REQUEST_FAILED",
|
|
2232
|
+
`Swap API error ${res.status}: ${text}`,
|
|
2233
|
+
{ statusCode: res.status, responseBody: text }
|
|
2194
2234
|
);
|
|
2195
2235
|
}
|
|
2196
|
-
const
|
|
2197
|
-
|
|
2198
|
-
try {
|
|
2199
|
-
parsed = JSON.parse(text);
|
|
2200
|
-
} catch {
|
|
2201
|
-
}
|
|
2202
|
-
if (!res.ok || !parsed?.success || typeof parsed.data?.intent !== "string" || typeof parsed.data.expiresAt !== "number") {
|
|
2236
|
+
const json = await res.json();
|
|
2237
|
+
if (!json.success) {
|
|
2203
2238
|
throw new OwneyError(
|
|
2204
|
-
"
|
|
2205
|
-
`
|
|
2206
|
-
{
|
|
2207
|
-
statusCode: res.status,
|
|
2208
|
-
responseBody: text.slice(0, 500),
|
|
2209
|
-
safeToFallback: true
|
|
2210
|
-
}
|
|
2239
|
+
"SWAP_REQUEST_FAILED",
|
|
2240
|
+
`Swap API request failed: ${json.message ?? "unknown error"}`,
|
|
2241
|
+
{ message: json.message }
|
|
2211
2242
|
);
|
|
2212
2243
|
}
|
|
2213
|
-
return
|
|
2244
|
+
return json.data;
|
|
2214
2245
|
}
|
|
2215
|
-
|
|
2216
|
-
|
|
2217
|
-
|
|
2218
|
-
|
|
2219
|
-
|
|
2220
|
-
|
|
2221
|
-
|
|
2222
|
-
|
|
2223
|
-
|
|
2224
|
-
|
|
2225
|
-
|
|
2226
|
-
|
|
2227
|
-
|
|
2228
|
-
|
|
2229
|
-
|
|
2230
|
-
|
|
2231
|
-
|
|
2232
|
-
|
|
2233
|
-
|
|
2234
|
-
|
|
2235
|
-
|
|
2236
|
-
|
|
2237
|
-
|
|
2238
|
-
|
|
2239
|
-
|
|
2240
|
-
|
|
2241
|
-
|
|
2242
|
-
|
|
2243
|
-
|
|
2244
|
-
|
|
2245
|
-
|
|
2246
|
+
function createSwapApi(baseUrl, apiKey) {
|
|
2247
|
+
return {
|
|
2248
|
+
/** Source assets the user may pay with, and each chain's deposit targets. */
|
|
2249
|
+
listTokens: () => request(baseUrl, apiKey, "/tokens"),
|
|
2250
|
+
/**
|
|
2251
|
+
* Search one chain's payable-with assets by name, symbol or address.
|
|
2252
|
+
*
|
|
2253
|
+
* Separate from `listTokens` on purpose: the full set is thousands of
|
|
2254
|
+
* tokens per chain, far too much to ship to a picker, so the short list
|
|
2255
|
+
* renders immediately and this reaches everything else on demand.
|
|
2256
|
+
*
|
|
2257
|
+
* Already filtered server-side to what a quote will accept, so anything
|
|
2258
|
+
* returned here can be paid with.
|
|
2259
|
+
*/
|
|
2260
|
+
searchTokens: (params) => request(
|
|
2261
|
+
baseUrl,
|
|
2262
|
+
apiKey,
|
|
2263
|
+
`/tokens/search?${new URLSearchParams({
|
|
2264
|
+
chainId: String(params.chainId),
|
|
2265
|
+
query: params.query,
|
|
2266
|
+
...params.limit === void 0 ? {} : { limit: String(params.limit) }
|
|
2267
|
+
}).toString()}`
|
|
2268
|
+
),
|
|
2269
|
+
/**
|
|
2270
|
+
* `walletAddress` is required even though the routing API could not infer
|
|
2271
|
+
* it: the Fusion+ quoter binds a quote to whoever will sign the order and
|
|
2272
|
+
* rejects the request without it.
|
|
2273
|
+
*/
|
|
2274
|
+
quote: (params) => request(baseUrl, apiKey, "/quote", {
|
|
2275
|
+
method: "POST",
|
|
2276
|
+
body: {
|
|
2277
|
+
srcChainId: params.from.chainId,
|
|
2278
|
+
srcSymbol: params.from.symbol,
|
|
2279
|
+
dstChainId: params.to.chainId,
|
|
2280
|
+
dstSymbol: params.to.symbol,
|
|
2281
|
+
amount: params.from.amount,
|
|
2282
|
+
walletAddress: params.walletAddress,
|
|
2283
|
+
...params.direction ? { direction: params.direction } : {}
|
|
2246
2284
|
}
|
|
2247
|
-
)
|
|
2248
|
-
|
|
2249
|
-
|
|
2250
|
-
|
|
2251
|
-
|
|
2252
|
-
|
|
2253
|
-
|
|
2254
|
-
|
|
2255
|
-
|
|
2256
|
-
|
|
2257
|
-
|
|
2258
|
-
|
|
2259
|
-
|
|
2260
|
-
"x-owney-api-key": input.apiKey
|
|
2261
|
-
},
|
|
2262
|
-
body: JSON.stringify(input.body)
|
|
2285
|
+
}),
|
|
2286
|
+
/** Ready-to-send calldata for a same-chain swap. */
|
|
2287
|
+
swapTx: (params) => request(baseUrl, apiKey, "/tx", {
|
|
2288
|
+
method: "POST",
|
|
2289
|
+
body: {
|
|
2290
|
+
srcChainId: params.from.chainId,
|
|
2291
|
+
srcSymbol: params.from.symbol,
|
|
2292
|
+
dstChainId: params.to.chainId,
|
|
2293
|
+
dstSymbol: params.to.symbol,
|
|
2294
|
+
amount: params.from.amount,
|
|
2295
|
+
walletAddress: params.walletAddress,
|
|
2296
|
+
slippage: params.slippage,
|
|
2297
|
+
...params.direction ? { direction: params.direction } : {}
|
|
2263
2298
|
}
|
|
2264
|
-
)
|
|
2265
|
-
|
|
2266
|
-
|
|
2267
|
-
|
|
2268
|
-
|
|
2269
|
-
|
|
2270
|
-
|
|
2271
|
-
|
|
2272
|
-
|
|
2273
|
-
|
|
2274
|
-
|
|
2275
|
-
|
|
2276
|
-
|
|
2277
|
-
|
|
2278
|
-
|
|
2279
|
-
|
|
2280
|
-
|
|
2299
|
+
}),
|
|
2300
|
+
/**
|
|
2301
|
+
* Builds a Fusion+ order server-side and returns EIP-712 typed data.
|
|
2302
|
+
*
|
|
2303
|
+
* Only HASHES go over the wire. The preimages never leave the browser —
|
|
2304
|
+
* see swap.secrets.
|
|
2305
|
+
*/
|
|
2306
|
+
buildOrder: (params) => request(baseUrl, apiKey, "/order/build", {
|
|
2307
|
+
method: "POST",
|
|
2308
|
+
body: {
|
|
2309
|
+
srcChainId: params.from.chainId,
|
|
2310
|
+
srcSymbol: params.from.symbol,
|
|
2311
|
+
dstChainId: params.to.chainId,
|
|
2312
|
+
dstSymbol: params.to.symbol,
|
|
2313
|
+
amount: params.from.amount,
|
|
2314
|
+
walletAddress: params.walletAddress,
|
|
2315
|
+
secretHashes: params.secretHashes,
|
|
2316
|
+
...params.direction ? { direction: params.direction } : {},
|
|
2317
|
+
...params.receiver ? { receiver: params.receiver } : {}
|
|
2281
2318
|
}
|
|
2282
|
-
)
|
|
2283
|
-
|
|
2284
|
-
|
|
2319
|
+
}),
|
|
2320
|
+
submitOrder: (body) => request(baseUrl, apiKey, "/order", { method: "POST", body }),
|
|
2321
|
+
/**
|
|
2322
|
+
* Only call once `readyForSecrets` reports the escrow deployed. Publishing
|
|
2323
|
+
* earlier hands a resolver the preimage while the user's funds are locked
|
|
2324
|
+
* and nothing has been posted on the destination chain.
|
|
2325
|
+
*/
|
|
2326
|
+
submitSecret: (orderHash, secret) => request(baseUrl, apiKey, "/order/secret", {
|
|
2327
|
+
method: "POST",
|
|
2328
|
+
body: { orderHash, secret }
|
|
2329
|
+
}),
|
|
2330
|
+
orderStatus: (orderHash) => request(baseUrl, apiKey, `/order/${orderHash}`),
|
|
2331
|
+
readyForSecrets: (orderHash) => request(
|
|
2332
|
+
baseUrl,
|
|
2333
|
+
apiKey,
|
|
2334
|
+
`/order/${orderHash}/ready-for-secrets`
|
|
2335
|
+
)
|
|
2336
|
+
};
|
|
2337
|
+
}
|
|
2338
|
+
|
|
2339
|
+
// src/lib/swap/swap.rpc.ts
|
|
2340
|
+
import { fallback, http as http2 } from "viem";
|
|
2341
|
+
var DEFAULT_RPC_URLS = {
|
|
2342
|
+
1: ["https://cloudflare-eth.com", "https://ethereum-rpc.publicnode.com"],
|
|
2343
|
+
8453: ["https://mainnet.base.org", "https://base-rpc.publicnode.com"],
|
|
2344
|
+
42161: [
|
|
2345
|
+
"https://arb1.arbitrum.io/rpc",
|
|
2346
|
+
"https://arbitrum-one-rpc.publicnode.com"
|
|
2347
|
+
]
|
|
2348
|
+
};
|
|
2349
|
+
function swapReadTransport(chainId, overrides) {
|
|
2350
|
+
const override = overrides?.[chainId];
|
|
2351
|
+
if (override) return http2(override);
|
|
2352
|
+
const urls = DEFAULT_RPC_URLS[chainId];
|
|
2353
|
+
if (!urls || urls.length === 0) return http2();
|
|
2354
|
+
return fallback(urls.map((url) => http2(url)));
|
|
2355
|
+
}
|
|
2356
|
+
function receiptTimeoutMs(chainId) {
|
|
2357
|
+
return chainId === 1 ? 6e5 : 18e4;
|
|
2285
2358
|
}
|
|
2286
2359
|
|
|
2287
2360
|
// src/lib/permit2.ts
|
|
2288
|
-
import { bytesToHex
|
|
2361
|
+
import { bytesToHex } from "viem";
|
|
2289
2362
|
var PERMIT2_ADDRESS = "0x000000000022D473030F116dDEE9F6B43aC78BA3";
|
|
2290
2363
|
var MAX_UINT256 = 2n ** 256n - 1n;
|
|
2291
|
-
function permit2ApprovalAmount(requiredAmount) {
|
|
2292
|
-
if (requiredAmount <= 0n) {
|
|
2293
|
-
throw new Error("Permit2 approval requires a positive deposit amount");
|
|
2294
|
-
}
|
|
2295
|
-
return MAX_UINT256;
|
|
2296
|
-
}
|
|
2297
2364
|
var ERC20_ALLOWANCE_ABI = [
|
|
2298
2365
|
{
|
|
2299
2366
|
type: "function",
|
|
@@ -2323,10 +2390,33 @@ var ERC20_ALLOWANCE_ABI = [
|
|
|
2323
2390
|
outputs: [{ name: "", type: "uint256" }]
|
|
2324
2391
|
}
|
|
2325
2392
|
];
|
|
2393
|
+
function buildPermitTransferFromTypedData(input) {
|
|
2394
|
+
return {
|
|
2395
|
+
domain: {
|
|
2396
|
+
name: "Permit2",
|
|
2397
|
+
chainId: input.chainId,
|
|
2398
|
+
verifyingContract: PERMIT2_ADDRESS
|
|
2399
|
+
},
|
|
2400
|
+
types: {
|
|
2401
|
+
PermitTransferFrom: [
|
|
2402
|
+
{ name: "permitted", type: "TokenPermissions" },
|
|
2403
|
+
{ name: "spender", type: "address" },
|
|
2404
|
+
{ name: "nonce", type: "uint256" },
|
|
2405
|
+
{ name: "deadline", type: "uint256" }
|
|
2406
|
+
],
|
|
2407
|
+
TokenPermissions: [
|
|
2408
|
+
{ name: "token", type: "address" },
|
|
2409
|
+
{ name: "amount", type: "uint256" }
|
|
2410
|
+
]
|
|
2411
|
+
},
|
|
2412
|
+
primaryType: "PermitTransferFrom",
|
|
2413
|
+
message: input.message
|
|
2414
|
+
};
|
|
2415
|
+
}
|
|
2326
2416
|
function randomPermit2Nonce() {
|
|
2327
2417
|
const bytes = new Uint8Array(32);
|
|
2328
2418
|
globalThis.crypto.getRandomValues(bytes);
|
|
2329
|
-
return BigInt(
|
|
2419
|
+
return BigInt(bytesToHex(bytes));
|
|
2330
2420
|
}
|
|
2331
2421
|
async function readPermit2Allowance(publicClient, token, owner) {
|
|
2332
2422
|
return publicClient.readContract({
|
|
@@ -2345,44 +2435,122 @@ async function readErc20Balance(publicClient, token, owner) {
|
|
|
2345
2435
|
});
|
|
2346
2436
|
}
|
|
2347
2437
|
|
|
2348
|
-
// src/lib/
|
|
2349
|
-
|
|
2350
|
-
var
|
|
2351
|
-
function
|
|
2352
|
-
|
|
2438
|
+
// src/lib/swap/swap.secrets.ts
|
|
2439
|
+
import { keccak256, toHex } from "viem";
|
|
2440
|
+
var SECRET_BYTES = 32;
|
|
2441
|
+
function randomBytes(length) {
|
|
2442
|
+
const bytes = new Uint8Array(length);
|
|
2443
|
+
const cryptoObj = typeof globalThis !== "undefined" ? globalThis.crypto : void 0;
|
|
2444
|
+
if (!cryptoObj?.getRandomValues) {
|
|
2445
|
+
throw new Error(
|
|
2446
|
+
"[owney-sdk] Secure randomness is unavailable, so a swap secret cannot be generated safely."
|
|
2447
|
+
);
|
|
2448
|
+
}
|
|
2449
|
+
cryptoObj.getRandomValues(bytes);
|
|
2450
|
+
return bytes;
|
|
2353
2451
|
}
|
|
2354
|
-
function
|
|
2355
|
-
|
|
2356
|
-
|
|
2357
|
-
|
|
2358
|
-
|
|
2359
|
-
|
|
2360
|
-
|
|
2361
|
-
|
|
2362
|
-
|
|
2363
|
-
|
|
2364
|
-
|
|
2365
|
-
|
|
2366
|
-
|
|
2452
|
+
function mintSecrets(count) {
|
|
2453
|
+
if (!Number.isInteger(count) || count < 1) {
|
|
2454
|
+
throw new Error(
|
|
2455
|
+
`[owney-sdk] A swap needs at least one secret, got ${String(count)}.`
|
|
2456
|
+
);
|
|
2457
|
+
}
|
|
2458
|
+
const secrets = [];
|
|
2459
|
+
const secretHashes = [];
|
|
2460
|
+
for (let i = 0; i < count; i++) {
|
|
2461
|
+
const secret = toHex(randomBytes(SECRET_BYTES));
|
|
2462
|
+
secrets.push(secret);
|
|
2463
|
+
secretHashes.push(keccak256(secret));
|
|
2464
|
+
}
|
|
2465
|
+
return { secrets, secretHashes };
|
|
2367
2466
|
}
|
|
2368
2467
|
|
|
2369
|
-
// src/
|
|
2370
|
-
|
|
2371
|
-
|
|
2372
|
-
|
|
2373
|
-
|
|
2374
|
-
|
|
2375
|
-
getAddress
|
|
2376
|
-
} from "viem";
|
|
2377
|
-
import { base as base2 } from "viem/chains";
|
|
2378
|
-
|
|
2379
|
-
// src/agents/yieldseeker/yieldseeker.auth-cache.ts
|
|
2380
|
-
var KEY_PREFIX2 = "owney.yieldseeker.session.v5";
|
|
2381
|
-
var INVALIDATED_KEY_PREFIXES = [
|
|
2382
|
-
"owney.yieldseeker.session",
|
|
2383
|
-
"owney.yieldseeker.session.v3",
|
|
2384
|
-
"owney.yieldseeker.session.v4"
|
|
2468
|
+
// src/lib/swap/swap.types.ts
|
|
2469
|
+
var SWAP_TERMINAL_STATUSES = [
|
|
2470
|
+
"executed",
|
|
2471
|
+
"expired",
|
|
2472
|
+
"cancelled",
|
|
2473
|
+
"refunded"
|
|
2385
2474
|
];
|
|
2475
|
+
var isSwapTerminal = (status) => SWAP_TERMINAL_STATUSES.includes(status);
|
|
2476
|
+
|
|
2477
|
+
// src/lib/swap/swap.order-runner.ts
|
|
2478
|
+
var DEFAULT_POLL_MS = 5e3;
|
|
2479
|
+
var MAX_BACKOFF_MS = 3e4;
|
|
2480
|
+
var backoffFor = (failures, base3) => Math.min(base3 * 2 ** Math.min(failures, 5), MAX_BACKOFF_MS);
|
|
2481
|
+
var DEFAULT_TIMEOUT_MS = 15 * 60 * 1e3;
|
|
2482
|
+
async function runFusionOrder(deps, options) {
|
|
2483
|
+
const {
|
|
2484
|
+
orderHash,
|
|
2485
|
+
secrets,
|
|
2486
|
+
onStage,
|
|
2487
|
+
pollIntervalMs = DEFAULT_POLL_MS,
|
|
2488
|
+
timeoutMs = DEFAULT_TIMEOUT_MS
|
|
2489
|
+
} = options;
|
|
2490
|
+
const deadline = deps.now() + timeoutMs;
|
|
2491
|
+
let failures = 0;
|
|
2492
|
+
const published = /* @__PURE__ */ new Set();
|
|
2493
|
+
onStage?.("swapping");
|
|
2494
|
+
for (; ; ) {
|
|
2495
|
+
if (deps.now() >= deadline) {
|
|
2496
|
+
throw new OwneyError(
|
|
2497
|
+
"SWAP_REQUEST_FAILED",
|
|
2498
|
+
"Timed out waiting for the swap to settle. It may still complete \u2014 check the order status before retrying.",
|
|
2499
|
+
{ orderHash }
|
|
2500
|
+
);
|
|
2501
|
+
}
|
|
2502
|
+
let ready;
|
|
2503
|
+
try {
|
|
2504
|
+
ready = await deps.readyForSecrets(orderHash);
|
|
2505
|
+
} catch {
|
|
2506
|
+
ready = {};
|
|
2507
|
+
}
|
|
2508
|
+
for (const fill of ready.fills ?? []) {
|
|
2509
|
+
if (published.has(fill.idx)) continue;
|
|
2510
|
+
const secret = secrets[fill.idx];
|
|
2511
|
+
if (secret === void 0) {
|
|
2512
|
+
throw new OwneyError(
|
|
2513
|
+
"SWAP_REQUEST_FAILED",
|
|
2514
|
+
`Swap needs a secret for fill ${fill.idx} that this session does not have. The order will refund once its timelock expires.`,
|
|
2515
|
+
{ orderHash, fillIndex: fill.idx }
|
|
2516
|
+
);
|
|
2517
|
+
}
|
|
2518
|
+
try {
|
|
2519
|
+
await deps.submitSecret(orderHash, secret);
|
|
2520
|
+
published.add(fill.idx);
|
|
2521
|
+
} catch {
|
|
2522
|
+
failures += 1;
|
|
2523
|
+
}
|
|
2524
|
+
}
|
|
2525
|
+
let status;
|
|
2526
|
+
try {
|
|
2527
|
+
({ status } = await deps.orderStatus(orderHash));
|
|
2528
|
+
failures = 0;
|
|
2529
|
+
} catch {
|
|
2530
|
+
failures += 1;
|
|
2531
|
+
await deps.sleep(backoffFor(failures, pollIntervalMs));
|
|
2532
|
+
continue;
|
|
2533
|
+
}
|
|
2534
|
+
if (status === "refunding") onStage?.("refunding");
|
|
2535
|
+
if (isSwapTerminal(status)) {
|
|
2536
|
+
if (status === "executed") {
|
|
2537
|
+
onStage?.("swapped");
|
|
2538
|
+
return { status, filled: true };
|
|
2539
|
+
}
|
|
2540
|
+
if (status === "refunded") onStage?.("refunded");
|
|
2541
|
+
throw new OwneyError(
|
|
2542
|
+
status === "refunded" ? "SWAP_ORDER_REFUNDED" : status === "cancelled" ? "SWAP_ORDER_CANCELLED" : "SWAP_ORDER_EXPIRED",
|
|
2543
|
+
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.",
|
|
2544
|
+
{ orderHash, status }
|
|
2545
|
+
);
|
|
2546
|
+
}
|
|
2547
|
+
await deps.sleep(pollIntervalMs);
|
|
2548
|
+
}
|
|
2549
|
+
}
|
|
2550
|
+
|
|
2551
|
+
// src/lib/swap/swap.secret-store.ts
|
|
2552
|
+
var KEY_PREFIX2 = "owney.swap.order";
|
|
2553
|
+
var MAX_AGE_MS = 24 * 60 * 60 * 1e3;
|
|
2386
2554
|
var storage2 = () => {
|
|
2387
2555
|
if (typeof window === "undefined") return null;
|
|
2388
2556
|
try {
|
|
@@ -2391,1649 +2559,287 @@ var storage2 = () => {
|
|
|
2391
2559
|
return null;
|
|
2392
2560
|
}
|
|
2393
2561
|
};
|
|
2394
|
-
var
|
|
2395
|
-
|
|
2396
|
-
|
|
2397
|
-
);
|
|
2398
|
-
var clearInvalidatedSessions = (store, address, chainId) => {
|
|
2399
|
-
for (const key2 of invalidatedKeys(address, chainId)) {
|
|
2400
|
-
memorySessions2.delete(key2);
|
|
2401
|
-
try {
|
|
2402
|
-
store?.removeItem(key2);
|
|
2403
|
-
} catch {
|
|
2404
|
-
}
|
|
2405
|
-
}
|
|
2406
|
-
};
|
|
2407
|
-
var memorySessions2 = /* @__PURE__ */ new Map();
|
|
2408
|
-
var isValidSession = (session) => {
|
|
2409
|
-
if (!session?.token) return false;
|
|
2562
|
+
var keyFor = (orderHash) => `${KEY_PREFIX2}.${orderHash}`;
|
|
2563
|
+
function saveOrder(order) {
|
|
2564
|
+
const store = storage2();
|
|
2565
|
+
if (!store) return;
|
|
2410
2566
|
try {
|
|
2411
|
-
|
|
2412
|
-
return typeof parsed.message === "string" && typeof parsed.signature === "string" && parsed.signature.startsWith("0x");
|
|
2567
|
+
store.setItem(keyFor(order.orderHash), JSON.stringify(order));
|
|
2413
2568
|
} catch {
|
|
2414
|
-
return false;
|
|
2415
2569
|
}
|
|
2416
|
-
}
|
|
2417
|
-
|
|
2418
|
-
if (typeof window === "undefined") return null;
|
|
2419
|
-
const key2 = buildKey2(address, chainId);
|
|
2570
|
+
}
|
|
2571
|
+
function clearOrder(orderHash) {
|
|
2420
2572
|
const store = storage2();
|
|
2421
|
-
|
|
2422
|
-
let raw2 = null;
|
|
2573
|
+
if (!store) return;
|
|
2423
2574
|
try {
|
|
2424
|
-
|
|
2575
|
+
store.removeItem(keyFor(orderHash));
|
|
2425
2576
|
} catch {
|
|
2426
|
-
raw2 = null;
|
|
2427
2577
|
}
|
|
2428
|
-
|
|
2429
|
-
|
|
2430
|
-
|
|
2431
|
-
|
|
2432
|
-
|
|
2578
|
+
}
|
|
2579
|
+
function listOrders(now = Date.now()) {
|
|
2580
|
+
const store = storage2();
|
|
2581
|
+
if (!store) return [];
|
|
2582
|
+
const out = [];
|
|
2583
|
+
try {
|
|
2584
|
+
const keys = [];
|
|
2585
|
+
for (let i = 0; i < store.length; i++) {
|
|
2586
|
+
const key2 = store.key(i);
|
|
2587
|
+
if (key2?.startsWith(`${KEY_PREFIX2}.`)) keys.push(key2);
|
|
2433
2588
|
}
|
|
2434
|
-
|
|
2435
|
-
|
|
2436
|
-
|
|
2437
|
-
|
|
2438
|
-
|
|
2439
|
-
|
|
2440
|
-
|
|
2441
|
-
|
|
2442
|
-
|
|
2443
|
-
|
|
2444
|
-
|
|
2445
|
-
}
|
|
2446
|
-
|
|
2447
|
-
|
|
2448
|
-
const session = { token };
|
|
2449
|
-
if (!isValidSession(session)) return;
|
|
2450
|
-
const key2 = buildKey2(address, chainId);
|
|
2451
|
-
memorySessions2.set(key2, session);
|
|
2452
|
-
const store = storage2();
|
|
2453
|
-
try {
|
|
2454
|
-
store?.setItem(key2, JSON.stringify(session));
|
|
2455
|
-
} catch {
|
|
2456
|
-
}
|
|
2457
|
-
};
|
|
2458
|
-
var clearYieldseekerSession = (address, chainId) => {
|
|
2459
|
-
const key2 = buildKey2(address, chainId);
|
|
2460
|
-
memorySessions2.delete(key2);
|
|
2461
|
-
const store = storage2();
|
|
2462
|
-
clearInvalidatedSessions(store, address, chainId);
|
|
2463
|
-
try {
|
|
2464
|
-
store?.removeItem(key2);
|
|
2465
|
-
} catch {
|
|
2466
|
-
}
|
|
2467
|
-
};
|
|
2468
|
-
|
|
2469
|
-
// src/agents/yieldseeker/yieldseeker.auth.ts
|
|
2470
|
-
function resolveSiweOrigin(override) {
|
|
2471
|
-
const origin = override?.trim() || (typeof window !== "undefined" ? window.location?.origin : void 0);
|
|
2472
|
-
if (!origin || origin === "null") {
|
|
2473
|
-
throw new Error("Yieldseeker sign-in requires the requesting app's browser origin.");
|
|
2474
|
-
}
|
|
2475
|
-
const url = new URL(origin);
|
|
2476
|
-
if (url.protocol !== "https:" && url.protocol !== "http:") {
|
|
2477
|
-
throw new Error("Yieldseeker sign-in requires an HTTP or HTTPS app origin.");
|
|
2478
|
-
}
|
|
2479
|
-
if (url.username || url.password || url.pathname !== "/" || url.search || url.hash) {
|
|
2480
|
-
throw new Error("Yieldseeker SIWE override must be an origin without credentials, path, query, or fragment.");
|
|
2481
|
-
}
|
|
2482
|
-
return url;
|
|
2483
|
-
}
|
|
2484
|
-
function createYieldseekerSiweMessage(address, chainId, dependencies = {}) {
|
|
2485
|
-
const url = resolveSiweOrigin(dependencies.origin);
|
|
2486
|
-
return new SiweMessage({
|
|
2487
|
-
scheme: url.protocol.slice(0, -1),
|
|
2488
|
-
domain: url.host,
|
|
2489
|
-
address: getAddress(address),
|
|
2490
|
-
uri: url.origin,
|
|
2491
|
-
version: "1",
|
|
2492
|
-
chainId,
|
|
2493
|
-
nonce: (dependencies.nonce ?? generateNonce)(),
|
|
2494
|
-
issuedAt: (dependencies.now ?? (() => /* @__PURE__ */ new Date()))().toISOString()
|
|
2495
|
-
}).prepareMessage();
|
|
2496
|
-
}
|
|
2497
|
-
function encodeYieldseekerAuthToken(token) {
|
|
2498
|
-
const bytes = new TextEncoder().encode(JSON.stringify(token));
|
|
2499
|
-
let binary = "";
|
|
2500
|
-
for (const byte of bytes) binary += String.fromCharCode(byte);
|
|
2501
|
-
return btoa(binary);
|
|
2502
|
-
}
|
|
2503
|
-
var YieldseekerAuth = class {
|
|
2504
|
-
constructor(dependencies = {}) {
|
|
2505
|
-
this.dependencies = dependencies;
|
|
2506
|
-
}
|
|
2507
|
-
dependencies;
|
|
2508
|
-
tokens = /* @__PURE__ */ new Map();
|
|
2509
|
-
pending = /* @__PURE__ */ new Map();
|
|
2510
|
-
scopes = /* @__PURE__ */ new Map();
|
|
2511
|
-
key(state, chainId) {
|
|
2512
|
-
return `${state.walletAddress.toLowerCase()}:${chainId}:${resolveSiweOrigin(this.dependencies.origin).origin}`;
|
|
2513
|
-
}
|
|
2514
|
-
async getToken(state, chainId) {
|
|
2515
|
-
const key2 = this.key(state, chainId);
|
|
2516
|
-
const scope = { address: state.walletAddress, chainId };
|
|
2517
|
-
this.scopes.set(key2, scope);
|
|
2518
|
-
const cached = this.tokens.get(key2);
|
|
2519
|
-
if (cached) return cached;
|
|
2520
|
-
const persisted = readYieldseekerSession(scope.address, scope.chainId);
|
|
2521
|
-
if (persisted && this.matchesOrigin(persisted)) {
|
|
2522
|
-
this.tokens.set(key2, persisted);
|
|
2523
|
-
return persisted;
|
|
2524
|
-
}
|
|
2525
|
-
if (persisted) clearYieldseekerSession(scope.address, scope.chainId);
|
|
2526
|
-
const inFlight = this.pending.get(key2);
|
|
2527
|
-
if (inFlight) return inFlight;
|
|
2528
|
-
const request = this.sign(state, chainId).then((token) => {
|
|
2529
|
-
if (this.pending.get(key2) !== request) throw new Error("Wallet sign-in session changed. Please try again.");
|
|
2530
|
-
this.tokens.set(key2, token);
|
|
2531
|
-
writeYieldseekerSession(scope.address, scope.chainId, token);
|
|
2532
|
-
return token;
|
|
2533
|
-
});
|
|
2534
|
-
this.pending.set(key2, request);
|
|
2535
|
-
try {
|
|
2536
|
-
return await request;
|
|
2537
|
-
} finally {
|
|
2538
|
-
if (this.pending.get(key2) === request) this.pending.delete(key2);
|
|
2539
|
-
}
|
|
2540
|
-
}
|
|
2541
|
-
async refreshToken(state, chainId, rejectedToken) {
|
|
2542
|
-
const key2 = this.key(state, chainId);
|
|
2543
|
-
if (this.tokens.get(key2) === rejectedToken) {
|
|
2544
|
-
this.tokens.delete(key2);
|
|
2545
|
-
clearYieldseekerSession(state.walletAddress, chainId);
|
|
2546
|
-
}
|
|
2547
|
-
return this.getToken(state, chainId);
|
|
2548
|
-
}
|
|
2549
|
-
matchesOrigin(token) {
|
|
2550
|
-
try {
|
|
2551
|
-
const message = new SiweMessage(JSON.parse(atob(token)).message);
|
|
2552
|
-
const url = resolveSiweOrigin(this.dependencies.origin);
|
|
2553
|
-
return message.domain === url.host && message.uri === url.origin && message.scheme === url.protocol.slice(0, -1);
|
|
2554
|
-
} catch {
|
|
2555
|
-
return false;
|
|
2556
|
-
}
|
|
2557
|
-
}
|
|
2558
|
-
clear(state, chainId) {
|
|
2559
|
-
if (!state || chainId === void 0) {
|
|
2560
|
-
for (const scope of this.scopes.values()) {
|
|
2561
|
-
clearYieldseekerSession(scope.address, scope.chainId);
|
|
2589
|
+
for (const key2 of keys) {
|
|
2590
|
+
const raw = store.getItem(key2);
|
|
2591
|
+
if (!raw) continue;
|
|
2592
|
+
try {
|
|
2593
|
+
const parsed = JSON.parse(raw);
|
|
2594
|
+
if (now - parsed.createdAt > MAX_AGE_MS) {
|
|
2595
|
+
store.removeItem(key2);
|
|
2596
|
+
continue;
|
|
2597
|
+
}
|
|
2598
|
+
if (Array.isArray(parsed.secrets) && parsed.secrets.length > 0) {
|
|
2599
|
+
out.push(parsed);
|
|
2600
|
+
}
|
|
2601
|
+
} catch {
|
|
2602
|
+
store.removeItem(key2);
|
|
2562
2603
|
}
|
|
2563
|
-
this.tokens.clear();
|
|
2564
|
-
this.pending.clear();
|
|
2565
|
-
this.scopes.clear();
|
|
2566
|
-
return;
|
|
2567
2604
|
}
|
|
2568
|
-
const key2 = this.key(state, chainId);
|
|
2569
|
-
this.tokens.delete(key2);
|
|
2570
|
-
this.pending.delete(key2);
|
|
2571
|
-
this.scopes.delete(key2);
|
|
2572
|
-
clearYieldseekerSession(state.walletAddress, chainId);
|
|
2573
|
-
}
|
|
2574
|
-
async sign(state, chainId) {
|
|
2575
|
-
const account = getAddress(state.walletAddress);
|
|
2576
|
-
const publicClient = createPublicClient2({
|
|
2577
|
-
chain: base2,
|
|
2578
|
-
transport: custom(state.provider)
|
|
2579
|
-
});
|
|
2580
|
-
const walletClient = createWalletClient({
|
|
2581
|
-
account,
|
|
2582
|
-
chain: base2,
|
|
2583
|
-
transport: custom(state.provider)
|
|
2584
|
-
});
|
|
2585
|
-
await ensureWalletOnChain(
|
|
2586
|
-
publicClient,
|
|
2587
|
-
walletClient,
|
|
2588
|
-
8453
|
|
2589
|
-
);
|
|
2590
|
-
const message = createYieldseekerSiweMessage(
|
|
2591
|
-
account,
|
|
2592
|
-
chainId,
|
|
2593
|
-
this.dependencies
|
|
2594
|
-
);
|
|
2595
|
-
const signature = await walletClient.signMessage({ account, message });
|
|
2596
|
-
return encodeYieldseekerAuthToken({ message, signature });
|
|
2597
|
-
}
|
|
2598
|
-
};
|
|
2599
|
-
|
|
2600
|
-
// src/agents/yieldseeker/yieldseeker.identity-cache.ts
|
|
2601
|
-
var KEY_PREFIX3 = "owney.yieldseeker.identity.v1";
|
|
2602
|
-
var YIELDSEEKER_IDENTITY_TTL_MS = 24 * 60 * 60 * 1e3;
|
|
2603
|
-
var memoryIdentities = /* @__PURE__ */ new Map();
|
|
2604
|
-
var storage3 = () => {
|
|
2605
|
-
if (typeof window === "undefined") return null;
|
|
2606
|
-
try {
|
|
2607
|
-
return window.localStorage;
|
|
2608
|
-
} catch {
|
|
2609
|
-
return null;
|
|
2610
|
-
}
|
|
2611
|
-
};
|
|
2612
|
-
var keyFor = (walletAddress, chainId) => `${KEY_PREFIX3}:${walletAddress.toLowerCase()}:${chainId}`;
|
|
2613
|
-
function valid(value, walletAddress, chainId, now) {
|
|
2614
|
-
return Boolean(
|
|
2615
|
-
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
|
|
2616
|
-
);
|
|
2617
|
-
}
|
|
2618
|
-
function readYieldseekerIdentity(walletAddress, chainId, now = Date.now()) {
|
|
2619
|
-
if (typeof window === "undefined") return null;
|
|
2620
|
-
const key2 = keyFor(walletAddress, chainId);
|
|
2621
|
-
const store = storage3();
|
|
2622
|
-
let parsed = null;
|
|
2623
|
-
try {
|
|
2624
|
-
const raw2 = store?.getItem(key2);
|
|
2625
|
-
parsed = raw2 ? JSON.parse(raw2) : null;
|
|
2626
|
-
} catch {
|
|
2627
|
-
parsed = null;
|
|
2628
|
-
}
|
|
2629
|
-
const candidate = parsed ?? memoryIdentities.get(key2);
|
|
2630
|
-
if (valid(candidate, walletAddress, chainId, now)) {
|
|
2631
|
-
memoryIdentities.set(key2, candidate);
|
|
2632
|
-
return { userId: candidate.userId };
|
|
2633
|
-
}
|
|
2634
|
-
memoryIdentities.delete(key2);
|
|
2635
|
-
try {
|
|
2636
|
-
store?.removeItem(key2);
|
|
2637
|
-
} catch {
|
|
2638
|
-
}
|
|
2639
|
-
return null;
|
|
2640
|
-
}
|
|
2641
|
-
function writeYieldseekerIdentity(walletAddress, chainId, userId, now = Date.now()) {
|
|
2642
|
-
if (typeof window === "undefined") return;
|
|
2643
|
-
const identity = {
|
|
2644
|
-
userId,
|
|
2645
|
-
walletAddress,
|
|
2646
|
-
chainId,
|
|
2647
|
-
expiresAt: now + YIELDSEEKER_IDENTITY_TTL_MS
|
|
2648
|
-
};
|
|
2649
|
-
if (!valid(identity, walletAddress, chainId, now)) return;
|
|
2650
|
-
const key2 = keyFor(walletAddress, chainId);
|
|
2651
|
-
memoryIdentities.set(key2, identity);
|
|
2652
|
-
try {
|
|
2653
|
-
storage3()?.setItem(key2, JSON.stringify(identity));
|
|
2654
|
-
} catch {
|
|
2655
|
-
}
|
|
2656
|
-
}
|
|
2657
|
-
function clearYieldseekerIdentity(walletAddress, chainId) {
|
|
2658
|
-
const key2 = keyFor(walletAddress, chainId);
|
|
2659
|
-
memoryIdentities.delete(key2);
|
|
2660
|
-
try {
|
|
2661
|
-
storage3()?.removeItem(key2);
|
|
2662
2605
|
} catch {
|
|
2606
|
+
return out;
|
|
2663
2607
|
}
|
|
2608
|
+
return out.sort((a, b) => b.createdAt - a.createdAt);
|
|
2664
2609
|
}
|
|
2665
2610
|
|
|
2666
|
-
// src/
|
|
2667
|
-
var
|
|
2668
|
-
function
|
|
2669
|
-
|
|
2670
|
-
|
|
2671
|
-
|
|
2672
|
-
|
|
2673
|
-
|
|
2674
|
-
|
|
2675
|
-
|
|
2676
|
-
|
|
2677
|
-
this.responseFields = responseFields;
|
|
2678
|
-
this.name = "YieldseekerApiError";
|
|
2679
|
-
}
|
|
2680
|
-
status;
|
|
2681
|
-
providerCode;
|
|
2682
|
-
responseFields;
|
|
2683
|
-
get isAuthenticationError() {
|
|
2684
|
-
return this.status === 401 || this.status === 403;
|
|
2685
|
-
}
|
|
2686
|
-
};
|
|
2687
|
-
function providerError(body, fallback) {
|
|
2688
|
-
if (!body || typeof body !== "object") return { code: fallback };
|
|
2689
|
-
const record = body;
|
|
2690
|
-
return {
|
|
2691
|
-
code: typeof record.message === "string" ? record.message : fallback,
|
|
2692
|
-
fields: record.fields && typeof record.fields === "object" ? record.fields : void 0
|
|
2693
|
-
};
|
|
2694
|
-
}
|
|
2695
|
-
var YieldseekerApiClient = class {
|
|
2696
|
-
constructor(owneyApiKey, baseUrl = YIELDSEEKER_API_BASE_URL, fetchFn = fetch.bind(globalThis)) {
|
|
2697
|
-
this.owneyApiKey = owneyApiKey;
|
|
2698
|
-
this.baseUrl = baseUrl;
|
|
2699
|
-
this.fetchFn = fetchFn;
|
|
2700
|
-
}
|
|
2701
|
-
owneyApiKey;
|
|
2702
|
-
baseUrl;
|
|
2703
|
-
fetchFn;
|
|
2704
|
-
async request(path, options = {}) {
|
|
2705
|
-
const controller = new AbortController();
|
|
2706
|
-
const timer = setTimeout(
|
|
2707
|
-
() => controller.abort(),
|
|
2708
|
-
options.timeoutMs ?? 15e3
|
|
2709
|
-
);
|
|
2710
|
-
try {
|
|
2711
|
-
const response = await this.fetchFn(`${this.baseUrl}${path}`, {
|
|
2712
|
-
method: options.method ?? "GET",
|
|
2713
|
-
headers: {
|
|
2714
|
-
"Content-Type": "application/json",
|
|
2715
|
-
"x-owney-api-key": this.owneyApiKey,
|
|
2716
|
-
...options.signature ? { Authorization: `Signature ${options.signature}` } : {}
|
|
2717
|
-
},
|
|
2718
|
-
body: options.body ? JSON.stringify(options.body) : void 0,
|
|
2719
|
-
signal: controller.signal
|
|
2720
|
-
});
|
|
2721
|
-
const payload = await response.json().catch(() => null);
|
|
2722
|
-
if (!response.ok) {
|
|
2723
|
-
const error = providerError(payload, `HTTP_${response.status}`);
|
|
2724
|
-
throw new YieldseekerApiError(
|
|
2725
|
-
response.status,
|
|
2726
|
-
error.code,
|
|
2727
|
-
error.fields
|
|
2728
|
-
);
|
|
2729
|
-
}
|
|
2730
|
-
if (payload && typeof payload === "object" && payload.success === true && "data" in payload) {
|
|
2731
|
-
return payload.data;
|
|
2732
|
-
}
|
|
2733
|
-
return payload;
|
|
2734
|
-
} catch (error) {
|
|
2735
|
-
if (error instanceof YieldseekerApiError) throw error;
|
|
2736
|
-
if (error instanceof DOMException && error.name === "AbortError") {
|
|
2737
|
-
throw new YieldseekerApiError(408, "REQUEST_TIMEOUT");
|
|
2738
|
-
}
|
|
2739
|
-
throw new YieldseekerApiError(0, "NETWORK_ERROR", {
|
|
2740
|
-
cause: error instanceof Error ? error.message : String(error)
|
|
2741
|
-
});
|
|
2742
|
-
} finally {
|
|
2743
|
-
clearTimeout(timer);
|
|
2744
|
-
}
|
|
2745
|
-
}
|
|
2746
|
-
};
|
|
2747
|
-
|
|
2748
|
-
// src/agents/yieldseeker/yieldseeker.mapper.ts
|
|
2749
|
-
import { formatUnits, isAddress } from "viem";
|
|
2750
|
-
|
|
2751
|
-
// src/lib/helpers/snapshot-apy.ts
|
|
2752
|
-
var DAY_MS = 864e5;
|
|
2753
|
-
function snapshotTime(date) {
|
|
2754
|
-
if (!/^\d{4}-\d{2}-\d{2}$/.test(date)) return void 0;
|
|
2755
|
-
const time = Date.parse(date);
|
|
2756
|
-
return Number.isFinite(time) && new Date(time).toISOString().slice(0, 10) === date ? time : void 0;
|
|
2757
|
-
}
|
|
2758
|
-
function returnFactor(value) {
|
|
2759
|
-
if (typeof value !== "number" && typeof value !== "string") return void 0;
|
|
2760
|
-
if (typeof value === "string" && value.trim() === "") return void 0;
|
|
2761
|
-
const factor = Number(value);
|
|
2762
|
-
return Number.isFinite(factor) && factor >= 0 ? factor : void 0;
|
|
2763
|
-
}
|
|
2764
|
-
function calculateSnapshotApy(snapshots, lookbackDays, now = Date.now()) {
|
|
2765
|
-
if (!Number.isFinite(lookbackDays) || lookbackDays <= 0 || !Number.isFinite(now)) {
|
|
2766
|
-
return void 0;
|
|
2767
|
-
}
|
|
2768
|
-
const points = snapshots.flatMap((snapshot) => {
|
|
2769
|
-
const time = snapshotTime(snapshot.date);
|
|
2770
|
-
return time !== void 0 && time <= now ? [{ snapshot, time }] : [];
|
|
2771
|
-
}).sort((a, b) => a.time - b.time);
|
|
2772
|
-
const end = points.at(-1);
|
|
2773
|
-
if (!end) return void 0;
|
|
2774
|
-
const cutoff = end.time - lookbackDays * DAY_MS;
|
|
2775
|
-
const start = points.find((point) => point.time >= cutoff);
|
|
2776
|
-
const actualDays = (end.time - start.time) / DAY_MS;
|
|
2777
|
-
if (actualDays <= 0) return void 0;
|
|
2778
|
-
const startFactor = returnFactor(start.snapshot.cumulativeReturnFactor);
|
|
2779
|
-
const endFactor = returnFactor(end.snapshot.cumulativeReturnFactor);
|
|
2780
|
-
if (startFactor === void 0 || startFactor === 0 || endFactor === void 0) {
|
|
2781
|
-
return void 0;
|
|
2782
|
-
}
|
|
2783
|
-
const periodReturn = endFactor / startFactor - 1;
|
|
2784
|
-
const apy = Math.pow(1 + periodReturn, 365 / actualDays) - 1;
|
|
2785
|
-
return Number.isFinite(apy) ? apy : void 0;
|
|
2786
|
-
}
|
|
2787
|
-
|
|
2788
|
-
// src/agents/yieldseeker/yieldseeker.types.ts
|
|
2789
|
-
var YIELDSEEKER_ASSET_METADATA = {
|
|
2790
|
-
USDC: {
|
|
2791
|
-
address: "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913",
|
|
2792
|
-
decimals: 6
|
|
2793
|
-
},
|
|
2794
|
-
WETH: {
|
|
2795
|
-
address: "0x4200000000000000000000000000000000000006",
|
|
2796
|
-
decimals: 18
|
|
2797
|
-
}
|
|
2798
|
-
};
|
|
2799
|
-
|
|
2800
|
-
// src/agents/yieldseeker/yieldseeker.mapper.ts
|
|
2801
|
-
function invalid(endpoint, detail) {
|
|
2802
|
-
throw new OwneyError(
|
|
2803
|
-
"AGENT_INVALID_RESPONSE",
|
|
2804
|
-
`Yieldseeker returned an invalid ${endpoint} response: ${detail}.`,
|
|
2805
|
-
{ endpoint, detail },
|
|
2806
|
-
"yieldseeker"
|
|
2807
|
-
);
|
|
2808
|
-
}
|
|
2809
|
-
function raw(value, endpoint) {
|
|
2810
|
-
if (typeof value !== "string" || !/^-?[0-9]+$/.test(value)) {
|
|
2811
|
-
return invalid(endpoint, "expected a base-10 integer string");
|
|
2812
|
-
}
|
|
2813
|
-
return BigInt(value);
|
|
2814
|
-
}
|
|
2815
|
-
function decimal(value, decimals, endpoint) {
|
|
2816
|
-
return formatUnits(raw(value, endpoint), decimals);
|
|
2817
|
-
}
|
|
2818
|
-
function usd(rawAmount, decimals, price) {
|
|
2819
|
-
return Number(formatUnits(rawAmount, decimals)) * price;
|
|
2820
|
-
}
|
|
2821
|
-
function percent(value) {
|
|
2822
|
-
const result = Number(value);
|
|
2823
|
-
return Number.isFinite(result) ? result * 100 : 0;
|
|
2824
|
-
}
|
|
2825
|
-
var YIELDSEEKER_POSITIVE_YIELD_FEE_RATE = 0.1;
|
|
2826
|
-
function publicApyAfterYieldseekerFee(value) {
|
|
2827
|
-
const grossPercent = percent(value);
|
|
2828
|
-
if (grossPercent <= 0) return grossPercent;
|
|
2829
|
-
const netPercent = grossPercent * (1 - YIELDSEEKER_POSITIVE_YIELD_FEE_RATE);
|
|
2830
|
-
return Math.round(netPercent * 1e12) / 1e12;
|
|
2831
|
-
}
|
|
2832
|
-
function riskAdjustedApyForDays(option, days) {
|
|
2833
|
-
if (days === "7D") return option.riskAdjustedApy7dAverage;
|
|
2834
|
-
if (days === "30D") return option.riskAdjustedApy30dAverage;
|
|
2835
|
-
return (option.riskAdjustedApy7dAverage + option.riskAdjustedApy30dAverage) / 2;
|
|
2836
|
-
}
|
|
2837
|
-
function assetAddressValue(record, address) {
|
|
2838
|
-
const entry = Object.entries(record).find(
|
|
2839
|
-
([key2]) => key2.toLowerCase() === address.toLowerCase()
|
|
2840
|
-
);
|
|
2841
|
-
return entry?.[1] ?? "0";
|
|
2842
|
-
}
|
|
2843
|
-
function position(value, asset, baseAssetDecimals) {
|
|
2844
|
-
const option = value?.yieldOption;
|
|
2845
|
-
if (!option || typeof option.provider !== "string" || typeof option.name !== "string" || typeof option.address !== "string" || !isAddress(option.address)) {
|
|
2846
|
-
return invalid("yield positions", "missing vault metadata");
|
|
2847
|
-
}
|
|
2848
|
-
return {
|
|
2849
|
-
chain: "BASE",
|
|
2850
|
-
protocol: option.provider,
|
|
2851
|
-
protocolId: option.address,
|
|
2852
|
-
pool: option.name,
|
|
2853
|
-
asset,
|
|
2854
|
-
// `assetsRaw` is the ERC-4626 vault-share quantity, whose decimals can
|
|
2855
|
-
// differ from the underlying asset. Yieldseeker already converts it to
|
|
2856
|
-
// underlying base-asset units in `assetsBase`; pair that value with the
|
|
2857
|
-
// snapshot's corresponding `baseAssetDecimals` for display. Keep the raw
|
|
2858
|
-
// share quantity separately because withdraw-from-position expects it.
|
|
2859
|
-
amount: decimal(
|
|
2860
|
-
value.assetsBase,
|
|
2861
|
-
baseAssetDecimals,
|
|
2862
|
-
"yield positions"
|
|
2863
|
-
),
|
|
2864
|
-
amountRaw: String(value.assetsRaw),
|
|
2865
|
-
apy: percent(option.riskAdjustedApy),
|
|
2866
|
-
tvl: Number(option.totalDepositsUsd),
|
|
2867
|
-
liquidity: Number(option.withdrawableDepositsUsd)
|
|
2868
|
-
};
|
|
2869
|
-
}
|
|
2870
|
-
function mapYieldseekerBalances(contexts) {
|
|
2871
|
-
const tokens = [];
|
|
2872
|
-
const assetBalances = [];
|
|
2873
|
-
const positions = [];
|
|
2874
|
-
let totalUsd = 0;
|
|
2875
|
-
for (const context of contexts) {
|
|
2876
|
-
const metadata = YIELDSEEKER_ASSET_METADATA[context.asset];
|
|
2877
|
-
assetBalances.push({
|
|
2878
|
-
chain: "BASE",
|
|
2879
|
-
chainId: 8453,
|
|
2880
|
-
asset: context.asset,
|
|
2881
|
-
amount: decimal(context.snapshot.totalValueBase, context.snapshot.baseAssetDecimals, "snapshot")
|
|
2882
|
-
});
|
|
2883
|
-
const idle = assetAddressValue(
|
|
2884
|
-
context.snapshot.tokenBalances,
|
|
2885
|
-
metadata.address
|
|
2886
|
-
);
|
|
2887
|
-
tokens.push({
|
|
2888
|
-
chain: "BASE",
|
|
2889
|
-
chainId: 8453,
|
|
2890
|
-
asset: context.asset,
|
|
2891
|
-
amount: decimal(idle, metadata.decimals, "snapshot")
|
|
2892
|
-
});
|
|
2893
|
-
positions.push(
|
|
2894
|
-
...context.positions.map(
|
|
2895
|
-
(entry) => position(
|
|
2896
|
-
entry,
|
|
2897
|
-
context.asset,
|
|
2898
|
-
context.snapshot.baseAssetDecimals
|
|
2899
|
-
)
|
|
2900
|
-
)
|
|
2901
|
-
);
|
|
2902
|
-
totalUsd += usd(
|
|
2903
|
-
raw(context.snapshot.totalValueBase, "snapshot"),
|
|
2904
|
-
context.snapshot.baseAssetDecimals,
|
|
2905
|
-
context.snapshot.baseAssetPriceUsd
|
|
2906
|
-
);
|
|
2907
|
-
}
|
|
2908
|
-
return {
|
|
2909
|
-
...contexts.length === 1 ? { smartWallet: contexts[0].wallet.walletAddress } : {},
|
|
2910
|
-
totalBalance: String(totalUsd),
|
|
2911
|
-
totalBalanceAsset: "usdc",
|
|
2912
|
-
assetBalances,
|
|
2913
|
-
tokens,
|
|
2914
|
-
positions
|
|
2915
|
-
};
|
|
2611
|
+
// src/lib/swap/swap.executor.ts
|
|
2612
|
+
var DEFAULT_SLIPPAGE = 1;
|
|
2613
|
+
async function affordableAmount(deps, quoted) {
|
|
2614
|
+
const balance = await deps.readSourceBalance();
|
|
2615
|
+
if (balance >= quoted) return quoted;
|
|
2616
|
+
debugLog("owney-sdk", "swap: trimming to the current source balance", {
|
|
2617
|
+
quoted: quoted.toString(),
|
|
2618
|
+
balance: balance.toString(),
|
|
2619
|
+
short: (quoted - balance).toString()
|
|
2620
|
+
});
|
|
2621
|
+
return balance;
|
|
2916
2622
|
}
|
|
2917
|
-
function
|
|
2918
|
-
const
|
|
2919
|
-
|
|
2920
|
-
|
|
2921
|
-
|
|
2922
|
-
|
|
2923
|
-
|
|
2924
|
-
|
|
2925
|
-
|
|
2926
|
-
|
|
2927
|
-
|
|
2928
|
-
|
|
2929
|
-
|
|
2930
|
-
|
|
2931
|
-
|
|
2623
|
+
async function executeSwap(deps, options) {
|
|
2624
|
+
const { quote, walletAddress, onStage } = options;
|
|
2625
|
+
debugLog("owney-sdk", "swap: start", {
|
|
2626
|
+
rail: quote.rail,
|
|
2627
|
+
from: `${quote.src.amount} ${quote.src.symbol} on ${quote.src.chainId}`,
|
|
2628
|
+
to: `${quote.dst.symbol} on ${quote.dst.chainId}`,
|
|
2629
|
+
expected: quote.dst.amount,
|
|
2630
|
+
floor: quote.dstAmountMin
|
|
2631
|
+
});
|
|
2632
|
+
const before = await deps.readTargetBalance();
|
|
2633
|
+
debugLog("owney-sdk", "swap: target balance before", before.toString());
|
|
2634
|
+
const result = quote.rail === "classic" ? await runClassic(deps, options) : await runFusion(deps, options, walletAddress);
|
|
2635
|
+
const after = await deps.readTargetBalance();
|
|
2636
|
+
const received = after - before;
|
|
2637
|
+
debugLog("owney-sdk", "swap: target balance after", {
|
|
2638
|
+
after: after.toString(),
|
|
2639
|
+
received: received.toString()
|
|
2640
|
+
});
|
|
2641
|
+
if (received <= 0n) {
|
|
2642
|
+
throw new OwneyError(
|
|
2643
|
+
"SWAP_REQUEST_FAILED",
|
|
2644
|
+
"The swap completed but no funds arrived in the wallet. Check the transaction before retrying.",
|
|
2645
|
+
{ rail: quote.rail, ...result }
|
|
2932
2646
|
);
|
|
2933
2647
|
}
|
|
2934
|
-
return {
|
|
2935
|
-
smartWallet: contexts[0]?.wallet.walletAddress ?? "0x0000000000000000000000000000000000000000",
|
|
2936
|
-
lifetimeEarnings,
|
|
2937
|
-
tokens
|
|
2938
|
-
};
|
|
2939
|
-
}
|
|
2940
|
-
function apyForDays(context, days, now) {
|
|
2941
|
-
if (days === "7D") return percent(context.snapshot.apy7d);
|
|
2942
|
-
if (days === "30D") return percent(context.snapshot.apy30d);
|
|
2943
|
-
const apy = calculateSnapshotApy(context.historic?.dailyYieldSnapshots ?? [], 14, now);
|
|
2944
|
-
const apyPercent = apy === void 0 ? void 0 : apy * 100;
|
|
2945
|
-
return apyPercent !== void 0 && Number.isFinite(apyPercent) ? apyPercent : void 0;
|
|
2946
|
-
}
|
|
2947
|
-
function dailyApy(point) {
|
|
2948
|
-
const total = raw(point.totalValueBase, "historic position");
|
|
2949
|
-
const earned = raw(point.dailyYieldBase, "historic position");
|
|
2950
|
-
const principal = total - earned;
|
|
2951
|
-
if (principal <= 0n || earned === 0n) return 0;
|
|
2952
|
-
return Number(earned) / Number(principal) * 365 * 100;
|
|
2648
|
+
return { received: received.toString(), ...result };
|
|
2953
2649
|
}
|
|
2954
|
-
function
|
|
2955
|
-
const
|
|
2956
|
-
|
|
2957
|
-
const assets = new Set(contexts.map((context) => context.asset.toUpperCase()));
|
|
2958
|
-
const unit = assets.size === 1 ? [...assets][0] : "USD";
|
|
2959
|
-
const byDate = /* @__PURE__ */ new Map();
|
|
2960
|
-
for (const context of contexts) {
|
|
2961
|
-
const points = context.historic?.dailyYieldSnapshots ?? [];
|
|
2962
|
-
for (const point of points) {
|
|
2963
|
-
if (!/^\d{4}-\d{2}-\d{2}$/.test(point.date) || !Number.isFinite(Date.parse(point.date)) || point.date < cutoff || point.date > today) continue;
|
|
2964
|
-
const tokens = Number(decimal(point.totalValueBase, point.baseAssetDecimals, "historic position"));
|
|
2965
|
-
const amount = assets.size === 1 ? tokens : tokens * point.baseAssetPriceUsd;
|
|
2966
|
-
if (!Number.isFinite(amount) || amount < 0) {
|
|
2967
|
-
invalid("historic position", "expected a finite non-negative balance");
|
|
2968
|
-
}
|
|
2969
|
-
const current = byDate.get(point.date) ?? { weighted: 0, amount: 0 };
|
|
2970
|
-
current.weighted += dailyApy(point) * amount;
|
|
2971
|
-
current.amount += amount;
|
|
2972
|
-
byDate.set(point.date, current);
|
|
2973
|
-
}
|
|
2974
|
-
}
|
|
2975
|
-
return [...byDate.entries()].sort(([left], [right]) => left.localeCompare(right)).map(([date, value]) => ({
|
|
2976
|
-
date,
|
|
2977
|
-
apy: value.amount > 0 ? value.weighted / value.amount : 0,
|
|
2978
|
-
historicalBalance: { amount: value.amount, unit }
|
|
2979
|
-
}));
|
|
2980
|
-
}
|
|
2981
|
-
function mapYieldseekerApy(walletAddress, contexts, days, now = Date.now()) {
|
|
2982
|
-
let weighted = 0;
|
|
2983
|
-
let totalUsd = 0;
|
|
2984
|
-
const byAsset = {};
|
|
2985
|
-
for (const context of contexts) {
|
|
2986
|
-
const valueUsd = usd(
|
|
2987
|
-
raw(context.snapshot.totalValueBase, "snapshot"),
|
|
2988
|
-
context.snapshot.baseAssetDecimals,
|
|
2989
|
-
context.snapshot.baseAssetPriceUsd
|
|
2990
|
-
);
|
|
2991
|
-
const apy = apyForDays(context, days, now);
|
|
2992
|
-
if (apy === void 0) continue;
|
|
2993
|
-
weighted += apy * valueUsd;
|
|
2994
|
-
totalUsd += valueUsd;
|
|
2995
|
-
byAsset[context.asset] = apy;
|
|
2996
|
-
}
|
|
2997
|
-
const dayCount = Number(days.slice(0, -1));
|
|
2998
|
-
return {
|
|
2650
|
+
async function runClassic(deps, options) {
|
|
2651
|
+
const {
|
|
2652
|
+
quote,
|
|
2999
2653
|
walletAddress,
|
|
3000
|
-
|
|
3001
|
-
|
|
3002
|
-
|
|
3003
|
-
};
|
|
3004
|
-
|
|
3005
|
-
|
|
3006
|
-
const
|
|
3007
|
-
|
|
3008
|
-
|
|
3009
|
-
|
|
3010
|
-
|
|
3011
|
-
|
|
3012
|
-
}
|
|
3013
|
-
|
|
3014
|
-
|
|
3015
|
-
|
|
3016
|
-
|
|
3017
|
-
|
|
3018
|
-
|
|
3019
|
-
|
|
3020
|
-
|
|
3021
|
-
|
|
3022
|
-
|
|
3023
|
-
|
|
3024
|
-
|
|
3025
|
-
|
|
3026
|
-
|
|
3027
|
-
|
|
3028
|
-
|
|
3029
|
-
|
|
3030
|
-
|
|
3031
|
-
|
|
3032
|
-
|
|
3033
|
-
|
|
3034
|
-
|
|
3035
|
-
|
|
3036
|
-
chainId: 8453
|
|
3037
|
-
}
|
|
3038
|
-
],
|
|
3039
|
-
rebalanceLog: []
|
|
3040
|
-
};
|
|
3041
|
-
}
|
|
3042
|
-
function depositDestination(context, movement) {
|
|
3043
|
-
const to = movement.toAddress.toLowerCase();
|
|
3044
|
-
const option = context.positions.find(({ yieldOption }) => yieldOption.chainId === movement.chainId && yieldOption.assetAddress.toLowerCase() === context.agent.assetAddress.toLowerCase() && yieldOption.address.toLowerCase() === to)?.yieldOption;
|
|
3045
|
-
if (option) return { protocol: option.provider || "Vault", pool: option.name, tokenSymbol: context.asset };
|
|
3046
|
-
const receipt = context.historic?.assets.find((asset) => asset.chainId === movement.chainId && !asset.isSpam && asset.address.toLowerCase() === to && asset.address.toLowerCase() !== context.agent.assetAddress.toLowerCase());
|
|
3047
|
-
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);
|
|
3048
|
-
if (receipt && minted) return { protocol: "Vault", pool: receipt.name || receipt.symbol, tokenSymbol: context.asset };
|
|
3049
|
-
return void 0;
|
|
3050
|
-
}
|
|
3051
|
-
function movementEntry(movement, wallet, agent, asset, ownerAddress, vaultAddresses, destination) {
|
|
3052
|
-
const from = movement.fromAddress.toLowerCase();
|
|
3053
|
-
const to = movement.toAddress.toLowerCase();
|
|
3054
|
-
const owner = ownerAddress.toLowerCase();
|
|
3055
|
-
const agentWallet = wallet.walletAddress.toLowerCase();
|
|
3056
|
-
const baseAsset = agent.assetAddress.toLowerCase();
|
|
3057
|
-
if (movement.chainId !== agent.chainId || movement.assetAddress.toLowerCase() !== baseAsset) {
|
|
3058
|
-
return void 0;
|
|
3059
|
-
}
|
|
3060
|
-
let action;
|
|
3061
|
-
if (to === agentWallet && !vaultAddresses.has(from)) {
|
|
3062
|
-
action = "Top up";
|
|
3063
|
-
} else if (from === agentWallet && to === owner) {
|
|
3064
|
-
action = "Withdraw";
|
|
3065
|
-
} else if (from === agentWallet && destination) {
|
|
3066
|
-
action = "Deposit";
|
|
3067
|
-
}
|
|
3068
|
-
if (!action) return void 0;
|
|
3069
|
-
return {
|
|
3070
|
-
agent: "yieldseeker",
|
|
3071
|
-
action,
|
|
3072
|
-
...action === "Deposit" && destination ? { positions: [{
|
|
3073
|
-
...destination,
|
|
3074
|
-
amount: decimal(movement.assetAmount, YIELDSEEKER_ASSET_METADATA[asset].decimals, "historic position")
|
|
3075
|
-
}] } : {},
|
|
3076
|
-
date: movement.blockDate,
|
|
3077
|
-
oldApy: null,
|
|
3078
|
-
newApy: null,
|
|
3079
|
-
transactions: [
|
|
3080
|
-
{
|
|
3081
|
-
txHashes: [movement.transactionHash],
|
|
3082
|
-
chainId: agent.chainId,
|
|
3083
|
-
tokenSymbol: asset,
|
|
3084
|
-
amount: decimal(
|
|
3085
|
-
movement.assetAmount,
|
|
3086
|
-
YIELDSEEKER_ASSET_METADATA[asset].decimals,
|
|
3087
|
-
"historic position"
|
|
3088
|
-
)
|
|
3089
|
-
}
|
|
3090
|
-
],
|
|
3091
|
-
rebalanceLog: []
|
|
3092
|
-
};
|
|
3093
|
-
}
|
|
3094
|
-
function mapYieldseekerHistory(contexts, options) {
|
|
3095
|
-
const entries = contexts.flatMap((context) => {
|
|
3096
|
-
const seenMovements = /* @__PURE__ */ new Set();
|
|
3097
|
-
const movements = (context.historic?.movements ?? []).filter((movement) => {
|
|
3098
|
-
const key2 = `${movement.chainId}:${movement.transactionHash.toLowerCase()}:${movement.logIndex}`;
|
|
3099
|
-
if (seenMovements.has(key2)) return false;
|
|
3100
|
-
seenMovements.add(key2);
|
|
3101
|
-
return true;
|
|
3102
|
-
});
|
|
3103
|
-
return [
|
|
3104
|
-
...movements.map(
|
|
3105
|
-
(movement) => movementEntry(
|
|
3106
|
-
movement,
|
|
3107
|
-
context.wallet,
|
|
3108
|
-
context.agent,
|
|
3109
|
-
context.asset,
|
|
3110
|
-
options.ownerAddress,
|
|
3111
|
-
options.vaultAddresses,
|
|
3112
|
-
depositDestination(context, movement)
|
|
3113
|
-
)
|
|
3114
|
-
),
|
|
3115
|
-
...(context.actions ?? []).map(actionEntry)
|
|
3116
|
-
].filter((entry) => entry !== void 0);
|
|
3117
|
-
});
|
|
3118
|
-
const grouped = /* @__PURE__ */ new Map();
|
|
3119
|
-
const ungrouped = [];
|
|
3120
|
-
for (const entry of entries) {
|
|
3121
|
-
const tx = entry.transactions[0];
|
|
3122
|
-
const hash = tx?.txHashes[0];
|
|
3123
|
-
if (!hash) {
|
|
3124
|
-
ungrouped.push(entry);
|
|
3125
|
-
continue;
|
|
3126
|
-
}
|
|
3127
|
-
const key2 = `${entry.agent}:${entry.action}:${tx.chainId}:${hash.toLowerCase()}`;
|
|
3128
|
-
const previous = grouped.get(key2);
|
|
3129
|
-
if (!previous) {
|
|
3130
|
-
grouped.set(key2, entry);
|
|
3131
|
-
continue;
|
|
3132
|
-
}
|
|
3133
|
-
if (entry.action === "Deposit" && entry.positions?.length) {
|
|
3134
|
-
if (!previous.positions?.length) {
|
|
3135
|
-
grouped.set(key2, entry);
|
|
3136
|
-
continue;
|
|
3137
|
-
}
|
|
3138
|
-
previous.positions.push(...entry.positions);
|
|
3139
|
-
previous.transactions.push(...entry.transactions);
|
|
3140
|
-
}
|
|
3141
|
-
}
|
|
3142
|
-
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));
|
|
3143
|
-
return {
|
|
3144
|
-
data: filtered.slice(0, options.limit),
|
|
3145
|
-
// v1 returns the whole action/movement collection and defines no cursor.
|
|
3146
|
-
// Report a terminal page so callers never loop over the same prefix.
|
|
3147
|
-
hasMore: false
|
|
3148
|
-
};
|
|
3149
|
-
}
|
|
3150
|
-
function mapYieldseekerProfile(address, contexts) {
|
|
3151
|
-
const protocols = /* @__PURE__ */ new Set();
|
|
3152
|
-
for (const context of contexts) {
|
|
3153
|
-
for (const current of context.positions) {
|
|
3154
|
-
if (current.yieldOption?.provider) {
|
|
3155
|
-
protocols.add(String(current.yieldOption.provider));
|
|
3156
|
-
}
|
|
3157
|
-
}
|
|
3158
|
-
}
|
|
3159
|
-
return {
|
|
3160
|
-
address,
|
|
3161
|
-
smartWallet: contexts[0]?.wallet.walletAddress ?? "0x0000000000000000000000000000000000000000",
|
|
3162
|
-
chains: contexts.length > 0 ? [8453] : [],
|
|
3163
|
-
hasActiveSessionKey: contexts.some(
|
|
3164
|
-
(context) => context.wallet.initializedDate != null
|
|
3165
|
-
),
|
|
3166
|
-
protocols: [...protocols]
|
|
3167
|
-
};
|
|
3168
|
-
}
|
|
3169
|
-
function mapYieldseekerAgentApy(options, days) {
|
|
3170
|
-
const perAsset = {};
|
|
3171
|
-
const all = [];
|
|
3172
|
-
for (const entry of options) {
|
|
3173
|
-
const apys = entry.yieldOptions.map(
|
|
3174
|
-
(option) => publicApyAfterYieldseekerFee(riskAdjustedApyForDays(option, days))
|
|
3175
|
-
).filter(Number.isFinite);
|
|
3176
|
-
if (apys.length === 0) continue;
|
|
3177
|
-
const average = apys.reduce((sum, value) => sum + value, 0) / apys.length;
|
|
3178
|
-
perAsset[entry.asset] = average;
|
|
3179
|
-
all.push(average);
|
|
3180
|
-
}
|
|
3181
|
-
return {
|
|
3182
|
-
averageApy: all.length > 0 ? all.reduce((sum, value) => sum + value, 0) / all.length : 0,
|
|
3183
|
-
detailedApys: { apyPerAsset: { 8453: perAsset } }
|
|
3184
|
-
};
|
|
3185
|
-
}
|
|
3186
|
-
|
|
3187
|
-
// src/agents/yieldseeker/yieldseeker.agent.ts
|
|
3188
|
-
var OWNEY_AGENT_NAME = "owney";
|
|
3189
|
-
var YIELDSEEKER_USERNAME_PREFIX = "owney_";
|
|
3190
|
-
var YIELDSEEKER_USERNAME_RANDOM_LENGTH = 14;
|
|
3191
|
-
var YIELDSEEKER_USERNAME_CREATE_ATTEMPTS = 3;
|
|
3192
|
-
var YIELDSEEKER_YIELD_OPTIONS_CACHE_MS = 6e4;
|
|
3193
|
-
function generateYieldseekerUsername() {
|
|
3194
|
-
const suffix = globalThis.crypto.randomUUID().replaceAll("-", "").slice(0, YIELDSEEKER_USERNAME_RANDOM_LENGTH).toLowerCase();
|
|
3195
|
-
return `${YIELDSEEKER_USERNAME_PREFIX}${suffix}`;
|
|
3196
|
-
}
|
|
3197
|
-
function isUsernameConflict(error) {
|
|
3198
|
-
if (!(error instanceof YieldseekerApiError)) return false;
|
|
3199
|
-
const code = error.providerCode.toUpperCase();
|
|
3200
|
-
return code.includes("USERNAME") && (code.includes("TAKEN") || code.includes("EXIST") || code.includes("UNAVAILABLE") || code.includes("IN_USE"));
|
|
3201
|
-
}
|
|
3202
|
-
var YIELDSEEKER_AGENT_WALLET_ABI = [
|
|
3203
|
-
{
|
|
3204
|
-
type: "function",
|
|
3205
|
-
name: "withdrawAssetToUser",
|
|
3206
|
-
stateMutability: "nonpayable",
|
|
3207
|
-
inputs: [
|
|
3208
|
-
{ name: "recipient", type: "address" },
|
|
3209
|
-
{ name: "asset", type: "address" },
|
|
3210
|
-
{ name: "amount", type: "uint256" }
|
|
3211
|
-
],
|
|
3212
|
-
outputs: []
|
|
3213
|
-
},
|
|
3214
|
-
{
|
|
3215
|
-
type: "function",
|
|
3216
|
-
name: "withdrawAllAssetToUser",
|
|
3217
|
-
stateMutability: "nonpayable",
|
|
3218
|
-
inputs: [
|
|
3219
|
-
{ name: "recipient", type: "address" },
|
|
3220
|
-
{ name: "asset", type: "address" }
|
|
3221
|
-
],
|
|
3222
|
-
outputs: []
|
|
3223
|
-
}
|
|
3224
|
-
];
|
|
3225
|
-
function query(params) {
|
|
3226
|
-
const search = new URLSearchParams();
|
|
3227
|
-
for (const [key2, value] of Object.entries(params)) {
|
|
3228
|
-
if (value !== void 0) search.set(key2, String(value));
|
|
3229
|
-
}
|
|
3230
|
-
const encoded = search.toString();
|
|
3231
|
-
return encoded ? `?${encoded}` : "";
|
|
3232
|
-
}
|
|
3233
|
-
var YieldseekerAgent = class {
|
|
3234
|
-
id = "yieldseeker";
|
|
3235
|
-
balanceComposition = "tokens-plus-positions";
|
|
3236
|
-
supportedChainIds = [8453];
|
|
3237
|
-
supportedAssets = [
|
|
3238
|
-
{
|
|
3239
|
-
chainId: 8453,
|
|
3240
|
-
chain: "BASE",
|
|
3241
|
-
assets: [
|
|
3242
|
-
{ symbol: "USDC", minDepositAmount: "10000000" },
|
|
3243
|
-
{ symbol: "WETH", minDepositAmount: "1" }
|
|
3244
|
-
]
|
|
3245
|
-
}
|
|
3246
|
-
];
|
|
3247
|
-
api;
|
|
3248
|
-
auth;
|
|
3249
|
-
transactionExecutor;
|
|
3250
|
-
unwindReceiptWaiter;
|
|
3251
|
-
agentContexts = /* @__PURE__ */ new Map();
|
|
3252
|
-
users = /* @__PURE__ */ new Map();
|
|
3253
|
-
pendingAgents = /* @__PURE__ */ new Map();
|
|
3254
|
-
yieldOptions = /* @__PURE__ */ new Map();
|
|
3255
|
-
pendingYieldOptions = /* @__PURE__ */ new Map();
|
|
3256
|
-
constructor(owneyApiKey, options = {}) {
|
|
3257
|
-
this.api = new YieldseekerApiClient(
|
|
3258
|
-
owneyApiKey,
|
|
3259
|
-
options.baseUrl ?? getYieldseekerProxyBaseUrl(),
|
|
3260
|
-
options.fetchFn
|
|
3261
|
-
);
|
|
3262
|
-
this.auth = new YieldseekerAuth(options.auth);
|
|
3263
|
-
this.transactionExecutor = options.transactionExecutor;
|
|
3264
|
-
this.unwindReceiptWaiter = options.unwindReceiptWaiter;
|
|
3265
|
-
}
|
|
3266
|
-
async disconnect() {
|
|
3267
|
-
this.auth.clear();
|
|
3268
|
-
for (const key2 of this.users.keys()) {
|
|
3269
|
-
const [walletAddress, chainId] = key2.split(":");
|
|
3270
|
-
clearYieldseekerIdentity(walletAddress, Number(chainId));
|
|
3271
|
-
}
|
|
3272
|
-
this.users.clear();
|
|
3273
|
-
this.agentContexts.clear();
|
|
3274
|
-
this.pendingAgents.clear();
|
|
3275
|
-
}
|
|
3276
|
-
async activateAgent(state, chainId, asset) {
|
|
3277
|
-
this.assertChain(chainId);
|
|
3278
|
-
const targetAsset = asset ?? "USDC";
|
|
3279
|
-
this.assertAsset(targetAsset);
|
|
3280
|
-
await this.ensureAgent(state, chainId, targetAsset);
|
|
3281
|
-
}
|
|
3282
|
-
async deposit(state, chainId, amount, asset, depositCallback) {
|
|
3283
|
-
this.assertChain(chainId);
|
|
3284
|
-
this.assertAsset(asset);
|
|
3285
|
-
if (BigInt(amount) <= 0n) {
|
|
3286
|
-
throw new OwneyError(
|
|
3287
|
-
"DEPOSIT_AMOUNT_BELOW_MINIMUM",
|
|
3288
|
-
"Yieldseeker deposits must be greater than zero.",
|
|
3289
|
-
{ amount, minDepositAmount: "1" },
|
|
3290
|
-
this.id
|
|
3291
|
-
);
|
|
3292
|
-
}
|
|
3293
|
-
const context = await this.ensureAgent(state, chainId, asset);
|
|
3294
|
-
let txHash;
|
|
3295
|
-
try {
|
|
3296
|
-
if (depositCallback) {
|
|
3297
|
-
provideDepositVerificationContext(depositCallback, {
|
|
3298
|
-
agentId: "yieldseeker",
|
|
3299
|
-
signature: await this.auth.getToken(state, chainId),
|
|
3300
|
-
userId: context.user.userId,
|
|
3301
|
-
yieldseekerAgentId: context.agent.agentId
|
|
3302
|
-
});
|
|
3303
|
-
txHash = await depositCallback(
|
|
3304
|
-
context.wallet.walletAddress,
|
|
3305
|
-
chainId,
|
|
3306
|
-
amount
|
|
3307
|
-
);
|
|
3308
|
-
await this.waitForReceipt(state, chainId, txHash);
|
|
3309
|
-
} else {
|
|
3310
|
-
txHash = await this.submitTransaction(state, chainId, {
|
|
3311
|
-
from: getAddress2(state.walletAddress),
|
|
3312
|
-
to: YIELDSEEKER_ASSET_METADATA[asset].address,
|
|
3313
|
-
data: encodeFunctionData({
|
|
3314
|
-
abi: erc20Abi,
|
|
3315
|
-
functionName: "transfer",
|
|
3316
|
-
args: [getAddress2(context.wallet.walletAddress), BigInt(amount)]
|
|
3317
|
-
}),
|
|
3318
|
-
value: "0",
|
|
3319
|
-
chainId
|
|
3320
|
-
});
|
|
3321
|
-
}
|
|
3322
|
-
} finally {
|
|
3323
|
-
await this.refreshSnapshotAfterMovement(
|
|
3324
|
-
state,
|
|
3325
|
-
chainId,
|
|
3326
|
-
context,
|
|
3327
|
-
"deposit"
|
|
3328
|
-
);
|
|
3329
|
-
}
|
|
3330
|
-
return {
|
|
3331
|
-
txHash,
|
|
3332
|
-
smartWallet: context.wallet.walletAddress,
|
|
3333
|
-
amount
|
|
3334
|
-
};
|
|
3335
|
-
}
|
|
3336
|
-
async withdraw(state, chainId, asset, amount) {
|
|
3337
|
-
this.assertChain(chainId);
|
|
3338
|
-
this.assertAsset(asset);
|
|
3339
|
-
if (amount !== void 0 && BigInt(amount) <= 0n) {
|
|
3340
|
-
throw new OwneyError(
|
|
3341
|
-
"WITHDRAW_FAILED",
|
|
3342
|
-
"Yieldseeker withdrawals must be greater than zero.",
|
|
3343
|
-
{ amount },
|
|
3344
|
-
this.id
|
|
3345
|
-
);
|
|
3346
|
-
}
|
|
3347
|
-
const context = await this.findAgent(state, chainId, asset);
|
|
3348
|
-
if (!context) {
|
|
3349
|
-
throw new OwneyError(
|
|
3350
|
-
"WITHDRAW_INSUFFICIENT_BALANCE",
|
|
3351
|
-
`No Yieldseeker ${asset} agent exists for this wallet.`,
|
|
3352
|
-
{ asset, available: "0" },
|
|
3353
|
-
this.id
|
|
3354
|
-
);
|
|
3355
|
-
}
|
|
3356
|
-
try {
|
|
3357
|
-
const portfolio = await this.loadPortfolioContext(
|
|
3358
|
-
state,
|
|
3359
|
-
chainId,
|
|
3360
|
-
context
|
|
3361
|
-
);
|
|
3362
|
-
const metadata = YIELDSEEKER_ASSET_METADATA[asset];
|
|
3363
|
-
const idleEntry = Object.entries(portfolio.snapshot.tokenBalances).find(
|
|
3364
|
-
([address]) => address.toLowerCase() === metadata.address.toLowerCase()
|
|
3365
|
-
);
|
|
3366
|
-
const idle = BigInt(idleEntry?.[1] ?? "0");
|
|
3367
|
-
const deployed = portfolio.positions.reduce(
|
|
3368
|
-
(total, position2) => total + BigInt(position2.withdrawableAssetsRaw),
|
|
3369
|
-
0n
|
|
3370
|
-
);
|
|
3371
|
-
const totalAvailable = idle + deployed;
|
|
3372
|
-
const requested = amount === void 0 ? totalAvailable : BigInt(amount);
|
|
3373
|
-
if (requested > totalAvailable) {
|
|
3374
|
-
throw new OwneyError(
|
|
3375
|
-
"WITHDRAW_INSUFFICIENT_BALANCE",
|
|
3376
|
-
`Requested withdrawal "${requested}" exceeds available Yieldseeker balance "${totalAvailable}" for asset "${asset}".`,
|
|
3377
|
-
{
|
|
3378
|
-
asset,
|
|
3379
|
-
requested: requested.toString(),
|
|
3380
|
-
available: totalAvailable.toString()
|
|
3381
|
-
},
|
|
3382
|
-
this.id
|
|
3383
|
-
);
|
|
3384
|
-
}
|
|
3385
|
-
let remaining = requested > idle ? requested - idle : 0n;
|
|
3386
|
-
for (const position2 of portfolio.positions) {
|
|
3387
|
-
if (remaining === 0n) break;
|
|
3388
|
-
const available = BigInt(position2.withdrawableAssetsRaw);
|
|
3389
|
-
if (available <= 0n) continue;
|
|
3390
|
-
const assetsRaw = available < remaining ? available : remaining;
|
|
3391
|
-
const response = await this.walletRequest(
|
|
3392
|
-
state,
|
|
3393
|
-
chainId,
|
|
3394
|
-
this.agentPath(context, "withdraw-from-position"),
|
|
3395
|
-
{
|
|
3396
|
-
method: "POST",
|
|
3397
|
-
body: {
|
|
3398
|
-
chainId,
|
|
3399
|
-
vaultAddress: position2.yieldOption.address,
|
|
3400
|
-
assetsRaw: assetsRaw.toString()
|
|
3401
|
-
}
|
|
3402
|
-
}
|
|
3403
|
-
);
|
|
3404
|
-
if (!this.isTransactionHash(response?.transactionHash)) {
|
|
3405
|
-
throw this.invalidResponse("position withdrawal");
|
|
3406
|
-
}
|
|
3407
|
-
await this.waitForReceipt(state, chainId, response.transactionHash);
|
|
3408
|
-
remaining -= assetsRaw;
|
|
3409
|
-
}
|
|
3410
|
-
if (remaining > 0n) {
|
|
3411
|
-
throw this.invalidResponse("yield positions", {
|
|
3412
|
-
reason: "Withdrawable positions could not cover the request.",
|
|
3413
|
-
remaining: remaining.toString()
|
|
3414
|
-
});
|
|
3415
|
-
}
|
|
3416
|
-
const account = getAddress2(state.walletAddress);
|
|
3417
|
-
const txHash = await this.submitTransaction(state, chainId, {
|
|
3418
|
-
from: account,
|
|
3419
|
-
to: getAddress2(context.wallet.walletAddress),
|
|
3420
|
-
data: amount === void 0 ? encodeFunctionData({
|
|
3421
|
-
abi: YIELDSEEKER_AGENT_WALLET_ABI,
|
|
3422
|
-
functionName: "withdrawAllAssetToUser",
|
|
3423
|
-
args: [account, metadata.address]
|
|
3424
|
-
}) : encodeFunctionData({
|
|
3425
|
-
abi: YIELDSEEKER_AGENT_WALLET_ABI,
|
|
3426
|
-
functionName: "withdrawAssetToUser",
|
|
3427
|
-
args: [account, metadata.address, requested]
|
|
3428
|
-
}),
|
|
3429
|
-
value: "0",
|
|
3430
|
-
chainId
|
|
3431
|
-
});
|
|
3432
|
-
return {
|
|
3433
|
-
txHash,
|
|
3434
|
-
type: amount === void 0 ? "full" : "partial",
|
|
3435
|
-
amount: requested.toString()
|
|
3436
|
-
};
|
|
3437
|
-
} finally {
|
|
3438
|
-
await this.refreshSnapshotAfterMovement(
|
|
3439
|
-
state,
|
|
3440
|
-
chainId,
|
|
3441
|
-
context,
|
|
3442
|
-
"withdrawal"
|
|
3443
|
-
);
|
|
3444
|
-
}
|
|
3445
|
-
}
|
|
3446
|
-
async getBalances(state, chainId) {
|
|
3447
|
-
this.assertChain(chainId);
|
|
3448
|
-
return mapYieldseekerBalances(await this.loadPortfolio(state, chainId, {}));
|
|
3449
|
-
}
|
|
3450
|
-
async getEarnings(state, chainId) {
|
|
3451
|
-
this.assertChain(chainId);
|
|
3452
|
-
return mapYieldseekerEarnings(await this.loadPortfolio(state, chainId, {}));
|
|
3453
|
-
}
|
|
3454
|
-
async getAccountApy(state, chainId, days, tokenSymbol) {
|
|
3455
|
-
this.assertChain(chainId);
|
|
3456
|
-
const asset = tokenSymbol?.toUpperCase();
|
|
3457
|
-
if (asset !== void 0) this.assertAsset(asset);
|
|
3458
|
-
const contexts = await this.loadPortfolio(state, chainId, {
|
|
3459
|
-
...asset ? { asset } : {},
|
|
3460
|
-
historic: true
|
|
3461
|
-
});
|
|
3462
|
-
return mapYieldseekerApy(state.walletAddress, contexts, days);
|
|
3463
|
-
}
|
|
3464
|
-
async getHistory(state, chainId, options) {
|
|
3465
|
-
this.assertChain(chainId);
|
|
3466
|
-
const asset = options?.tokenSymbol?.toUpperCase();
|
|
3467
|
-
if (asset !== void 0) this.assertAsset(asset);
|
|
3468
|
-
const contexts = await this.loadPortfolio(state, chainId, {
|
|
3469
|
-
...asset ? { asset } : {},
|
|
3470
|
-
historic: true,
|
|
3471
|
-
actions: true
|
|
3472
|
-
});
|
|
3473
|
-
const catalog = await Promise.all(
|
|
3474
|
-
[...new Set(contexts.map((context) => context.asset))].map(
|
|
3475
|
-
(contextAsset) => this.loadYieldOptions(contextAsset)
|
|
3476
|
-
)
|
|
3477
|
-
);
|
|
3478
|
-
const vaultAddresses = new Set(
|
|
3479
|
-
catalog.flat().filter(
|
|
3480
|
-
(yieldOption) => yieldOption.chainId === chainId && isAddress2(yieldOption.address)
|
|
3481
|
-
).map((yieldOption) => yieldOption.address.toLowerCase())
|
|
3482
|
-
);
|
|
3483
|
-
return mapYieldseekerHistory(contexts, {
|
|
3484
|
-
limit: options?.limit ?? 10,
|
|
3485
|
-
ownerAddress: state.walletAddress,
|
|
3486
|
-
vaultAddresses,
|
|
3487
|
-
...options?.fromDate ? { fromDate: options.fromDate } : {},
|
|
3488
|
-
...options?.toDate ? { toDate: options.toDate } : {}
|
|
3489
|
-
});
|
|
3490
|
-
}
|
|
3491
|
-
async getUserProfile(state, chainId) {
|
|
3492
|
-
this.assertChain(chainId);
|
|
3493
|
-
return mapYieldseekerProfile(
|
|
3494
|
-
state.walletAddress,
|
|
3495
|
-
await this.loadPortfolio(state, chainId, {})
|
|
3496
|
-
);
|
|
3497
|
-
}
|
|
3498
|
-
async getAgentApy(days, options) {
|
|
3499
|
-
this.assertOptionalChain(options?.chainId);
|
|
3500
|
-
const requested = options?.tokenSymbol?.toUpperCase();
|
|
3501
|
-
if (requested !== void 0) this.assertAsset(requested);
|
|
3502
|
-
const assets = requested ? [requested] : ["USDC", "WETH"];
|
|
3503
|
-
const values = await Promise.all(
|
|
3504
|
-
assets.map(async (asset) => {
|
|
3505
|
-
return { asset, yieldOptions: await this.loadYieldOptions(asset) };
|
|
3506
|
-
})
|
|
3507
|
-
);
|
|
3508
|
-
return mapYieldseekerAgentApy(values, days);
|
|
3509
|
-
}
|
|
3510
|
-
async loadYieldOptions(asset) {
|
|
3511
|
-
const cached = this.yieldOptions.get(asset);
|
|
3512
|
-
if (cached && cached.expiresAt > Date.now()) return cached.value;
|
|
3513
|
-
const pending = this.pendingYieldOptions.get(asset);
|
|
3514
|
-
if (pending) return pending;
|
|
3515
|
-
const metadata = YIELDSEEKER_ASSET_METADATA[asset];
|
|
3516
|
-
const request = this.api.request(
|
|
3517
|
-
`/chains/8453/assets/${metadata.address}/yield-options`
|
|
3518
|
-
).then((response) => {
|
|
3519
|
-
if (!Array.isArray(response?.yieldOptions)) {
|
|
3520
|
-
throw this.invalidResponse("yield options");
|
|
3521
|
-
}
|
|
3522
|
-
this.yieldOptions.set(asset, {
|
|
3523
|
-
expiresAt: Date.now() + YIELDSEEKER_YIELD_OPTIONS_CACHE_MS,
|
|
3524
|
-
value: response.yieldOptions
|
|
3525
|
-
});
|
|
3526
|
-
return response.yieldOptions;
|
|
3527
|
-
}).finally(() => this.pendingYieldOptions.delete(asset));
|
|
3528
|
-
this.pendingYieldOptions.set(asset, request);
|
|
3529
|
-
return request;
|
|
3530
|
-
}
|
|
3531
|
-
userKey(state, chainId) {
|
|
3532
|
-
return `${state.walletAddress.toLowerCase()}:${chainId}`;
|
|
3533
|
-
}
|
|
3534
|
-
contextKey(state, chainId, asset) {
|
|
3535
|
-
return `${this.userKey(state, chainId)}:${asset}`;
|
|
3536
|
-
}
|
|
3537
|
-
async resolveUser(state, chainId) {
|
|
3538
|
-
const key2 = this.userKey(state, chainId);
|
|
3539
|
-
const inMemory = this.users.get(key2);
|
|
3540
|
-
if (inMemory) return inMemory;
|
|
3541
|
-
const persisted = readYieldseekerIdentity(state.walletAddress, chainId);
|
|
3542
|
-
if (persisted) {
|
|
3543
|
-
this.users.set(key2, persisted);
|
|
3544
|
-
return persisted;
|
|
3545
|
-
}
|
|
3546
|
-
const walletAddress = getAddress2(state.walletAddress);
|
|
3547
|
-
let user = null;
|
|
3548
|
-
try {
|
|
3549
|
-
const login = await this.providerRequest(
|
|
3550
|
-
state,
|
|
3551
|
-
chainId,
|
|
3552
|
-
"/users/login-with-wallet",
|
|
3553
|
-
{ method: "POST", body: { walletAddress } }
|
|
3554
|
-
);
|
|
3555
|
-
user = login?.user ?? null;
|
|
3556
|
-
if (!user) {
|
|
3557
|
-
throw this.invalidResponse("wallet login", {
|
|
3558
|
-
reason: "A successful login returned no user."
|
|
3559
|
-
});
|
|
3560
|
-
}
|
|
3561
|
-
} catch (error) {
|
|
3562
|
-
if (!(error instanceof YieldseekerApiError) || error.providerCode !== "NO_USER") {
|
|
3563
|
-
if (error instanceof OwneyError) throw error;
|
|
3564
|
-
throw this.mapApiError(error);
|
|
3565
|
-
}
|
|
3566
|
-
let created;
|
|
3567
|
-
for (let attempt = 0; attempt < YIELDSEEKER_USERNAME_CREATE_ATTEMPTS; attempt += 1) {
|
|
3568
|
-
try {
|
|
3569
|
-
created = await this.providerRequest(
|
|
3570
|
-
state,
|
|
3571
|
-
chainId,
|
|
3572
|
-
"/users",
|
|
3573
|
-
{
|
|
3574
|
-
method: "POST",
|
|
3575
|
-
body: {
|
|
3576
|
-
walletAddress,
|
|
3577
|
-
username: generateYieldseekerUsername()
|
|
3578
|
-
}
|
|
3579
|
-
}
|
|
3580
|
-
);
|
|
3581
|
-
break;
|
|
3582
|
-
} catch (createError) {
|
|
3583
|
-
const canRetry = isUsernameConflict(createError) && attempt + 1 < YIELDSEEKER_USERNAME_CREATE_ATTEMPTS;
|
|
3584
|
-
if (canRetry) continue;
|
|
3585
|
-
throw this.mapApiError(createError);
|
|
3586
|
-
}
|
|
3587
|
-
}
|
|
3588
|
-
user = created?.user ?? null;
|
|
3589
|
-
}
|
|
3590
|
-
if (!user || !/^[a-zA-Z0-9_-]{1,128}$/.test(user.userId)) {
|
|
3591
|
-
throw this.invalidResponse("wallet identity");
|
|
3592
|
-
}
|
|
3593
|
-
const resolved = { userId: user.userId };
|
|
3594
|
-
this.users.set(key2, resolved);
|
|
3595
|
-
writeYieldseekerIdentity(state.walletAddress, chainId, resolved.userId);
|
|
3596
|
-
return resolved;
|
|
3597
|
-
}
|
|
3598
|
-
forgetUser(state, chainId) {
|
|
3599
|
-
this.users.delete(this.userKey(state, chainId));
|
|
3600
|
-
clearYieldseekerIdentity(state.walletAddress, chainId);
|
|
3601
|
-
}
|
|
3602
|
-
async ensureAgent(state, chainId, asset) {
|
|
3603
|
-
const key2 = this.contextKey(state, chainId, asset);
|
|
3604
|
-
const cached = this.agentContexts.get(key2);
|
|
3605
|
-
if (cached) return cached;
|
|
3606
|
-
const pending = this.pendingAgents.get(key2);
|
|
3607
|
-
if (pending) return pending;
|
|
3608
|
-
const request = this.resolveAgent(state, chainId, asset, true).then(
|
|
3609
|
-
async (context) => {
|
|
3610
|
-
if (!context) throw this.invalidResponse("agent creation");
|
|
3611
|
-
await this.deployAgent(state, chainId, context);
|
|
3612
|
-
this.agentContexts.set(key2, context);
|
|
3613
|
-
return context;
|
|
3614
|
-
}
|
|
3615
|
-
);
|
|
3616
|
-
this.pendingAgents.set(key2, request);
|
|
3617
|
-
try {
|
|
3618
|
-
return await request;
|
|
3619
|
-
} finally {
|
|
3620
|
-
this.pendingAgents.delete(key2);
|
|
3621
|
-
}
|
|
3622
|
-
}
|
|
3623
|
-
async findAgent(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 context = await this.resolveAgent(state, chainId, asset, false);
|
|
3628
|
-
if (context) this.agentContexts.set(key2, context);
|
|
3629
|
-
return context;
|
|
3630
|
-
}
|
|
3631
|
-
async resolveAgent(state, chainId, asset, createIfMissing) {
|
|
3632
|
-
const user = await this.resolveUser(state, chainId);
|
|
3633
|
-
const response = await this.walletRequest(
|
|
3634
|
-
state,
|
|
3635
|
-
chainId,
|
|
3636
|
-
`/users/${user.userId}/agents`
|
|
3637
|
-
);
|
|
3638
|
-
if (!Array.isArray(response?.agents)) {
|
|
3639
|
-
throw this.invalidResponse("agent list");
|
|
3640
|
-
}
|
|
3641
|
-
const metadata = YIELDSEEKER_ASSET_METADATA[asset];
|
|
3642
|
-
let agent = response.agents.find(
|
|
3643
|
-
(candidate) => this.isOwneyAgent(candidate) && candidate.chainId === chainId && candidate.type === "vault" && candidate.assetAddress.toLowerCase() === metadata.address.toLowerCase()
|
|
3644
|
-
);
|
|
3645
|
-
if (!agent && createIfMissing) {
|
|
3646
|
-
const created = await this.walletRequest(
|
|
3647
|
-
state,
|
|
3648
|
-
chainId,
|
|
3649
|
-
`/users/${user.userId}/agents`,
|
|
3650
|
-
{
|
|
3651
|
-
method: "POST",
|
|
3652
|
-
body: {
|
|
3653
|
-
name: OWNEY_AGENT_NAME,
|
|
3654
|
-
emoji: "\u{1F989}",
|
|
3655
|
-
chainId,
|
|
3656
|
-
assetAddress: metadata.address,
|
|
3657
|
-
type: "vault",
|
|
3658
|
-
rulePreset: null
|
|
3659
|
-
}
|
|
3660
|
-
}
|
|
3661
|
-
);
|
|
3662
|
-
agent = created?.agent;
|
|
3663
|
-
}
|
|
3664
|
-
if (!agent) return null;
|
|
3665
|
-
this.assertAgent(agent);
|
|
3666
|
-
const walletResponse = await this.walletRequest(
|
|
3667
|
-
state,
|
|
3668
|
-
chainId,
|
|
3669
|
-
`/users/${user.userId}/agents/${agent.agentId}/wallet`
|
|
3670
|
-
);
|
|
3671
|
-
if (!walletResponse?.agentWallet || !isAddress2(walletResponse.agentWallet.walletAddress)) {
|
|
3672
|
-
throw this.invalidResponse("agent wallet");
|
|
3673
|
-
}
|
|
3674
|
-
return { user, agent, wallet: walletResponse.agentWallet, asset };
|
|
3675
|
-
}
|
|
3676
|
-
async loadPortfolio(state, chainId, options) {
|
|
3677
|
-
const user = await this.resolveUser(state, chainId);
|
|
3678
|
-
const response = await this.walletRequest(
|
|
3679
|
-
state,
|
|
3680
|
-
chainId,
|
|
3681
|
-
`/users/${user.userId}/agents`
|
|
3682
|
-
);
|
|
3683
|
-
if (!Array.isArray(response?.agents)) {
|
|
3684
|
-
throw this.invalidResponse("agent list");
|
|
3685
|
-
}
|
|
3686
|
-
const contexts = [];
|
|
3687
|
-
for (const agent of response.agents) {
|
|
3688
|
-
const asset = this.assetForAgent(agent);
|
|
3689
|
-
if (!this.isOwneyAgent(agent) || !asset || agent.chainId !== chainId || agent.type !== "vault" || options.asset && options.asset !== asset) {
|
|
3690
|
-
continue;
|
|
3691
|
-
}
|
|
3692
|
-
this.assertAgent(agent);
|
|
3693
|
-
const walletResponse = await this.walletRequest(
|
|
3694
|
-
state,
|
|
3695
|
-
chainId,
|
|
3696
|
-
`/users/${user.userId}/agents/${agent.agentId}/wallet`
|
|
3697
|
-
);
|
|
3698
|
-
if (!walletResponse?.agentWallet || !isAddress2(walletResponse.agentWallet.walletAddress)) {
|
|
3699
|
-
throw this.invalidResponse("agent wallet");
|
|
3700
|
-
}
|
|
3701
|
-
const context = {
|
|
3702
|
-
user,
|
|
3703
|
-
agent,
|
|
3704
|
-
wallet: walletResponse.agentWallet,
|
|
3705
|
-
asset
|
|
3706
|
-
};
|
|
3707
|
-
this.agentContexts.set(this.contextKey(state, chainId, asset), context);
|
|
3708
|
-
contexts.push(context);
|
|
3709
|
-
}
|
|
3710
|
-
return Promise.all(
|
|
3711
|
-
contexts.map(
|
|
3712
|
-
(context) => this.loadPortfolioContext(state, chainId, context, options)
|
|
3713
|
-
)
|
|
3714
|
-
);
|
|
3715
|
-
}
|
|
3716
|
-
async loadPortfolioContext(state, chainId, context, options = {}) {
|
|
3717
|
-
const [snapshot, positions, historic, actions] = await Promise.all([
|
|
3718
|
-
this.walletRequest(
|
|
3719
|
-
state,
|
|
3720
|
-
chainId,
|
|
3721
|
-
`${this.agentPath(context, "snapshot")}${query({
|
|
3722
|
-
shouldOnlyUseRecentValue: true,
|
|
3723
|
-
shouldAllowStaleOnError: true
|
|
3724
|
-
})}`
|
|
3725
|
-
),
|
|
3726
|
-
this.walletRequest(
|
|
3727
|
-
state,
|
|
3728
|
-
chainId,
|
|
3729
|
-
this.agentPath(context, "yield-positions")
|
|
3730
|
-
),
|
|
3731
|
-
options.historic ? this.walletRequest(
|
|
3732
|
-
state,
|
|
3733
|
-
chainId,
|
|
3734
|
-
this.agentPath(context, "wallet/historic-position")
|
|
3735
|
-
) : Promise.resolve(void 0),
|
|
3736
|
-
options.actions ? this.walletRequest(
|
|
3737
|
-
state,
|
|
3738
|
-
chainId,
|
|
3739
|
-
this.agentPath(context, "actions")
|
|
3740
|
-
) : Promise.resolve(void 0)
|
|
3741
|
-
]);
|
|
3742
|
-
if (!snapshot?.agentSnapshot) {
|
|
3743
|
-
throw this.invalidResponse("agent snapshot");
|
|
3744
|
-
}
|
|
3745
|
-
if (!Array.isArray(positions?.yieldPositions)) {
|
|
3746
|
-
throw this.invalidResponse("yield positions");
|
|
3747
|
-
}
|
|
3748
|
-
return {
|
|
3749
|
-
...context,
|
|
3750
|
-
snapshot: snapshot.agentSnapshot,
|
|
3751
|
-
positions: positions.yieldPositions,
|
|
3752
|
-
...historic?.position ? { historic: historic.position } : {},
|
|
3753
|
-
...actions?.actions ? { actions: actions.actions } : {}
|
|
3754
|
-
};
|
|
3755
|
-
}
|
|
3756
|
-
async deployAgent(state, chainId, context) {
|
|
3757
|
-
if (context.wallet.initializedDate != null) return;
|
|
3758
|
-
const walletAddress = context.wallet.walletAddress.toLowerCase();
|
|
3759
|
-
const deployed = await this.walletRequest(
|
|
3760
|
-
state,
|
|
3761
|
-
chainId,
|
|
3762
|
-
this.agentPath(context, "deploy"),
|
|
3763
|
-
{ method: "POST", body: {} }
|
|
3764
|
-
);
|
|
3765
|
-
if (!deployed?.agentWallet || !isAddress2(deployed.agentWallet.walletAddress) || deployed.agentWallet.walletAddress.toLowerCase() !== walletAddress) {
|
|
3766
|
-
throw this.invalidResponse("agent deployment", {
|
|
3767
|
-
reason: "Deploy did not return the expected Agent Wallet."
|
|
3768
|
-
});
|
|
3769
|
-
}
|
|
3770
|
-
context.wallet = deployed.agentWallet;
|
|
3771
|
-
}
|
|
3772
|
-
async refreshSnapshotAfterMovement(state, chainId, context, movement) {
|
|
3773
|
-
try {
|
|
3774
|
-
const response = await this.walletRequest(
|
|
3775
|
-
state,
|
|
3776
|
-
chainId,
|
|
3777
|
-
`${this.agentPath(context, "snapshot")}${query({
|
|
3778
|
-
shouldForceRefresh: true
|
|
3779
|
-
})}`
|
|
3780
|
-
);
|
|
3781
|
-
if (!response?.agentSnapshot) {
|
|
3782
|
-
throw this.invalidResponse("agent snapshot refresh");
|
|
3783
|
-
}
|
|
3784
|
-
} catch (error) {
|
|
3785
|
-
console.warn(
|
|
3786
|
-
`[owney-sdk] Yieldseeker ${movement} snapshot refresh failed:`,
|
|
3787
|
-
error
|
|
3788
|
-
);
|
|
3789
|
-
}
|
|
3790
|
-
}
|
|
3791
|
-
agentPath(context, suffix) {
|
|
3792
|
-
return `/users/${context.user.userId}/agents/${context.agent.agentId}/${suffix}`;
|
|
3793
|
-
}
|
|
3794
|
-
async walletRequest(state, chainId, path, options = {}) {
|
|
3795
|
-
try {
|
|
3796
|
-
return await this.providerRequest(state, chainId, path, options);
|
|
3797
|
-
} catch (error) {
|
|
3798
|
-
throw this.mapApiError(error);
|
|
3799
|
-
}
|
|
3800
|
-
}
|
|
3801
|
-
async providerRequest(state, chainId, path, options = {}) {
|
|
3802
|
-
this.assertChain(chainId);
|
|
3803
|
-
const request = (signature2) => this.api.request(path, {
|
|
3804
|
-
...options,
|
|
3805
|
-
signature: signature2
|
|
3806
|
-
});
|
|
3807
|
-
let signature = await this.auth.getToken(state, chainId);
|
|
3808
|
-
try {
|
|
3809
|
-
return await request(signature);
|
|
3810
|
-
} catch (error) {
|
|
3811
|
-
if (!(error instanceof YieldseekerApiError)) throw error;
|
|
3812
|
-
if (error.providerCode === "NO_USER") throw error;
|
|
3813
|
-
if (!error.isAuthenticationError) throw error;
|
|
3814
|
-
signature = await this.auth.refreshToken(state, chainId, signature);
|
|
3815
|
-
try {
|
|
3816
|
-
return await request(signature);
|
|
3817
|
-
} catch (retryError) {
|
|
3818
|
-
if (retryError instanceof YieldseekerApiError && retryError.isAuthenticationError) {
|
|
3819
|
-
this.forgetUser(state, chainId);
|
|
3820
|
-
}
|
|
3821
|
-
throw retryError;
|
|
3822
|
-
}
|
|
3823
|
-
}
|
|
3824
|
-
}
|
|
3825
|
-
mapApiError(error) {
|
|
3826
|
-
if (!(error instanceof YieldseekerApiError)) {
|
|
3827
|
-
return new OwneyError(
|
|
3828
|
-
"AGENT_API_ERROR",
|
|
3829
|
-
"Yieldseeker request failed.",
|
|
3830
|
-
{ cause: error instanceof Error ? error.message : String(error) },
|
|
3831
|
-
this.id
|
|
3832
|
-
);
|
|
3833
|
-
}
|
|
3834
|
-
const code = error.isAuthenticationError ? "AGENT_AUTH_FAILED" : error.providerCode === "REQUEST_TIMEOUT" ? "AGENT_TIMEOUT" : "AGENT_API_ERROR";
|
|
3835
|
-
return new OwneyError(
|
|
3836
|
-
code,
|
|
3837
|
-
`Yieldseeker request failed: ${error.providerCode}.`,
|
|
3838
|
-
{
|
|
3839
|
-
statusCode: error.status,
|
|
3840
|
-
providerCode: error.providerCode,
|
|
3841
|
-
...error.responseFields ? { fields: error.responseFields } : {}
|
|
3842
|
-
},
|
|
3843
|
-
this.id
|
|
3844
|
-
);
|
|
3845
|
-
}
|
|
3846
|
-
async submitTransaction(state, chainId, transaction) {
|
|
3847
|
-
if (this.transactionExecutor) {
|
|
3848
|
-
return this.transactionExecutor(state, chainId, transaction);
|
|
3849
|
-
}
|
|
3850
|
-
this.assertTransaction(transaction, state, chainId);
|
|
3851
|
-
const account = getAddress2(state.walletAddress);
|
|
3852
|
-
const walletClient = createWalletClient2({
|
|
3853
|
-
account,
|
|
3854
|
-
chain: base3,
|
|
3855
|
-
transport: custom2(state.provider)
|
|
3856
|
-
});
|
|
3857
|
-
const publicClient = createPublicClient3({
|
|
3858
|
-
chain: base3,
|
|
3859
|
-
transport: custom2(state.provider)
|
|
3860
|
-
});
|
|
3861
|
-
await ensureWalletOnChain(
|
|
3862
|
-
publicClient,
|
|
3863
|
-
walletClient,
|
|
3864
|
-
8453
|
|
3865
|
-
);
|
|
3866
|
-
const hash = await walletClient.sendTransaction({
|
|
3867
|
-
account,
|
|
3868
|
-
chain: base3,
|
|
3869
|
-
to: getAddress2(transaction.to),
|
|
3870
|
-
data: transaction.data,
|
|
3871
|
-
value: BigInt(transaction.value)
|
|
3872
|
-
});
|
|
3873
|
-
const receipt = await publicClient.waitForTransactionReceipt({
|
|
3874
|
-
hash,
|
|
3875
|
-
confirmations: 1
|
|
3876
|
-
});
|
|
3877
|
-
if (receipt.status !== "success") {
|
|
3878
|
-
throw new OwneyError(
|
|
3879
|
-
"AGENT_TRANSACTION_REVERTED",
|
|
3880
|
-
`Yieldseeker transaction reverted (${hash}).`,
|
|
3881
|
-
{ transactionHash: hash },
|
|
3882
|
-
this.id
|
|
3883
|
-
);
|
|
3884
|
-
}
|
|
3885
|
-
return hash;
|
|
3886
|
-
}
|
|
3887
|
-
async waitForReceipt(state, chainId, transactionHash) {
|
|
3888
|
-
if (this.unwindReceiptWaiter) {
|
|
3889
|
-
await this.unwindReceiptWaiter(state, chainId, transactionHash);
|
|
3890
|
-
return;
|
|
3891
|
-
}
|
|
3892
|
-
const publicClient = createPublicClient3({
|
|
3893
|
-
chain: base3,
|
|
3894
|
-
transport: custom2(state.provider)
|
|
3895
|
-
});
|
|
3896
|
-
const receipt = await publicClient.waitForTransactionReceipt({
|
|
3897
|
-
hash: transactionHash,
|
|
3898
|
-
confirmations: 1
|
|
3899
|
-
});
|
|
3900
|
-
if (receipt.status !== "success") {
|
|
3901
|
-
throw new OwneyError(
|
|
3902
|
-
"AGENT_TRANSACTION_REVERTED",
|
|
3903
|
-
`Yieldseeker transaction reverted (${transactionHash}).`,
|
|
3904
|
-
{ transactionHash },
|
|
3905
|
-
this.id
|
|
3906
|
-
);
|
|
3907
|
-
}
|
|
3908
|
-
}
|
|
3909
|
-
assertTransaction(transaction, state, chainId) {
|
|
3910
|
-
if (!transaction || typeof transaction.from !== "string" || !isAddress2(transaction.from) || typeof transaction.to !== "string" || !isAddress2(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 || getAddress2(transaction.from) !== getAddress2(state.walletAddress)) {
|
|
3911
|
-
throw this.invalidResponse("transaction");
|
|
3912
|
-
}
|
|
3913
|
-
}
|
|
3914
|
-
assertAgent(agent) {
|
|
3915
|
-
if (typeof agent.agentId !== "string" || typeof agent.assetAddress !== "string" || !isAddress2(agent.assetAddress) || agent.chainId !== 8453) {
|
|
3916
|
-
throw this.invalidResponse("agent");
|
|
3917
|
-
}
|
|
3918
|
-
}
|
|
3919
|
-
isOwneyAgent(agent) {
|
|
3920
|
-
return typeof agent.name === "string" && agent.name.trim().toLowerCase() === OWNEY_AGENT_NAME;
|
|
3921
|
-
}
|
|
3922
|
-
assetForAgent(agent) {
|
|
3923
|
-
for (const asset of ["USDC", "WETH"]) {
|
|
3924
|
-
if (agent.assetAddress.toLowerCase() === YIELDSEEKER_ASSET_METADATA[asset].address.toLowerCase()) {
|
|
3925
|
-
return asset;
|
|
3926
|
-
}
|
|
3927
|
-
}
|
|
3928
|
-
return null;
|
|
3929
|
-
}
|
|
3930
|
-
isTransactionHash(value) {
|
|
3931
|
-
return typeof value === "string" && /^0x[a-fA-F0-9]{64}$/.test(value);
|
|
3932
|
-
}
|
|
3933
|
-
assertChain(chainId) {
|
|
3934
|
-
if (chainId !== 8453) {
|
|
3935
|
-
throw new OwneyError(
|
|
3936
|
-
"CHAIN_UNSUPPORTED",
|
|
3937
|
-
`Yieldseeker does not support chain ${chainId}.`,
|
|
3938
|
-
{ chainId, supportedChainIds: [8453] },
|
|
3939
|
-
this.id
|
|
3940
|
-
);
|
|
3941
|
-
}
|
|
3942
|
-
}
|
|
3943
|
-
assertOptionalChain(chainId) {
|
|
3944
|
-
if (chainId !== void 0) this.assertChain(chainId);
|
|
3945
|
-
}
|
|
3946
|
-
assertAsset(asset) {
|
|
3947
|
-
if (asset !== "USDC" && asset !== "WETH") {
|
|
3948
|
-
throw new OwneyError(
|
|
3949
|
-
"ASSET_UNSUPPORTED",
|
|
3950
|
-
`Yieldseeker does not support asset ${asset} in the Owney rollout.`,
|
|
3951
|
-
{
|
|
3952
|
-
asset,
|
|
3953
|
-
supportedAssets: ["USDC", "WETH"],
|
|
3954
|
-
providerAlsoAdvertises: ["cbBTC"]
|
|
3955
|
-
},
|
|
3956
|
-
this.id
|
|
2654
|
+
slippage = DEFAULT_SLIPPAGE,
|
|
2655
|
+
direction,
|
|
2656
|
+
onStage
|
|
2657
|
+
} = options;
|
|
2658
|
+
const isNativeSource = quote.src.address.toLowerCase().startsWith("0xeeee");
|
|
2659
|
+
const amount = isNativeSource ? BigInt(quote.src.amount) : await affordableAmount(deps, BigInt(quote.src.amount));
|
|
2660
|
+
const swapTxRequest = {
|
|
2661
|
+
from: {
|
|
2662
|
+
chainId: quote.src.chainId,
|
|
2663
|
+
symbol: quote.src.symbol,
|
|
2664
|
+
amount: amount.toString()
|
|
2665
|
+
},
|
|
2666
|
+
to: { chainId: quote.dst.chainId, symbol: quote.dst.symbol },
|
|
2667
|
+
walletAddress,
|
|
2668
|
+
slippage,
|
|
2669
|
+
...direction ? { direction } : {}
|
|
2670
|
+
};
|
|
2671
|
+
onStage?.("quoting");
|
|
2672
|
+
debugLog("owney-sdk", "swap: fetching classic calldata");
|
|
2673
|
+
let { tx } = await deps.api.swapTx(swapTxRequest);
|
|
2674
|
+
const isNative = BigInt(tx.value ?? "0") > 0n;
|
|
2675
|
+
if (!isNative) {
|
|
2676
|
+
const needed = amount;
|
|
2677
|
+
const current = await deps.readAllowance(tx.to);
|
|
2678
|
+
debugLog("owney-sdk", "swap: allowance", {
|
|
2679
|
+
spender: tx.to,
|
|
2680
|
+
current: current.toString(),
|
|
2681
|
+
needed: needed.toString()
|
|
2682
|
+
});
|
|
2683
|
+
if (current < needed) {
|
|
2684
|
+
onStage?.("approving");
|
|
2685
|
+
await deps.ensureChain(quote.src.chainId);
|
|
2686
|
+
await deps.approve(tx.to, MAX_UINT256);
|
|
2687
|
+
debugLog(
|
|
2688
|
+
"owney-sdk",
|
|
2689
|
+
"swap: re-fetching classic calldata after approval"
|
|
3957
2690
|
);
|
|
2691
|
+
({ tx } = await deps.api.swapTx(swapTxRequest));
|
|
3958
2692
|
}
|
|
3959
2693
|
}
|
|
3960
|
-
|
|
3961
|
-
|
|
3962
|
-
|
|
3963
|
-
|
|
3964
|
-
|
|
3965
|
-
|
|
3966
|
-
|
|
2694
|
+
onStage?.("signing");
|
|
2695
|
+
await deps.ensureChain(quote.src.chainId);
|
|
2696
|
+
debugLog("owney-sdk", "swap: sending classic swap tx", { to: tx.to });
|
|
2697
|
+
const txHash = await deps.sendTransaction({
|
|
2698
|
+
to: tx.to,
|
|
2699
|
+
data: tx.data,
|
|
2700
|
+
value: tx.value ?? "0"
|
|
2701
|
+
});
|
|
2702
|
+
onStage?.("swapped");
|
|
2703
|
+
return { txHash };
|
|
2704
|
+
}
|
|
2705
|
+
async function runFusion(deps, options, walletAddress) {
|
|
2706
|
+
const { quote, direction, onStage } = options;
|
|
2707
|
+
const isNativeSource = quote.src.address.toLowerCase().startsWith("0xeeee");
|
|
2708
|
+
const amount = isNativeSource ? BigInt(quote.src.amount) : await affordableAmount(deps, BigInt(quote.src.amount));
|
|
2709
|
+
if (quote.spender && !isNativeSource) {
|
|
2710
|
+
const needed = amount;
|
|
2711
|
+
const current = await deps.readAllowance(quote.spender);
|
|
2712
|
+
debugLog("owney-sdk", "swap: fusion allowance", {
|
|
2713
|
+
spender: quote.spender,
|
|
2714
|
+
current: current.toString(),
|
|
2715
|
+
needed: needed.toString()
|
|
2716
|
+
});
|
|
2717
|
+
if (current < needed) {
|
|
2718
|
+
onStage?.("approving");
|
|
2719
|
+
await deps.ensureChain(quote.src.chainId);
|
|
2720
|
+
await deps.approve(quote.spender, MAX_UINT256);
|
|
2721
|
+
debugLog("owney-sdk", "swap: approved limit order protocol");
|
|
2722
|
+
}
|
|
3967
2723
|
}
|
|
3968
|
-
};
|
|
3969
|
-
|
|
3970
|
-
|
|
3971
|
-
|
|
3972
|
-
|
|
3973
|
-
const
|
|
2724
|
+
const { secrets, secretHashes } = mintSecrets(quote.secretsCount ?? 1);
|
|
2725
|
+
onStage?.("quoting");
|
|
2726
|
+
debugLog("owney-sdk", "swap: building fusion order", {
|
|
2727
|
+
secrets: secretHashes.length
|
|
2728
|
+
});
|
|
2729
|
+
const built = await deps.api.buildOrder({
|
|
2730
|
+
from: {
|
|
2731
|
+
chainId: quote.src.chainId,
|
|
2732
|
+
symbol: quote.src.symbol,
|
|
2733
|
+
// The trimmed amount — the order is re-quoted at this size server-side.
|
|
2734
|
+
amount: amount.toString()
|
|
2735
|
+
},
|
|
2736
|
+
to: { chainId: quote.dst.chainId, symbol: quote.dst.symbol },
|
|
2737
|
+
walletAddress,
|
|
2738
|
+
secretHashes,
|
|
2739
|
+
...direction ? { direction } : {}
|
|
2740
|
+
});
|
|
2741
|
+
saveOrder({
|
|
2742
|
+
orderHash: built.orderHash,
|
|
2743
|
+
secrets,
|
|
2744
|
+
srcChainId: quote.src.chainId,
|
|
2745
|
+
srcSymbol: quote.src.symbol,
|
|
2746
|
+
dstChainId: quote.dst.chainId,
|
|
2747
|
+
dstSymbol: quote.dst.symbol,
|
|
2748
|
+
amount: amount.toString(),
|
|
2749
|
+
createdAt: Date.now()
|
|
2750
|
+
});
|
|
2751
|
+
debugLog("owney-sdk", "swap: order built", { orderHash: built.orderHash });
|
|
2752
|
+
onStage?.("signing");
|
|
2753
|
+
await deps.ensureChain(quote.src.chainId);
|
|
2754
|
+
debugLog("owney-sdk", "swap: awaiting signature in wallet", {
|
|
2755
|
+
signingOnChain: quote.src.chainId
|
|
2756
|
+
});
|
|
2757
|
+
const signature = await deps.signTypedData(built.typedData);
|
|
2758
|
+
debugLog("owney-sdk", "swap: signed, submitting to relayer");
|
|
2759
|
+
await deps.api.submitOrder({
|
|
2760
|
+
srcChainId: quote.src.chainId,
|
|
2761
|
+
// The ORDER STRUCT, not the typed-data envelope we just signed. Sending
|
|
2762
|
+
// the envelope here gets a bare 500 from the relayer.
|
|
2763
|
+
order: built.order,
|
|
2764
|
+
signature,
|
|
2765
|
+
quoteId: built.quoteId,
|
|
2766
|
+
// Single-fill orders must NOT carry secretHashes — the relayer rejects
|
|
2767
|
+
// them with SECRET_HASHES_NOT_REQUIRED. The one hash is already inside the
|
|
2768
|
+
// order's hashlock, so repeating it here is redundant, and only a
|
|
2769
|
+
// multi-fill order (a Merkle tree of hashes) needs them listed.
|
|
2770
|
+
...secretHashes.length > 1 ? { secretHashes } : {},
|
|
2771
|
+
...built.extension ? { extension: built.extension } : {}
|
|
2772
|
+
});
|
|
2773
|
+
debugLog("owney-sdk", "swap: order submitted, polling escrows");
|
|
3974
2774
|
try {
|
|
3975
|
-
|
|
3976
|
-
|
|
3977
|
-
|
|
3978
|
-
|
|
3979
|
-
"x-owney-api-key": `${apiKey}`
|
|
3980
|
-
}
|
|
2775
|
+
await runFusionOrder(deps.runner, {
|
|
2776
|
+
orderHash: built.orderHash,
|
|
2777
|
+
secrets,
|
|
2778
|
+
...onStage ? { onStage } : {}
|
|
3981
2779
|
});
|
|
3982
|
-
if (!res.ok) {
|
|
3983
|
-
if (res.status !== 404) {
|
|
3984
|
-
console.warn(
|
|
3985
|
-
`[owney-sdk] Could not read org agent config (${res.status}); leaving user profiles unchanged.`
|
|
3986
|
-
);
|
|
3987
|
-
}
|
|
3988
|
-
return null;
|
|
3989
|
-
}
|
|
3990
|
-
const json = await res.json();
|
|
3991
|
-
const policy = json.success ? json.data ?? null : null;
|
|
3992
|
-
debugLog(
|
|
3993
|
-
"owney-sdk",
|
|
3994
|
-
policy ? "org agent config: loaded" : "org agent config: none set by this partner \u2014 user profiles will be left as they are",
|
|
3995
|
-
policy ?? void 0
|
|
3996
|
-
);
|
|
3997
|
-
return policy;
|
|
3998
2780
|
} catch (error) {
|
|
3999
|
-
|
|
4000
|
-
|
|
4001
|
-
|
|
4002
|
-
|
|
4003
|
-
return null;
|
|
2781
|
+
if (error instanceof OwneyError && (error.code === "SWAP_ORDER_REFUNDED" || error.code === "SWAP_ORDER_CANCELLED")) {
|
|
2782
|
+
clearOrder(built.orderHash);
|
|
2783
|
+
}
|
|
2784
|
+
throw error;
|
|
4004
2785
|
}
|
|
2786
|
+
clearOrder(built.orderHash);
|
|
2787
|
+
return { orderHash: built.orderHash };
|
|
4005
2788
|
}
|
|
4006
|
-
|
|
4007
|
-
|
|
4008
|
-
|
|
4009
|
-
|
|
4010
|
-
|
|
4011
|
-
|
|
4012
|
-
|
|
4013
|
-
|
|
2789
|
+
|
|
2790
|
+
// src/lib/swap/swap.arrival.ts
|
|
2791
|
+
var DEFAULT_TIMEOUT_MS2 = 18e4;
|
|
2792
|
+
var DEFAULT_POLL_MS2 = 4e3;
|
|
2793
|
+
var sleep = (ms) => new Promise((r) => setTimeout(r, ms));
|
|
2794
|
+
async function awaitWithdrawalArrival(options) {
|
|
2795
|
+
const {
|
|
2796
|
+
readBalance,
|
|
2797
|
+
baseline,
|
|
2798
|
+
timeoutMs = DEFAULT_TIMEOUT_MS2,
|
|
2799
|
+
pollMs = DEFAULT_POLL_MS2
|
|
2800
|
+
} = options;
|
|
2801
|
+
const deadline = Date.now() + timeoutMs;
|
|
2802
|
+
debugLog("owney-sdk", "withdraw: waiting for funds to land", {
|
|
2803
|
+
baseline: baseline.toString(),
|
|
2804
|
+
timeoutMs
|
|
4014
2805
|
});
|
|
4015
|
-
|
|
4016
|
-
|
|
4017
|
-
|
|
4018
|
-
|
|
4019
|
-
|
|
4020
|
-
|
|
4021
|
-
|
|
4022
|
-
|
|
4023
|
-
|
|
4024
|
-
|
|
4025
|
-
|
|
4026
|
-
|
|
4027
|
-
|
|
4028
|
-
|
|
4029
|
-
|
|
2806
|
+
let lastError;
|
|
2807
|
+
for (; ; ) {
|
|
2808
|
+
try {
|
|
2809
|
+
const balance = await readBalance();
|
|
2810
|
+
if (balance > baseline) {
|
|
2811
|
+
const arrived = balance - baseline;
|
|
2812
|
+
debugLog("owney-sdk", "withdraw: funds landed", {
|
|
2813
|
+
arrived: arrived.toString()
|
|
2814
|
+
});
|
|
2815
|
+
return arrived;
|
|
2816
|
+
}
|
|
2817
|
+
} catch (error) {
|
|
2818
|
+
lastError = error;
|
|
2819
|
+
debugLog("owney-sdk", "withdraw: balance read failed, retrying", {
|
|
2820
|
+
message: error instanceof Error ? error.message : String(error)
|
|
2821
|
+
});
|
|
2822
|
+
}
|
|
2823
|
+
if (Date.now() >= deadline) {
|
|
2824
|
+
throw new OwneyError(
|
|
2825
|
+
"WITHDRAW_ARRIVAL_TIMEOUT",
|
|
2826
|
+
"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.",
|
|
2827
|
+
{
|
|
2828
|
+
baseline: baseline.toString(),
|
|
2829
|
+
waitedMs: timeoutMs,
|
|
2830
|
+
...lastError ? {
|
|
2831
|
+
lastReadError: lastError instanceof Error ? lastError.message : String(lastError)
|
|
2832
|
+
} : {}
|
|
2833
|
+
}
|
|
2834
|
+
);
|
|
2835
|
+
}
|
|
2836
|
+
await sleep(pollMs);
|
|
4030
2837
|
}
|
|
4031
|
-
return json.data;
|
|
4032
2838
|
}
|
|
4033
2839
|
|
|
4034
2840
|
// src/lib/health-report.ts
|
|
4035
|
-
var
|
|
4036
|
-
async function reportAgentFailure(apiKey, agentType, errorCode, baseUrl =
|
|
2841
|
+
var ROUTING_API_BASE_URL2 = "https://owney-routing-api-243946518160.europe-west4.run.app";
|
|
2842
|
+
async function reportAgentFailure(apiKey, agentType, errorCode, baseUrl = ROUTING_API_BASE_URL2) {
|
|
4037
2843
|
try {
|
|
4038
2844
|
await fetch(`${baseUrl}/api/v1/agent/health-report`, {
|
|
4039
2845
|
method: "POST",
|
|
@@ -4073,29 +2879,8 @@ function projectAgentBalancesForAsset(agents, aggregated, chainId, asset, decima
|
|
|
4073
2879
|
const tokenBalance = agentBalance?.tokens.find(
|
|
4074
2880
|
(t) => t.chainId === chainId && t.asset.toUpperCase() === target
|
|
4075
2881
|
);
|
|
4076
|
-
|
|
4077
|
-
|
|
4078
|
-
const chainNameById = {
|
|
4079
|
-
1: "ETHEREUM",
|
|
4080
|
-
8453: "BASE",
|
|
4081
|
-
42161: "ARBITRUM"
|
|
4082
|
-
};
|
|
4083
|
-
const targetChain = chainNameById[chainId];
|
|
4084
|
-
for (const position2 of agentBalance?.positions ?? []) {
|
|
4085
|
-
const positionChain = position2.chain.trim().toUpperCase();
|
|
4086
|
-
const matchesChain = positionChain === String(chainId) || targetChain !== void 0 && positionChain === targetChain;
|
|
4087
|
-
if (!matchesChain || position2.asset.toUpperCase() !== target) continue;
|
|
4088
|
-
if (position2.amountRaw !== void 0) {
|
|
4089
|
-
try {
|
|
4090
|
-
balance += BigInt(position2.amountRaw);
|
|
4091
|
-
continue;
|
|
4092
|
-
} catch {
|
|
4093
|
-
}
|
|
4094
|
-
}
|
|
4095
|
-
balance += parseUnits(position2.amount, decimals);
|
|
4096
|
-
}
|
|
4097
|
-
}
|
|
4098
|
-
return { agent, balance };
|
|
2882
|
+
if (!tokenBalance) return { agent, balance: 0n };
|
|
2883
|
+
return { agent, balance: parseUnits(tokenBalance.amount, decimals) };
|
|
4099
2884
|
});
|
|
4100
2885
|
}
|
|
4101
2886
|
function planProportionalShares(balances, requested, totalAvailable) {
|
|
@@ -4121,9 +2906,7 @@ function planProportionalShares(balances, requested, totalAvailable) {
|
|
|
4121
2906
|
return plans;
|
|
4122
2907
|
}
|
|
4123
2908
|
function planDisabledDrain(disabled, requested) {
|
|
4124
|
-
const sorted = [...disabled].filter((d) => d.balance > 0n).sort(
|
|
4125
|
-
(a, b) => b.balance > a.balance ? 1 : b.balance < a.balance ? -1 : 0
|
|
4126
|
-
);
|
|
2909
|
+
const sorted = [...disabled].filter((d) => d.balance > 0n).sort((a, b) => b.balance > a.balance ? 1 : b.balance < a.balance ? -1 : 0);
|
|
4127
2910
|
const plans = [];
|
|
4128
2911
|
let remaining = requested;
|
|
4129
2912
|
for (const { agent, balance } of sorted) {
|
|
@@ -4174,13 +2957,6 @@ function balanceForApyScope(balance, chainId, tokenSymbol) {
|
|
|
4174
2957
|
return Number.isFinite(total) && total > 0 ? total : 0;
|
|
4175
2958
|
}
|
|
4176
2959
|
const normalizedToken = tokenSymbol.toUpperCase();
|
|
4177
|
-
const snapshots = balance.assetBalances?.filter(
|
|
4178
|
-
(token) => Number(token.chainId) === chainId && String(token.asset).toUpperCase() === normalizedToken
|
|
4179
|
-
);
|
|
4180
|
-
if (snapshots?.length) {
|
|
4181
|
-
const amount = snapshots.reduce((sum, token) => sum + Number(token.amount), 0);
|
|
4182
|
-
if (Number.isFinite(amount)) return Math.max(0, amount);
|
|
4183
|
-
}
|
|
4184
2960
|
return balance.tokens.reduce((total, token) => {
|
|
4185
2961
|
if (Number(token.chainId) !== chainId || String(token.asset).toUpperCase() !== normalizedToken) {
|
|
4186
2962
|
return total;
|
|
@@ -4252,312 +3028,329 @@ function aggregateApyByChainAndAsset(agentApys, agentBalances) {
|
|
|
4252
3028
|
|
|
4253
3029
|
// src/client.ts
|
|
4254
3030
|
import {
|
|
4255
|
-
createPublicClient as
|
|
4256
|
-
createWalletClient
|
|
4257
|
-
custom
|
|
4258
|
-
|
|
4259
|
-
import { base as base4, arbitrum as arbitrum2, mainnet as mainnet2 } from "viem/chains";
|
|
4260
|
-
|
|
4261
|
-
// src/lib/sponsored-token-batch.ts
|
|
4262
|
-
import {
|
|
4263
|
-
isAddressEqual,
|
|
4264
|
-
keccak256,
|
|
4265
|
-
toBytes
|
|
3031
|
+
createPublicClient as createPublicClient2,
|
|
3032
|
+
createWalletClient,
|
|
3033
|
+
custom,
|
|
3034
|
+
erc20Abi as erc20Abi2
|
|
4266
3035
|
} from "viem";
|
|
3036
|
+
import { base as base2, arbitrum as arbitrum2, mainnet as mainnet2 } from "viem/chains";
|
|
4267
3037
|
|
|
4268
|
-
// src/lib/
|
|
4269
|
-
import {
|
|
4270
|
-
var
|
|
4271
|
-
|
|
4272
|
-
|
|
4273
|
-
|
|
4274
|
-
|
|
4275
|
-
{ name: "nonce", type: "uint256" },
|
|
4276
|
-
{ name: "deadline", type: "uint256" },
|
|
4277
|
-
{ name: "witness", type: "Deposit" }
|
|
4278
|
-
],
|
|
4279
|
-
Deposit: [{ name: "recipients", type: "address[]" }],
|
|
4280
|
-
TokenPermissions: [
|
|
4281
|
-
{ name: "token", type: "address" },
|
|
4282
|
-
{ name: "amount", type: "uint256" }
|
|
4283
|
-
]
|
|
4284
|
-
};
|
|
4285
|
-
var PERMIT2_BATCH_ABI = parseAbi2([
|
|
4286
|
-
"struct TokenPermissions { address token; uint256 amount; }",
|
|
4287
|
-
"struct PermitBatchTransferFrom { TokenPermissions[] permitted; uint256 nonce; uint256 deadline; }",
|
|
4288
|
-
"struct SignatureTransferDetails { address to; uint256 requestedAmount; }",
|
|
4289
|
-
"function permitWitnessTransferFrom(PermitBatchTransferFrom permit,SignatureTransferDetails[] transferDetails,address owner,bytes32 witness,string witnessTypeString,bytes signature)",
|
|
4290
|
-
"function nonceBitmap(address owner,uint256 wordPos) view returns (uint256)"
|
|
4291
|
-
]);
|
|
4292
|
-
function batchPermit(b) {
|
|
4293
|
-
return {
|
|
4294
|
-
permitted: b.transfers.map((t) => ({
|
|
4295
|
-
token: b.token,
|
|
4296
|
-
amount: BigInt(t.amount)
|
|
4297
|
-
})),
|
|
4298
|
-
nonce: BigInt(b.nonce),
|
|
4299
|
-
deadline: BigInt(b.deadline)
|
|
4300
|
-
};
|
|
4301
|
-
}
|
|
4302
|
-
function batchTypedData(b, spender) {
|
|
3038
|
+
// src/lib/transfer-auth.ts
|
|
3039
|
+
import { bytesToHex as bytesToHex2 } from "viem";
|
|
3040
|
+
var ERC20_META_ABI = [
|
|
3041
|
+
{ type: "function", name: "name", stateMutability: "view", inputs: [], outputs: [{ name: "", type: "string" }] },
|
|
3042
|
+
{ type: "function", name: "version", stateMutability: "view", inputs: [], outputs: [{ name: "", type: "string" }] }
|
|
3043
|
+
];
|
|
3044
|
+
function buildTransferWithAuthorizationTypedData(input) {
|
|
4303
3045
|
return {
|
|
4304
|
-
domain: {
|
|
4305
|
-
|
|
4306
|
-
|
|
4307
|
-
|
|
3046
|
+
domain: { name: input.tokenName, version: input.tokenVersion, chainId: input.chainId, verifyingContract: input.token },
|
|
3047
|
+
types: {
|
|
3048
|
+
TransferWithAuthorization: [
|
|
3049
|
+
{ name: "from", type: "address" },
|
|
3050
|
+
{ name: "to", type: "address" },
|
|
3051
|
+
{ name: "value", type: "uint256" },
|
|
3052
|
+
{ name: "validAfter", type: "uint256" },
|
|
3053
|
+
{ name: "validBefore", type: "uint256" },
|
|
3054
|
+
{ name: "nonce", type: "bytes32" }
|
|
3055
|
+
]
|
|
4308
3056
|
},
|
|
4309
|
-
|
|
4310
|
-
|
|
4311
|
-
message: {
|
|
4312
|
-
...batchPermit(b),
|
|
4313
|
-
spender,
|
|
4314
|
-
witness: { recipients: b.transfers.map((t) => t.to) }
|
|
4315
|
-
}
|
|
3057
|
+
primaryType: "TransferWithAuthorization",
|
|
3058
|
+
message: input.message
|
|
4316
3059
|
};
|
|
4317
3060
|
}
|
|
4318
|
-
|
|
4319
|
-
|
|
4320
|
-
|
|
4321
|
-
|
|
4322
|
-
|
|
4323
|
-
|
|
4324
|
-
to: t.to.toLowerCase(),
|
|
4325
|
-
amount: BigInt(t.amount).toString()
|
|
4326
|
-
}))
|
|
4327
|
-
);
|
|
4328
|
-
function read(key2) {
|
|
4329
|
-
return typeof window === "undefined" ? memory.get(key2) : window.localStorage.getItem(key2);
|
|
4330
|
-
}
|
|
4331
|
-
function save(key2, body) {
|
|
4332
|
-
const value = JSON.stringify({
|
|
4333
|
-
...body,
|
|
4334
|
-
transfers: body.transfers.map(({ to, amount }) => ({ to, amount }))
|
|
4335
|
-
});
|
|
4336
|
-
if (typeof window === "undefined") memory.set(key2, value);
|
|
4337
|
-
else window.localStorage.setItem(key2, value);
|
|
3061
|
+
async function readTokenMeta(publicClient, token) {
|
|
3062
|
+
const [tokenName, tokenVersion] = await Promise.all([
|
|
3063
|
+
publicClient.readContract({ address: token, abi: ERC20_META_ABI, functionName: "name" }),
|
|
3064
|
+
publicClient.readContract({ address: token, abi: ERC20_META_ABI, functionName: "version" }).catch(() => "2")
|
|
3065
|
+
]);
|
|
3066
|
+
return { tokenName, tokenVersion };
|
|
4338
3067
|
}
|
|
4339
|
-
function
|
|
4340
|
-
|
|
4341
|
-
|
|
3068
|
+
function randomAuthNonce() {
|
|
3069
|
+
const bytes = new Uint8Array(32);
|
|
3070
|
+
globalThis.crypto.getRandomValues(bytes);
|
|
3071
|
+
return bytesToHex2(bytes);
|
|
4342
3072
|
}
|
|
4343
|
-
|
|
4344
|
-
|
|
4345
|
-
|
|
4346
|
-
|
|
4347
|
-
|
|
4348
|
-
|
|
4349
|
-
|
|
4350
|
-
|
|
4351
|
-
|
|
4352
|
-
|
|
4353
|
-
|
|
4354
|
-
|
|
3073
|
+
|
|
3074
|
+
// src/lib/sponsor-client.ts
|
|
3075
|
+
var ROUTING_API_BASE_URL3 = "https://owney-routing-api-243946518160.europe-west4.run.app";
|
|
3076
|
+
async function postSponsorTransferAuth(input) {
|
|
3077
|
+
const base3 = input.baseUrl ?? ROUTING_API_BASE_URL3;
|
|
3078
|
+
let res;
|
|
3079
|
+
try {
|
|
3080
|
+
res = await fetch(`${base3}/api/v1/sponsor/erc20-transfer-auth`, {
|
|
3081
|
+
method: "POST",
|
|
3082
|
+
headers: {
|
|
3083
|
+
"content-type": "application/json",
|
|
3084
|
+
"x-owney-api-key": input.apiKey
|
|
3085
|
+
},
|
|
3086
|
+
body: JSON.stringify(input.body)
|
|
3087
|
+
});
|
|
3088
|
+
} catch (networkError) {
|
|
3089
|
+
throw new OwneyError(
|
|
3090
|
+
"SPONSOR_REQUEST_FAILED",
|
|
3091
|
+
`Sponsor API network error: ${networkError instanceof Error ? networkError.message : String(networkError)}`,
|
|
3092
|
+
{ cause: String(networkError) }
|
|
3093
|
+
);
|
|
3094
|
+
}
|
|
3095
|
+
const text = await res.text();
|
|
3096
|
+
let parsed = null;
|
|
3097
|
+
try {
|
|
3098
|
+
parsed = JSON.parse(text);
|
|
3099
|
+
} catch {
|
|
3100
|
+
}
|
|
3101
|
+
if (!res.ok || !parsed?.success || !parsed.data) {
|
|
3102
|
+
throw new OwneyError(
|
|
3103
|
+
"SPONSOR_REQUEST_FAILED",
|
|
3104
|
+
`Sponsor API error ${res.status}: ${parsed?.message ?? text.slice(0, 500)}`,
|
|
3105
|
+
{
|
|
3106
|
+
statusCode: res.status,
|
|
3107
|
+
responseBody: text.slice(0, 500),
|
|
3108
|
+
// 503 SPONSOR_UNAVAILABLE = relayer out of gas; the tx was rejected
|
|
3109
|
+
// before broadcast, so it is safe to fall back to a user-paid deposit.
|
|
3110
|
+
safeToFallback: res.status === 503
|
|
3111
|
+
}
|
|
3112
|
+
);
|
|
4355
3113
|
}
|
|
4356
|
-
|
|
4357
|
-
inflight.set(key2, { plan, promise });
|
|
4358
|
-
return promise;
|
|
3114
|
+
return parsed.data;
|
|
4359
3115
|
}
|
|
4360
|
-
async function
|
|
4361
|
-
|
|
4362
|
-
|
|
4363
|
-
|
|
4364
|
-
|
|
4365
|
-
|
|
4366
|
-
|
|
4367
|
-
|
|
4368
|
-
|
|
4369
|
-
|
|
4370
|
-
|
|
4371
|
-
|
|
4372
|
-
|
|
4373
|
-
|
|
4374
|
-
|
|
4375
|
-
|
|
4376
|
-
|
|
4377
|
-
|
|
4378
|
-
|
|
4379
|
-
|
|
4380
|
-
|
|
4381
|
-
|
|
4382
|
-
|
|
4383
|
-
|
|
3116
|
+
async function postSponsorPermit2Transfer(input) {
|
|
3117
|
+
const base3 = input.baseUrl ?? ROUTING_API_BASE_URL3;
|
|
3118
|
+
let res;
|
|
3119
|
+
try {
|
|
3120
|
+
res = await fetch(`${base3}/api/v1/sponsor/permit2-transfer`, {
|
|
3121
|
+
method: "POST",
|
|
3122
|
+
headers: {
|
|
3123
|
+
"content-type": "application/json",
|
|
3124
|
+
"x-owney-api-key": input.apiKey
|
|
3125
|
+
},
|
|
3126
|
+
body: JSON.stringify(input.body)
|
|
3127
|
+
});
|
|
3128
|
+
} catch (networkError) {
|
|
3129
|
+
throw new OwneyError(
|
|
3130
|
+
"SPONSOR_REQUEST_FAILED",
|
|
3131
|
+
`Sponsor API network error: ${networkError instanceof Error ? networkError.message : String(networkError)}`,
|
|
3132
|
+
{ cause: String(networkError), safeToFallback: false }
|
|
3133
|
+
);
|
|
3134
|
+
}
|
|
3135
|
+
const text = await res.text();
|
|
3136
|
+
let parsed = null;
|
|
3137
|
+
try {
|
|
3138
|
+
parsed = JSON.parse(text);
|
|
3139
|
+
} catch {
|
|
3140
|
+
}
|
|
3141
|
+
if (!res.ok || !parsed?.success || !parsed.data) {
|
|
3142
|
+
throw new OwneyError(
|
|
3143
|
+
"SPONSOR_REQUEST_FAILED",
|
|
3144
|
+
`Sponsor API error ${res.status}: ${parsed?.message ?? text.slice(0, 500)}`,
|
|
3145
|
+
{
|
|
3146
|
+
statusCode: res.status,
|
|
3147
|
+
responseBody: text.slice(0, 500),
|
|
3148
|
+
safeToFallback: res.status >= 400 && res.status < 500 || res.status === 503
|
|
4384
3149
|
}
|
|
4385
|
-
|
|
4386
|
-
apiKey: i.apiKey,
|
|
4387
|
-
baseUrl: i.baseUrl,
|
|
4388
|
-
body
|
|
4389
|
-
});
|
|
4390
|
-
if (result.txHash !== keccak256(body.serializedTransaction))
|
|
4391
|
-
throw new Error(
|
|
4392
|
-
"Sponsorship receipt does not match the pending transaction."
|
|
4393
|
-
);
|
|
4394
|
-
clear(key2);
|
|
4395
|
-
return result.txHash;
|
|
4396
|
-
} catch (error) {
|
|
4397
|
-
if (!body.serializedTransaction || error instanceof OwneyError && error.details?.notSubmitted === true)
|
|
4398
|
-
clear(key2);
|
|
4399
|
-
throw error;
|
|
4400
|
-
}
|
|
4401
|
-
};
|
|
4402
|
-
const saved = read(key2);
|
|
4403
|
-
if (saved) {
|
|
4404
|
-
const previous = JSON.parse(saved);
|
|
4405
|
-
if (previous.chainId !== i.chainId || !isAddressEqual(previous.from, i.owner) || !isAddressEqual(previous.token, i.token) || planOf(previous.transfers) !== plan)
|
|
4406
|
-
throw new Error(
|
|
4407
|
-
"Retry the previous token deposit and agent split first to reconcile its status."
|
|
4408
|
-
);
|
|
4409
|
-
i.onApproved?.();
|
|
4410
|
-
return send({ ...previous, transfers: i.transfers });
|
|
3150
|
+
);
|
|
4411
3151
|
}
|
|
4412
|
-
|
|
4413
|
-
|
|
4414
|
-
|
|
4415
|
-
|
|
4416
|
-
|
|
4417
|
-
|
|
3152
|
+
return parsed.data;
|
|
3153
|
+
}
|
|
3154
|
+
async function getSponsorRelayerAddress(input) {
|
|
3155
|
+
const base3 = input.baseUrl ?? ROUTING_API_BASE_URL3;
|
|
3156
|
+
let res;
|
|
3157
|
+
try {
|
|
3158
|
+
res = await fetch(
|
|
3159
|
+
`${base3}/api/v1/sponsor/relayer-address?chainId=${input.chainId}`,
|
|
3160
|
+
{
|
|
3161
|
+
headers: { "x-owney-api-key": input.apiKey }
|
|
3162
|
+
}
|
|
3163
|
+
);
|
|
3164
|
+
} catch (networkError) {
|
|
4418
3165
|
throw new OwneyError(
|
|
4419
|
-
"
|
|
4420
|
-
|
|
3166
|
+
"SPONSOR_REQUEST_FAILED",
|
|
3167
|
+
`Sponsor API network error: ${networkError instanceof Error ? networkError.message : String(networkError)}`,
|
|
3168
|
+
{ cause: String(networkError), safeToFallback: true }
|
|
4421
3169
|
);
|
|
4422
|
-
|
|
3170
|
+
}
|
|
3171
|
+
const text = await res.text();
|
|
3172
|
+
let parsed = null;
|
|
3173
|
+
try {
|
|
3174
|
+
parsed = JSON.parse(text);
|
|
3175
|
+
} catch {
|
|
3176
|
+
}
|
|
3177
|
+
if (!res.ok || !parsed?.success || !parsed.data?.relayer) {
|
|
4423
3178
|
throw new OwneyError(
|
|
4424
|
-
"
|
|
4425
|
-
|
|
3179
|
+
"SPONSOR_REQUEST_FAILED",
|
|
3180
|
+
`Sponsor API error ${res.status}: ${parsed?.message ?? text.slice(0, 500)}`,
|
|
3181
|
+
{
|
|
3182
|
+
statusCode: res.status,
|
|
3183
|
+
responseBody: text.slice(0, 500),
|
|
3184
|
+
safeToFallback: true
|
|
3185
|
+
}
|
|
4426
3186
|
);
|
|
4427
|
-
|
|
4428
|
-
|
|
4429
|
-
|
|
4430
|
-
|
|
4431
|
-
|
|
4432
|
-
|
|
4433
|
-
|
|
4434
|
-
|
|
4435
|
-
|
|
4436
|
-
|
|
4437
|
-
|
|
4438
|
-
|
|
4439
|
-
|
|
3187
|
+
}
|
|
3188
|
+
return parsed.data.relayer;
|
|
3189
|
+
}
|
|
3190
|
+
|
|
3191
|
+
// src/lib/sponsored-deposit.ts
|
|
3192
|
+
var AUTH_WINDOW_SECONDS = 15 * 60;
|
|
3193
|
+
function makeSponsoredDepositCallback(deps) {
|
|
3194
|
+
const post = deps.httpPost ?? postSponsorTransferAuth;
|
|
3195
|
+
return async (smartWallet, chainId, amount) => {
|
|
3196
|
+
const cid = chainId;
|
|
3197
|
+
const token = deps.tokenAddressByChain[cid];
|
|
3198
|
+
if (!token) {
|
|
3199
|
+
throw new OwneyError(
|
|
3200
|
+
"CHAIN_UNSUPPORTED",
|
|
3201
|
+
`No sponsored token configured for chain ${chainId}`
|
|
3202
|
+
);
|
|
3203
|
+
}
|
|
3204
|
+
const pub = deps.getPublicClient(cid);
|
|
3205
|
+
const wallet = deps.getWalletClient(cid);
|
|
3206
|
+
await ensureWalletOnChain(pub, wallet, cid);
|
|
3207
|
+
try {
|
|
3208
|
+
const balance = await readErc20Balance(pub, token, deps.ownerAddress);
|
|
3209
|
+
if (balance < BigInt(amount)) {
|
|
3210
|
+
throw new OwneyError(
|
|
3211
|
+
"DEPOSIT_INSUFFICIENT_BALANCE",
|
|
3212
|
+
"Insufficient balance for this deposit.",
|
|
3213
|
+
{ token, chainId: cid, balance: balance.toString(), amount }
|
|
3214
|
+
);
|
|
3215
|
+
}
|
|
3216
|
+
} catch (err) {
|
|
3217
|
+
if (err instanceof OwneyError) throw err;
|
|
3218
|
+
console.warn(
|
|
3219
|
+
"[owney-sdk] Deposit balance pre-check failed (non-fatal):",
|
|
3220
|
+
err instanceof Error ? err.message : String(err)
|
|
3221
|
+
);
|
|
3222
|
+
}
|
|
3223
|
+
const { tokenName, tokenVersion } = await readTokenMeta(pub, token);
|
|
3224
|
+
const validAfter = 0n;
|
|
3225
|
+
const validBefore = BigInt(
|
|
3226
|
+
Math.floor(Date.now() / 1e3) + AUTH_WINDOW_SECONDS
|
|
3227
|
+
);
|
|
3228
|
+
const nonce = randomAuthNonce();
|
|
3229
|
+
const typedData = buildTransferWithAuthorizationTypedData({
|
|
3230
|
+
token,
|
|
3231
|
+
chainId: cid,
|
|
3232
|
+
tokenName,
|
|
3233
|
+
tokenVersion,
|
|
3234
|
+
message: {
|
|
3235
|
+
from: deps.ownerAddress,
|
|
3236
|
+
to: smartWallet,
|
|
3237
|
+
value: BigInt(amount),
|
|
3238
|
+
validAfter,
|
|
3239
|
+
validBefore,
|
|
3240
|
+
nonce
|
|
3241
|
+
}
|
|
3242
|
+
});
|
|
3243
|
+
const authSignature = await wallet.signTypedData({
|
|
3244
|
+
account: deps.ownerAddress,
|
|
3245
|
+
...typedData
|
|
3246
|
+
});
|
|
3247
|
+
deps.onApproved?.();
|
|
3248
|
+
const result = await post({
|
|
3249
|
+
baseUrl: deps.baseUrl,
|
|
3250
|
+
apiKey: deps.apiKey,
|
|
3251
|
+
body: {
|
|
3252
|
+
chainId: cid,
|
|
3253
|
+
token,
|
|
3254
|
+
from: deps.ownerAddress,
|
|
3255
|
+
to: smartWallet,
|
|
3256
|
+
value: amount,
|
|
3257
|
+
validAfter: validAfter.toString(),
|
|
3258
|
+
validBefore: validBefore.toString(),
|
|
3259
|
+
nonce,
|
|
3260
|
+
authSignature,
|
|
3261
|
+
tokenName,
|
|
3262
|
+
tokenVersion
|
|
3263
|
+
}
|
|
3264
|
+
});
|
|
3265
|
+
return result.txHash;
|
|
4440
3266
|
};
|
|
4441
|
-
const signature = await i.wallet.signTypedData({
|
|
4442
|
-
account: i.owner,
|
|
4443
|
-
...batchTypedData(unsigned, relayer)
|
|
4444
|
-
});
|
|
4445
|
-
i.onApproved?.();
|
|
4446
|
-
return send({ ...unsigned, signature });
|
|
4447
3267
|
}
|
|
4448
3268
|
|
|
4449
|
-
// src/lib/sponsored-
|
|
4450
|
-
|
|
4451
|
-
|
|
4452
|
-
|
|
3269
|
+
// src/lib/sponsored-weth-deposit.ts
|
|
3270
|
+
var PERMIT_WINDOW_SECONDS = 15 * 60;
|
|
3271
|
+
function makeSponsoredWethCallback(deps) {
|
|
3272
|
+
const get = deps.httpGet ?? getSponsorRelayerAddress;
|
|
3273
|
+
const post = deps.httpPost ?? postSponsorPermit2Transfer;
|
|
3274
|
+
return async (smartWallet, chainId, amount) => {
|
|
3275
|
+
const cid = chainId;
|
|
3276
|
+
const token = deps.tokenAddressByChain[cid];
|
|
3277
|
+
if (!token) {
|
|
4453
3278
|
throw new OwneyError(
|
|
4454
3279
|
"CHAIN_UNSUPPORTED",
|
|
4455
|
-
`No sponsored
|
|
3280
|
+
`No sponsored WETH configured for chain ${chainId}`
|
|
3281
|
+
);
|
|
3282
|
+
}
|
|
3283
|
+
const amountWei = BigInt(amount);
|
|
3284
|
+
const pub = deps.getPublicClient(cid);
|
|
3285
|
+
const wallet = deps.getWalletClient(cid);
|
|
3286
|
+
await ensureWalletOnChain(pub, wallet, cid);
|
|
3287
|
+
try {
|
|
3288
|
+
const balance = await readErc20Balance(pub, token, deps.ownerAddress);
|
|
3289
|
+
if (balance < amountWei) {
|
|
3290
|
+
throw new OwneyError(
|
|
3291
|
+
"DEPOSIT_INSUFFICIENT_BALANCE",
|
|
3292
|
+
"Insufficient WETH balance for this deposit.",
|
|
3293
|
+
{ token, chainId: cid, balance: balance.toString(), amount }
|
|
3294
|
+
);
|
|
3295
|
+
}
|
|
3296
|
+
} catch (err) {
|
|
3297
|
+
if (err instanceof OwneyError) throw err;
|
|
3298
|
+
console.warn(
|
|
3299
|
+
"[owney-sdk] WETH balance pre-check failed (non-fatal):",
|
|
3300
|
+
err instanceof Error ? err.message : String(err)
|
|
4456
3301
|
);
|
|
4457
|
-
|
|
4458
|
-
|
|
3302
|
+
}
|
|
3303
|
+
const allowance = await readPermit2Allowance(pub, token, deps.ownerAddress);
|
|
3304
|
+
if (allowance < amountWei) {
|
|
4459
3305
|
throw new OwneyError(
|
|
4460
|
-
"
|
|
4461
|
-
|
|
3306
|
+
"PERMIT2_APPROVAL_REQUIRED",
|
|
3307
|
+
"WETH gasless deposits need a one-time Permit2 approval; call approvePermit2() first",
|
|
3308
|
+
{ token, chainId: cid, allowance: allowance.toString(), amount }
|
|
4462
3309
|
);
|
|
4463
|
-
|
|
4464
|
-
await
|
|
4465
|
-
|
|
3310
|
+
}
|
|
3311
|
+
const relayer = await get({
|
|
3312
|
+
baseUrl: deps.baseUrl,
|
|
4466
3313
|
apiKey: deps.apiKey,
|
|
3314
|
+
chainId: cid
|
|
3315
|
+
});
|
|
3316
|
+
const nonce = randomPermit2Nonce();
|
|
3317
|
+
const deadline = BigInt(
|
|
3318
|
+
Math.floor(Date.now() / 1e3) + PERMIT_WINDOW_SECONDS
|
|
3319
|
+
);
|
|
3320
|
+
const typedData = buildPermitTransferFromTypedData({
|
|
3321
|
+
chainId: cid,
|
|
3322
|
+
message: {
|
|
3323
|
+
permitted: { token, amount: amountWei },
|
|
3324
|
+
spender: relayer,
|
|
3325
|
+
nonce,
|
|
3326
|
+
deadline
|
|
3327
|
+
}
|
|
3328
|
+
});
|
|
3329
|
+
const signature = await wallet.signTypedData({
|
|
3330
|
+
account: deps.ownerAddress,
|
|
3331
|
+
...typedData
|
|
3332
|
+
});
|
|
3333
|
+
deps.onApproved?.();
|
|
3334
|
+
const result = await post({
|
|
4467
3335
|
baseUrl: deps.baseUrl,
|
|
4468
|
-
|
|
4469
|
-
|
|
4470
|
-
|
|
4471
|
-
|
|
4472
|
-
|
|
4473
|
-
|
|
4474
|
-
|
|
3336
|
+
apiKey: deps.apiKey,
|
|
3337
|
+
body: {
|
|
3338
|
+
chainId: cid,
|
|
3339
|
+
token,
|
|
3340
|
+
from: deps.ownerAddress,
|
|
3341
|
+
to: smartWallet,
|
|
3342
|
+
amount,
|
|
3343
|
+
nonce: nonce.toString(),
|
|
3344
|
+
deadline: deadline.toString(),
|
|
3345
|
+
signature
|
|
3346
|
+
}
|
|
4475
3347
|
});
|
|
3348
|
+
return result.txHash;
|
|
4476
3349
|
};
|
|
4477
|
-
const callback = makeVerificationAwareDepositCallback(
|
|
4478
|
-
(to, chainId, amount, verification) => batch(chainId, [toBatchTransfer(to, amount, verification)])
|
|
4479
|
-
);
|
|
4480
|
-
registerDepositBatch(callback, batch);
|
|
4481
|
-
return callback;
|
|
4482
|
-
}
|
|
4483
|
-
|
|
4484
|
-
// src/lib/agent-deposit-batch.ts
|
|
4485
|
-
function deferred() {
|
|
4486
|
-
let resolve, reject;
|
|
4487
|
-
const promise = new Promise((yes, no) => {
|
|
4488
|
-
resolve = yes;
|
|
4489
|
-
reject = no;
|
|
4490
|
-
});
|
|
4491
|
-
void promise.catch(() => {
|
|
4492
|
-
});
|
|
4493
|
-
return { promise, resolve, reject };
|
|
4494
|
-
}
|
|
4495
|
-
async function runAgentDepositBatch(chainId, legs, transfer) {
|
|
4496
|
-
const funding = deferred();
|
|
4497
|
-
const tasks = [];
|
|
4498
|
-
const transfers = [];
|
|
4499
|
-
try {
|
|
4500
|
-
for (const leg of legs) {
|
|
4501
|
-
const ready = deferred();
|
|
4502
|
-
let entered = false;
|
|
4503
|
-
const callback = makeVerificationAwareDepositCallback(
|
|
4504
|
-
(to, cid, amount, verification) => {
|
|
4505
|
-
if (entered || cid !== chainId || BigInt(amount) !== BigInt(leg.amount)) {
|
|
4506
|
-
const error = new Error(
|
|
4507
|
-
"Agent changed its prepared deposit share."
|
|
4508
|
-
);
|
|
4509
|
-
ready.reject(error);
|
|
4510
|
-
throw error;
|
|
4511
|
-
}
|
|
4512
|
-
entered = true;
|
|
4513
|
-
ready.resolve(toBatchTransfer(to, amount, verification));
|
|
4514
|
-
return funding.promise;
|
|
4515
|
-
}
|
|
4516
|
-
);
|
|
4517
|
-
const task = Promise.resolve().then(() => leg.run(callback));
|
|
4518
|
-
tasks.push(task);
|
|
4519
|
-
void task.then(
|
|
4520
|
-
() => {
|
|
4521
|
-
if (!entered)
|
|
4522
|
-
ready.reject(
|
|
4523
|
-
new Error("Agent did not prepare a deposit transfer.")
|
|
4524
|
-
);
|
|
4525
|
-
},
|
|
4526
|
-
(error) => ready.reject(error)
|
|
4527
|
-
);
|
|
4528
|
-
transfers.push(await ready.promise);
|
|
4529
|
-
}
|
|
4530
|
-
const txHash = await transfer(chainId, transfers);
|
|
4531
|
-
funding.resolve(txHash);
|
|
4532
|
-
const settled = await Promise.allSettled(tasks);
|
|
4533
|
-
const agentResults = {};
|
|
4534
|
-
const failures = [];
|
|
4535
|
-
for (const [index, result] of settled.entries()) {
|
|
4536
|
-
if (result.status === "fulfilled")
|
|
4537
|
-
agentResults[legs[index].id] = result.value;
|
|
4538
|
-
else failures.push(legs[index].id);
|
|
4539
|
-
}
|
|
4540
|
-
if (failures.length)
|
|
4541
|
-
throw new OwneyError(
|
|
4542
|
-
"DEPOSIT_PARTIAL_FAILURE",
|
|
4543
|
-
"The deposit was sent to all agents, but some agent updates could not be confirmed. Check activity before depositing again.",
|
|
4544
|
-
{
|
|
4545
|
-
txHash,
|
|
4546
|
-
fundsSubmitted: true,
|
|
4547
|
-
agentResults,
|
|
4548
|
-
failedAgentIds: failures
|
|
4549
|
-
}
|
|
4550
|
-
);
|
|
4551
|
-
return { agentResults };
|
|
4552
|
-
} catch (error) {
|
|
4553
|
-
funding.reject(error);
|
|
4554
|
-
await Promise.allSettled(tasks);
|
|
4555
|
-
throw error;
|
|
4556
|
-
}
|
|
4557
3350
|
}
|
|
4558
3351
|
|
|
4559
3352
|
// src/lib/sponsored-calls-deposit.ts
|
|
4560
|
-
import { encodeFunctionData
|
|
3353
|
+
import { encodeFunctionData, erc20Abi, toHex as toHex2 } from "viem";
|
|
4561
3354
|
var DEFAULT_POLL_INTERVAL_MS = 1500;
|
|
4562
3355
|
var DEFAULT_MAX_POLLS = 30;
|
|
4563
3356
|
async function paymasterSupported(provider, owner, chainId) {
|
|
@@ -4565,7 +3358,7 @@ async function paymasterSupported(provider, owner, chainId) {
|
|
|
4565
3358
|
method: "wallet_getCapabilities",
|
|
4566
3359
|
params: [owner]
|
|
4567
3360
|
});
|
|
4568
|
-
const forChain = caps?.[
|
|
3361
|
+
const forChain = caps?.[toHex2(chainId)] ?? caps?.[String(chainId)];
|
|
4569
3362
|
return Boolean(forChain?.paymasterService?.supported);
|
|
4570
3363
|
}
|
|
4571
3364
|
function makeSponsoredCallsCallback(deps) {
|
|
@@ -4583,7 +3376,7 @@ function makeSponsoredCallsCallback(deps) {
|
|
|
4583
3376
|
}
|
|
4584
3377
|
return new URL(configured, origin).toString();
|
|
4585
3378
|
};
|
|
4586
|
-
|
|
3379
|
+
return async (smartWallet, chainId, amount) => {
|
|
4587
3380
|
const cid = chainId;
|
|
4588
3381
|
const token = deps.tokenAddressByChain[cid];
|
|
4589
3382
|
if (!token) {
|
|
@@ -4599,53 +3392,22 @@ function makeSponsoredCallsCallback(deps) {
|
|
|
4599
3392
|
{ chainId }
|
|
4600
3393
|
);
|
|
4601
3394
|
}
|
|
4602
|
-
const
|
|
4603
|
-
|
|
4604
|
-
|
|
4605
|
-
|
|
4606
|
-
|
|
4607
|
-
functionName: "transfer",
|
|
4608
|
-
args: [transfer.to, BigInt(transfer.amount)]
|
|
4609
|
-
})
|
|
4610
|
-
}));
|
|
4611
|
-
let paymasterUrl = absolutePaymasterUrl();
|
|
4612
|
-
for (const transfer of transfers) {
|
|
4613
|
-
const verification = transfer.yieldseeker;
|
|
4614
|
-
if (!verification) continue;
|
|
4615
|
-
if (chainId !== 8453)
|
|
4616
|
-
throw new OwneyError(
|
|
4617
|
-
"CHAIN_UNSUPPORTED",
|
|
4618
|
-
`Yieldseeker sponsorship is not available on chain ${chainId}.`
|
|
4619
|
-
);
|
|
4620
|
-
const { intent } = await postPaymasterIntent({
|
|
4621
|
-
baseUrl: deps.routingApiBaseUrl,
|
|
4622
|
-
apiKey: deps.apiKey,
|
|
4623
|
-
yieldseekerSignature: verification.signature,
|
|
4624
|
-
body: {
|
|
4625
|
-
chainId,
|
|
4626
|
-
token,
|
|
4627
|
-
from: deps.ownerAddress,
|
|
4628
|
-
to: transfer.to,
|
|
4629
|
-
amount: transfer.amount,
|
|
4630
|
-
yieldseekerUserId: verification.userId,
|
|
4631
|
-
yieldseekerAgentId: verification.agentId
|
|
4632
|
-
}
|
|
4633
|
-
});
|
|
4634
|
-
const url = new URL(paymasterUrl);
|
|
4635
|
-
url.searchParams.append("owneyIntent", intent);
|
|
4636
|
-
paymasterUrl = url.toString();
|
|
4637
|
-
}
|
|
3395
|
+
const data = encodeFunctionData({
|
|
3396
|
+
abi: erc20Abi,
|
|
3397
|
+
functionName: "transfer",
|
|
3398
|
+
args: [smartWallet, BigInt(amount)]
|
|
3399
|
+
});
|
|
4638
3400
|
const sendResult = await deps.provider.request({
|
|
4639
3401
|
method: "wallet_sendCalls",
|
|
4640
3402
|
params: [
|
|
4641
3403
|
{
|
|
4642
3404
|
version: "2.0.0",
|
|
4643
3405
|
from: deps.ownerAddress,
|
|
4644
|
-
chainId:
|
|
4645
|
-
atomicRequired:
|
|
4646
|
-
calls,
|
|
3406
|
+
chainId: toHex2(chainId),
|
|
3407
|
+
atomicRequired: false,
|
|
3408
|
+
calls: [{ to: token, value: "0x0", data }],
|
|
4647
3409
|
capabilities: {
|
|
4648
|
-
paymasterService: { url:
|
|
3410
|
+
paymasterService: { url: absolutePaymasterUrl() }
|
|
4649
3411
|
}
|
|
4650
3412
|
}
|
|
4651
3413
|
]
|
|
@@ -4665,24 +3427,7 @@ function makeSponsoredCallsCallback(deps) {
|
|
|
4665
3427
|
params: [callsId]
|
|
4666
3428
|
});
|
|
4667
3429
|
const txHash = status?.receipts?.[0]?.transactionHash;
|
|
4668
|
-
if (
|
|
4669
|
-
throw new OwneyError(
|
|
4670
|
-
"SPONSOR_REQUEST_FAILED",
|
|
4671
|
-
"The sponsored deposit did not complete successfully.",
|
|
4672
|
-
{ chainId, callsId, safeToFallback: false }
|
|
4673
|
-
);
|
|
4674
|
-
}
|
|
4675
|
-
if (txHash && (transfers.length === 1 || status?.status === 200 || status?.status === "CONFIRMED")) {
|
|
4676
|
-
if (status?.receipts?.some(
|
|
4677
|
-
(receipt) => receipt.transactionHash !== txHash
|
|
4678
|
-
))
|
|
4679
|
-
throw new OwneyError(
|
|
4680
|
-
"SPONSORED_CALLS_NO_RECEIPT",
|
|
4681
|
-
"The wallet returned multiple transactions for an atomic deposit. Check activity before trying again.",
|
|
4682
|
-
{ chainId, callsId }
|
|
4683
|
-
);
|
|
4684
|
-
return txHash;
|
|
4685
|
-
}
|
|
3430
|
+
if (txHash) return txHash;
|
|
4686
3431
|
if (pollIntervalMs > 0) {
|
|
4687
3432
|
await new Promise((resolve) => setTimeout(resolve, pollIntervalMs));
|
|
4688
3433
|
}
|
|
@@ -4693,11 +3438,6 @@ function makeSponsoredCallsCallback(deps) {
|
|
|
4693
3438
|
{ chainId, callsId }
|
|
4694
3439
|
);
|
|
4695
3440
|
};
|
|
4696
|
-
const callback = makeVerificationAwareDepositCallback(
|
|
4697
|
-
(to, chainId, amount, verification) => batch(chainId, [toBatchTransfer(to, amount, verification)])
|
|
4698
|
-
);
|
|
4699
|
-
registerDepositBatch(callback, batch);
|
|
4700
|
-
return callback;
|
|
4701
3441
|
}
|
|
4702
3442
|
|
|
4703
3443
|
// src/client.ts
|
|
@@ -4727,7 +3467,7 @@ var SPONSORED_USDC_BY_CHAIN = {
|
|
|
4727
3467
|
1: "0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48"
|
|
4728
3468
|
};
|
|
4729
3469
|
var VIEM_CHAIN2 = {
|
|
4730
|
-
8453:
|
|
3470
|
+
8453: base2,
|
|
4731
3471
|
42161: arbitrum2,
|
|
4732
3472
|
1: mainnet2
|
|
4733
3473
|
};
|
|
@@ -4736,11 +3476,6 @@ var SPONSORED_WETH_BY_CHAIN = {
|
|
|
4736
3476
|
42161: "0x82aF49447D8a07e3bd95BD0d56f35241523fBab1",
|
|
4737
3477
|
1: "0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2"
|
|
4738
3478
|
};
|
|
4739
|
-
var SPONSORED_TOKENS_BY_ASSET = { USDC: SPONSORED_USDC_BY_CHAIN, WETH: SPONSORED_WETH_BY_CHAIN };
|
|
4740
|
-
function sponsoredTokensFor(asset) {
|
|
4741
|
-
if (!Object.prototype.hasOwnProperty.call(SPONSORED_TOKENS_BY_ASSET, asset)) throw new OwneyError("ASSET_UNSUPPORTED", `No sponsored token configured for ${asset}`);
|
|
4742
|
-
return SPONSORED_TOKENS_BY_ASSET[asset];
|
|
4743
|
-
}
|
|
4744
3479
|
function shouldFallbackToUserPaid(error, asset, appCallback) {
|
|
4745
3480
|
return (asset === "WETH" || asset === "USDC") && appCallback === void 0 && error instanceof OwneyError && error.code === "SPONSOR_REQUEST_FAILED" && error.details?.safeToFallback === true;
|
|
4746
3481
|
}
|
|
@@ -4762,8 +3497,6 @@ var OwneySDK = class {
|
|
|
4762
3497
|
orgAgentConfig;
|
|
4763
3498
|
orgAgentConfigPromise = null;
|
|
4764
3499
|
zyfaiRpcUrls;
|
|
4765
|
-
yieldseekerApiBaseUrl;
|
|
4766
|
-
yieldseekerSiweOrigin;
|
|
4767
3500
|
routingApiBaseUrl;
|
|
4768
3501
|
referralSource;
|
|
4769
3502
|
cachedSponsoredCallback = null;
|
|
@@ -4786,8 +3519,6 @@ var OwneySDK = class {
|
|
|
4786
3519
|
this.apiKey = config.apiKey;
|
|
4787
3520
|
if (config.debug) setOwneyDebug(true);
|
|
4788
3521
|
this.zyfaiRpcUrls = config.zyfaiRpcUrls;
|
|
4789
|
-
this.yieldseekerApiBaseUrl = config.yieldseekerApiBaseUrl;
|
|
4790
|
-
this.yieldseekerSiweOrigin = config.yieldseekerSiweOrigin;
|
|
4791
3522
|
this.routingApiBaseUrl = config.routingApiBaseUrl;
|
|
4792
3523
|
this.paymasterServiceUrl = config.paymasterServiceUrl;
|
|
4793
3524
|
this.referralSource = config.referralSource;
|
|
@@ -4821,7 +3552,6 @@ var OwneySDK = class {
|
|
|
4821
3552
|
* After calling this, `connect()` must be called again before using agent methods.
|
|
4822
3553
|
*/
|
|
4823
3554
|
async disconnect() {
|
|
4824
|
-
this.state = null;
|
|
4825
3555
|
for (const agent of this.agents.values()) {
|
|
4826
3556
|
await agent.disconnect();
|
|
4827
3557
|
}
|
|
@@ -4875,13 +3605,18 @@ var OwneySDK = class {
|
|
|
4875
3605
|
}
|
|
4876
3606
|
return this.state.provider;
|
|
4877
3607
|
}
|
|
4878
|
-
/**
|
|
3608
|
+
/**
|
|
3609
|
+
* Lazily builds (and caches) the default EIP-3009 sponsored deposit callback
|
|
3610
|
+
* used when the caller omits `depositCallback`. Wraps the connected EIP-1193
|
|
3611
|
+
* provider with viem `custom(provider)` to read token meta and sign the
|
|
3612
|
+
* `TransferWithAuthorization`, then POSTs to the sponsor API.
|
|
3613
|
+
*/
|
|
4879
3614
|
getDefaultSponsoredCallback(onApproved) {
|
|
4880
3615
|
if (!onApproved && this.cachedSponsoredCallback)
|
|
4881
3616
|
return this.cachedSponsoredCallback;
|
|
4882
3617
|
const provider = this.requireConnectedProvider();
|
|
4883
3618
|
const owner = this.state.walletAddress;
|
|
4884
|
-
const callback =
|
|
3619
|
+
const callback = makeSponsoredDepositCallback({
|
|
4885
3620
|
apiKey: this.apiKey,
|
|
4886
3621
|
baseUrl: this.routingApiBaseUrl,
|
|
4887
3622
|
ownerAddress: owner,
|
|
@@ -4890,32 +3625,35 @@ var OwneySDK = class {
|
|
|
4890
3625
|
// Casts work around viem's chain-narrowed Client vs the generic
|
|
4891
3626
|
// PublicClient/WalletClient param types — structurally identical at
|
|
4892
3627
|
// runtime, but the two share a name TS treats as unrelated.
|
|
4893
|
-
getPublicClient: (cid) =>
|
|
3628
|
+
getPublicClient: (cid) => createPublicClient2({
|
|
4894
3629
|
chain: VIEM_CHAIN2[cid],
|
|
4895
|
-
transport:
|
|
3630
|
+
transport: custom(provider)
|
|
4896
3631
|
}),
|
|
4897
|
-
getWalletClient: (cid) =>
|
|
3632
|
+
getWalletClient: (cid) => createWalletClient({
|
|
4898
3633
|
account: owner,
|
|
4899
3634
|
chain: VIEM_CHAIN2[cid],
|
|
4900
|
-
transport:
|
|
3635
|
+
transport: custom(provider)
|
|
4901
3636
|
})
|
|
4902
3637
|
});
|
|
4903
3638
|
if (!onApproved) this.cachedSponsoredCallback = callback;
|
|
4904
3639
|
return callback;
|
|
4905
3640
|
}
|
|
4906
|
-
/**
|
|
3641
|
+
/**
|
|
3642
|
+
* Lazily builds (and caches) the default Permit2 sponsored WETH deposit
|
|
3643
|
+
* callback used when the caller omits `depositCallback` for a WETH
|
|
3644
|
+
* deposit. Mirrors `getDefaultSponsoredCallback()` but signs a Permit2
|
|
3645
|
+
* `PermitTransferFrom` instead of an EIP-3009 authorization.
|
|
3646
|
+
*/
|
|
4907
3647
|
getDefaultSponsoredCallsCallback(asset, onApproved) {
|
|
4908
3648
|
const cached = this.cachedSponsoredCallsCallbacks.get(asset);
|
|
4909
3649
|
if (!onApproved && cached) return cached;
|
|
4910
3650
|
const provider = this.requireConnectedProvider();
|
|
4911
3651
|
const callback = makeSponsoredCallsCallback({
|
|
4912
|
-
apiKey: this.apiKey,
|
|
4913
|
-
routingApiBaseUrl: this.routingApiBaseUrl,
|
|
4914
3652
|
provider,
|
|
4915
3653
|
ownerAddress: this.state.walletAddress,
|
|
4916
3654
|
paymasterServiceUrl: this.paymasterServiceUrl,
|
|
4917
3655
|
onApproved,
|
|
4918
|
-
tokenAddressByChain:
|
|
3656
|
+
tokenAddressByChain: asset === "WETH" ? SPONSORED_WETH_BY_CHAIN : SPONSORED_USDC_BY_CHAIN
|
|
4919
3657
|
});
|
|
4920
3658
|
if (!onApproved) this.cachedSponsoredCallsCallbacks.set(asset, callback);
|
|
4921
3659
|
return callback;
|
|
@@ -4924,14 +3662,14 @@ var OwneySDK = class {
|
|
|
4924
3662
|
* Lazily builds (and caches) the default Permit2 sponsored WETH deposit
|
|
4925
3663
|
* callback used when the caller omits `depositCallback` for a WETH deposit.
|
|
4926
3664
|
* Mirrors `getDefaultSponsoredCallback()` but signs a Permit2
|
|
4927
|
-
*
|
|
3665
|
+
* `PermitTransferFrom` instead of an EIP-3009 authorization.
|
|
4928
3666
|
*/
|
|
4929
3667
|
getDefaultWethSponsoredCallback(onApproved) {
|
|
4930
3668
|
if (!onApproved && this.cachedWethSponsoredCallback)
|
|
4931
3669
|
return this.cachedWethSponsoredCallback;
|
|
4932
3670
|
const provider = this.requireConnectedProvider();
|
|
4933
3671
|
const owner = this.state.walletAddress;
|
|
4934
|
-
const callback =
|
|
3672
|
+
const callback = makeSponsoredWethCallback({
|
|
4935
3673
|
apiKey: this.apiKey,
|
|
4936
3674
|
baseUrl: this.routingApiBaseUrl,
|
|
4937
3675
|
ownerAddress: owner,
|
|
@@ -4940,14 +3678,14 @@ var OwneySDK = class {
|
|
|
4940
3678
|
// Casts work around viem's chain-narrowed Client vs the generic
|
|
4941
3679
|
// PublicClient/WalletClient param types — structurally identical at
|
|
4942
3680
|
// runtime, but the two share a name TS treats as unrelated.
|
|
4943
|
-
getPublicClient: (cid) =>
|
|
3681
|
+
getPublicClient: (cid) => createPublicClient2({
|
|
4944
3682
|
chain: VIEM_CHAIN2[cid],
|
|
4945
|
-
transport:
|
|
3683
|
+
transport: custom(provider)
|
|
4946
3684
|
}),
|
|
4947
|
-
getWalletClient: (cid) =>
|
|
3685
|
+
getWalletClient: (cid) => createWalletClient({
|
|
4948
3686
|
account: owner,
|
|
4949
3687
|
chain: VIEM_CHAIN2[cid],
|
|
4950
|
-
transport:
|
|
3688
|
+
transport: custom(provider)
|
|
4951
3689
|
})
|
|
4952
3690
|
});
|
|
4953
3691
|
if (!onApproved) this.cachedWethSponsoredCallback = callback;
|
|
@@ -5021,14 +3759,7 @@ var OwneySDK = class {
|
|
|
5021
3759
|
this.routingApiBaseUrl
|
|
5022
3760
|
);
|
|
5023
3761
|
this.disabledAgents.clear();
|
|
5024
|
-
for (const {
|
|
5025
|
-
key: key2,
|
|
5026
|
-
agent_type,
|
|
5027
|
-
is_enabled,
|
|
5028
|
-
is_configured
|
|
5029
|
-
} of agentKeys) {
|
|
5030
|
-
const configured = is_configured ?? Boolean(key2);
|
|
5031
|
-
if (!configured) continue;
|
|
3762
|
+
for (const { key: key2, agent_type, is_enabled } of agentKeys) {
|
|
5032
3763
|
const agent = this.createAgent(agent_type, key2);
|
|
5033
3764
|
if (!agent) continue;
|
|
5034
3765
|
this.agents.set(agent_type, agent);
|
|
@@ -5052,15 +3783,8 @@ var OwneySDK = class {
|
|
|
5052
3783
|
}
|
|
5053
3784
|
createAgent(agentId, key2) {
|
|
5054
3785
|
if (agentId === "zyfai") {
|
|
5055
|
-
if (!key2) return null;
|
|
5056
3786
|
return new ZyfaiAgent(key2, this.zyfaiRpcUrls, this.referralSource);
|
|
5057
3787
|
}
|
|
5058
|
-
if (agentId === "yieldseeker") {
|
|
5059
|
-
return new YieldseekerAgent(this.apiKey, {
|
|
5060
|
-
auth: { origin: this.yieldseekerSiweOrigin },
|
|
5061
|
-
baseUrl: this.yieldseekerApiBaseUrl ?? getYieldseekerProxyBaseUrl(this.routingApiBaseUrl)
|
|
5062
|
-
});
|
|
5063
|
-
}
|
|
5064
3788
|
return null;
|
|
5065
3789
|
}
|
|
5066
3790
|
/**
|
|
@@ -5105,10 +3829,9 @@ var OwneySDK = class {
|
|
|
5105
3829
|
* If provided, ALL specified agents must support the chainId or the call
|
|
5106
3830
|
* throws before activating any agent.
|
|
5107
3831
|
*/
|
|
5108
|
-
async activateAgent(chainId, agentId
|
|
3832
|
+
async activateAgent(chainId, agentId) {
|
|
5109
3833
|
const state = this.requireState();
|
|
5110
3834
|
await this.ensureAgentsInitialized();
|
|
5111
|
-
this.assertActivationSession(state);
|
|
5112
3835
|
if (agentId !== void 0) {
|
|
5113
3836
|
if (agentId.length === 0) {
|
|
5114
3837
|
throw new OwneyError(
|
|
@@ -5142,7 +3865,7 @@ var OwneySDK = class {
|
|
|
5142
3865
|
this.activeAgents.add(id);
|
|
5143
3866
|
}
|
|
5144
3867
|
state.chainId = chainId;
|
|
5145
|
-
await this.activateAgentsInTurn(agents, state, chainId
|
|
3868
|
+
await this.activateAgentsInTurn(agents, state, chainId);
|
|
5146
3869
|
return;
|
|
5147
3870
|
}
|
|
5148
3871
|
const compatible = [...this.agents.values()].filter(
|
|
@@ -5163,12 +3886,7 @@ var OwneySDK = class {
|
|
|
5163
3886
|
const enabledCompatible = compatible.filter(
|
|
5164
3887
|
(agent) => !this.isAgentDisabled(agent.id)
|
|
5165
3888
|
);
|
|
5166
|
-
await this.activateAgentsInTurn(enabledCompatible, state, chainId
|
|
5167
|
-
}
|
|
5168
|
-
assertActivationSession(state) {
|
|
5169
|
-
if (this.state !== state) {
|
|
5170
|
-
throw new OwneyError("NOT_CONNECTED", "Wallet connection changed. Please try again.");
|
|
5171
|
-
}
|
|
3889
|
+
await this.activateAgentsInTurn(enabledCompatible, state, chainId);
|
|
5172
3890
|
}
|
|
5173
3891
|
/**
|
|
5174
3892
|
* Activate agents ONE AT A TIME, each followed by its org policy.
|
|
@@ -5183,51 +3901,26 @@ var OwneySDK = class {
|
|
|
5183
3901
|
* Serializing costs no real wall-clock: the user can only approve one prompt
|
|
5184
3902
|
* at a time anyway.
|
|
5185
3903
|
*
|
|
5186
|
-
*
|
|
5187
|
-
*
|
|
5188
|
-
*
|
|
3904
|
+
* Every agent is attempted even if an earlier one fails, so one declined
|
|
3905
|
+
* signature can't deny the remaining agents their turn. The first failure is
|
|
3906
|
+
* rethrown (matching the previous `Promise.all` rejection) once all agents
|
|
3907
|
+
* have had a chance to activate.
|
|
5189
3908
|
*/
|
|
5190
|
-
async activateAgentsInTurn(agents, state, chainId
|
|
3909
|
+
async activateAgentsInTurn(agents, state, chainId) {
|
|
5191
3910
|
let firstError = null;
|
|
5192
|
-
const activatedAgentIds = [];
|
|
5193
|
-
const failedAgents = [];
|
|
5194
3911
|
for (const agent of agents) {
|
|
5195
|
-
this.assertActivationSession(state);
|
|
5196
3912
|
try {
|
|
5197
|
-
await agent.activateAgent(state, chainId
|
|
5198
|
-
this.assertActivationSession(state);
|
|
3913
|
+
await agent.activateAgent(state, chainId);
|
|
5199
3914
|
await this.applyOrgPolicyTo(agent, state, chainId);
|
|
5200
|
-
this.assertActivationSession(state);
|
|
5201
|
-
activatedAgentIds.push(agent.id);
|
|
5202
3915
|
} catch (error) {
|
|
5203
|
-
this.assertActivationSession(state);
|
|
5204
|
-
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.";
|
|
5205
|
-
failedAgents.push({
|
|
5206
|
-
agentId: agent.id,
|
|
5207
|
-
code: error instanceof OwneyError ? error.code : void 0,
|
|
5208
|
-
message,
|
|
5209
|
-
...error instanceof OwneyError && error.details ? { details: error.details } : {}
|
|
5210
|
-
});
|
|
5211
3916
|
if (firstError === null) {
|
|
5212
3917
|
firstError = error;
|
|
5213
3918
|
} else {
|
|
5214
3919
|
console.error(`activateAgent(${agent.id}) failed:`, error);
|
|
5215
3920
|
}
|
|
5216
|
-
break;
|
|
5217
3921
|
}
|
|
5218
3922
|
}
|
|
5219
|
-
if (firstError
|
|
5220
|
-
if (activatedAgentIds.length === 0) throw firstError;
|
|
5221
|
-
const failedAgentIds = failedAgents.map(({ agentId }) => agentId);
|
|
5222
|
-
const activeNames = activatedAgentIds.map(this.formatAgentName).join(", ");
|
|
5223
|
-
const failureMessages = failedAgents.map(
|
|
5224
|
-
({ agentId, message }) => `${this.formatAgentName(agentId)} activation failed: ${message}`
|
|
5225
|
-
).join(" ");
|
|
5226
|
-
throw new OwneyError(
|
|
5227
|
-
"AGENT_ACTIVATION_PARTIAL_FAILURE",
|
|
5228
|
-
`${activeNames} activated. ${failureMessages}`,
|
|
5229
|
-
{ activatedAgentIds, failedAgentIds, failures: failedAgents }
|
|
5230
|
-
);
|
|
3923
|
+
if (firstError !== null) throw firstError;
|
|
5231
3924
|
}
|
|
5232
3925
|
/**
|
|
5233
3926
|
* Deposit into a specific agent, or distribute across all eligible agents.
|
|
@@ -5237,8 +3930,7 @@ var OwneySDK = class {
|
|
|
5237
3930
|
* @param options.asset - Asset symbol to deposit (e.g. "USDC")
|
|
5238
3931
|
* @param options.depositCallback - Callback that performs the token transfer and returns a tx hash.
|
|
5239
3932
|
* When agentId is omitted, this callback is invoked once per eligible agent with that agent's
|
|
5240
|
-
* split amount and smart wallet address
|
|
5241
|
-
* all shares into one signature; custom callbacks still run once per agent.
|
|
3933
|
+
* split amount and smart wallet address — expect multiple wallet prompts.
|
|
5242
3934
|
* @param options.agentId - Optional explicit target. Otherwise split equally,
|
|
5243
3935
|
* or fund remaining agents when a recovery deposit cannot meet every minimum.
|
|
5244
3936
|
* @returns {OwneyDepositResult} for a single agent, or {OwneyMultiDepositResult} with per-agent results
|
|
@@ -5323,39 +4015,6 @@ var OwneySDK = class {
|
|
|
5323
4015
|
}
|
|
5324
4016
|
);
|
|
5325
4017
|
}
|
|
5326
|
-
const batchTransfer = getDepositBatchTransfer(effectiveCallback);
|
|
5327
|
-
if (!depositCallback && batchTransfer) {
|
|
5328
|
-
return runAgentDepositBatch(
|
|
5329
|
-
chainId,
|
|
5330
|
-
agentAmounts.map(({ agent, amount: amount2 }) => ({
|
|
5331
|
-
id: agent.id,
|
|
5332
|
-
amount: amount2,
|
|
5333
|
-
run: (callback) => withFailureReporting(
|
|
5334
|
-
this.apiKey,
|
|
5335
|
-
agent.id,
|
|
5336
|
-
() => agent.deposit(state, chainId, amount2, asset, callback),
|
|
5337
|
-
this.routingApiBaseUrl
|
|
5338
|
-
)
|
|
5339
|
-
})),
|
|
5340
|
-
async (cid, transfers) => {
|
|
5341
|
-
try {
|
|
5342
|
-
return await batchTransfer(cid, transfers);
|
|
5343
|
-
} catch (error) {
|
|
5344
|
-
if (!(error instanceof OwneyError) || error.code !== "PERMIT2_APPROVAL_REQUIRED")
|
|
5345
|
-
throw error;
|
|
5346
|
-
const requiredAmount = transfers.reduce(
|
|
5347
|
-
(sum, transfer) => sum + BigInt(transfer.amount),
|
|
5348
|
-
0n
|
|
5349
|
-
);
|
|
5350
|
-
await this.approvePermit2(
|
|
5351
|
-
asset,
|
|
5352
|
-
requiredAmount
|
|
5353
|
-
);
|
|
5354
|
-
return batchTransfer(cid, transfers);
|
|
5355
|
-
}
|
|
5356
|
-
}
|
|
5357
|
-
);
|
|
5358
|
-
}
|
|
5359
4018
|
const agentResults = {};
|
|
5360
4019
|
for (const [
|
|
5361
4020
|
index,
|
|
@@ -5395,7 +4054,7 @@ var OwneySDK = class {
|
|
|
5395
4054
|
*
|
|
5396
4055
|
* 1. Missing Permit2 allowance: when the app did not supply its own
|
|
5397
4056
|
* callback and the attempt fails with `PERMIT2_APPROVAL_REQUIRED` on a
|
|
5398
|
-
*
|
|
4057
|
+
* WETH deposit, this is the wallet's first gasless WETH deposit. We send
|
|
5399
4058
|
* the one-time (user-paid) Permit2 approval via `approvePermit2()` and
|
|
5400
4059
|
* retry the SAME sponsored attempt once. Bounded to one approval attempt
|
|
5401
4060
|
* per call so a wallet/agent that keeps reporting the allowance as
|
|
@@ -5432,15 +4091,12 @@ var OwneySDK = class {
|
|
|
5432
4091
|
try {
|
|
5433
4092
|
return await attempt(effectiveCallback);
|
|
5434
4093
|
} catch (error) {
|
|
5435
|
-
if (!approvalAttempted && appCallback === void 0 &&
|
|
4094
|
+
if (!approvalAttempted && appCallback === void 0 && asset === "WETH" && error instanceof OwneyError && error.code === "PERMIT2_APPROVAL_REQUIRED") {
|
|
5436
4095
|
approvalAttempted = true;
|
|
5437
4096
|
console.warn(
|
|
5438
|
-
"[owney-sdk] First
|
|
5439
|
-
);
|
|
5440
|
-
await this.approvePermit2(
|
|
5441
|
-
asset,
|
|
5442
|
-
BigInt(amount)
|
|
4097
|
+
"[owney-sdk] First WETH deposit: sending one-time Permit2 approval..."
|
|
5443
4098
|
);
|
|
4099
|
+
await this.approvePermit2();
|
|
5444
4100
|
continue;
|
|
5445
4101
|
}
|
|
5446
4102
|
if (!shouldFallbackToUserPaid(error, asset, appCallback)) throw error;
|
|
@@ -5478,10 +4134,10 @@ var OwneySDK = class {
|
|
|
5478
4134
|
agent,
|
|
5479
4135
|
amount: i === agents.length - 1 ? perAgent + remainder : perAgent
|
|
5480
4136
|
}));
|
|
5481
|
-
const
|
|
4137
|
+
const valid = splits.filter(
|
|
5482
4138
|
(s) => s.amount > 0n && (exempt.has(s.agent.id) || s.amount >= this.getMinDepositAmount(s.agent, chainId, asset))
|
|
5483
4139
|
);
|
|
5484
|
-
if (
|
|
4140
|
+
if (valid.length === agents.length) {
|
|
5485
4141
|
return splits.map((s) => ({ agent: s.agent, amount: String(s.amount) }));
|
|
5486
4142
|
}
|
|
5487
4143
|
const targets = agentsRequiringActivation.length > 0 ? agentsRequiringActivation : agents;
|
|
@@ -5500,11 +4156,6 @@ var OwneySDK = class {
|
|
|
5500
4156
|
)
|
|
5501
4157
|
}));
|
|
5502
4158
|
}
|
|
5503
|
-
formatAgentName(agentId) {
|
|
5504
|
-
if (agentId === "zyfai") return "Zyfai";
|
|
5505
|
-
if (agentId === "yieldseeker") return "Yieldseeker";
|
|
5506
|
-
return agentId;
|
|
5507
|
-
}
|
|
5508
4159
|
async validateMinDepositAmount(agent, state, chainId, asset, amount) {
|
|
5509
4160
|
const minDepositAmount = this.getMinDepositAmount(agent, chainId, asset);
|
|
5510
4161
|
const parsedAmount = BigInt(amount);
|
|
@@ -5536,12 +4187,12 @@ var OwneySDK = class {
|
|
|
5536
4187
|
(t) => t.chainId === chainId && t.asset.toLowerCase() === target
|
|
5537
4188
|
);
|
|
5538
4189
|
const targetChainName = agent.supportedAssets.find((entry) => entry.chainId === chainId)?.chain?.trim().toUpperCase();
|
|
5539
|
-
const
|
|
4190
|
+
const position = (balance.positions ?? []).find((p) => {
|
|
5540
4191
|
const positionChain = p.chain.trim().toUpperCase();
|
|
5541
4192
|
const matchesChain = positionChain === String(chainId) || targetChainName !== void 0 && positionChain === targetChainName;
|
|
5542
4193
|
return matchesChain && p.asset.toLowerCase() === target && Number(p.amount) > 0;
|
|
5543
4194
|
});
|
|
5544
|
-
return !!token && Number(token.amount) > 0 || !!
|
|
4195
|
+
return !!token && Number(token.amount) > 0 || !!position;
|
|
5545
4196
|
} catch (error) {
|
|
5546
4197
|
if (requireReliableRead) {
|
|
5547
4198
|
throw new OwneyError(
|
|
@@ -5587,6 +4238,354 @@ var OwneySDK = class {
|
|
|
5587
4238
|
return eligible;
|
|
5588
4239
|
}
|
|
5589
4240
|
// --- Fund operations ---
|
|
4241
|
+
// --- Swap to yield (ROUT-242) ---
|
|
4242
|
+
/** Lazily built so an app that never swaps pays nothing for it. */
|
|
4243
|
+
swapApiClient;
|
|
4244
|
+
swapApi() {
|
|
4245
|
+
this.swapApiClient ??= createSwapApi(
|
|
4246
|
+
this.routingApiBaseUrl ?? ROUTING_API_BASE_URL,
|
|
4247
|
+
this.apiKey
|
|
4248
|
+
);
|
|
4249
|
+
return this.swapApiClient;
|
|
4250
|
+
}
|
|
4251
|
+
/**
|
|
4252
|
+
* Put the wallet on `chainId`, or fail with something actionable.
|
|
4253
|
+
*
|
|
4254
|
+
* Reuses the same guard the deposit rail uses, which re-reads the chain after
|
|
4255
|
+
* switching — some wallets resolve wallet_switchEthereumChain before the
|
|
4256
|
+
* network has actually changed.
|
|
4257
|
+
*/
|
|
4258
|
+
async ensureSwapChain(chainId) {
|
|
4259
|
+
const provider = this.requireConnectedProvider();
|
|
4260
|
+
const state = this.requireState();
|
|
4261
|
+
const chain = VIEM_CHAIN2[chainId];
|
|
4262
|
+
if (!chain) {
|
|
4263
|
+
throw new OwneyError(
|
|
4264
|
+
"CHAIN_UNSUPPORTED",
|
|
4265
|
+
`Chain ${chainId} is not supported`,
|
|
4266
|
+
{ chainId }
|
|
4267
|
+
);
|
|
4268
|
+
}
|
|
4269
|
+
await ensureWalletOnChain(
|
|
4270
|
+
createPublicClient2({ chain, transport: custom(provider) }),
|
|
4271
|
+
createWalletClient({
|
|
4272
|
+
account: state.walletAddress,
|
|
4273
|
+
chain,
|
|
4274
|
+
transport: custom(provider)
|
|
4275
|
+
}),
|
|
4276
|
+
chainId
|
|
4277
|
+
);
|
|
4278
|
+
}
|
|
4279
|
+
/**
|
|
4280
|
+
* Binds the executor's abstract deps to this client's wallet.
|
|
4281
|
+
*
|
|
4282
|
+
* Kept as a builder rather than baked into the executor so the whole swap
|
|
4283
|
+
* flow stays testable without a provider — the executor never imports viem.
|
|
4284
|
+
*/
|
|
4285
|
+
buildSwapDeps(quote) {
|
|
4286
|
+
const state = this.requireState();
|
|
4287
|
+
const provider = this.requireConnectedProvider();
|
|
4288
|
+
const srcChain = VIEM_CHAIN2[quote.src.chainId];
|
|
4289
|
+
const dstChain = VIEM_CHAIN2[quote.dst.chainId];
|
|
4290
|
+
const wallet = createWalletClient({
|
|
4291
|
+
account: state.walletAddress,
|
|
4292
|
+
chain: srcChain,
|
|
4293
|
+
transport: custom(provider)
|
|
4294
|
+
});
|
|
4295
|
+
const srcPublic = createPublicClient2({
|
|
4296
|
+
chain: srcChain,
|
|
4297
|
+
transport: swapReadTransport(quote.src.chainId, this.zyfaiRpcUrls)
|
|
4298
|
+
});
|
|
4299
|
+
const dstPublic = createPublicClient2({
|
|
4300
|
+
chain: dstChain,
|
|
4301
|
+
transport: swapReadTransport(quote.dst.chainId, this.zyfaiRpcUrls)
|
|
4302
|
+
});
|
|
4303
|
+
return {
|
|
4304
|
+
api: this.swapApi(),
|
|
4305
|
+
// Native-aware, like readSourceBalance below. Native ETH is never a
|
|
4306
|
+
// DEPOSIT target, so this only ever mattered once withdrawal shipped —
|
|
4307
|
+
// and there it is the headline case. balanceOf() on the 0xEeee sentinel
|
|
4308
|
+
// reverts, which would have read as "the swap landed nothing".
|
|
4309
|
+
readTargetBalance: async () => {
|
|
4310
|
+
const dst = quote.dst.address;
|
|
4311
|
+
if (dst.toLowerCase().startsWith("0xeeee")) {
|
|
4312
|
+
return dstPublic.getBalance({ address: state.walletAddress });
|
|
4313
|
+
}
|
|
4314
|
+
return dstPublic.readContract({
|
|
4315
|
+
address: dst,
|
|
4316
|
+
abi: erc20Abi2,
|
|
4317
|
+
functionName: "balanceOf",
|
|
4318
|
+
args: [state.walletAddress]
|
|
4319
|
+
});
|
|
4320
|
+
},
|
|
4321
|
+
sendTransaction: async (tx) => {
|
|
4322
|
+
const hash = await wallet.sendTransaction({
|
|
4323
|
+
to: tx.to,
|
|
4324
|
+
data: tx.data,
|
|
4325
|
+
value: BigInt(tx.value || "0"),
|
|
4326
|
+
account: state.walletAddress,
|
|
4327
|
+
chain: srcChain
|
|
4328
|
+
});
|
|
4329
|
+
const receipt = await srcPublic.waitForTransactionReceipt({
|
|
4330
|
+
timeout: receiptTimeoutMs(quote.src.chainId),
|
|
4331
|
+
hash,
|
|
4332
|
+
confirmations: 1
|
|
4333
|
+
});
|
|
4334
|
+
if (receipt.status !== "success") {
|
|
4335
|
+
throw new OwneyError(
|
|
4336
|
+
"SWAP_REQUEST_FAILED",
|
|
4337
|
+
`Swap transaction reverted (tx ${hash})`,
|
|
4338
|
+
{ hash }
|
|
4339
|
+
);
|
|
4340
|
+
}
|
|
4341
|
+
return hash;
|
|
4342
|
+
},
|
|
4343
|
+
signTypedData: (typedData) => wallet.signTypedData({
|
|
4344
|
+
account: state.walletAddress,
|
|
4345
|
+
...typedData
|
|
4346
|
+
}),
|
|
4347
|
+
// Chain-bound like every other read here: the wallet provider's chain is
|
|
4348
|
+
// not ours to rely on mid-swap.
|
|
4349
|
+
readSourceBalance: async () => {
|
|
4350
|
+
const src = quote.src.address;
|
|
4351
|
+
if (src.toLowerCase().startsWith("0xeeee")) {
|
|
4352
|
+
return srcPublic.getBalance({ address: state.walletAddress });
|
|
4353
|
+
}
|
|
4354
|
+
return srcPublic.readContract({
|
|
4355
|
+
address: src,
|
|
4356
|
+
abi: ERC20_ALLOWANCE_ABI,
|
|
4357
|
+
functionName: "balanceOf",
|
|
4358
|
+
args: [state.walletAddress]
|
|
4359
|
+
});
|
|
4360
|
+
},
|
|
4361
|
+
readAllowance: (spender) => srcPublic.readContract({
|
|
4362
|
+
address: quote.src.address,
|
|
4363
|
+
abi: ERC20_ALLOWANCE_ABI,
|
|
4364
|
+
functionName: "allowance",
|
|
4365
|
+
args: [state.walletAddress, spender]
|
|
4366
|
+
}),
|
|
4367
|
+
approve: async (spender, amount) => {
|
|
4368
|
+
const hash = await wallet.writeContract({
|
|
4369
|
+
address: quote.src.address,
|
|
4370
|
+
abi: ERC20_ALLOWANCE_ABI,
|
|
4371
|
+
functionName: "approve",
|
|
4372
|
+
args: [spender, amount],
|
|
4373
|
+
account: state.walletAddress,
|
|
4374
|
+
chain: srcChain
|
|
4375
|
+
});
|
|
4376
|
+
await srcPublic.waitForTransactionReceipt({
|
|
4377
|
+
hash,
|
|
4378
|
+
confirmations: 1,
|
|
4379
|
+
timeout: receiptTimeoutMs(quote.src.chainId)
|
|
4380
|
+
});
|
|
4381
|
+
return hash;
|
|
4382
|
+
},
|
|
4383
|
+
ensureChain: (chainId) => this.ensureSwapChain(chainId),
|
|
4384
|
+
runner: {
|
|
4385
|
+
readyForSecrets: (h) => this.swapApi().readyForSecrets(h),
|
|
4386
|
+
submitSecret: (h, secret) => this.swapApi().submitSecret(h, secret),
|
|
4387
|
+
orderStatus: (h) => this.swapApi().orderStatus(h),
|
|
4388
|
+
sleep: (ms) => new Promise((resolve) => setTimeout(resolve, ms)),
|
|
4389
|
+
now: () => Date.now()
|
|
4390
|
+
}
|
|
4391
|
+
};
|
|
4392
|
+
}
|
|
4393
|
+
/**
|
|
4394
|
+
* Assets the user may pay with, and what each chain deposits into.
|
|
4395
|
+
*
|
|
4396
|
+
* The source list is deliberately wider than the deposit list: it includes
|
|
4397
|
+
* native ETH and USDT, which Owney never holds but users often do.
|
|
4398
|
+
*/
|
|
4399
|
+
async getSwapTokens() {
|
|
4400
|
+
return this.swapApi().listTokens();
|
|
4401
|
+
}
|
|
4402
|
+
/**
|
|
4403
|
+
* Search the assets a user may pay with on one chain.
|
|
4404
|
+
*
|
|
4405
|
+
* `getSwapTokens` returns the short list worth rendering unprompted. This
|
|
4406
|
+
* reaches everything else the routing API will accept — thousands per chain
|
|
4407
|
+
* once the wider allowlist is enabled, which is why it is a query rather
|
|
4408
|
+
* than a download.
|
|
4409
|
+
*
|
|
4410
|
+
* Results are filtered server-side to what a quote will accept, so anything
|
|
4411
|
+
* returned can be paid with. They are NOT ranked by trustworthiness: several
|
|
4412
|
+
* tokens can share a ticker, and `providers` (how many token lists carry the
|
|
4413
|
+
* address) is the only usable signal for telling them apart. Surface it.
|
|
4414
|
+
*
|
|
4415
|
+
* Returns nothing for a blank query rather than asking for the whole list.
|
|
4416
|
+
*/
|
|
4417
|
+
async searchSwapTokens(params) {
|
|
4418
|
+
const query = params.query.trim();
|
|
4419
|
+
if (!query) return { tokens: [] };
|
|
4420
|
+
return this.swapApi().searchTokens({
|
|
4421
|
+
chainId: params.chainId,
|
|
4422
|
+
query,
|
|
4423
|
+
...params.limit === void 0 ? {} : { limit: params.limit }
|
|
4424
|
+
});
|
|
4425
|
+
}
|
|
4426
|
+
/**
|
|
4427
|
+
* Price a swap without committing to it.
|
|
4428
|
+
*
|
|
4429
|
+
* `dstAmountMin` is the number to validate against a deposit minimum —
|
|
4430
|
+
* `dst.amount` is an estimate that a decaying auction or slippage can undercut,
|
|
4431
|
+
* and a swap landing below the floor leaves the user swapped but not
|
|
4432
|
+
* deposited.
|
|
4433
|
+
*/
|
|
4434
|
+
async getSwapQuote(params) {
|
|
4435
|
+
const state = this.requireState();
|
|
4436
|
+
return this.swapApi().quote({
|
|
4437
|
+
...params,
|
|
4438
|
+
walletAddress: state.walletAddress
|
|
4439
|
+
});
|
|
4440
|
+
}
|
|
4441
|
+
/**
|
|
4442
|
+
* Swap an asset the user holds into a deposit asset, then deposit it.
|
|
4443
|
+
*
|
|
4444
|
+
* Kept separate from `deposit()` rather than bolted on as an option: the
|
|
4445
|
+
* return shape differs, the staging callback is meaningless on the plain
|
|
4446
|
+
* path, and integrators who never swap should not have to reason about any
|
|
4447
|
+
* of it.
|
|
4448
|
+
*
|
|
4449
|
+
* The deposit runs on the MEASURED arrival, not the quote. A quote is an
|
|
4450
|
+
* estimate, so depositing the quoted figure would either strand dust or try
|
|
4451
|
+
* to move funds that never came.
|
|
4452
|
+
*
|
|
4453
|
+
* Failure modes differ in a way callers must respect. A same-chain swap is
|
|
4454
|
+
* atomic — if it fails, nothing moved. A cross-chain swap escrows the user's
|
|
4455
|
+
* funds first, so SWAP_ORDER_EXPIRED / REFUNDED / CANCELLED all mean the
|
|
4456
|
+
* money left the wallet. Only the former can honestly say "nothing has left
|
|
4457
|
+
* your wallet".
|
|
4458
|
+
*/
|
|
4459
|
+
async swapAndDeposit(options) {
|
|
4460
|
+
const state = this.requireState();
|
|
4461
|
+
const api = this.swapApi();
|
|
4462
|
+
const quote = await api.quote({
|
|
4463
|
+
from: options.from,
|
|
4464
|
+
to: options.to,
|
|
4465
|
+
walletAddress: state.walletAddress
|
|
4466
|
+
});
|
|
4467
|
+
await this.ensureSwapChain(quote.src.chainId);
|
|
4468
|
+
const swap = await executeSwap(this.buildSwapDeps(quote), {
|
|
4469
|
+
quote,
|
|
4470
|
+
walletAddress: state.walletAddress,
|
|
4471
|
+
...options.slippage === void 0 ? {} : { slippage: options.slippage },
|
|
4472
|
+
...options.onSwapProgress ? { onStage: options.onSwapProgress } : {}
|
|
4473
|
+
});
|
|
4474
|
+
options.onSwapProgress?.("depositing");
|
|
4475
|
+
await this.ensureSwapChain(quote.dst.chainId);
|
|
4476
|
+
const deposit = await this.deposit({
|
|
4477
|
+
amount: swap.received,
|
|
4478
|
+
asset: options.to.symbol,
|
|
4479
|
+
...options.agentId ? { agentId: options.agentId } : {}
|
|
4480
|
+
});
|
|
4481
|
+
return { swap, deposit };
|
|
4482
|
+
}
|
|
4483
|
+
/**
|
|
4484
|
+
* Withdraw from an agent and swap the proceeds into whatever the user wants
|
|
4485
|
+
* to hold, delivered to their own wallet.
|
|
4486
|
+
*
|
|
4487
|
+
* The mirror of `swapAndDeposit()`, with one structural difference that
|
|
4488
|
+
* drives the whole implementation: a deposit swap starts from funds already
|
|
4489
|
+
* sitting in the wallet, but a withdrawal has to wait for them. The agent's
|
|
4490
|
+
* provider acknowledges a withdrawal and *then* queues the on-chain transfer
|
|
4491
|
+
* to the EOA, so `withdraw()` resolving means "accepted", not "arrived".
|
|
4492
|
+
* Quoting before the tokens land would size the swap against a balance that
|
|
4493
|
+
* is not there yet.
|
|
4494
|
+
*
|
|
4495
|
+
* The swap is therefore sized from the MEASURED arrival, exactly as the
|
|
4496
|
+
* deposit path sizes its deposit from the measured swap output. On a full
|
|
4497
|
+
* withdrawal there is no other number available — "MAX" has no figure until
|
|
4498
|
+
* the agent picks one.
|
|
4499
|
+
*
|
|
4500
|
+
* **Failure here is not symmetrical with the deposit path.** A failed
|
|
4501
|
+
* deposit-swap leaves the user holding what they started with. A failed
|
|
4502
|
+
* withdrawal-swap leaves them holding the AGENT'S asset in their own wallet:
|
|
4503
|
+
* the money is out, safe, and in the wrong denomination. Both
|
|
4504
|
+
* `WITHDRAW_ARRIVAL_TIMEOUT` and `WITHDRAW_SWAP_FAILED` carry `withdrawn` for
|
|
4505
|
+
* that reason — the UI has to tell the user where their money actually is,
|
|
4506
|
+
* and must never present either as a lost withdrawal.
|
|
4507
|
+
*/
|
|
4508
|
+
async withdrawAndSwap(options) {
|
|
4509
|
+
const state = this.requireState();
|
|
4510
|
+
const activeChainId = this.requireChainId();
|
|
4511
|
+
if (options.from.chainId !== activeChainId) {
|
|
4512
|
+
throw new OwneyError(
|
|
4513
|
+
"CHAIN_MISMATCH",
|
|
4514
|
+
`Cannot withdraw from chain ${options.from.chainId} while the active chain is ${activeChainId}. Activate on that chain first.`,
|
|
4515
|
+
{ requested: options.from.chainId, active: activeChainId }
|
|
4516
|
+
);
|
|
4517
|
+
}
|
|
4518
|
+
const asset = SupportedAssets.find(
|
|
4519
|
+
(a) => a.chainId === options.from.chainId && a.symbol === options.from.symbol.toUpperCase()
|
|
4520
|
+
);
|
|
4521
|
+
if (!asset) {
|
|
4522
|
+
throw new OwneyError(
|
|
4523
|
+
"WITHDRAW_NO_PERMITTED_TOKENS",
|
|
4524
|
+
`${options.from.symbol} on chain ${options.from.chainId} is not an asset Owney holds`,
|
|
4525
|
+
{ ...options.from }
|
|
4526
|
+
);
|
|
4527
|
+
}
|
|
4528
|
+
const srcChain = VIEM_CHAIN2[options.from.chainId];
|
|
4529
|
+
const srcPublic = createPublicClient2({
|
|
4530
|
+
chain: srcChain,
|
|
4531
|
+
transport: swapReadTransport(options.from.chainId, this.zyfaiRpcUrls)
|
|
4532
|
+
});
|
|
4533
|
+
const readWalletBalance = () => srcPublic.readContract({
|
|
4534
|
+
address: asset.address,
|
|
4535
|
+
abi: erc20Abi2,
|
|
4536
|
+
functionName: "balanceOf",
|
|
4537
|
+
args: [state.walletAddress]
|
|
4538
|
+
});
|
|
4539
|
+
const baseline = await readWalletBalance();
|
|
4540
|
+
debugLog("owney-sdk", "withdrawAndSwap: baseline", {
|
|
4541
|
+
asset: `${asset.symbol}@${asset.chainId}`,
|
|
4542
|
+
baseline: baseline.toString()
|
|
4543
|
+
});
|
|
4544
|
+
options.onSwapProgress?.("withdrawing");
|
|
4545
|
+
const withdraw = await this.withdraw({
|
|
4546
|
+
asset: options.from.symbol,
|
|
4547
|
+
...options.amount === void 0 ? {} : { amount: options.amount },
|
|
4548
|
+
...options.agentId ? { agentId: options.agentId } : {}
|
|
4549
|
+
});
|
|
4550
|
+
const arrived = await awaitWithdrawalArrival({
|
|
4551
|
+
readBalance: readWalletBalance,
|
|
4552
|
+
baseline,
|
|
4553
|
+
...options.arrivalTimeoutMs === void 0 ? {} : { timeoutMs: options.arrivalTimeoutMs }
|
|
4554
|
+
});
|
|
4555
|
+
const withdrawn = arrived.toString();
|
|
4556
|
+
options.onSwapProgress?.("withdrawn");
|
|
4557
|
+
try {
|
|
4558
|
+
const quote = await this.swapApi().quote({
|
|
4559
|
+
from: { ...options.from, amount: withdrawn },
|
|
4560
|
+
to: options.to,
|
|
4561
|
+
direction: "withdraw",
|
|
4562
|
+
walletAddress: state.walletAddress
|
|
4563
|
+
});
|
|
4564
|
+
await this.ensureSwapChain(quote.src.chainId);
|
|
4565
|
+
const swap = await executeSwap(this.buildSwapDeps(quote), {
|
|
4566
|
+
quote,
|
|
4567
|
+
walletAddress: state.walletAddress,
|
|
4568
|
+
direction: "withdraw",
|
|
4569
|
+
...options.slippage === void 0 ? {} : { slippage: options.slippage },
|
|
4570
|
+
...options.onSwapProgress ? { onStage: options.onSwapProgress } : {}
|
|
4571
|
+
});
|
|
4572
|
+
return { withdraw, withdrawn, swap };
|
|
4573
|
+
} catch (error) {
|
|
4574
|
+
throw new OwneyError(
|
|
4575
|
+
"WITHDRAW_SWAP_FAILED",
|
|
4576
|
+
`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}.`,
|
|
4577
|
+
{
|
|
4578
|
+
withdrawn,
|
|
4579
|
+
asset: asset.symbol,
|
|
4580
|
+
chainId: asset.chainId,
|
|
4581
|
+
intendedSymbol: options.to.symbol,
|
|
4582
|
+
intendedChainId: options.to.chainId,
|
|
4583
|
+
cause: error instanceof Error ? error.message : String(error),
|
|
4584
|
+
...error instanceof OwneyError ? { causeCode: error.code } : {}
|
|
4585
|
+
}
|
|
4586
|
+
);
|
|
4587
|
+
}
|
|
4588
|
+
}
|
|
5590
4589
|
/**
|
|
5591
4590
|
* Withdraw funds from a specific agent, or all agents that support the active chain+asset if agentId is omitted.
|
|
5592
4591
|
* Validates that the asset is supported by the target agent(s) on the active chain.
|
|
@@ -5656,10 +4655,6 @@ var OwneySDK = class {
|
|
|
5656
4655
|
}
|
|
5657
4656
|
const requested = BigInt(amount);
|
|
5658
4657
|
const aggregated = await this.getBalances();
|
|
5659
|
-
const unavailableAgents = eligibleAgents.filter(
|
|
5660
|
-
(agent) => !(agent.id in aggregated.agentBalances)
|
|
5661
|
-
);
|
|
5662
|
-
const unavailableAgentIds = unavailableAgents.map((agent) => agent.id);
|
|
5663
4658
|
const balances = projectAgentBalancesForAsset(
|
|
5664
4659
|
eligibleAgents,
|
|
5665
4660
|
aggregated.agentBalances,
|
|
@@ -5668,18 +4663,7 @@ var OwneySDK = class {
|
|
|
5668
4663
|
assetInfo.decimals
|
|
5669
4664
|
);
|
|
5670
4665
|
const totalAvailable = balances.reduce((sum, x) => sum + x.balance, 0n);
|
|
5671
|
-
if (totalAvailable
|
|
5672
|
-
throw new OwneyError(
|
|
5673
|
-
"WITHDRAW_BALANCE_UNAVAILABLE",
|
|
5674
|
-
`Cannot safely plan the withdrawal because balance data is unavailable for: ${unavailableAgentIds.join(", ")}.`,
|
|
5675
|
-
{
|
|
5676
|
-
asset,
|
|
5677
|
-
unavailableAgents: unavailableAgentIds,
|
|
5678
|
-
agentErrors: aggregated.agentErrors
|
|
5679
|
-
}
|
|
5680
|
-
);
|
|
5681
|
-
}
|
|
5682
|
-
if (totalAvailable < requested && unavailableAgents.length === 0) {
|
|
4666
|
+
if (totalAvailable < requested) {
|
|
5683
4667
|
throw new OwneyError(
|
|
5684
4668
|
"WITHDRAW_INSUFFICIENT_BALANCE",
|
|
5685
4669
|
`Requested withdrawal "${amount}" exceeds available balance "${totalAvailable.toString()}" for asset "${asset}".`,
|
|
@@ -5690,7 +4674,6 @@ var OwneySDK = class {
|
|
|
5690
4674
|
}
|
|
5691
4675
|
);
|
|
5692
4676
|
}
|
|
5693
|
-
const plannedTarget = totalAvailable < requested ? totalAvailable : requested;
|
|
5694
4677
|
const disabledBalances = balances.filter(
|
|
5695
4678
|
(b) => this.isAgentDisabled(b.agent.id)
|
|
5696
4679
|
);
|
|
@@ -5699,7 +4682,7 @@ var OwneySDK = class {
|
|
|
5699
4682
|
);
|
|
5700
4683
|
const { plans: disabledPlans, remaining: afterDrain } = planDisabledDrain(
|
|
5701
4684
|
disabledBalances,
|
|
5702
|
-
|
|
4685
|
+
requested
|
|
5703
4686
|
);
|
|
5704
4687
|
const enabledTotal = enabledBalances.reduce((s, b) => s + b.balance, 0n);
|
|
5705
4688
|
const enabledPlans = afterDrain > 0n ? planProportionalShares(enabledBalances, afterDrain, enabledTotal) : enabledBalances.map(({ agent, balance }) => ({
|
|
@@ -5709,9 +4692,7 @@ var OwneySDK = class {
|
|
|
5709
4692
|
}));
|
|
5710
4693
|
const plans = [...disabledPlans, ...enabledPlans];
|
|
5711
4694
|
const results = {};
|
|
5712
|
-
const agentErrors = {
|
|
5713
|
-
...aggregated.agentErrors ?? {}
|
|
5714
|
-
};
|
|
4695
|
+
const agentErrors = {};
|
|
5715
4696
|
for (let i = 0; i < plans.length; i++) {
|
|
5716
4697
|
const p = plans[i];
|
|
5717
4698
|
if (p.planned === 0n) continue;
|
|
@@ -5758,8 +4739,7 @@ var OwneySDK = class {
|
|
|
5758
4739
|
requested: amount,
|
|
5759
4740
|
withdrawn: withdrawn.toString(),
|
|
5760
4741
|
partialResults: results,
|
|
5761
|
-
agentErrors
|
|
5762
|
-
...unavailableAgentIds.length > 0 ? { unavailableAgents: unavailableAgentIds } : {}
|
|
4742
|
+
agentErrors
|
|
5763
4743
|
}
|
|
5764
4744
|
);
|
|
5765
4745
|
}
|
|
@@ -5776,25 +4756,24 @@ var OwneySDK = class {
|
|
|
5776
4756
|
const chainId = this.requireChainId();
|
|
5777
4757
|
if (agentId) {
|
|
5778
4758
|
const agent = this.getAgent(agentId);
|
|
5779
|
-
const result = await this.readAgent(
|
|
5780
|
-
|
|
5781
|
-
|
|
5782
|
-
|
|
5783
|
-
|
|
4759
|
+
const result = await this.readAgent(
|
|
4760
|
+
agent,
|
|
4761
|
+
"balances",
|
|
4762
|
+
() => agent.getBalances(state, chainId)
|
|
4763
|
+
);
|
|
4764
|
+
return result;
|
|
5784
4765
|
}
|
|
5785
4766
|
let totalBalance = 0;
|
|
5786
4767
|
const results = {};
|
|
5787
4768
|
const entries = [...this.getActiveAgents().entries()];
|
|
5788
4769
|
const balanceResults = await Promise.allSettled(
|
|
5789
4770
|
entries.map(async ([id, agent]) => {
|
|
5790
|
-
const b = await this.readAgent(
|
|
5791
|
-
|
|
5792
|
-
|
|
5793
|
-
|
|
5794
|
-
|
|
5795
|
-
|
|
5796
|
-
}
|
|
5797
|
-
];
|
|
4771
|
+
const b = await this.readAgent(
|
|
4772
|
+
agent,
|
|
4773
|
+
"balances",
|
|
4774
|
+
() => agent.getBalances(state, chainId)
|
|
4775
|
+
);
|
|
4776
|
+
return [id, b];
|
|
5798
4777
|
})
|
|
5799
4778
|
);
|
|
5800
4779
|
let successCount = 0;
|
|
@@ -5814,9 +4793,9 @@ var OwneySDK = class {
|
|
|
5814
4793
|
const reason = settledResult.reason;
|
|
5815
4794
|
agentFailures.push(reason);
|
|
5816
4795
|
const retryDelay = rateLimitDelay(reason);
|
|
5817
|
-
if (retryDelay !== void 0)
|
|
4796
|
+
if (retryDelay !== void 0)
|
|
4797
|
+
agentRetryAt[agentId2] = Date.now() + retryDelay;
|
|
5818
4798
|
agentErrors[agentId2] = reason instanceof Error ? reason.message : String(reason);
|
|
5819
|
-
console.error(`[owney-sdk] Balance fetch failed for agent "${agentId2}":`, reason);
|
|
5820
4799
|
}
|
|
5821
4800
|
if (successCount === 0) {
|
|
5822
4801
|
throw new OwneyError(
|
|
@@ -5842,14 +4821,22 @@ var OwneySDK = class {
|
|
|
5842
4821
|
const chainId = this.requireChainId();
|
|
5843
4822
|
if (agentId) {
|
|
5844
4823
|
const agent = this.getAgent(agentId);
|
|
5845
|
-
return this.readAgent(
|
|
4824
|
+
return this.readAgent(
|
|
4825
|
+
agent,
|
|
4826
|
+
"earnings",
|
|
4827
|
+
() => agent.getEarnings(state, chainId)
|
|
4828
|
+
);
|
|
5846
4829
|
}
|
|
5847
4830
|
let totalEarnings = 0;
|
|
5848
4831
|
const results = {};
|
|
5849
4832
|
const entries = [...this.getActiveAgents().entries()];
|
|
5850
4833
|
const earningsResults = await Promise.all(
|
|
5851
4834
|
entries.map(async ([id, agent]) => {
|
|
5852
|
-
const e = await this.readAgent(
|
|
4835
|
+
const e = await this.readAgent(
|
|
4836
|
+
agent,
|
|
4837
|
+
"earnings",
|
|
4838
|
+
() => agent.getEarnings(state, chainId)
|
|
4839
|
+
);
|
|
5853
4840
|
return [id, e];
|
|
5854
4841
|
})
|
|
5855
4842
|
);
|
|
@@ -5994,11 +4981,12 @@ var OwneySDK = class {
|
|
|
5994
4981
|
),
|
|
5995
4982
|
Promise.all(
|
|
5996
4983
|
entries.map(async ([id, agent]) => {
|
|
5997
|
-
const b = await this.readAgent(
|
|
5998
|
-
|
|
5999
|
-
|
|
6000
|
-
|
|
6001
|
-
|
|
4984
|
+
const b = await this.readAgent(
|
|
4985
|
+
agent,
|
|
4986
|
+
"balances",
|
|
4987
|
+
() => agent.getBalances(state, chainId)
|
|
4988
|
+
);
|
|
4989
|
+
return [id, balanceForApyScope(b, chainId, tokenSymbol)];
|
|
6002
4990
|
})
|
|
6003
4991
|
)
|
|
6004
4992
|
]);
|
|
@@ -6057,7 +5045,12 @@ var OwneySDK = class {
|
|
|
6057
5045
|
const { agentId, filters } = options ?? {};
|
|
6058
5046
|
if (agentId) {
|
|
6059
5047
|
const agent = this.getAgent(agentId);
|
|
6060
|
-
return this.readAgent(
|
|
5048
|
+
return this.readAgent(
|
|
5049
|
+
agent,
|
|
5050
|
+
"history",
|
|
5051
|
+
() => agent.getHistory(state, chainId, filters),
|
|
5052
|
+
filters
|
|
5053
|
+
);
|
|
6061
5054
|
}
|
|
6062
5055
|
const activeAgents = [...this.getActiveAgents().values()];
|
|
6063
5056
|
const cursorMap = filters?.cursor ? decodeMultiAgentCursor(filters.cursor) : {};
|
|
@@ -6114,13 +5107,21 @@ var OwneySDK = class {
|
|
|
6114
5107
|
const chainId = this.requireChainId();
|
|
6115
5108
|
if (agentId) {
|
|
6116
5109
|
const agent = this.getAgent(agentId);
|
|
6117
|
-
return this.readAgent(
|
|
5110
|
+
return this.readAgent(
|
|
5111
|
+
agent,
|
|
5112
|
+
"profile",
|
|
5113
|
+
() => agent.getUserProfile(state, chainId)
|
|
5114
|
+
);
|
|
6118
5115
|
}
|
|
6119
5116
|
const results = {};
|
|
6120
5117
|
const entries = [...this.getActiveAgents().entries()];
|
|
6121
5118
|
const profileResults = await Promise.all(
|
|
6122
5119
|
entries.map(async ([id, agent]) => {
|
|
6123
|
-
const p = await this.readAgent(
|
|
5120
|
+
const p = await this.readAgent(
|
|
5121
|
+
agent,
|
|
5122
|
+
"profile",
|
|
5123
|
+
() => agent.getUserProfile(state, chainId)
|
|
5124
|
+
);
|
|
6124
5125
|
return [id, p];
|
|
6125
5126
|
})
|
|
6126
5127
|
);
|
|
@@ -6159,44 +5160,43 @@ var OwneySDK = class {
|
|
|
6159
5160
|
return pending;
|
|
6160
5161
|
}
|
|
6161
5162
|
/**
|
|
6162
|
-
*
|
|
6163
|
-
*
|
|
6164
|
-
*
|
|
6165
|
-
*
|
|
6166
|
-
*
|
|
6167
|
-
* @param requiredAmount Raw base-unit amount the pending deposit must cover.
|
|
5163
|
+
* One-time, user-paid approval of Permit2 on the sponsored WETH token for
|
|
5164
|
+
* the active chain. Required once per wallet per chain before gasless WETH
|
|
5165
|
+
* deposits; afterwards deposit() is signature-only. Resolves only after the
|
|
5166
|
+
* approval transaction is mined (1 confirmation), so a subsequent deposit()
|
|
5167
|
+
* will see the new allowance; throws if the transaction reverted.
|
|
6168
5168
|
* @returns the approval transaction hash.
|
|
6169
5169
|
*/
|
|
6170
|
-
async approvePermit2(asset = "WETH"
|
|
5170
|
+
async approvePermit2(asset = "WETH") {
|
|
5171
|
+
void asset;
|
|
6171
5172
|
const state = this.requireState();
|
|
6172
5173
|
const chainId = this.requireChainId();
|
|
6173
|
-
this.
|
|
6174
|
-
const token =
|
|
5174
|
+
this.validateAssetSupport(this.getAgent("zyfai"), chainId, "WETH");
|
|
5175
|
+
const token = SPONSORED_WETH_BY_CHAIN[chainId];
|
|
6175
5176
|
if (!token) {
|
|
6176
5177
|
throw new OwneyError(
|
|
6177
5178
|
"CHAIN_UNSUPPORTED",
|
|
6178
|
-
`No sponsored
|
|
5179
|
+
`No sponsored WETH on chain ${chainId}`
|
|
6179
5180
|
);
|
|
6180
5181
|
}
|
|
6181
5182
|
const provider = this.requireConnectedProvider();
|
|
6182
|
-
const
|
|
6183
|
-
chain: VIEM_CHAIN2[chainId],
|
|
6184
|
-
transport: custom3(provider)
|
|
6185
|
-
});
|
|
6186
|
-
const approvalAmount = permit2ApprovalAmount(requiredAmount);
|
|
6187
|
-
const wallet = createWalletClient3({
|
|
5183
|
+
const wallet = createWalletClient({
|
|
6188
5184
|
account: state.walletAddress,
|
|
6189
5185
|
chain: VIEM_CHAIN2[chainId],
|
|
6190
|
-
transport:
|
|
5186
|
+
transport: custom(provider)
|
|
6191
5187
|
});
|
|
6192
5188
|
const hash = await wallet.writeContract({
|
|
6193
5189
|
address: token,
|
|
6194
5190
|
abi: ERC20_ALLOWANCE_ABI,
|
|
6195
5191
|
functionName: "approve",
|
|
6196
|
-
args: [PERMIT2_ADDRESS,
|
|
5192
|
+
args: [PERMIT2_ADDRESS, MAX_UINT256],
|
|
6197
5193
|
account: state.walletAddress,
|
|
6198
5194
|
chain: VIEM_CHAIN2[chainId]
|
|
6199
5195
|
});
|
|
5196
|
+
const publicClient = createPublicClient2({
|
|
5197
|
+
chain: VIEM_CHAIN2[chainId],
|
|
5198
|
+
transport: custom(provider)
|
|
5199
|
+
});
|
|
6200
5200
|
const receipt = await publicClient.waitForTransactionReceipt({
|
|
6201
5201
|
hash,
|
|
6202
5202
|
confirmations: 1
|
|
@@ -6229,15 +5229,23 @@ var OwneySDK = class {
|
|
|
6229
5229
|
const agentOptions = { tokenSymbol, chainId };
|
|
6230
5230
|
if (agentId) {
|
|
6231
5231
|
const agent = this.getAgent(agentId);
|
|
6232
|
-
return this.readAgent(
|
|
5232
|
+
return this.readAgent(
|
|
5233
|
+
agent,
|
|
5234
|
+
"agentApy",
|
|
5235
|
+
() => agent.getAgentApy(days, agentOptions),
|
|
5236
|
+
{ days, ...agentOptions }
|
|
5237
|
+
);
|
|
6233
5238
|
}
|
|
6234
5239
|
const results = {};
|
|
6235
|
-
const agentEntries = [...this.agents.entries()]
|
|
6236
|
-
([id]) => !this.isAgentDisabled(id)
|
|
6237
|
-
);
|
|
5240
|
+
const agentEntries = [...this.agents.entries()];
|
|
6238
5241
|
const apyResults = await Promise.all(
|
|
6239
5242
|
agentEntries.map(async ([id, agent]) => {
|
|
6240
|
-
const apy = await this.readAgent(
|
|
5243
|
+
const apy = await this.readAgent(
|
|
5244
|
+
agent,
|
|
5245
|
+
"agentApy",
|
|
5246
|
+
() => agent.getAgentApy(days, agentOptions),
|
|
5247
|
+
{ days, ...agentOptions }
|
|
5248
|
+
);
|
|
6241
5249
|
return [id, apy];
|
|
6242
5250
|
})
|
|
6243
5251
|
);
|
|
@@ -6264,7 +5272,11 @@ var OwneySDK = class {
|
|
|
6264
5272
|
const entries = [...activeAgents.entries()];
|
|
6265
5273
|
const balanceResults = await Promise.allSettled(
|
|
6266
5274
|
entries.map(async ([id, agent]) => {
|
|
6267
|
-
const b = await this.readAgent(
|
|
5275
|
+
const b = await this.readAgent(
|
|
5276
|
+
agent,
|
|
5277
|
+
"balances",
|
|
5278
|
+
() => agent.getBalances(state, chainId)
|
|
5279
|
+
);
|
|
6268
5280
|
return [id, b.positions ?? []];
|
|
6269
5281
|
})
|
|
6270
5282
|
);
|
|
@@ -6309,13 +5321,13 @@ var OwneySDK = class {
|
|
|
6309
5321
|
};
|
|
6310
5322
|
|
|
6311
5323
|
// src/agents/zyfai/zyfai.siwx.ts
|
|
6312
|
-
import { getAddress
|
|
6313
|
-
import { SiweMessage
|
|
5324
|
+
import { getAddress } from "viem";
|
|
5325
|
+
import { SiweMessage } from "siwe";
|
|
6314
5326
|
import { ZyfaiSDK as ZyfaiSDK2 } from "@zyfai/sdk";
|
|
6315
5327
|
|
|
6316
5328
|
// src/agents/zyfai/zyfai.siwx-cache.ts
|
|
6317
|
-
var
|
|
6318
|
-
var
|
|
5329
|
+
var KEY_PREFIX3 = "owney.siwx.session";
|
|
5330
|
+
var storage3 = () => {
|
|
6319
5331
|
if (typeof window === "undefined") return null;
|
|
6320
5332
|
try {
|
|
6321
5333
|
return window.localStorage;
|
|
@@ -6323,8 +5335,8 @@ var storage4 = () => {
|
|
|
6323
5335
|
return null;
|
|
6324
5336
|
}
|
|
6325
5337
|
};
|
|
6326
|
-
var
|
|
6327
|
-
var legacyKeyPrefix2 = (address) => `${
|
|
5338
|
+
var buildKey2 = (address) => `${KEY_PREFIX3}:${address.toLowerCase()}`;
|
|
5339
|
+
var legacyKeyPrefix2 = (address) => `${KEY_PREFIX3}:${address.toLowerCase()}:`;
|
|
6328
5340
|
var memorySiwxSessions = /* @__PURE__ */ new Map();
|
|
6329
5341
|
var readLegacySiwxSession = (store, address) => {
|
|
6330
5342
|
if (!store) return null;
|
|
@@ -6355,17 +5367,17 @@ var readLegacySiwxSession = (store, address) => {
|
|
|
6355
5367
|
};
|
|
6356
5368
|
var readSiwxSession = (address, chainId) => {
|
|
6357
5369
|
if (typeof window === "undefined") return null;
|
|
6358
|
-
const key2 =
|
|
6359
|
-
const store =
|
|
6360
|
-
let
|
|
5370
|
+
const key2 = buildKey2(address);
|
|
5371
|
+
const store = storage3();
|
|
5372
|
+
let raw = null;
|
|
6361
5373
|
try {
|
|
6362
|
-
|
|
5374
|
+
raw = store?.getItem(key2) ?? null;
|
|
6363
5375
|
} catch {
|
|
6364
|
-
|
|
5376
|
+
raw = null;
|
|
6365
5377
|
}
|
|
6366
|
-
if (
|
|
5378
|
+
if (raw) {
|
|
6367
5379
|
try {
|
|
6368
|
-
return JSON.parse(
|
|
5380
|
+
return JSON.parse(raw);
|
|
6369
5381
|
} catch {
|
|
6370
5382
|
memorySiwxSessions.delete(key2);
|
|
6371
5383
|
try {
|
|
@@ -6384,18 +5396,18 @@ var readSiwxSession = (address, chainId) => {
|
|
|
6384
5396
|
};
|
|
6385
5397
|
var writeSiwxSession = (address, _chainId, session) => {
|
|
6386
5398
|
if (typeof window === "undefined") return;
|
|
6387
|
-
const key2 =
|
|
5399
|
+
const key2 = buildKey2(address);
|
|
6388
5400
|
memorySiwxSessions.set(key2, session);
|
|
6389
|
-
const store =
|
|
5401
|
+
const store = storage3();
|
|
6390
5402
|
try {
|
|
6391
5403
|
store?.setItem(key2, JSON.stringify(session));
|
|
6392
5404
|
} catch {
|
|
6393
5405
|
}
|
|
6394
5406
|
};
|
|
6395
5407
|
var clearSiwxSession = (address, _chainId) => {
|
|
6396
|
-
const key2 =
|
|
5408
|
+
const key2 = buildKey2(address);
|
|
6397
5409
|
memorySiwxSessions.delete(key2);
|
|
6398
|
-
const store =
|
|
5410
|
+
const store = storage3();
|
|
6399
5411
|
try {
|
|
6400
5412
|
store?.removeItem(key2);
|
|
6401
5413
|
} catch {
|
|
@@ -6435,8 +5447,8 @@ function buildSIWXConfig(deps) {
|
|
|
6435
5447
|
statement: STATEMENT,
|
|
6436
5448
|
issuedAt,
|
|
6437
5449
|
toString() {
|
|
6438
|
-
return new
|
|
6439
|
-
address:
|
|
5450
|
+
return new SiweMessage({
|
|
5451
|
+
address: getAddress(accountAddress),
|
|
6440
5452
|
chainId: numericChainId(chainId),
|
|
6441
5453
|
domain,
|
|
6442
5454
|
uri,
|
|
@@ -6478,7 +5490,7 @@ function buildSIWXConfig(deps) {
|
|
|
6478
5490
|
const persistSession = async (session) => {
|
|
6479
5491
|
const address = session.data.accountAddress;
|
|
6480
5492
|
const id = numericChainId(session.data.chainId);
|
|
6481
|
-
const message = new
|
|
5493
|
+
const message = new SiweMessage(session.message);
|
|
6482
5494
|
const login = await post("/auth/login", {
|
|
6483
5495
|
message,
|
|
6484
5496
|
signature: session.signature,
|
|
@@ -6514,9 +5526,9 @@ function buildSIWXConfig(deps) {
|
|
|
6514
5526
|
}
|
|
6515
5527
|
function createOwneySIWX(config) {
|
|
6516
5528
|
const zyfai = new ZyfaiSDK2({ apiKey: config.apiKey });
|
|
6517
|
-
const
|
|
5529
|
+
const http4 = zyfai.httpClient;
|
|
6518
5530
|
return buildSIWXConfig({
|
|
6519
|
-
post: (url, data) =>
|
|
5531
|
+
post: (url, data) => http4.post(url, data),
|
|
6520
5532
|
referralSource: config.referralSource
|
|
6521
5533
|
});
|
|
6522
5534
|
}
|
|
@@ -6527,7 +5539,7 @@ export {
|
|
|
6527
5539
|
NotConnectedError,
|
|
6528
5540
|
OwneyError,
|
|
6529
5541
|
OwneySDK,
|
|
6530
|
-
YieldseekerAgent,
|
|
6531
5542
|
createOwneySIWX,
|
|
5543
|
+
listOrders as listPendingSwaps,
|
|
6532
5544
|
setOwneyDebug
|
|
6533
5545
|
};
|