@owney/sdk 0.7.32-beta.13 → 0.7.32-beta.14
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 +1 -1
- package/dist/index.cjs +345 -84
- package/dist/index.d.cts +46 -6
- package/dist/index.d.ts +46 -6
- package/dist/index.js +345 -84
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1051,7 +1051,7 @@ var SnapshotHistory = class {
|
|
|
1051
1051
|
};
|
|
1052
1052
|
|
|
1053
1053
|
// src/lib/funding-ledger.ts
|
|
1054
|
-
var SDK_VERSION = "0.7.32-beta.
|
|
1054
|
+
var SDK_VERSION = "0.7.32-beta.14";
|
|
1055
1055
|
var SCOPE2 = "funding-ledger";
|
|
1056
1056
|
var REQUEST_TIMEOUT_MS2 = 5e3;
|
|
1057
1057
|
var RETRY_DELAYS_MS = [1e3, 4e3, 16e3];
|
|
@@ -3314,14 +3314,16 @@ function splitOpportunity(opportunity) {
|
|
|
3314
3314
|
}
|
|
3315
3315
|
function mapEntries(rawEntries, chainId) {
|
|
3316
3316
|
const actionMap = {
|
|
3317
|
-
|
|
3317
|
+
// EOA -> smart wallet. Named "Top up" before ROUT-758; "Deposit" is what
|
|
3318
|
+
// users call it.
|
|
3319
|
+
"Top up wallet": "Deposit",
|
|
3318
3320
|
"Partial withdraw from protocol": "Withdraw",
|
|
3319
3321
|
"Withdraw from protocol": "Withdraw",
|
|
3320
|
-
// The agent's own leg of a
|
|
3322
|
+
// The agent's own leg of a deposit: the funds the user sent moving into the
|
|
3321
3323
|
// pool that earns the APY. Zyfai emits it as a separate entry seconds after
|
|
3322
|
-
// "Top up wallet" and for slightly less (gas).
|
|
3323
|
-
//
|
|
3324
|
-
"Deposit to protocol": "
|
|
3324
|
+
// "Top up wallet" and for slightly less (gas). Smart wallet -> pool, so
|
|
3325
|
+
// "Allocate" (ROUT-758; it was "Deposit").
|
|
3326
|
+
"Deposit to protocol": "Allocate",
|
|
3325
3327
|
// Withdrawing from an async vault (Superform) is logged under its own
|
|
3326
3328
|
// label and paid out later in a separate batch (ROUT-624).
|
|
3327
3329
|
"Request async withdrawal": "Withdraw",
|
|
@@ -3372,7 +3374,7 @@ function mapEntries(rawEntries, chainId) {
|
|
|
3372
3374
|
const asyncRequest = entry.action === "Request async withdrawal";
|
|
3373
3375
|
const rawAmount2 = entry?.positions?.[0]?.amount;
|
|
3374
3376
|
const hasAmount = (mappedAction !== "Withdraw" || asyncRequest) && typeof rawAmount2 === "string" && rawAmount2 !== "" && rawAmount2 !== "0x" && rawAmount2 !== "0x0" && rawAmount2 !== "0";
|
|
3375
|
-
const rawDelta = mappedAction === "
|
|
3377
|
+
const rawDelta = mappedAction === "Allocate" ? decodeDeltaAmount(
|
|
3376
3378
|
entry?.positions?.[0]?.deltaAmount,
|
|
3377
3379
|
tokenDecimals(entry?.positions?.[0]?.token_symbol)
|
|
3378
3380
|
) : void 0;
|
|
@@ -3647,7 +3649,7 @@ var isJwtExpired = (token) => {
|
|
|
3647
3649
|
}
|
|
3648
3650
|
};
|
|
3649
3651
|
var memorySessions = /* @__PURE__ */ new Map();
|
|
3650
|
-
var isFreshSession = (session) =>
|
|
3652
|
+
var isFreshSession = (session) => typeof session === "object" && session !== null && typeof session.isPredeployed === "boolean" && !!session.token && !isJwtExpired(session.token);
|
|
3651
3653
|
var readLegacySession = (store, address) => {
|
|
3652
3654
|
if (!store) return null;
|
|
3653
3655
|
const prefix = legacyKeyPrefix(address);
|
|
@@ -3729,13 +3731,24 @@ var clearSession = (address, _chainId) => {
|
|
|
3729
3731
|
}
|
|
3730
3732
|
readLegacySession(store, address);
|
|
3731
3733
|
};
|
|
3734
|
+
var BrowserSessionStore = class {
|
|
3735
|
+
read(_agentId, address) {
|
|
3736
|
+
return readSession(address, 0);
|
|
3737
|
+
}
|
|
3738
|
+
write(_agentId, address, session) {
|
|
3739
|
+
writeSession(address, 0, session);
|
|
3740
|
+
}
|
|
3741
|
+
clear(_agentId, address) {
|
|
3742
|
+
clearSession(address, 0);
|
|
3743
|
+
}
|
|
3744
|
+
};
|
|
3732
3745
|
|
|
3733
3746
|
// src/agents/zyfai/autoSelect.ts
|
|
3734
3747
|
function buildAutoSelectUpdate(current, asset, chainId) {
|
|
3735
3748
|
const chains = current.chains ?? [];
|
|
3736
3749
|
const chainMissing = chainId !== void 0 && !chains.includes(chainId);
|
|
3737
3750
|
const nextChains = chainMissing ? [...chains, chainId] : chains;
|
|
3738
|
-
if (current.savedPoolChoices) {
|
|
3751
|
+
if (current.savedPoolChoices || current.autoSelectProtocols === false) {
|
|
3739
3752
|
return chainMissing ? { asset, chains: nextChains } : null;
|
|
3740
3753
|
}
|
|
3741
3754
|
if (current.autoSelectProtocols === true && !chainMissing) return null;
|
|
@@ -3747,15 +3760,34 @@ function buildAutoSelectUpdate(current, asset, chainId) {
|
|
|
3747
3760
|
}
|
|
3748
3761
|
|
|
3749
3762
|
// src/agents/zyfai/protocol-merge.ts
|
|
3750
|
-
function
|
|
3763
|
+
function isExcludedProtocol(protocol, excluded) {
|
|
3764
|
+
if (excluded.length === 0) return false;
|
|
3765
|
+
const wanted = new Set(excluded.map((entry) => entry.toLowerCase()));
|
|
3766
|
+
return wanted.has(protocol.id.toLowerCase()) || protocol.name !== void 0 && wanted.has(protocol.name.toLowerCase());
|
|
3767
|
+
}
|
|
3768
|
+
function buildProtocolMergeUpdate(available, current, asset, excluded = []) {
|
|
3769
|
+
const excludedIds = /* @__PURE__ */ new Set([
|
|
3770
|
+
...excluded.map((entry) => entry.toLowerCase()),
|
|
3771
|
+
...available.filter((p) => isExcludedProtocol(p, excluded)).map((p) => p.id.toLowerCase())
|
|
3772
|
+
]);
|
|
3773
|
+
const isExcludedId = (id) => excluded.length > 0 && excludedIds.has(id.toLowerCase());
|
|
3751
3774
|
const enabled = current.protocols ?? [];
|
|
3752
|
-
const
|
|
3753
|
-
const
|
|
3754
|
-
|
|
3775
|
+
const kept = enabled.filter((id) => !isExcludedId(id));
|
|
3776
|
+
const keptSet = new Set(kept);
|
|
3777
|
+
const missing = current.autoSelectProtocols === false ? [] : available.filter((p) => !keptSet.has(p.id) && !isExcluded(p));
|
|
3778
|
+
const fixAutoSelect = excluded.length > 0 && current.autoSelectProtocols !== false;
|
|
3779
|
+
const removedAny = kept.length !== enabled.length;
|
|
3780
|
+
if (missing.length === 0 && !removedAny && !fixAutoSelect) return null;
|
|
3781
|
+
const protocols = [.../* @__PURE__ */ new Set([...kept, ...missing.map((p) => p.id)])];
|
|
3782
|
+
if (protocols.length === 0) return null;
|
|
3755
3783
|
return {
|
|
3756
3784
|
asset,
|
|
3757
|
-
protocols
|
|
3785
|
+
protocols,
|
|
3786
|
+
...excluded.length > 0 ? { autoSelectProtocols: false } : {}
|
|
3758
3787
|
};
|
|
3788
|
+
function isExcluded(p) {
|
|
3789
|
+
return isExcludedProtocol(p, excluded);
|
|
3790
|
+
}
|
|
3759
3791
|
}
|
|
3760
3792
|
|
|
3761
3793
|
// src/agents/zyfai/splitting.ts
|
|
@@ -4320,6 +4352,7 @@ var ERC7579_IS_MODULE_INSTALLED_ABI = parseAbi3([
|
|
|
4320
4352
|
"function isModuleInstalled(uint256 moduleTypeId, address module, bytes additionalContext) view returns (bool)"
|
|
4321
4353
|
]);
|
|
4322
4354
|
var ZYFAI_SIGN_IN_REQUIRED_MESSAGE = "No Zyfai sign-in is available without a prompt.";
|
|
4355
|
+
var isPromiseLike = (value) => typeof value?.then === "function";
|
|
4323
4356
|
var isSignInFailure = (error) => error instanceof OwneyError && error.code === "AGENT_AUTH_FAILED";
|
|
4324
4357
|
var WETH_ADDRESS_BY_CHAIN = {
|
|
4325
4358
|
8453: "0x4200000000000000000000000000000000000006",
|
|
@@ -4389,16 +4422,20 @@ function belowMinimumCeiling(rejection, token, decimals) {
|
|
|
4389
4422
|
return idle === void 0 || minimum === void 0 ? void 0 : idle < minimum ? idle : minimum;
|
|
4390
4423
|
}
|
|
4391
4424
|
var ZyfaiAgent = class _ZyfaiAgent {
|
|
4392
|
-
constructor(apiKey, rpcUrls, referralSource, accountReporting = {}) {
|
|
4425
|
+
constructor(apiKey, rpcUrls, referralSource, accountReporting = {}, sessionStore = new BrowserSessionStore(), excludedProtocols = []) {
|
|
4393
4426
|
this.apiKey = apiKey;
|
|
4394
4427
|
this.referralSource = referralSource;
|
|
4395
4428
|
this.accountReporting = accountReporting;
|
|
4429
|
+
this.sessionStore = sessionStore;
|
|
4430
|
+
this.excludedProtocols = excludedProtocols;
|
|
4396
4431
|
this.rpcUrls = resolveRpcUrls(rpcUrls);
|
|
4397
4432
|
this.sdk = this.createSdk();
|
|
4398
4433
|
}
|
|
4399
4434
|
apiKey;
|
|
4400
4435
|
referralSource;
|
|
4401
4436
|
accountReporting;
|
|
4437
|
+
sessionStore;
|
|
4438
|
+
excludedProtocols;
|
|
4402
4439
|
id = "zyfai";
|
|
4403
4440
|
/** This adapter can hand its withdrawals to our server (part 4). */
|
|
4404
4441
|
supportsServerTasks = true;
|
|
@@ -4550,7 +4587,7 @@ var ZyfaiAgent = class _ZyfaiAgent {
|
|
|
4550
4587
|
*/
|
|
4551
4588
|
async resolveFundingTransfers(entries, chainId, recipient, smartWallet, tokenSymbol) {
|
|
4552
4589
|
const movements = entries.filter(
|
|
4553
|
-
(e) => (e.action === "Withdraw" && !e.asyncRequest || e.action === "
|
|
4590
|
+
(e) => (e.action === "Withdraw" && !e.asyncRequest || e.action === "Deposit") && e.transactions[0]?.txHashes[0]
|
|
4554
4591
|
);
|
|
4555
4592
|
if (movements.length === 0) return;
|
|
4556
4593
|
const client = this.getPublicClient(chainId);
|
|
@@ -4607,6 +4644,48 @@ var ZyfaiAgent = class _ZyfaiAgent {
|
|
|
4607
4644
|
})
|
|
4608
4645
|
);
|
|
4609
4646
|
}
|
|
4647
|
+
/**
|
|
4648
|
+
* The session store is a cache: an unavailable store must never block
|
|
4649
|
+
* authentication or teardown. Failures read as a cache miss. The store is
|
|
4650
|
+
* called synchronously, so a synchronous store (the browser default) has
|
|
4651
|
+
* already acted when this returns.
|
|
4652
|
+
*/
|
|
4653
|
+
async storeOp(op) {
|
|
4654
|
+
try {
|
|
4655
|
+
return await op();
|
|
4656
|
+
} catch (error) {
|
|
4657
|
+
console.warn(
|
|
4658
|
+
"owney-sdk: agent session store failed, continuing without it",
|
|
4659
|
+
error
|
|
4660
|
+
);
|
|
4661
|
+
return null;
|
|
4662
|
+
}
|
|
4663
|
+
}
|
|
4664
|
+
/**
|
|
4665
|
+
* The fresh saved session for `address`, or null. Answered synchronously
|
|
4666
|
+
* when the store answers synchronously (the browser default), so a check
|
|
4667
|
+
* that must not yield keeps its order; a promise for an asynchronous store.
|
|
4668
|
+
* A store failure reads as no session.
|
|
4669
|
+
*/
|
|
4670
|
+
savedSession(address) {
|
|
4671
|
+
let value;
|
|
4672
|
+
try {
|
|
4673
|
+
value = this.sessionStore.read(this.id, address);
|
|
4674
|
+
} catch (error) {
|
|
4675
|
+
console.warn("owney-sdk: agent session store failed, continuing without it", error);
|
|
4676
|
+
return null;
|
|
4677
|
+
}
|
|
4678
|
+
if (isPromiseLike(value)) {
|
|
4679
|
+
return Promise.resolve(value).then(
|
|
4680
|
+
(session) => isFreshSession(session) ? session : null,
|
|
4681
|
+
(error) => {
|
|
4682
|
+
console.warn("owney-sdk: agent session store failed, continuing without it", error);
|
|
4683
|
+
return null;
|
|
4684
|
+
}
|
|
4685
|
+
);
|
|
4686
|
+
}
|
|
4687
|
+
return isFreshSession(value) ? value : null;
|
|
4688
|
+
}
|
|
4610
4689
|
/**
|
|
4611
4690
|
* Patches `sdk.authenticateUser` so a fresh page can reuse the JWT from a
|
|
4612
4691
|
* prior session instead of triggering a new SIWE prompt. Runs inside
|
|
@@ -4614,21 +4693,21 @@ var ZyfaiAgent = class _ZyfaiAgent {
|
|
|
4614
4693
|
* (Zyfai dist line 1374). At that point `walletClient` + `currentChainId`
|
|
4615
4694
|
* are populated, so the cache lookup has both keys it needs.
|
|
4616
4695
|
*
|
|
4617
|
-
*
|
|
4618
|
-
*
|
|
4696
|
+
* The session lives in `sessionStore`: localStorage in the browser (a no-op
|
|
4697
|
+
* on the server), or whatever the host passed in `OwneySDKConfig`.
|
|
4619
4698
|
*/
|
|
4620
4699
|
installAuthCache(sdk = this.sdk) {
|
|
4621
|
-
if (typeof window === "undefined") return;
|
|
4622
4700
|
const internals = sdk;
|
|
4623
4701
|
const original = internals.authenticateUser.bind(internals);
|
|
4624
4702
|
let inFlight2 = null;
|
|
4625
4703
|
const authenticate = async () => {
|
|
4626
4704
|
if (internals.authenticatedUserId !== null) return;
|
|
4627
4705
|
const address = internals.walletClient?.account?.address;
|
|
4628
|
-
const chainId = internals.currentChainId ?? 0;
|
|
4629
4706
|
if (address) {
|
|
4630
|
-
const cached =
|
|
4631
|
-
|
|
4707
|
+
const cached = await this.storeOp(
|
|
4708
|
+
() => this.sessionStore.read(this.id, address)
|
|
4709
|
+
);
|
|
4710
|
+
if (isFreshSession(cached)) {
|
|
4632
4711
|
internals.httpClient.setAuthToken(cached.token);
|
|
4633
4712
|
internals.authenticatedUserId = cached.userId;
|
|
4634
4713
|
internals.hasActiveSessionKey = cached.hasActiveSessionKey;
|
|
@@ -4639,15 +4718,16 @@ var ZyfaiAgent = class _ZyfaiAgent {
|
|
|
4639
4718
|
if (this.promptlessSdks.has(sdk)) throw this.signInRequired();
|
|
4640
4719
|
await original();
|
|
4641
4720
|
const newAddress = internals.walletClient?.account?.address;
|
|
4642
|
-
const newChainId = internals.currentChainId ?? 0;
|
|
4643
4721
|
const newToken = internals.httpClient.authToken;
|
|
4644
4722
|
if (newAddress && newToken) {
|
|
4645
|
-
|
|
4646
|
-
|
|
4647
|
-
|
|
4648
|
-
|
|
4649
|
-
|
|
4650
|
-
|
|
4723
|
+
await this.storeOp(
|
|
4724
|
+
() => this.sessionStore.write(this.id, newAddress, {
|
|
4725
|
+
token: newToken,
|
|
4726
|
+
userId: internals.authenticatedUserId,
|
|
4727
|
+
hasActiveSessionKey: internals.hasActiveSessionKey,
|
|
4728
|
+
isPredeployed: internals.isPredeployed
|
|
4729
|
+
})
|
|
4730
|
+
);
|
|
4651
4731
|
}
|
|
4652
4732
|
};
|
|
4653
4733
|
internals.authenticateUser = () => {
|
|
@@ -4676,11 +4756,19 @@ var ZyfaiAgent = class _ZyfaiAgent {
|
|
|
4676
4756
|
* Whether connecting now would ask the wallet to sign in: not connected for
|
|
4677
4757
|
* this wallet and chain (the check `connectAuth` returns early on) and no
|
|
4678
4758
|
* fresh saved session. Never prompts; reads only what is saved.
|
|
4759
|
+
*
|
|
4760
|
+
* A session store that answers only asynchronously (a host's own
|
|
4761
|
+
* `sessionStore`) cannot be read here, so this throws: the caller counts an
|
|
4762
|
+
* unknown answer its own way (`OwneySDK.signInsNeeded` as a sign-in).
|
|
4679
4763
|
*/
|
|
4680
4764
|
needsSignIn(state, chainId) {
|
|
4681
4765
|
const owner = state.walletAddress.toLowerCase();
|
|
4682
4766
|
if (this.connectedAddress?.toLowerCase() === owner && this.connectedChainId === chainId) return false;
|
|
4683
|
-
|
|
4767
|
+
const saved = this.savedSession(state.walletAddress);
|
|
4768
|
+
if (isPromiseLike(saved)) {
|
|
4769
|
+
throw new Error("The Zyfai session store answers asynchronously; whether a sign-in is needed is unknown.");
|
|
4770
|
+
}
|
|
4771
|
+
return saved === null;
|
|
4684
4772
|
}
|
|
4685
4773
|
/** A read (promptless state) needs a sign-in it may not ask for. */
|
|
4686
4774
|
signInRequired() {
|
|
@@ -4710,7 +4798,15 @@ var ZyfaiAgent = class _ZyfaiAgent {
|
|
|
4710
4798
|
else await this.connectAuthPromise;
|
|
4711
4799
|
return this.connectAuth(state, chainId);
|
|
4712
4800
|
}
|
|
4713
|
-
if (promptless
|
|
4801
|
+
if (promptless) {
|
|
4802
|
+
let saved = this.savedSession(state.walletAddress);
|
|
4803
|
+
if (isPromiseLike(saved)) {
|
|
4804
|
+
saved = await saved;
|
|
4805
|
+
if (saved === null) throw this.signInRequired();
|
|
4806
|
+
if (this.connectedAddress?.toLowerCase() === owner && this.connectedChainId === validChainId || this.connectAuthPromise && this.connectAuthScope === scope) return this.connectAuth(state, chainId);
|
|
4807
|
+
}
|
|
4808
|
+
if (saved === null) throw this.signInRequired();
|
|
4809
|
+
}
|
|
4714
4810
|
if (this.sdkHasConnected || this.connectedAddress) this.sdk = this.createSdk();
|
|
4715
4811
|
this.sdkHasConnected = true;
|
|
4716
4812
|
const executionSdk = this.sdk;
|
|
@@ -4770,8 +4866,10 @@ var ZyfaiAgent = class _ZyfaiAgent {
|
|
|
4770
4866
|
if (!message.toLowerCase().includes("unauthorized")) throw error;
|
|
4771
4867
|
const internals = executionSdk;
|
|
4772
4868
|
const address = internals.walletClient?.account?.address;
|
|
4773
|
-
if (promptless) throw this.dropRefusedReadSession(address, executionSdk, internals.httpClient.authToken, message);
|
|
4774
|
-
if (address)
|
|
4869
|
+
if (promptless) throw await this.dropRefusedReadSession(address, executionSdk, internals.httpClient.authToken, message);
|
|
4870
|
+
if (address) {
|
|
4871
|
+
await this.storeOp(() => this.sessionStore.clear(this.id, address));
|
|
4872
|
+
}
|
|
4775
4873
|
return await executionSdk.connectAccount(provider, chainId);
|
|
4776
4874
|
}
|
|
4777
4875
|
}
|
|
@@ -4794,14 +4892,10 @@ var ZyfaiAgent = class _ZyfaiAgent {
|
|
|
4794
4892
|
* the user's (connect, deposit, withdraw), on a new client. Returns the
|
|
4795
4893
|
* read's error.
|
|
4796
4894
|
*/
|
|
4797
|
-
dropRefusedReadSession(owner, executionSdk, authToken, refusal) {
|
|
4895
|
+
async dropRefusedReadSession(owner, executionSdk, authToken, refusal) {
|
|
4798
4896
|
debugLog("zyfai:auth", "a read's session was refused; dropped without signing in again", { refusal });
|
|
4799
4897
|
if (owner && typeof authToken === "string") {
|
|
4800
4898
|
let dropped = false;
|
|
4801
|
-
if (readSession(owner, 0)?.token === authToken) {
|
|
4802
|
-
clearSession(owner, 0);
|
|
4803
|
-
dropped = true;
|
|
4804
|
-
}
|
|
4805
4899
|
const internals = executionSdk;
|
|
4806
4900
|
if (internals.httpClient.authToken === authToken) {
|
|
4807
4901
|
dropped = true;
|
|
@@ -4811,6 +4905,11 @@ var ZyfaiAgent = class _ZyfaiAgent {
|
|
|
4811
4905
|
if (executionSdk === this.sdk && this.connectedAddress?.toLowerCase() === owner.toLowerCase())
|
|
4812
4906
|
this.connectedChainId = null;
|
|
4813
4907
|
}
|
|
4908
|
+
const saved = await this.savedSession(owner);
|
|
4909
|
+
if (saved?.token === authToken) {
|
|
4910
|
+
await this.storeOp(() => this.sessionStore.clear(this.id, owner));
|
|
4911
|
+
dropped = true;
|
|
4912
|
+
}
|
|
4814
4913
|
if (dropped) this.tellSignInRefused();
|
|
4815
4914
|
}
|
|
4816
4915
|
return this.signInRequired();
|
|
@@ -4830,7 +4929,7 @@ var ZyfaiAgent = class _ZyfaiAgent {
|
|
|
4830
4929
|
if (state.promptless !== true || error instanceof OwneyError) throw error;
|
|
4831
4930
|
if (message.includes(ZYFAI_SIGN_IN_REQUIRED_MESSAGE)) throw this.signInRequired();
|
|
4832
4931
|
if (!isZyfaiSessionRejected(message)) throw error;
|
|
4833
|
-
throw this.dropRefusedReadSession(state.walletAddress, executionSdk, authToken, message);
|
|
4932
|
+
throw await this.dropRefusedReadSession(state.walletAddress, executionSdk, authToken, message);
|
|
4834
4933
|
}
|
|
4835
4934
|
}
|
|
4836
4935
|
/**
|
|
@@ -4866,7 +4965,8 @@ var ZyfaiAgent = class _ZyfaiAgent {
|
|
|
4866
4965
|
dropWithdrawalSession(state, chainId, authToken) {
|
|
4867
4966
|
const internals = this.sdk;
|
|
4868
4967
|
if (typeof authToken !== "string" || internals.httpClient.authToken !== authToken || this.connectedAddress?.toLowerCase() !== state.walletAddress.toLowerCase() || this.connectedChainId !== chainId) return;
|
|
4869
|
-
|
|
4968
|
+
const owner = state.walletAddress;
|
|
4969
|
+
void this.storeOp(() => this.sessionStore.clear(this.id, owner));
|
|
4870
4970
|
internals.httpClient.clearAuthToken();
|
|
4871
4971
|
internals.authenticatedUserId = null;
|
|
4872
4972
|
this.connectedChainId = null;
|
|
@@ -4907,10 +5007,15 @@ var ZyfaiAgent = class _ZyfaiAgent {
|
|
|
4907
5007
|
available,
|
|
4908
5008
|
current.chains ?? []
|
|
4909
5009
|
);
|
|
5010
|
+
const excluded = this.excludedProtocols.length === 0 ? [] : [
|
|
5011
|
+
...this.excludedProtocols,
|
|
5012
|
+
...available.filter((protocol) => isExcludedProtocol(protocol, this.excludedProtocols)).map((protocol) => protocol.id)
|
|
5013
|
+
];
|
|
4910
5014
|
const update = buildProtocolMergeUpdate(
|
|
4911
5015
|
available.filter((protocol) => !decided.has(protocol.id)),
|
|
4912
5016
|
current,
|
|
4913
|
-
asset
|
|
5017
|
+
asset,
|
|
5018
|
+
excluded
|
|
4914
5019
|
);
|
|
4915
5020
|
if (!update) return;
|
|
4916
5021
|
await this.sdk.updateUserProfile(update);
|
|
@@ -4985,9 +5090,8 @@ var ZyfaiAgent = class _ZyfaiAgent {
|
|
|
4985
5090
|
this.holdActiveScopes.clear();
|
|
4986
5091
|
this.pendingRegistrations.clear();
|
|
4987
5092
|
this.lastGoodEarnings.clear();
|
|
4988
|
-
|
|
4989
|
-
|
|
4990
|
-
}
|
|
5093
|
+
const address = this.connectedAddress;
|
|
5094
|
+
const sessionCleared = !options?.keepSignIns && address ? this.storeOp(() => this.sessionStore.clear(this.id, address)) : void 0;
|
|
4991
5095
|
this.connectedAddress = null;
|
|
4992
5096
|
this.connectedChainId = null;
|
|
4993
5097
|
this.connectAuthPromise = null;
|
|
@@ -4997,6 +5101,7 @@ var ZyfaiAgent = class _ZyfaiAgent {
|
|
|
4997
5101
|
this.reportedAccounts.clear();
|
|
4998
5102
|
this.sdk = this.createSdk();
|
|
4999
5103
|
this.sdkHasConnected = false;
|
|
5104
|
+
await sessionCleared;
|
|
5000
5105
|
await executionSdk.disconnectAccount();
|
|
5001
5106
|
}
|
|
5002
5107
|
// --- IAgent: Account lifecycle ---
|
|
@@ -5208,9 +5313,12 @@ var ZyfaiAgent = class _ZyfaiAgent {
|
|
|
5208
5313
|
* lookup fails is skipped rather than failing the whole catalogue.
|
|
5209
5314
|
*/
|
|
5210
5315
|
async getPoolCatalog(params) {
|
|
5211
|
-
const { protocols:
|
|
5316
|
+
const { protocols: allProtocols } = await this.sdk.getAvailableProtocols(
|
|
5212
5317
|
this.supportedChainIds[0]
|
|
5213
5318
|
);
|
|
5319
|
+
const universe = allProtocols.filter(
|
|
5320
|
+
(protocol) => !isExcludedProtocol(protocol, this.excludedProtocols)
|
|
5321
|
+
);
|
|
5214
5322
|
const poolResults = await Promise.all(
|
|
5215
5323
|
universe.map(async (protocol) => {
|
|
5216
5324
|
try {
|
|
@@ -5362,6 +5470,7 @@ var ZyfaiAgent = class _ZyfaiAgent {
|
|
|
5362
5470
|
}
|
|
5363
5471
|
for (const protocol of universe) {
|
|
5364
5472
|
if (excluded.has(protocol.id)) continue;
|
|
5473
|
+
if (isExcludedProtocol(protocol, this.excludedProtocols)) continue;
|
|
5365
5474
|
try {
|
|
5366
5475
|
const names = mapAvailablePools(await this.sdk.getAvailablePools(protocol.id, "yieldmaxxing")).filter((pool) => pool.chainId === chainId && pool.token.toUpperCase() === asset).map((pool) => pool.name);
|
|
5367
5476
|
if (names.length === 0) continue;
|
|
@@ -5748,6 +5857,10 @@ var ZyfaiAgent = class _ZyfaiAgent {
|
|
|
5748
5857
|
assertCurrent();
|
|
5749
5858
|
const setupResult = await executionSdk.ensureFirstDepositSetup("aggressive");
|
|
5750
5859
|
debugLog("zyfai:first-deposit", "setup call completed", { asset, chainId: validChainId, requestedStrategy: "aggressive", setupResult });
|
|
5860
|
+
if (this.excludedProtocols.length > 0) {
|
|
5861
|
+
assertCurrent();
|
|
5862
|
+
await this.ensureProtocolsSynced(validChainId, asset);
|
|
5863
|
+
}
|
|
5751
5864
|
if (isOwneyDebug()) {
|
|
5752
5865
|
try {
|
|
5753
5866
|
const profile = await executionSdk.getUserDetails(asset === "WETH" ? "WETH" : "USDC");
|
|
@@ -7972,6 +8085,10 @@ function dailyApy(point) {
|
|
|
7972
8085
|
if (principal <= 0n || earned === 0n) return 0;
|
|
7973
8086
|
return Number(earned) / Number(principal) * 365 * 100;
|
|
7974
8087
|
}
|
|
8088
|
+
var DUST_USD = 5e-3;
|
|
8089
|
+
function heldPosition(tokens, priceUsd) {
|
|
8090
|
+
return Number.isFinite(priceUsd) && priceUsd > 0 ? tokens * priceUsd >= DUST_USD : tokens > 0;
|
|
8091
|
+
}
|
|
7975
8092
|
function aggregateHistory(contexts, dayCount, now, scopedAsset) {
|
|
7976
8093
|
const today = new Date(now).toISOString().slice(0, 10);
|
|
7977
8094
|
const cutoff = new Date(Date.parse(today) - (dayCount - 1) * 864e5).toISOString().slice(0, 10);
|
|
@@ -7988,6 +8105,7 @@ function aggregateHistory(contexts, dayCount, now, scopedAsset) {
|
|
|
7988
8105
|
if (!Number.isFinite(amount) || amount < 0) {
|
|
7989
8106
|
invalid("historic position", "expected a finite non-negative balance");
|
|
7990
8107
|
}
|
|
8108
|
+
if (!heldPosition(tokens, point.baseAssetPriceUsd)) continue;
|
|
7991
8109
|
const current = byDate.get(point.date) ?? { weighted: 0, amount: 0 };
|
|
7992
8110
|
current.weighted += dailyApy(point) * amount;
|
|
7993
8111
|
current.amount += amount;
|
|
@@ -8008,7 +8126,8 @@ function historyCoverage2(contexts, dayCount, now) {
|
|
|
8008
8126
|
for (const context of contexts) {
|
|
8009
8127
|
for (const point of context.historic?.dailyYieldSnapshots ?? []) {
|
|
8010
8128
|
if (!/^\d{4}-\d{2}-\d{2}$/.test(point.date) || point.date < cutoff || point.date > today) continue;
|
|
8011
|
-
|
|
8129
|
+
const tokens = Number(decimal(point.totalValueBase, point.baseAssetDecimals, "historic position"));
|
|
8130
|
+
if (!heldPosition(tokens, point.baseAssetPriceUsd)) continue;
|
|
8012
8131
|
const asset = context.asset.toUpperCase();
|
|
8013
8132
|
const dates = datesByAsset.get(asset) ?? /* @__PURE__ */ new Set();
|
|
8014
8133
|
dates.add(point.date);
|
|
@@ -8050,7 +8169,7 @@ function mapYieldseekerApy(walletAddress, contexts, days, now = Date.now(), scop
|
|
|
8050
8169
|
}
|
|
8051
8170
|
function actionType(value) {
|
|
8052
8171
|
const normalized = value.toLowerCase();
|
|
8053
|
-
if (normalized.includes("deposit")) return "
|
|
8172
|
+
if (normalized.includes("deposit")) return "Allocate";
|
|
8054
8173
|
if (normalized.includes("withdraw")) return "Withdraw";
|
|
8055
8174
|
if (normalized.includes("yield") || normalized.includes("earn"))
|
|
8056
8175
|
return "Earned";
|
|
@@ -8111,14 +8230,87 @@ function allocationLegs(value, context, requireAmount) {
|
|
|
8111
8230
|
}
|
|
8112
8231
|
return legs;
|
|
8113
8232
|
}
|
|
8114
|
-
function
|
|
8233
|
+
function vaultBook(context, vaultAddresses, catalog = []) {
|
|
8234
|
+
const base7 = context.agent.assetAddress.toLowerCase();
|
|
8235
|
+
const labels = /* @__PURE__ */ new Map();
|
|
8236
|
+
const name = (address, label) => {
|
|
8237
|
+
if (typeof address !== "string" || !isAddress3(address)) return;
|
|
8238
|
+
const key2 = address.toLowerCase();
|
|
8239
|
+
if (!labels.has(key2)) labels.set(key2, label);
|
|
8240
|
+
};
|
|
8241
|
+
for (const action of context.actions ?? []) {
|
|
8242
|
+
for (const list of [action.details?.deposits, action.details?.withdrawals]) {
|
|
8243
|
+
if (!Array.isArray(list)) continue;
|
|
8244
|
+
for (const leg of list) {
|
|
8245
|
+
if (leg && typeof leg.vaultProvider === "string" && leg.vaultProvider)
|
|
8246
|
+
name(leg.vaultAddress, {
|
|
8247
|
+
protocol: leg.vaultProvider,
|
|
8248
|
+
...typeof leg.vaultName === "string" && leg.vaultName ? { pool: leg.vaultName } : {}
|
|
8249
|
+
});
|
|
8250
|
+
}
|
|
8251
|
+
}
|
|
8252
|
+
}
|
|
8253
|
+
for (const option of [...context.positions.map((entry) => entry.vaultOption), ...catalog])
|
|
8254
|
+
if (option?.chainId === context.agent.chainId)
|
|
8255
|
+
name(option.address, { protocol: option.provider || "Vault", ...option.name ? { pool: option.name } : {} });
|
|
8256
|
+
for (const asset of context.historic?.assets ?? [])
|
|
8257
|
+
if (asset.chainId === context.agent.chainId && !asset.isSpam && asset.address.toLowerCase() !== base7)
|
|
8258
|
+
name(asset.address, { protocol: "Vault", ...asset.name || asset.symbol ? { pool: asset.name || asset.symbol } : {} });
|
|
8259
|
+
const addresses = /* @__PURE__ */ new Set([...vaultAddresses, ...labels.keys()]);
|
|
8260
|
+
return { addresses, label: (address) => labels.get(address.toLowerCase()) ?? { protocol: "Vault" } };
|
|
8261
|
+
}
|
|
8262
|
+
function recycledDeposits(context, movements, vaults) {
|
|
8263
|
+
const base7 = context.agent.assetAddress.toLowerCase();
|
|
8264
|
+
const agentWallet = context.wallet.walletAddress.toLowerCase();
|
|
8265
|
+
const relevant = movements.filter((movement) => movement.chainId === context.agent.chainId && movement.assetAddress.toLowerCase() === base7 && /^\d+$/.test(movement.assetAmount) && BigInt(movement.assetAmount) > 0n && (movement.fromAddress.toLowerCase() === agentWallet || movement.toAddress.toLowerCase() === agentWallet)).sort((a, b) => a.blockDate.localeCompare(b.blockDate) || a.blockNumber - b.blockNumber || a.logIndex - b.logIndex);
|
|
8266
|
+
const transactions = /* @__PURE__ */ new Map();
|
|
8267
|
+
for (const movement of relevant) {
|
|
8268
|
+
const hash2 = movement.transactionHash.toLowerCase();
|
|
8269
|
+
transactions.set(hash2, [...transactions.get(hash2) ?? [], movement]);
|
|
8270
|
+
}
|
|
8271
|
+
const held = [];
|
|
8272
|
+
const spend = (amount) => {
|
|
8273
|
+
const used = [];
|
|
8274
|
+
while (amount > 0n && held.length) {
|
|
8275
|
+
const first = held[0];
|
|
8276
|
+
const taken = first.amount < amount ? first.amount : amount;
|
|
8277
|
+
if (!used.some((entry) => entry.vault === first.vault && entry.hash === first.hash))
|
|
8278
|
+
used.push({ vault: first.vault, hash: first.hash });
|
|
8279
|
+
first.amount -= taken;
|
|
8280
|
+
amount -= taken;
|
|
8281
|
+
if (first.amount === 0n) held.shift();
|
|
8282
|
+
}
|
|
8283
|
+
return used;
|
|
8284
|
+
};
|
|
8285
|
+
const covered = /* @__PURE__ */ new Map();
|
|
8286
|
+
for (const [hash2, legs] of transactions) {
|
|
8287
|
+
let deposited = 0n;
|
|
8288
|
+
for (const movement of legs) {
|
|
8289
|
+
const from = movement.fromAddress.toLowerCase();
|
|
8290
|
+
const to = movement.toAddress.toLowerCase();
|
|
8291
|
+
const amount = BigInt(movement.assetAmount);
|
|
8292
|
+
if (to === agentWallet && from !== agentWallet) {
|
|
8293
|
+
if (vaults.has(from)) held.push({ vault: from, hash: hash2, amount });
|
|
8294
|
+
} else if (from === agentWallet && to !== agentWallet) {
|
|
8295
|
+
if (vaults.has(to)) deposited += amount;
|
|
8296
|
+
else spend(amount);
|
|
8297
|
+
}
|
|
8298
|
+
}
|
|
8299
|
+
if (deposited === 0n) continue;
|
|
8300
|
+
const available = held.reduce((total, entry) => total + entry.amount, 0n);
|
|
8301
|
+
const used = spend(deposited);
|
|
8302
|
+
if (available >= deposited) covered.set(hash2, used);
|
|
8303
|
+
}
|
|
8304
|
+
return covered;
|
|
8305
|
+
}
|
|
8306
|
+
function allocationEntry(action, context, evidence) {
|
|
8115
8307
|
if (action.actionType.toLowerCase() !== "autoseek") return void 0;
|
|
8116
8308
|
const hash2 = action.details?.depositTransactionHash;
|
|
8117
8309
|
const withdrawHash = action.details?.withdrawTransactionHash;
|
|
8118
8310
|
if (typeof hash2 !== "string" || !TX_HASH3.test(hash2)) return null;
|
|
8119
8311
|
const deposits = allocationLegs(action.details?.deposits, context, true);
|
|
8120
|
-
const
|
|
8121
|
-
if (!deposits?.length || !
|
|
8312
|
+
const listed = action.details?.withdrawals == null ? [] : allocationLegs(action.details.withdrawals, context, false);
|
|
8313
|
+
if (!deposits?.length || !listed) return null;
|
|
8122
8314
|
const decimals = YIELDSEEKER_ASSET_METADATA[context.asset].decimals;
|
|
8123
8315
|
const positions = deposits.map((leg) => ({
|
|
8124
8316
|
protocol: leg.protocol,
|
|
@@ -8127,15 +8319,26 @@ function allocationEntry(action, context) {
|
|
|
8127
8319
|
amount: formatUnits3(leg.rawAmount, decimals)
|
|
8128
8320
|
}));
|
|
8129
8321
|
const amountRaw = deposits.reduce((total, leg) => total + leg.rawAmount, 0n);
|
|
8322
|
+
const withdrawTx = typeof withdrawHash === "string" && TX_HASH3.test(withdrawHash) && withdrawHash.toLowerCase() !== hash2.toLowerCase() ? withdrawHash : void 0;
|
|
8323
|
+
let withdrawals = listed;
|
|
8324
|
+
let hashes = listed.length && withdrawTx ? [hash2, withdrawTx] : [hash2];
|
|
8325
|
+
if (!listed.length) {
|
|
8326
|
+
const agentWallet = context.wallet.walletAddress.toLowerCase();
|
|
8327
|
+
const inWithdrawTx = withdrawTx ? evidence.movements.filter((movement) => movement.transactionHash.toLowerCase() === withdrawTx.toLowerCase() && movement.assetAddress.toLowerCase() === context.agent.assetAddress.toLowerCase() && movement.toAddress.toLowerCase() === agentWallet && evidence.book.addresses.has(movement.fromAddress.toLowerCase())).map((movement) => ({ vault: movement.fromAddress.toLowerCase(), hash: withdrawTx })) : [];
|
|
8328
|
+
const recycled = evidence.recycled.get(hash2.toLowerCase()) ?? [];
|
|
8329
|
+
const sources = inWithdrawTx.length ? inWithdrawTx : recycled;
|
|
8330
|
+
withdrawals = [...new Set(sources.map((source2) => source2.vault))].map((vault) => evidence.book.label(vault));
|
|
8331
|
+
hashes = [hash2, ...new Set(withdrawTx ? [withdrawTx] : sources.map((source2) => source2.hash).filter((value) => value !== hash2.toLowerCase()))];
|
|
8332
|
+
}
|
|
8130
8333
|
const rebalance = withdrawals.length > 0;
|
|
8131
|
-
|
|
8334
|
+
if (!rebalance) hashes = [hash2];
|
|
8132
8335
|
const source = withdrawals.length === 1 ? withdrawals[0] : {
|
|
8133
8336
|
protocol: [...new Set(withdrawals.map((leg) => leg.protocol))].join(" + "),
|
|
8134
8337
|
pool: withdrawals.map((leg) => leg.pool).filter(Boolean).join(" + ") || void 0
|
|
8135
8338
|
};
|
|
8136
8339
|
return {
|
|
8137
8340
|
agent: "yieldseeker",
|
|
8138
|
-
action: rebalance ? "Rebalance" : "
|
|
8341
|
+
action: rebalance ? "Rebalance" : "Allocate",
|
|
8139
8342
|
date: action.createdDate,
|
|
8140
8343
|
oldApy: null,
|
|
8141
8344
|
newApy: null,
|
|
@@ -8182,17 +8385,17 @@ function movementEntry(movement, wallet, agent, asset, ownerAddress, vaultAddres
|
|
|
8182
8385
|
}
|
|
8183
8386
|
let action;
|
|
8184
8387
|
if (to === agentWallet && !vaultAddresses.has(from)) {
|
|
8185
|
-
action = "
|
|
8388
|
+
action = "Deposit";
|
|
8186
8389
|
} else if (from === agentWallet && to === owner) {
|
|
8187
8390
|
action = "Withdraw";
|
|
8188
8391
|
} else if (from === agentWallet && destination) {
|
|
8189
|
-
action = "
|
|
8392
|
+
action = "Allocate";
|
|
8190
8393
|
}
|
|
8191
8394
|
if (!action) return void 0;
|
|
8192
8395
|
return {
|
|
8193
8396
|
agent: "yieldseeker",
|
|
8194
8397
|
action,
|
|
8195
|
-
...action === "
|
|
8398
|
+
...action === "Allocate" && destination ? { positions: [{
|
|
8196
8399
|
...destination,
|
|
8197
8400
|
amount: decimal(movement.assetAmount, YIELDSEEKER_ASSET_METADATA[asset].decimals, "historic position")
|
|
8198
8401
|
}] } : {},
|
|
@@ -8229,11 +8432,13 @@ function mapYieldseekerHistory(contexts, options) {
|
|
|
8229
8432
|
seenMovements.add(key2);
|
|
8230
8433
|
return true;
|
|
8231
8434
|
});
|
|
8435
|
+
const book = vaultBook(context, options.vaultAddresses, options.vaultOptions);
|
|
8436
|
+
const evidence = { book, movements, recycled: recycledDeposits(context, movements, book.addresses) };
|
|
8232
8437
|
const allocations = /* @__PURE__ */ new Map();
|
|
8233
8438
|
const rebalanceHashes = /* @__PURE__ */ new Set();
|
|
8234
8439
|
const actions = [];
|
|
8235
8440
|
for (const action of context.actions ?? []) {
|
|
8236
|
-
const allocation = allocationEntry(action, context);
|
|
8441
|
+
const allocation = allocationEntry(action, context, evidence);
|
|
8237
8442
|
if (allocation === null) continue;
|
|
8238
8443
|
if (!allocation) {
|
|
8239
8444
|
const entry = actionEntry(action);
|
|
@@ -8253,11 +8458,11 @@ function mapYieldseekerHistory(contexts, options) {
|
|
|
8253
8458
|
context.agent,
|
|
8254
8459
|
context.asset,
|
|
8255
8460
|
options.ownerAddress,
|
|
8256
|
-
|
|
8461
|
+
book.addresses,
|
|
8257
8462
|
depositDestination(context, movement)
|
|
8258
8463
|
)
|
|
8259
|
-
).filter((entry) => entry !== void 0 && !((entry.action === "
|
|
8260
|
-
const deposits = new Set(movementEntries.filter((entry) => entry.action === "
|
|
8464
|
+
).filter((entry) => entry !== void 0 && !((entry.action === "Allocate" || entry.action === "Deposit") && rebalanceHashes.has(entry.transactions[0]?.txHashes[0]?.toLowerCase() ?? "")));
|
|
8465
|
+
const deposits = new Set(movementEntries.filter((entry) => entry.action === "Allocate").map((entry) => entry.transactions[0]?.txHashes[0]?.toLowerCase()));
|
|
8261
8466
|
for (const [hash2, allocation] of allocations)
|
|
8262
8467
|
if (allocation.action === "Rebalance" || !deposits.has(hash2)) actions.push(allocation);
|
|
8263
8468
|
return [...movementEntries, ...actions];
|
|
@@ -8278,14 +8483,14 @@ function mapYieldseekerHistory(contexts, options) {
|
|
|
8278
8483
|
grouped.set(key2, entry);
|
|
8279
8484
|
continue;
|
|
8280
8485
|
}
|
|
8281
|
-
if (entry.action === "
|
|
8486
|
+
if (entry.action === "Allocate" && entry.positions?.length) {
|
|
8282
8487
|
if (!previous.positions?.length) {
|
|
8283
8488
|
grouped.set(key2, entry);
|
|
8284
8489
|
continue;
|
|
8285
8490
|
}
|
|
8286
8491
|
previous.positions.push(...entry.positions);
|
|
8287
8492
|
previous.transactions.push(...entry.transactions);
|
|
8288
|
-
} else if ((entry.action === "
|
|
8493
|
+
} else if ((entry.action === "Deposit" || entry.action === "Withdraw") && tx.amountRaw) {
|
|
8289
8494
|
const target = previous.transactions[0];
|
|
8290
8495
|
const known = new Set(target.logIndexes ?? []);
|
|
8291
8496
|
if (tx.logIndexes?.some((index) => !known.has(index))) {
|
|
@@ -11592,16 +11797,18 @@ var YieldseekerAgent = class {
|
|
|
11592
11797
|
(contextAsset) => this.loadVaultOptions(contextAsset, { includeUnavailable: true })
|
|
11593
11798
|
)
|
|
11594
11799
|
);
|
|
11800
|
+
const vaultOptions = catalog.flat().filter(
|
|
11801
|
+
(vaultOption) => vaultOption.chainId === chainId && isAddress4(vaultOption.address)
|
|
11802
|
+
);
|
|
11595
11803
|
const vaultAddresses = new Set(
|
|
11596
|
-
|
|
11597
|
-
(vaultOption) => vaultOption.chainId === chainId && isAddress4(vaultOption.address)
|
|
11598
|
-
).map((vaultOption) => vaultOption.address.toLowerCase())
|
|
11804
|
+
vaultOptions.map((vaultOption) => vaultOption.address.toLowerCase())
|
|
11599
11805
|
);
|
|
11600
11806
|
return mapYieldseekerHistory(contexts, {
|
|
11601
11807
|
limit: options?.limit ?? 10,
|
|
11602
11808
|
cursor: options?.cursor,
|
|
11603
11809
|
ownerAddress: state.walletAddress,
|
|
11604
11810
|
vaultAddresses,
|
|
11811
|
+
vaultOptions,
|
|
11605
11812
|
...options?.fromDate ? { fromDate: options.fromDate } : {},
|
|
11606
11813
|
...options?.toDate ? { toDate: options.toDate } : {}
|
|
11607
11814
|
});
|
|
@@ -16735,7 +16942,6 @@ async function runAgentDepositBatch(chainId, legs, transfer) {
|
|
|
16735
16942
|
// src/lib/walletconnect-switch.ts
|
|
16736
16943
|
var WALLET_SWITCH_TIMEOUT_MS = 12e4;
|
|
16737
16944
|
var HOLD_CHAIN_MS = 15e3;
|
|
16738
|
-
var MAX_RESENDS = 2;
|
|
16739
16945
|
var holds = /* @__PURE__ */ new Map();
|
|
16740
16946
|
function parseChainId(raw2) {
|
|
16741
16947
|
if (typeof raw2 === "number") return raw2;
|
|
@@ -16744,28 +16950,76 @@ function parseChainId(raw2) {
|
|
|
16744
16950
|
const id = ref.startsWith("0x") ? Number.parseInt(ref, 16) : Number(ref);
|
|
16745
16951
|
return Number.isFinite(id) ? id : void 0;
|
|
16746
16952
|
}
|
|
16747
|
-
function
|
|
16953
|
+
function walletConnectSession(provider) {
|
|
16748
16954
|
const p = provider;
|
|
16749
16955
|
const core = p?.signer ?? p;
|
|
16750
|
-
if (typeof core?.client?.request !== "function" || typeof core.setDefaultChain !== "function" || typeof core.session?.topic !== "string") {
|
|
16956
|
+
if (typeof core?.request !== "function" || typeof core?.client?.request !== "function" || typeof core.setDefaultChain !== "function" || typeof core.session?.topic !== "string") {
|
|
16751
16957
|
return null;
|
|
16752
16958
|
}
|
|
16753
16959
|
const peer = core.session.peer?.metadata?.name ?? "";
|
|
16754
|
-
if (
|
|
16755
|
-
|
|
16960
|
+
if (/metamask/i.test(peer)) {
|
|
16961
|
+
return { core, strategy: "remote-wallet" };
|
|
16962
|
+
}
|
|
16963
|
+
if (/fireblocks/i.test(peer)) {
|
|
16964
|
+
return { core, strategy: "session-default" };
|
|
16965
|
+
}
|
|
16966
|
+
return null;
|
|
16967
|
+
}
|
|
16968
|
+
function approvedChains(core) {
|
|
16969
|
+
const approved = /* @__PURE__ */ new Set();
|
|
16970
|
+
for (const namespace of Object.values(core.session.namespaces ?? {})) {
|
|
16971
|
+
for (const chain2 of namespace.chains ?? []) approved.add(chain2);
|
|
16972
|
+
for (const account of namespace.accounts ?? []) {
|
|
16973
|
+
const [namespaceName, reference] = account.split(":");
|
|
16974
|
+
if (namespaceName && reference) {
|
|
16975
|
+
approved.add(`${namespaceName}:${reference}`);
|
|
16976
|
+
}
|
|
16977
|
+
}
|
|
16978
|
+
}
|
|
16979
|
+
return approved;
|
|
16980
|
+
}
|
|
16981
|
+
async function selectSessionDefaultChain(core, chainId) {
|
|
16982
|
+
const target = `eip155:${chainId}`;
|
|
16983
|
+
if (!approvedChains(core).has(target)) {
|
|
16984
|
+
throw new Error(
|
|
16985
|
+
`The WalletConnect session has not approved ${target}. Reconnect the wallet and try again.`
|
|
16986
|
+
);
|
|
16987
|
+
}
|
|
16988
|
+
core.setDefaultChain(target);
|
|
16989
|
+
const selected = parseChainId(
|
|
16990
|
+
await core.request({ method: "eth_chainId" })
|
|
16991
|
+
);
|
|
16992
|
+
debugLog("wc-switch", "selected WalletConnect session default", {
|
|
16993
|
+
peer: core.session.peer?.metadata?.name,
|
|
16994
|
+
target: chainId,
|
|
16995
|
+
selected
|
|
16996
|
+
});
|
|
16997
|
+
if (selected !== chainId) {
|
|
16998
|
+
throw new Error(
|
|
16999
|
+
`WalletConnect stayed on chain ${selected ?? "unknown"}; expected ${chainId}.`
|
|
17000
|
+
);
|
|
17001
|
+
}
|
|
16756
17002
|
}
|
|
16757
17003
|
async function switchWalletConnectChain(provider, chainId, timeoutMs = WALLET_SWITCH_TIMEOUT_MS) {
|
|
16758
|
-
const
|
|
16759
|
-
if (!
|
|
17004
|
+
const session = walletConnectSession(provider);
|
|
17005
|
+
if (!session) return false;
|
|
17006
|
+
const { core, strategy } = session;
|
|
16760
17007
|
holds.get(core.session.topic)?.();
|
|
17008
|
+
if (strategy === "session-default") {
|
|
17009
|
+
await selectSessionDefaultChain(core, chainId);
|
|
17010
|
+
return true;
|
|
17011
|
+
}
|
|
16761
17012
|
await requestSwitch(core, provider, chainId, timeoutMs);
|
|
16762
|
-
holdChain(core,
|
|
17013
|
+
holdChain(core, chainId);
|
|
16763
17014
|
return true;
|
|
16764
17015
|
}
|
|
16765
17016
|
async function requestSwitch(core, provider, chainId, timeoutMs) {
|
|
16766
|
-
const current =
|
|
17017
|
+
const current = parseChainId(
|
|
16767
17018
|
await provider.request({ method: "eth_chainId" })
|
|
16768
17019
|
);
|
|
17020
|
+
if (current === void 0) {
|
|
17021
|
+
throw new Error("WalletConnect could not report its current chain.");
|
|
17022
|
+
}
|
|
16769
17023
|
const hexChainId = `0x${chainId.toString(16)}`;
|
|
16770
17024
|
let timer;
|
|
16771
17025
|
try {
|
|
@@ -16795,26 +17049,27 @@ async function requestSwitch(core, provider, chainId, timeoutMs) {
|
|
|
16795
17049
|
} catch {
|
|
16796
17050
|
}
|
|
16797
17051
|
}
|
|
16798
|
-
function holdChain(core,
|
|
17052
|
+
function holdChain(core, chainId) {
|
|
16799
17053
|
if (typeof core.on !== "function" || typeof core.removeListener !== "function") {
|
|
16800
17054
|
return;
|
|
16801
17055
|
}
|
|
16802
|
-
let
|
|
17056
|
+
let repins = 0;
|
|
16803
17057
|
const listener = (raw2) => {
|
|
16804
17058
|
const reported = parseChainId(raw2);
|
|
16805
17059
|
debugLog("wc-switch", "wallet reported chain", {
|
|
16806
17060
|
reported,
|
|
16807
17061
|
holding: chainId,
|
|
16808
|
-
|
|
17062
|
+
repins
|
|
16809
17063
|
});
|
|
16810
17064
|
if (reported === void 0 || reported === chainId) return;
|
|
16811
|
-
|
|
16812
|
-
|
|
16813
|
-
|
|
16814
|
-
|
|
17065
|
+
repins += 1;
|
|
17066
|
+
try {
|
|
17067
|
+
core.setDefaultChain(`eip155:${chainId}`);
|
|
17068
|
+
} catch (error) {
|
|
17069
|
+
debugLog("wc-switch", "session re-pin failed", {
|
|
16815
17070
|
error: error instanceof Error ? error.message : String(error)
|
|
16816
|
-
})
|
|
16817
|
-
|
|
17071
|
+
});
|
|
17072
|
+
}
|
|
16818
17073
|
};
|
|
16819
17074
|
const release = () => {
|
|
16820
17075
|
clearTimeout(timer);
|
|
@@ -16828,7 +17083,7 @@ function holdChain(core, provider, chainId) {
|
|
|
16828
17083
|
holds.set(core.session.topic, release);
|
|
16829
17084
|
}
|
|
16830
17085
|
function withWalletConnectSwitch(provider) {
|
|
16831
|
-
if (!
|
|
17086
|
+
if (!walletConnectSession(provider)) return provider;
|
|
16832
17087
|
const target = provider;
|
|
16833
17088
|
const request2 = async (args) => {
|
|
16834
17089
|
if (args?.method !== "wallet_switchEthereumChain") {
|
|
@@ -17178,6 +17433,7 @@ var OwneySDK = class {
|
|
|
17178
17433
|
yieldseekerApiBaseUrl;
|
|
17179
17434
|
yieldseekerSiweOrigin;
|
|
17180
17435
|
userPoolCustomization = false;
|
|
17436
|
+
excludedProtocols = [];
|
|
17181
17437
|
routingApiBaseUrl;
|
|
17182
17438
|
referralSource;
|
|
17183
17439
|
ledger;
|
|
@@ -17188,6 +17444,7 @@ var OwneySDK = class {
|
|
|
17188
17444
|
zyfaiServerTasks;
|
|
17189
17445
|
/** The caller opted in to the Fusion+ secret handoff (`fusionSecretHandoff: true`). */
|
|
17190
17446
|
fusionSecretHandoff;
|
|
17447
|
+
sessionStore;
|
|
17191
17448
|
cachedSponsoredCallback = null;
|
|
17192
17449
|
cachedWethSponsoredCallback = null;
|
|
17193
17450
|
paymasterServiceUrl;
|
|
@@ -17230,7 +17487,9 @@ var OwneySDK = class {
|
|
|
17230
17487
|
this.routingApiBaseUrl = config.routingApiBaseUrl;
|
|
17231
17488
|
this.paymasterServiceUrl = config.paymasterServiceUrl;
|
|
17232
17489
|
this.referralSource = config.referralSource;
|
|
17490
|
+
this.sessionStore = config.sessionStore;
|
|
17233
17491
|
this.userPoolCustomization = config.userPoolCustomization ?? false;
|
|
17492
|
+
this.excludedProtocols = config.excludedProtocols ?? [];
|
|
17234
17493
|
this.ledger = createFundingLedger({
|
|
17235
17494
|
apiKey: config.apiKey,
|
|
17236
17495
|
baseUrl: config.routingApiBaseUrl,
|
|
@@ -17985,7 +18244,9 @@ var OwneySDK = class {
|
|
|
17985
18244
|
// Only an explicit opt-in lets the agent hand the Zyfai session to
|
|
17986
18245
|
// Owney; a function is passed as it is and read per handoff.
|
|
17987
18246
|
...this.zyfaiServerTasks !== void 0 ? { zyfaiServerTasks: this.zyfaiServerTasks } : {}
|
|
17988
|
-
}
|
|
18247
|
+
},
|
|
18248
|
+
this.sessionStore,
|
|
18249
|
+
this.excludedProtocols
|
|
17989
18250
|
);
|
|
17990
18251
|
}
|
|
17991
18252
|
if (agentId === "yieldseeker") {
|