@owney/sdk 0.7.29 → 0.7.31-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/dist/index.cjs CHANGED
@@ -34,6 +34,7 @@ __export(index_exports, {
34
34
  saveWithdrawSwap: () => saveWithdrawSwap,
35
35
  setOwneyDebug: () => setOwneyDebug,
36
36
  subscribeWithdrawSwaps: () => subscribeWithdrawSwaps,
37
+ switchWalletConnectChain: () => switchWalletConnectChain,
37
38
  updateWithdrawSwap: () => updateWithdrawSwap
38
39
  });
39
40
  module.exports = __toCommonJS(index_exports);
@@ -2982,6 +2983,8 @@ var FALLBACK_WRAP_GAS = 50000n;
2982
2983
  var APPROVE_GAS = 60000n;
2983
2984
  var GAS_SAFETY = 2n;
2984
2985
  var MIN_WALLET_GAS_PRICE = 3000000000n;
2986
+ var WRAP_WATCH_INTERVAL_MS = 4e3;
2987
+ var WRAP_PROMPT_TIMEOUT_MS = 5 * 60 * 1e3;
2985
2988
  async function wrapNative(deps, options) {
2986
2989
  const { chainId, wrapper, nativeSymbol, requested } = options;
2987
2990
  const balance = await deps.readNativeBalance();
@@ -3039,16 +3042,90 @@ async function wrapNative(deps, options) {
3039
3042
  }
3040
3043
  );
3041
3044
  }
3045
+ let baseline;
3046
+ if (deps.readWrappedBalance) {
3047
+ try {
3048
+ baseline = await deps.readWrappedBalance();
3049
+ } catch (error) {
3050
+ debugLog("owney-sdk", "wrap: balance read failed, not watching", {
3051
+ message: error instanceof Error ? error.message : String(error)
3052
+ });
3053
+ }
3054
+ }
3042
3055
  await deps.ensureChain(chainId);
3043
3056
  debugLog("owney-sdk", "wrap: sending deposit()", {
3044
3057
  wrapper,
3045
3058
  value: wrapped.toString()
3046
3059
  });
3047
- const txHash = await deps.sendTransaction(
3048
- { to: wrapper, data: WRAP_SELECTOR, value: wrapped.toString() },
3049
- options.onSubmitted
3050
- );
3051
- return { wrapped, txHash };
3060
+ let notified = false;
3061
+ const notify2 = (hash) => {
3062
+ if (notified) return;
3063
+ notified = true;
3064
+ options.onSubmitted?.(hash);
3065
+ };
3066
+ const outcome = await new Promise((resolve, reject) => {
3067
+ let done = false;
3068
+ let timer;
3069
+ const finish = (settle) => {
3070
+ if (done) return;
3071
+ done = true;
3072
+ clearTimeout(timer);
3073
+ settle();
3074
+ };
3075
+ timer = setTimeout(
3076
+ () => finish(
3077
+ () => reject(
3078
+ new OwneyError(
3079
+ "SWAP_WALLET_PROMPT_TIMEOUT",
3080
+ // Hedged on purpose: a wallet that never answered may still have
3081
+ // sent it, and wrapping again would wrap twice.
3082
+ `Your wallet didn't answer the request to wrap your ${nativeSymbol}. Check your wallet before trying again \u2014 if the wrap went through, your funds are there as wrapped ${nativeSymbol}.`,
3083
+ { chainId, prompt: "wrap", timeoutMs: WRAP_PROMPT_TIMEOUT_MS }
3084
+ )
3085
+ )
3086
+ ),
3087
+ WRAP_PROMPT_TIMEOUT_MS
3088
+ );
3089
+ deps.sendTransaction(
3090
+ { to: wrapper, data: WRAP_SELECTOR, value: wrapped.toString() },
3091
+ (hash) => {
3092
+ clearTimeout(timer);
3093
+ notify2(hash);
3094
+ }
3095
+ ).then(
3096
+ (txHash) => finish(() => resolve({ txHash })),
3097
+ (error) => finish(() => reject(error))
3098
+ );
3099
+ if (baseline !== void 0 && deps.readWrappedBalance) {
3100
+ const read = deps.readWrappedBalance;
3101
+ const target = baseline + wrapped;
3102
+ const sleep2 = deps.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms)));
3103
+ void (async () => {
3104
+ while (!done) {
3105
+ await sleep2(WRAP_WATCH_INTERVAL_MS);
3106
+ if (done) return;
3107
+ try {
3108
+ if (await read() >= target) {
3109
+ debugLog(
3110
+ "owney-sdk",
3111
+ "wrap: landed on chain before the wallet answered"
3112
+ );
3113
+ finish(() => {
3114
+ notify2();
3115
+ resolve({});
3116
+ });
3117
+ return;
3118
+ }
3119
+ } catch {
3120
+ }
3121
+ }
3122
+ })();
3123
+ }
3124
+ });
3125
+ return {
3126
+ wrapped,
3127
+ ...outcome.txHash ? { txHash: outcome.txHash } : {}
3128
+ };
3052
3129
  }
3053
3130
  function requireWrapper(quote) {
3054
3131
  const wrapper = quote.wrappedNative;
@@ -4511,6 +4588,76 @@ function makeSponsoredDepositCallback(deps) {
4511
4588
  };
4512
4589
  }
4513
4590
 
4591
+ // src/lib/walletconnect-switch.ts
4592
+ var WALLET_SWITCH_TIMEOUT_MS = 12e4;
4593
+ function walletConnectCore(provider) {
4594
+ const p = provider;
4595
+ const core = p?.signer ?? p;
4596
+ if (typeof core?.client?.request !== "function" || typeof core.setDefaultChain !== "function" || typeof core.session?.topic !== "string") {
4597
+ return null;
4598
+ }
4599
+ const peer = core.session.peer?.metadata?.name ?? "";
4600
+ if (!/metamask/i.test(peer)) return null;
4601
+ return core;
4602
+ }
4603
+ async function switchWalletConnectChain(provider, chainId, timeoutMs = WALLET_SWITCH_TIMEOUT_MS) {
4604
+ const core = walletConnectCore(provider);
4605
+ if (!core) return false;
4606
+ const current = Number(
4607
+ await provider.request({ method: "eth_chainId" })
4608
+ );
4609
+ const hexChainId = `0x${chainId.toString(16)}`;
4610
+ let timer;
4611
+ try {
4612
+ await Promise.race([
4613
+ core.client.request({
4614
+ topic: core.session.topic,
4615
+ chainId: `eip155:${current}`,
4616
+ request: {
4617
+ method: "wallet_switchEthereumChain",
4618
+ params: [{ chainId: hexChainId }]
4619
+ }
4620
+ }),
4621
+ new Promise((_, reject) => {
4622
+ timer = setTimeout(
4623
+ () => reject(
4624
+ new Error("The wallet did not answer the network switch in time")
4625
+ ),
4626
+ timeoutMs
4627
+ );
4628
+ })
4629
+ ]);
4630
+ } finally {
4631
+ clearTimeout(timer);
4632
+ }
4633
+ try {
4634
+ core.setDefaultChain(`eip155:${chainId}`);
4635
+ } catch {
4636
+ }
4637
+ return true;
4638
+ }
4639
+ function withWalletConnectSwitch(provider) {
4640
+ if (!walletConnectCore(provider)) return provider;
4641
+ const target = provider;
4642
+ const request2 = async (args) => {
4643
+ if (args?.method !== "wallet_switchEthereumChain") {
4644
+ return target.request(args);
4645
+ }
4646
+ const [param] = args.params ?? [];
4647
+ const chainId = Number.parseInt(param?.chainId ?? "", 16);
4648
+ if (!Number.isFinite(chainId)) return target.request(args);
4649
+ await switchWalletConnectChain(target, chainId);
4650
+ return null;
4651
+ };
4652
+ return new Proxy(target, {
4653
+ get(obj, prop) {
4654
+ if (prop === "request") return request2;
4655
+ const value = Reflect.get(obj, prop, obj);
4656
+ return typeof value === "function" ? value.bind(obj) : value;
4657
+ }
4658
+ });
4659
+ }
4660
+
4514
4661
  // src/lib/sponsored-weth-deposit.ts
4515
4662
  var PERMIT_WINDOW_SECONDS = 15 * 60;
4516
4663
  function makeSponsoredWethCallback(deps) {
@@ -4809,7 +4956,11 @@ var OwneySDK = class {
4809
4956
  }
4810
4957
  this.agentReads.clearInFlight();
4811
4958
  this.activationChecks.clear();
4812
- this.state = { provider, walletAddress, chainId: null };
4959
+ this.state = {
4960
+ provider: withWalletConnectSwitch(provider),
4961
+ walletAddress,
4962
+ chainId: null
4963
+ };
4813
4964
  this.cachedSponsoredCallback = null;
4814
4965
  this.cachedWethSponsoredCallback = null;
4815
4966
  this.cachedSponsoredCallsCallbacks.clear();
@@ -5660,6 +5811,14 @@ var OwneySDK = class {
5660
5811
  return hash;
5661
5812
  },
5662
5813
  ensureChain: (id) => this.ensureSwapChain(id),
5814
+ // Over HTTP, so a wallet that broadcast the wrap without telling the
5815
+ // page cannot also hide that it landed (ROUT-726).
5816
+ readWrappedBalance: () => publicClient.readContract({
5817
+ address: wrapper.address,
5818
+ abi: ERC20_ALLOWANCE_ABI,
5819
+ functionName: "balanceOf",
5820
+ args: [walletAddress]
5821
+ }),
5663
5822
  // Read through the same public client as every other sizing input, so
5664
5823
  // a wallet sitting on the wrong chain cannot answer for this one.
5665
5824
  readAllowance: (token, spender) => publicClient.readContract({
@@ -7625,5 +7784,6 @@ function createOwneySIWX(config) {
7625
7784
  saveWithdrawSwap,
7626
7785
  setOwneyDebug,
7627
7786
  subscribeWithdrawSwaps,
7787
+ switchWalletConnectChain,
7628
7788
  updateWithdrawSwap
7629
7789
  });
package/dist/index.d.cts CHANGED
@@ -1953,6 +1953,23 @@ type OwneySIWXConfig = {
1953
1953
  */
1954
1954
  declare function createOwneySIWX(config: OwneySIWXConfig): SIWXConfig;
1955
1955
 
1956
+ /**
1957
+ * Ask the wallet ITSELF to switch networks, over WalletConnect.
1958
+ *
1959
+ * WalletConnect's provider answers `wallet_switchEthereumChain` locally when
1960
+ * the chain was approved at connect time: it moves its own default chain and
1961
+ * reports success without telling the wallet. MetaMask mobile then stays on
1962
+ * its network, keeps reporting it, and every guard downstream fails with
1963
+ * CHAIN_MISMATCH — after a swap, with the user's funds already moved (ROUT-727).
1964
+ * Sending the request through the session client reaches the wallet, which
1965
+ * shows a real "switch network" prompt; the client also deep-links the wallet
1966
+ * app open on mobile.
1967
+ *
1968
+ * Returns false when `provider` is not a WalletConnect session, so the caller
1969
+ * can fall back to an ordinary switch.
1970
+ */
1971
+ declare function switchWalletConnectChain(provider: unknown, chainId: number, timeoutMs?: number): Promise<boolean>;
1972
+
1956
1973
  /**
1957
1974
  * Persists cross-chain swap secrets so an in-flight order survives a reload.
1958
1975
  *
@@ -1989,4 +2006,4 @@ type StoredOrder = {
1989
2006
  */
1990
2007
  declare function listOrders(now?: number): StoredOrder[];
1991
2008
 
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 };
2009
+ 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, switchWalletConnectChain, updateWithdrawSwap };
package/dist/index.d.ts CHANGED
@@ -1953,6 +1953,23 @@ type OwneySIWXConfig = {
1953
1953
  */
1954
1954
  declare function createOwneySIWX(config: OwneySIWXConfig): SIWXConfig;
1955
1955
 
1956
+ /**
1957
+ * Ask the wallet ITSELF to switch networks, over WalletConnect.
1958
+ *
1959
+ * WalletConnect's provider answers `wallet_switchEthereumChain` locally when
1960
+ * the chain was approved at connect time: it moves its own default chain and
1961
+ * reports success without telling the wallet. MetaMask mobile then stays on
1962
+ * its network, keeps reporting it, and every guard downstream fails with
1963
+ * CHAIN_MISMATCH — after a swap, with the user's funds already moved (ROUT-727).
1964
+ * Sending the request through the session client reaches the wallet, which
1965
+ * shows a real "switch network" prompt; the client also deep-links the wallet
1966
+ * app open on mobile.
1967
+ *
1968
+ * Returns false when `provider` is not a WalletConnect session, so the caller
1969
+ * can fall back to an ordinary switch.
1970
+ */
1971
+ declare function switchWalletConnectChain(provider: unknown, chainId: number, timeoutMs?: number): Promise<boolean>;
1972
+
1956
1973
  /**
1957
1974
  * Persists cross-chain swap secrets so an in-flight order survives a reload.
1958
1975
  *
@@ -1989,4 +2006,4 @@ type StoredOrder = {
1989
2006
  */
1990
2007
  declare function listOrders(now?: number): StoredOrder[];
1991
2008
 
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 };
2009
+ 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, switchWalletConnectChain, updateWithdrawSwap };
package/dist/index.js CHANGED
@@ -2942,6 +2942,8 @@ var FALLBACK_WRAP_GAS = 50000n;
2942
2942
  var APPROVE_GAS = 60000n;
2943
2943
  var GAS_SAFETY = 2n;
2944
2944
  var MIN_WALLET_GAS_PRICE = 3000000000n;
2945
+ var WRAP_WATCH_INTERVAL_MS = 4e3;
2946
+ var WRAP_PROMPT_TIMEOUT_MS = 5 * 60 * 1e3;
2945
2947
  async function wrapNative(deps, options) {
2946
2948
  const { chainId, wrapper, nativeSymbol, requested } = options;
2947
2949
  const balance = await deps.readNativeBalance();
@@ -2999,16 +3001,90 @@ async function wrapNative(deps, options) {
2999
3001
  }
3000
3002
  );
3001
3003
  }
3004
+ let baseline;
3005
+ if (deps.readWrappedBalance) {
3006
+ try {
3007
+ baseline = await deps.readWrappedBalance();
3008
+ } catch (error) {
3009
+ debugLog("owney-sdk", "wrap: balance read failed, not watching", {
3010
+ message: error instanceof Error ? error.message : String(error)
3011
+ });
3012
+ }
3013
+ }
3002
3014
  await deps.ensureChain(chainId);
3003
3015
  debugLog("owney-sdk", "wrap: sending deposit()", {
3004
3016
  wrapper,
3005
3017
  value: wrapped.toString()
3006
3018
  });
3007
- const txHash = await deps.sendTransaction(
3008
- { to: wrapper, data: WRAP_SELECTOR, value: wrapped.toString() },
3009
- options.onSubmitted
3010
- );
3011
- return { wrapped, txHash };
3019
+ let notified = false;
3020
+ const notify2 = (hash) => {
3021
+ if (notified) return;
3022
+ notified = true;
3023
+ options.onSubmitted?.(hash);
3024
+ };
3025
+ const outcome = await new Promise((resolve, reject) => {
3026
+ let done = false;
3027
+ let timer;
3028
+ const finish = (settle) => {
3029
+ if (done) return;
3030
+ done = true;
3031
+ clearTimeout(timer);
3032
+ settle();
3033
+ };
3034
+ timer = setTimeout(
3035
+ () => finish(
3036
+ () => reject(
3037
+ new OwneyError(
3038
+ "SWAP_WALLET_PROMPT_TIMEOUT",
3039
+ // Hedged on purpose: a wallet that never answered may still have
3040
+ // sent it, and wrapping again would wrap twice.
3041
+ `Your wallet didn't answer the request to wrap your ${nativeSymbol}. Check your wallet before trying again \u2014 if the wrap went through, your funds are there as wrapped ${nativeSymbol}.`,
3042
+ { chainId, prompt: "wrap", timeoutMs: WRAP_PROMPT_TIMEOUT_MS }
3043
+ )
3044
+ )
3045
+ ),
3046
+ WRAP_PROMPT_TIMEOUT_MS
3047
+ );
3048
+ deps.sendTransaction(
3049
+ { to: wrapper, data: WRAP_SELECTOR, value: wrapped.toString() },
3050
+ (hash) => {
3051
+ clearTimeout(timer);
3052
+ notify2(hash);
3053
+ }
3054
+ ).then(
3055
+ (txHash) => finish(() => resolve({ txHash })),
3056
+ (error) => finish(() => reject(error))
3057
+ );
3058
+ if (baseline !== void 0 && deps.readWrappedBalance) {
3059
+ const read = deps.readWrappedBalance;
3060
+ const target = baseline + wrapped;
3061
+ const sleep2 = deps.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms)));
3062
+ void (async () => {
3063
+ while (!done) {
3064
+ await sleep2(WRAP_WATCH_INTERVAL_MS);
3065
+ if (done) return;
3066
+ try {
3067
+ if (await read() >= target) {
3068
+ debugLog(
3069
+ "owney-sdk",
3070
+ "wrap: landed on chain before the wallet answered"
3071
+ );
3072
+ finish(() => {
3073
+ notify2();
3074
+ resolve({});
3075
+ });
3076
+ return;
3077
+ }
3078
+ } catch {
3079
+ }
3080
+ }
3081
+ })();
3082
+ }
3083
+ });
3084
+ return {
3085
+ wrapped,
3086
+ ...outcome.txHash ? { txHash: outcome.txHash } : {}
3087
+ };
3012
3088
  }
3013
3089
  function requireWrapper(quote) {
3014
3090
  const wrapper = quote.wrappedNative;
@@ -4492,6 +4568,76 @@ function makeSponsoredDepositCallback(deps) {
4492
4568
  };
4493
4569
  }
4494
4570
 
4571
+ // src/lib/walletconnect-switch.ts
4572
+ var WALLET_SWITCH_TIMEOUT_MS = 12e4;
4573
+ function walletConnectCore(provider) {
4574
+ const p = provider;
4575
+ const core = p?.signer ?? p;
4576
+ if (typeof core?.client?.request !== "function" || typeof core.setDefaultChain !== "function" || typeof core.session?.topic !== "string") {
4577
+ return null;
4578
+ }
4579
+ const peer = core.session.peer?.metadata?.name ?? "";
4580
+ if (!/metamask/i.test(peer)) return null;
4581
+ return core;
4582
+ }
4583
+ async function switchWalletConnectChain(provider, chainId, timeoutMs = WALLET_SWITCH_TIMEOUT_MS) {
4584
+ const core = walletConnectCore(provider);
4585
+ if (!core) return false;
4586
+ const current = Number(
4587
+ await provider.request({ method: "eth_chainId" })
4588
+ );
4589
+ const hexChainId = `0x${chainId.toString(16)}`;
4590
+ let timer;
4591
+ try {
4592
+ await Promise.race([
4593
+ core.client.request({
4594
+ topic: core.session.topic,
4595
+ chainId: `eip155:${current}`,
4596
+ request: {
4597
+ method: "wallet_switchEthereumChain",
4598
+ params: [{ chainId: hexChainId }]
4599
+ }
4600
+ }),
4601
+ new Promise((_, reject) => {
4602
+ timer = setTimeout(
4603
+ () => reject(
4604
+ new Error("The wallet did not answer the network switch in time")
4605
+ ),
4606
+ timeoutMs
4607
+ );
4608
+ })
4609
+ ]);
4610
+ } finally {
4611
+ clearTimeout(timer);
4612
+ }
4613
+ try {
4614
+ core.setDefaultChain(`eip155:${chainId}`);
4615
+ } catch {
4616
+ }
4617
+ return true;
4618
+ }
4619
+ function withWalletConnectSwitch(provider) {
4620
+ if (!walletConnectCore(provider)) return provider;
4621
+ const target = provider;
4622
+ const request2 = async (args) => {
4623
+ if (args?.method !== "wallet_switchEthereumChain") {
4624
+ return target.request(args);
4625
+ }
4626
+ const [param] = args.params ?? [];
4627
+ const chainId = Number.parseInt(param?.chainId ?? "", 16);
4628
+ if (!Number.isFinite(chainId)) return target.request(args);
4629
+ await switchWalletConnectChain(target, chainId);
4630
+ return null;
4631
+ };
4632
+ return new Proxy(target, {
4633
+ get(obj, prop) {
4634
+ if (prop === "request") return request2;
4635
+ const value = Reflect.get(obj, prop, obj);
4636
+ return typeof value === "function" ? value.bind(obj) : value;
4637
+ }
4638
+ });
4639
+ }
4640
+
4495
4641
  // src/lib/sponsored-weth-deposit.ts
4496
4642
  var PERMIT_WINDOW_SECONDS = 15 * 60;
4497
4643
  function makeSponsoredWethCallback(deps) {
@@ -4790,7 +4936,11 @@ var OwneySDK = class {
4790
4936
  }
4791
4937
  this.agentReads.clearInFlight();
4792
4938
  this.activationChecks.clear();
4793
- this.state = { provider, walletAddress, chainId: null };
4939
+ this.state = {
4940
+ provider: withWalletConnectSwitch(provider),
4941
+ walletAddress,
4942
+ chainId: null
4943
+ };
4794
4944
  this.cachedSponsoredCallback = null;
4795
4945
  this.cachedWethSponsoredCallback = null;
4796
4946
  this.cachedSponsoredCallsCallbacks.clear();
@@ -5641,6 +5791,14 @@ var OwneySDK = class {
5641
5791
  return hash;
5642
5792
  },
5643
5793
  ensureChain: (id) => this.ensureSwapChain(id),
5794
+ // Over HTTP, so a wallet that broadcast the wrap without telling the
5795
+ // page cannot also hide that it landed (ROUT-726).
5796
+ readWrappedBalance: () => publicClient.readContract({
5797
+ address: wrapper.address,
5798
+ abi: ERC20_ALLOWANCE_ABI,
5799
+ functionName: "balanceOf",
5800
+ args: [walletAddress]
5801
+ }),
5644
5802
  // Read through the same public client as every other sizing input, so
5645
5803
  // a wallet sitting on the wrong chain cannot answer for this one.
5646
5804
  readAllowance: (token, spender) => publicClient.readContract({
@@ -7605,5 +7763,6 @@ export {
7605
7763
  saveWithdrawSwap,
7606
7764
  setOwneyDebug,
7607
7765
  subscribeWithdrawSwaps,
7766
+ switchWalletConnectChain,
7608
7767
  updateWithdrawSwap
7609
7768
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@owney/sdk",
3
- "version": "0.7.29",
3
+ "version": "0.7.31-beta.0",
4
4
  "type": "module",
5
5
  "main": "dist/index.cjs",
6
6
  "module": "dist/index.js",