@owney/sdk 0.7.28-beta.8 → 0.7.29-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 CHANGED
@@ -134,6 +134,13 @@ Deposit funds into a specific agent, or split equally across all agents if `agen
134
134
  | `options.depositCallback` | `DepositCallback` | Callback that performs the token transfer and returns a tx hash |
135
135
  | `options.agentId` | `AgentId` (optional) | Target agent. Omit to split equally across all agents. |
136
136
 
137
+ Zyfai's native transfer path uses `sendDeposit()`. It returns after the token
138
+ transfer confirms and the deposit is registered, while balance credit may still
139
+ be queued. Balance reads reflect subsequent credit and allocation; the deposit
140
+ call does not wait for `waitForDepositCredit()`.
141
+ A successful deposit result confirms the transfer; it does not guarantee that
142
+ the funds are already credited or earning yield.
143
+
137
144
  Returns: `OwneyDepositResult` (single agent) or `OwneyMultiDepositResult` (all agents)
138
145
 
139
146
  ```typescript
package/dist/index.cjs CHANGED
@@ -1444,7 +1444,7 @@ var ZyfaiAgent = class _ZyfaiAgent {
1444
1444
  * chain/account switch fires the provider's `accountsChanged` →
1445
1445
  * `disconnectAccount` (nulls walletClient + authenticatedUserId) while our
1446
1446
  * own `connectAuth` guard still believes this chain is connected and
1447
- * early-returns. Without this, authenticated calls (depositFunds,
1447
+ * early-returns. Without this, authenticated calls (sendDeposit,
1448
1448
  * withdrawFunds) fail with "No account connected".
1449
1449
  */
1450
1450
  async ensureConnected(state, chainId) {
@@ -1529,12 +1529,16 @@ var ZyfaiAgent = class _ZyfaiAgent {
1529
1529
  }
1530
1530
  // --- IAgent: Account lifecycle ---
1531
1531
  async activateAgent(state, chainId) {
1532
+ const startedAt = Date.now();
1532
1533
  try {
1533
1534
  debugLog("zyfai:activation", "starting", {
1534
1535
  walletAddress: state.walletAddress,
1535
1536
  chainId
1536
1537
  });
1537
1538
  await this.connectAuth(state, chainId);
1539
+ debugLog("zyfai:activation", "signed in", {
1540
+ ms: Date.now() - startedAt
1541
+ });
1538
1542
  const validChainId = isValidChainId(chainId);
1539
1543
  await Promise.all([
1540
1544
  this.ensureProtocolsSynced(validChainId, "USDC"),
@@ -1545,7 +1549,10 @@ var ZyfaiAgent = class _ZyfaiAgent {
1545
1549
  // validator, so pool-wallet users see no prompt. Non-fatal.
1546
1550
  this.ensureSessionKeyIfDeployed(validChainId)
1547
1551
  ]);
1548
- debugLog("zyfai:activation", "completed", { chainId: validChainId });
1552
+ debugLog("zyfai:activation", "completed", {
1553
+ chainId: validChainId,
1554
+ ms: Date.now() - startedAt
1555
+ });
1549
1556
  } catch (error) {
1550
1557
  throw error;
1551
1558
  }
@@ -2231,8 +2238,10 @@ var ZyfaiAgent = class _ZyfaiAgent {
2231
2238
  }
2232
2239
  // --- IAgent: Portfolio reads ---
2233
2240
  async getBalances(state, chainId) {
2241
+ const startedAt = Date.now();
2234
2242
  const { smartWallet, chainId: validChainId } = await this.resolveSmartWallet(state, chainId);
2235
2243
  const raw = await this.sdk.getPortfolio(this.getAddress());
2244
+ debugLog("zyfai:balances", "read", { ms: Date.now() - startedAt });
2236
2245
  return mapBalances(raw, validChainId, smartWallet);
2237
2246
  }
2238
2247
  earningsKey(state, chainId, smartWallet) {
@@ -2927,9 +2936,24 @@ async function wrapNative(deps, options) {
2927
2936
  message: error instanceof Error ? error.message : String(error)
2928
2937
  });
2929
2938
  }
2939
+ let approvalPending = true;
2940
+ if (options.spender && deps.readAllowance) {
2941
+ try {
2942
+ const allowance = await deps.readAllowance(wrapper, options.spender);
2943
+ approvalPending = allowance < requested;
2944
+ } catch (error) {
2945
+ debugLog(
2946
+ "owney-sdk",
2947
+ "wrap: allowance read failed, assuming an approve",
2948
+ {
2949
+ message: error instanceof Error ? error.message : String(error)
2950
+ }
2951
+ );
2952
+ }
2953
+ }
2930
2954
  const measured = await deps.getMaxFeePerGas();
2931
2955
  const gasPrice = measured > MIN_WALLET_GAS_PRICE ? measured : MIN_WALLET_GAS_PRICE;
2932
- const reserve = (wrapGas + APPROVE_GAS) * gasPrice * GAS_SAFETY;
2956
+ const reserve = (wrapGas + (approvalPending ? APPROVE_GAS : 0n)) * gasPrice * GAS_SAFETY;
2933
2957
  const spendable = balance > reserve ? balance - reserve : 0n;
2934
2958
  const wrapped = requested < spendable ? requested : spendable;
2935
2959
  debugLog("owney-sdk", "wrap: sizing", {
@@ -2937,6 +2961,7 @@ async function wrapNative(deps, options) {
2937
2961
  requested: requested.toString(),
2938
2962
  measuredGasPrice: measured.toString(),
2939
2963
  reservedAtGasPrice: gasPrice.toString(),
2964
+ approvalPending,
2940
2965
  reserve: reserve.toString(),
2941
2966
  wrapped: wrapped.toString()
2942
2967
  });
@@ -3582,7 +3607,7 @@ async function runSameChainFusion(deps, options, walletAddress) {
3582
3607
  const isNativeSource = quote.src.address.toLowerCase().startsWith("0xeeee");
3583
3608
  const amount = isNativeSource ? BigInt(quote.src.amount) : await affordableAmount(deps, BigInt(quote.src.amount));
3584
3609
  const permit = await authoriseSpend(deps, options, amount, isNativeSource);
3585
- onStage?.("quoting");
3610
+ onStage?.("building");
3586
3611
  debugLog("owney-sdk", "swap: building same-chain fusion order");
3587
3612
  const built = await deps.api.buildOrder({
3588
3613
  from: {
@@ -3664,7 +3689,7 @@ async function runFusion(deps, options, walletAddress) {
3664
3689
  const amount = await affordableAmount(deps, BigInt(quote.src.amount));
3665
3690
  const permit = await authoriseSpend(deps, options, amount, false);
3666
3691
  const { secrets, secretHashes } = mintSecrets(quote.secretsCount ?? 1);
3667
- onStage?.("quoting");
3692
+ onStage?.("building");
3668
3693
  debugLog("owney-sdk", "swap: building fusion order", {
3669
3694
  secrets: secretHashes.length
3670
3695
  });
@@ -5018,8 +5043,9 @@ var OwneySDK = class {
5018
5043
  * that support the given chainId (incompatible agents are silently skipped).
5019
5044
  * If provided, ALL specified agents must support the chainId or the call
5020
5045
  * throws before activating any agent.
5046
+ * @param options - Optional. `onAgentsSelected` fires once reads can start.
5021
5047
  */
5022
- async activateAgent(chainId, agentId) {
5048
+ async activateAgent(chainId, agentId, options = {}) {
5023
5049
  const state = this.requireState();
5024
5050
  await this.ensureAgentsInitialized();
5025
5051
  if (agentId !== void 0) {
@@ -5055,6 +5081,7 @@ var OwneySDK = class {
5055
5081
  this.activeAgents.add(id);
5056
5082
  }
5057
5083
  state.chainId = chainId;
5084
+ options.onAgentsSelected?.();
5058
5085
  await this.activateAgentsInTurn(agents, state, chainId);
5059
5086
  return;
5060
5087
  }
@@ -5073,6 +5100,7 @@ var OwneySDK = class {
5073
5100
  this.activeAgents.add(agent.id);
5074
5101
  }
5075
5102
  state.chainId = chainId;
5103
+ options.onAgentsSelected?.();
5076
5104
  const enabledCompatible = compatible.filter(
5077
5105
  (agent) => !this.isAgentDisabled(agent.id)
5078
5106
  );
@@ -5572,13 +5600,25 @@ var OwneySDK = class {
5572
5600
  }
5573
5601
  return hash;
5574
5602
  },
5575
- ensureChain: (id) => this.ensureSwapChain(id)
5603
+ ensureChain: (id) => this.ensureSwapChain(id),
5604
+ // Read through the same public client as every other sizing input, so
5605
+ // a wallet sitting on the wrong chain cannot answer for this one.
5606
+ readAllowance: (token, spender) => publicClient.readContract({
5607
+ address: token,
5608
+ abi: ERC20_ALLOWANCE_ABI,
5609
+ functionName: "allowance",
5610
+ args: [walletAddress, spender]
5611
+ })
5576
5612
  },
5577
5613
  {
5578
5614
  chainId,
5579
5615
  wrapper: wrapper.address,
5580
5616
  nativeSymbol: quote.src.symbol,
5581
5617
  requested: BigInt(quote.src.amount),
5618
+ // Lets the reserve skip the approve's gas when one is already in
5619
+ // place. Absent on a quote that names no spender, which keeps the
5620
+ // full reserve (ROUT-242, comment 16234).
5621
+ ...quote.spender ? { spender: quote.spender } : {},
5582
5622
  onSubmitted: () => onStage?.("wrapped")
5583
5623
  }
5584
5624
  );
package/dist/index.d.cts CHANGED
@@ -220,7 +220,7 @@ type SwapOrderStatus = "pending" | "executed" | "expired" | "cancelled" | "refun
220
220
  * of the flow and the one place a user would otherwise think nothing is
221
221
  * happening.
222
222
  */
223
- type SwapStage = "withdrawing" | "withdrawn" | "quoting" | "wrapping" | "wrapped" | "approving" | "signing" | "swapping" | "swapped" | "depositing" | "refunding" | "refunded";
223
+ type SwapStage = "withdrawing" | "withdrawn" | "quoting" | "wrapping" | "wrapped" | "approving" | "building" | "signing" | "swapping" | "swapped" | "depositing" | "refunding" | "refunded";
224
224
  /**
225
225
  * Which way the funds travel, which decides what each side may be.
226
226
  *
@@ -326,6 +326,15 @@ type AvailableAgent = {
326
326
  supportedChainIds: readonly number[];
327
327
  supportedAssets: readonly AgentSupportedAssets[];
328
328
  };
329
+ type ActivateAgentOptions = {
330
+ /**
331
+ * Called once the chain and agents are registered, before any agent signs in
332
+ * or runs its setup. From then on reads such as `getBalances` are safe to
333
+ * start: each agent's reads wait on that agent's own sign-in, so they share
334
+ * the activation's one wallet prompt instead of waiting for all of setup.
335
+ */
336
+ onAgentsSelected?: () => void;
337
+ };
329
338
  type AvailableAgentsOptions = {
330
339
  chainId?: number;
331
340
  asset?: Asset;
@@ -1260,8 +1269,9 @@ declare class OwneySDK {
1260
1269
  * that support the given chainId (incompatible agents are silently skipped).
1261
1270
  * If provided, ALL specified agents must support the chainId or the call
1262
1271
  * throws before activating any agent.
1272
+ * @param options - Optional. `onAgentsSelected` fires once reads can start.
1263
1273
  */
1264
- activateAgent(chainId: number, agentId?: AgentId[]): Promise<void>;
1274
+ activateAgent(chainId: number, agentId?: AgentId[], options?: ActivateAgentOptions): Promise<void>;
1265
1275
  /**
1266
1276
  * Activate agents ONE AT A TIME, each followed by its org policy.
1267
1277
  *
@@ -1979,4 +1989,4 @@ type StoredOrder = {
1979
1989
  */
1980
1990
  declare function listOrders(now?: number): StoredOrder[];
1981
1991
 
1982
- export { type AccountAgentApy, type AccountApyOptions, type AccountDailyEarnings, type AgentApy, type AgentApyDetails, type AgentBalance, AgentChainIncompatibleError, type AgentEarnings, type AgentHistoryEntry, type AgentHistoryPosition, type AgentId, AgentNotFoundError, type AgentSupportedAsset, type AgentSupportedAssets, type AgentUserProfile, type AgentWithdrawResult, type AgentsApyOptions, type AllocationAgentApy, type AllocationApyOptions, type ApyByChainAndAsset, type ApyCoverage, type ApyHistoryPoint, type Asset, type AssetDailyEarnings, type AvailableAgent, type AvailableAgentsOptions, type AvailablePool, type ConnectionState, type DailyApyDays, type DailyEarningsOptions, type DailyEarningsPoint, type DepositCallback, type DepositOptions, type HistoryAction, type HistoryFilters, type HistoryOptions, type HistoryTransaction, type IAgent, InvalidHistoryCursorError, type LookbackDays, NotConnectedError, type OrgPoolPolicy, type OrgPoolSelection, type OwneyAccountApy, type OwneyAgentApy, type OwneyAgentHistory, type OwneyAllocationApy, type OwneyBalances, type OwneyDepositResult, type OwneyEarnings, OwneyError, type OwneyErrorCode, type OwneyMultiDepositResult, type OwneyPosition, OwneySDK, type OwneySDKConfig, type OwneySIWXConfig, type OwneySupportedChainId, type OwneySupportedChains, type OwneySupportedTokens, type OwneyToken, type OwneyUserProfile, type OwneyWithdrawAllLeg, type OwneyWithdrawAllResult, type OwneyWithdrawResult, type PendingDeposit, type PoolCatalogProtocol, type PoolSelectionStrategy, type RebalanceLog, type SavedPoolSelection, type SwapChainTokens, type SwapDirection, type SwapOrderStatus, type SwapQuote, type SwapQuoteParams, type SwapRail, type SwapStage, type SwapTokenInfo, type SwapTokenSearchResult, type UserPoolSelection, type UserPoolSelectionRequest, type WithdrawOptions, type WithdrawSwapRecord, type WithdrawSwapStatus, clearWithdrawSwap, createOwneySIWX, listPendingDeposits, listOrders as listPendingSwaps, listWithdrawSwaps, saveWithdrawSwap, setOwneyDebug, subscribeWithdrawSwaps, updateWithdrawSwap };
1992
+ export { type AccountAgentApy, type AccountApyOptions, type AccountDailyEarnings, type ActivateAgentOptions, type AgentApy, type AgentApyDetails, type AgentBalance, AgentChainIncompatibleError, type AgentEarnings, type AgentHistoryEntry, type AgentHistoryPosition, type AgentId, AgentNotFoundError, type AgentSupportedAsset, type AgentSupportedAssets, type AgentUserProfile, type AgentWithdrawResult, type AgentsApyOptions, type AllocationAgentApy, type AllocationApyOptions, type ApyByChainAndAsset, type ApyCoverage, type ApyHistoryPoint, type Asset, type AssetDailyEarnings, type AvailableAgent, type AvailableAgentsOptions, type AvailablePool, type ConnectionState, type DailyApyDays, type DailyEarningsOptions, type DailyEarningsPoint, type DepositCallback, type DepositOptions, type HistoryAction, type HistoryFilters, type HistoryOptions, type HistoryTransaction, type IAgent, InvalidHistoryCursorError, type LookbackDays, NotConnectedError, type OrgPoolPolicy, type OrgPoolSelection, type OwneyAccountApy, type OwneyAgentApy, type OwneyAgentHistory, type OwneyAllocationApy, type OwneyBalances, type OwneyDepositResult, type OwneyEarnings, OwneyError, type OwneyErrorCode, type OwneyMultiDepositResult, type OwneyPosition, OwneySDK, type OwneySDKConfig, type OwneySIWXConfig, type OwneySupportedChainId, type OwneySupportedChains, type OwneySupportedTokens, type OwneyToken, type OwneyUserProfile, type OwneyWithdrawAllLeg, type OwneyWithdrawAllResult, type OwneyWithdrawResult, type PendingDeposit, type PoolCatalogProtocol, type PoolSelectionStrategy, type RebalanceLog, type SavedPoolSelection, type SwapChainTokens, type SwapDirection, type SwapOrderStatus, type SwapQuote, type SwapQuoteParams, type SwapRail, type SwapStage, type SwapTokenInfo, type SwapTokenSearchResult, type UserPoolSelection, type UserPoolSelectionRequest, type WithdrawOptions, type WithdrawSwapRecord, type WithdrawSwapStatus, clearWithdrawSwap, createOwneySIWX, listPendingDeposits, listOrders as listPendingSwaps, listWithdrawSwaps, saveWithdrawSwap, setOwneyDebug, subscribeWithdrawSwaps, updateWithdrawSwap };
package/dist/index.d.ts CHANGED
@@ -220,7 +220,7 @@ type SwapOrderStatus = "pending" | "executed" | "expired" | "cancelled" | "refun
220
220
  * of the flow and the one place a user would otherwise think nothing is
221
221
  * happening.
222
222
  */
223
- type SwapStage = "withdrawing" | "withdrawn" | "quoting" | "wrapping" | "wrapped" | "approving" | "signing" | "swapping" | "swapped" | "depositing" | "refunding" | "refunded";
223
+ type SwapStage = "withdrawing" | "withdrawn" | "quoting" | "wrapping" | "wrapped" | "approving" | "building" | "signing" | "swapping" | "swapped" | "depositing" | "refunding" | "refunded";
224
224
  /**
225
225
  * Which way the funds travel, which decides what each side may be.
226
226
  *
@@ -326,6 +326,15 @@ type AvailableAgent = {
326
326
  supportedChainIds: readonly number[];
327
327
  supportedAssets: readonly AgentSupportedAssets[];
328
328
  };
329
+ type ActivateAgentOptions = {
330
+ /**
331
+ * Called once the chain and agents are registered, before any agent signs in
332
+ * or runs its setup. From then on reads such as `getBalances` are safe to
333
+ * start: each agent's reads wait on that agent's own sign-in, so they share
334
+ * the activation's one wallet prompt instead of waiting for all of setup.
335
+ */
336
+ onAgentsSelected?: () => void;
337
+ };
329
338
  type AvailableAgentsOptions = {
330
339
  chainId?: number;
331
340
  asset?: Asset;
@@ -1260,8 +1269,9 @@ declare class OwneySDK {
1260
1269
  * that support the given chainId (incompatible agents are silently skipped).
1261
1270
  * If provided, ALL specified agents must support the chainId or the call
1262
1271
  * throws before activating any agent.
1272
+ * @param options - Optional. `onAgentsSelected` fires once reads can start.
1263
1273
  */
1264
- activateAgent(chainId: number, agentId?: AgentId[]): Promise<void>;
1274
+ activateAgent(chainId: number, agentId?: AgentId[], options?: ActivateAgentOptions): Promise<void>;
1265
1275
  /**
1266
1276
  * Activate agents ONE AT A TIME, each followed by its org policy.
1267
1277
  *
@@ -1979,4 +1989,4 @@ type StoredOrder = {
1979
1989
  */
1980
1990
  declare function listOrders(now?: number): StoredOrder[];
1981
1991
 
1982
- export { type AccountAgentApy, type AccountApyOptions, type AccountDailyEarnings, type AgentApy, type AgentApyDetails, type AgentBalance, AgentChainIncompatibleError, type AgentEarnings, type AgentHistoryEntry, type AgentHistoryPosition, type AgentId, AgentNotFoundError, type AgentSupportedAsset, type AgentSupportedAssets, type AgentUserProfile, type AgentWithdrawResult, type AgentsApyOptions, type AllocationAgentApy, type AllocationApyOptions, type ApyByChainAndAsset, type ApyCoverage, type ApyHistoryPoint, type Asset, type AssetDailyEarnings, type AvailableAgent, type AvailableAgentsOptions, type AvailablePool, type ConnectionState, type DailyApyDays, type DailyEarningsOptions, type DailyEarningsPoint, type DepositCallback, type DepositOptions, type HistoryAction, type HistoryFilters, type HistoryOptions, type HistoryTransaction, type IAgent, InvalidHistoryCursorError, type LookbackDays, NotConnectedError, type OrgPoolPolicy, type OrgPoolSelection, type OwneyAccountApy, type OwneyAgentApy, type OwneyAgentHistory, type OwneyAllocationApy, type OwneyBalances, type OwneyDepositResult, type OwneyEarnings, OwneyError, type OwneyErrorCode, type OwneyMultiDepositResult, type OwneyPosition, OwneySDK, type OwneySDKConfig, type OwneySIWXConfig, type OwneySupportedChainId, type OwneySupportedChains, type OwneySupportedTokens, type OwneyToken, type OwneyUserProfile, type OwneyWithdrawAllLeg, type OwneyWithdrawAllResult, type OwneyWithdrawResult, type PendingDeposit, type PoolCatalogProtocol, type PoolSelectionStrategy, type RebalanceLog, type SavedPoolSelection, type SwapChainTokens, type SwapDirection, type SwapOrderStatus, type SwapQuote, type SwapQuoteParams, type SwapRail, type SwapStage, type SwapTokenInfo, type SwapTokenSearchResult, type UserPoolSelection, type UserPoolSelectionRequest, type WithdrawOptions, type WithdrawSwapRecord, type WithdrawSwapStatus, clearWithdrawSwap, createOwneySIWX, listPendingDeposits, listOrders as listPendingSwaps, listWithdrawSwaps, saveWithdrawSwap, setOwneyDebug, subscribeWithdrawSwaps, updateWithdrawSwap };
1992
+ export { type AccountAgentApy, type AccountApyOptions, type AccountDailyEarnings, type ActivateAgentOptions, type AgentApy, type AgentApyDetails, type AgentBalance, AgentChainIncompatibleError, type AgentEarnings, type AgentHistoryEntry, type AgentHistoryPosition, type AgentId, AgentNotFoundError, type AgentSupportedAsset, type AgentSupportedAssets, type AgentUserProfile, type AgentWithdrawResult, type AgentsApyOptions, type AllocationAgentApy, type AllocationApyOptions, type ApyByChainAndAsset, type ApyCoverage, type ApyHistoryPoint, type Asset, type AssetDailyEarnings, type AvailableAgent, type AvailableAgentsOptions, type AvailablePool, type ConnectionState, type DailyApyDays, type DailyEarningsOptions, type DailyEarningsPoint, type DepositCallback, type DepositOptions, type HistoryAction, type HistoryFilters, type HistoryOptions, type HistoryTransaction, type IAgent, InvalidHistoryCursorError, type LookbackDays, NotConnectedError, type OrgPoolPolicy, type OrgPoolSelection, type OwneyAccountApy, type OwneyAgentApy, type OwneyAgentHistory, type OwneyAllocationApy, type OwneyBalances, type OwneyDepositResult, type OwneyEarnings, OwneyError, type OwneyErrorCode, type OwneyMultiDepositResult, type OwneyPosition, OwneySDK, type OwneySDKConfig, type OwneySIWXConfig, type OwneySupportedChainId, type OwneySupportedChains, type OwneySupportedTokens, type OwneyToken, type OwneyUserProfile, type OwneyWithdrawAllLeg, type OwneyWithdrawAllResult, type OwneyWithdrawResult, type PendingDeposit, type PoolCatalogProtocol, type PoolSelectionStrategy, type RebalanceLog, type SavedPoolSelection, type SwapChainTokens, type SwapDirection, type SwapOrderStatus, type SwapQuote, type SwapQuoteParams, type SwapRail, type SwapStage, type SwapTokenInfo, type SwapTokenSearchResult, type UserPoolSelection, type UserPoolSelectionRequest, type WithdrawOptions, type WithdrawSwapRecord, type WithdrawSwapStatus, clearWithdrawSwap, createOwneySIWX, listPendingDeposits, listOrders as listPendingSwaps, listWithdrawSwaps, saveWithdrawSwap, setOwneyDebug, subscribeWithdrawSwaps, updateWithdrawSwap };
package/dist/index.js CHANGED
@@ -1404,7 +1404,7 @@ var ZyfaiAgent = class _ZyfaiAgent {
1404
1404
  * chain/account switch fires the provider's `accountsChanged` →
1405
1405
  * `disconnectAccount` (nulls walletClient + authenticatedUserId) while our
1406
1406
  * own `connectAuth` guard still believes this chain is connected and
1407
- * early-returns. Without this, authenticated calls (depositFunds,
1407
+ * early-returns. Without this, authenticated calls (sendDeposit,
1408
1408
  * withdrawFunds) fail with "No account connected".
1409
1409
  */
1410
1410
  async ensureConnected(state, chainId) {
@@ -1489,12 +1489,16 @@ var ZyfaiAgent = class _ZyfaiAgent {
1489
1489
  }
1490
1490
  // --- IAgent: Account lifecycle ---
1491
1491
  async activateAgent(state, chainId) {
1492
+ const startedAt = Date.now();
1492
1493
  try {
1493
1494
  debugLog("zyfai:activation", "starting", {
1494
1495
  walletAddress: state.walletAddress,
1495
1496
  chainId
1496
1497
  });
1497
1498
  await this.connectAuth(state, chainId);
1499
+ debugLog("zyfai:activation", "signed in", {
1500
+ ms: Date.now() - startedAt
1501
+ });
1498
1502
  const validChainId = isValidChainId(chainId);
1499
1503
  await Promise.all([
1500
1504
  this.ensureProtocolsSynced(validChainId, "USDC"),
@@ -1505,7 +1509,10 @@ var ZyfaiAgent = class _ZyfaiAgent {
1505
1509
  // validator, so pool-wallet users see no prompt. Non-fatal.
1506
1510
  this.ensureSessionKeyIfDeployed(validChainId)
1507
1511
  ]);
1508
- debugLog("zyfai:activation", "completed", { chainId: validChainId });
1512
+ debugLog("zyfai:activation", "completed", {
1513
+ chainId: validChainId,
1514
+ ms: Date.now() - startedAt
1515
+ });
1509
1516
  } catch (error) {
1510
1517
  throw error;
1511
1518
  }
@@ -2191,8 +2198,10 @@ var ZyfaiAgent = class _ZyfaiAgent {
2191
2198
  }
2192
2199
  // --- IAgent: Portfolio reads ---
2193
2200
  async getBalances(state, chainId) {
2201
+ const startedAt = Date.now();
2194
2202
  const { smartWallet, chainId: validChainId } = await this.resolveSmartWallet(state, chainId);
2195
2203
  const raw = await this.sdk.getPortfolio(this.getAddress());
2204
+ debugLog("zyfai:balances", "read", { ms: Date.now() - startedAt });
2196
2205
  return mapBalances(raw, validChainId, smartWallet);
2197
2206
  }
2198
2207
  earningsKey(state, chainId, smartWallet) {
@@ -2887,9 +2896,24 @@ async function wrapNative(deps, options) {
2887
2896
  message: error instanceof Error ? error.message : String(error)
2888
2897
  });
2889
2898
  }
2899
+ let approvalPending = true;
2900
+ if (options.spender && deps.readAllowance) {
2901
+ try {
2902
+ const allowance = await deps.readAllowance(wrapper, options.spender);
2903
+ approvalPending = allowance < requested;
2904
+ } catch (error) {
2905
+ debugLog(
2906
+ "owney-sdk",
2907
+ "wrap: allowance read failed, assuming an approve",
2908
+ {
2909
+ message: error instanceof Error ? error.message : String(error)
2910
+ }
2911
+ );
2912
+ }
2913
+ }
2890
2914
  const measured = await deps.getMaxFeePerGas();
2891
2915
  const gasPrice = measured > MIN_WALLET_GAS_PRICE ? measured : MIN_WALLET_GAS_PRICE;
2892
- const reserve = (wrapGas + APPROVE_GAS) * gasPrice * GAS_SAFETY;
2916
+ const reserve = (wrapGas + (approvalPending ? APPROVE_GAS : 0n)) * gasPrice * GAS_SAFETY;
2893
2917
  const spendable = balance > reserve ? balance - reserve : 0n;
2894
2918
  const wrapped = requested < spendable ? requested : spendable;
2895
2919
  debugLog("owney-sdk", "wrap: sizing", {
@@ -2897,6 +2921,7 @@ async function wrapNative(deps, options) {
2897
2921
  requested: requested.toString(),
2898
2922
  measuredGasPrice: measured.toString(),
2899
2923
  reservedAtGasPrice: gasPrice.toString(),
2924
+ approvalPending,
2900
2925
  reserve: reserve.toString(),
2901
2926
  wrapped: wrapped.toString()
2902
2927
  });
@@ -3552,7 +3577,7 @@ async function runSameChainFusion(deps, options, walletAddress) {
3552
3577
  const isNativeSource = quote.src.address.toLowerCase().startsWith("0xeeee");
3553
3578
  const amount = isNativeSource ? BigInt(quote.src.amount) : await affordableAmount(deps, BigInt(quote.src.amount));
3554
3579
  const permit = await authoriseSpend(deps, options, amount, isNativeSource);
3555
- onStage?.("quoting");
3580
+ onStage?.("building");
3556
3581
  debugLog("owney-sdk", "swap: building same-chain fusion order");
3557
3582
  const built = await deps.api.buildOrder({
3558
3583
  from: {
@@ -3634,7 +3659,7 @@ async function runFusion(deps, options, walletAddress) {
3634
3659
  const amount = await affordableAmount(deps, BigInt(quote.src.amount));
3635
3660
  const permit = await authoriseSpend(deps, options, amount, false);
3636
3661
  const { secrets, secretHashes } = mintSecrets(quote.secretsCount ?? 1);
3637
- onStage?.("quoting");
3662
+ onStage?.("building");
3638
3663
  debugLog("owney-sdk", "swap: building fusion order", {
3639
3664
  secrets: secretHashes.length
3640
3665
  });
@@ -4999,8 +5024,9 @@ var OwneySDK = class {
4999
5024
  * that support the given chainId (incompatible agents are silently skipped).
5000
5025
  * If provided, ALL specified agents must support the chainId or the call
5001
5026
  * throws before activating any agent.
5027
+ * @param options - Optional. `onAgentsSelected` fires once reads can start.
5002
5028
  */
5003
- async activateAgent(chainId, agentId) {
5029
+ async activateAgent(chainId, agentId, options = {}) {
5004
5030
  const state = this.requireState();
5005
5031
  await this.ensureAgentsInitialized();
5006
5032
  if (agentId !== void 0) {
@@ -5036,6 +5062,7 @@ var OwneySDK = class {
5036
5062
  this.activeAgents.add(id);
5037
5063
  }
5038
5064
  state.chainId = chainId;
5065
+ options.onAgentsSelected?.();
5039
5066
  await this.activateAgentsInTurn(agents, state, chainId);
5040
5067
  return;
5041
5068
  }
@@ -5054,6 +5081,7 @@ var OwneySDK = class {
5054
5081
  this.activeAgents.add(agent.id);
5055
5082
  }
5056
5083
  state.chainId = chainId;
5084
+ options.onAgentsSelected?.();
5057
5085
  const enabledCompatible = compatible.filter(
5058
5086
  (agent) => !this.isAgentDisabled(agent.id)
5059
5087
  );
@@ -5553,13 +5581,25 @@ var OwneySDK = class {
5553
5581
  }
5554
5582
  return hash;
5555
5583
  },
5556
- ensureChain: (id) => this.ensureSwapChain(id)
5584
+ ensureChain: (id) => this.ensureSwapChain(id),
5585
+ // Read through the same public client as every other sizing input, so
5586
+ // a wallet sitting on the wrong chain cannot answer for this one.
5587
+ readAllowance: (token, spender) => publicClient.readContract({
5588
+ address: token,
5589
+ abi: ERC20_ALLOWANCE_ABI,
5590
+ functionName: "allowance",
5591
+ args: [walletAddress, spender]
5592
+ })
5557
5593
  },
5558
5594
  {
5559
5595
  chainId,
5560
5596
  wrapper: wrapper.address,
5561
5597
  nativeSymbol: quote.src.symbol,
5562
5598
  requested: BigInt(quote.src.amount),
5599
+ // Lets the reserve skip the approve's gas when one is already in
5600
+ // place. Absent on a quote that names no spender, which keeps the
5601
+ // full reserve (ROUT-242, comment 16234).
5602
+ ...quote.spender ? { spender: quote.spender } : {},
5563
5603
  onSubmitted: () => onStage?.("wrapped")
5564
5604
  }
5565
5605
  );
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@owney/sdk",
3
- "version": "0.7.28-beta.8",
3
+ "version": "0.7.29-beta.0",
4
4
  "type": "module",
5
5
  "main": "dist/index.cjs",
6
6
  "module": "dist/index.js",