@cordystackx/cordy_minikit 3.0.6 → 3.1.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.
Files changed (71) hide show
  1. package/README.md +65 -12
  2. package/dist/client/authTypes.d.ts +13 -0
  3. package/dist/client/authTypes.d.ts.map +1 -0
  4. package/dist/client/authTypes.js +1 -0
  5. package/dist/client/cons.d.ts +31 -0
  6. package/dist/client/cons.d.ts.map +1 -0
  7. package/dist/client/cons.js +63 -0
  8. package/dist/client/consRuntime.d.ts +5 -0
  9. package/dist/client/consRuntime.d.ts.map +1 -0
  10. package/dist/client/consRuntime.js +32 -0
  11. package/dist/client/runtimeConfig.d.ts +51 -3
  12. package/dist/client/runtimeConfig.d.ts.map +1 -1
  13. package/dist/client/runtimeConfig.js +15 -1
  14. package/dist/client/transfer.d.ts +21 -5
  15. package/dist/client/transfer.d.ts.map +1 -1
  16. package/dist/client/transfer.js +423 -72
  17. package/dist/client/useConsSession.d.ts +3 -0
  18. package/dist/client/useConsSession.d.ts.map +1 -0
  19. package/dist/client/useConsSession.js +36 -0
  20. package/dist/client.d.ts +4 -3
  21. package/dist/client.d.ts.map +1 -1
  22. package/dist/client.js +2 -1
  23. package/dist/client__provider.d.ts +2 -1
  24. package/dist/client__provider.d.ts.map +1 -1
  25. package/dist/client__provider.js +6 -6
  26. package/dist/components/Connect_wallet_bt.d.ts +3 -3
  27. package/dist/components/Connect_wallet_bt.d.ts.map +1 -1
  28. package/dist/components/Connect_wallet_bt.js +12 -20
  29. package/dist/components/UI_Comp.d.ts.map +1 -1
  30. package/dist/components/UI_Comp.js +124 -10
  31. package/dist/config/walletConfig.d.ts.map +1 -1
  32. package/dist/config/walletConfig.js +17 -1
  33. package/dist/controllers/BridgeEvmWalletModal.d.ts +11 -0
  34. package/dist/controllers/BridgeEvmWalletModal.d.ts.map +1 -0
  35. package/dist/controllers/BridgeEvmWalletModal.js +154 -0
  36. package/dist/controllers/DisConnect.d.ts.map +1 -1
  37. package/dist/controllers/DisConnect.js +8 -1
  38. package/dist/controllers/Get_Balance.d.ts.map +1 -1
  39. package/dist/controllers/Get_Balance.js +3 -2
  40. package/dist/controllers/Transactions.js +2 -2
  41. package/dist/controllers/bridgeWalletSession.d.ts +13 -0
  42. package/dist/controllers/bridgeWalletSession.d.ts.map +1 -0
  43. package/dist/controllers/bridgeWalletSession.js +37 -0
  44. package/dist/controllers/cctpBridge.d.ts +6 -0
  45. package/dist/controllers/cctpBridge.d.ts.map +1 -0
  46. package/dist/controllers/cctpBridge.js +326 -0
  47. package/dist/controllers/index.d.ts +4 -0
  48. package/dist/controllers/index.d.ts.map +1 -1
  49. package/dist/controllers/index.js +2 -0
  50. package/dist/controllers/useBridgeEvmWallet.d.ts +23 -0
  51. package/dist/controllers/useBridgeEvmWallet.d.ts.map +1 -0
  52. package/dist/controllers/useBridgeEvmWallet.js +83 -0
  53. package/dist/css/UI_Comp/styles.module.css +10 -0
  54. package/dist/index.d.ts +4 -2
  55. package/dist/index.d.ts.map +1 -1
  56. package/dist/index.js +2 -1
  57. package/dist/package.json +11 -7
  58. package/dist/server/cons.d.ts +67 -0
  59. package/dist/server/cons.d.ts.map +1 -0
  60. package/dist/server/cons.js +383 -0
  61. package/dist/server/jwt.d.ts +0 -17
  62. package/dist/server/jwt.d.ts.map +1 -1
  63. package/dist/server/jwt.js +1 -35
  64. package/dist/server.d.ts +3 -2
  65. package/dist/server.d.ts.map +1 -1
  66. package/dist/server.js +2 -1
  67. package/dist/tsconfig.tsbuildinfo +1 -1
  68. package/dist/wagmi__providers.d.ts +13 -3
  69. package/dist/wagmi__providers.d.ts.map +1 -1
  70. package/dist/wagmi__providers.js +102 -15
  71. package/package.json +11 -7
@@ -5,18 +5,14 @@ import { BrowserProvider, Contract, formatUnits, isAddress, JsonRpcProvider, par
5
5
  import { getActiveWagmiConfig } from "../config/walletConfig";
6
6
  import { readTokenBalance } from "../controllers/Get_Balance";
7
7
  import loadStellarBalance from "../controllers/loadStellarBalance";
8
+ import { cctpBridge } from "../controllers/cctpBridge";
8
9
  import tokenAbi from "../config/ERC20_ABI.json";
9
10
  import { setCordyRuntimeConfig } from "./runtimeConfig";
11
+ import { waitForBridgeEvmWallet } from "../controllers/bridgeWalletSession";
12
+ import { getConfiguredEvmAssets, requireConfiguredEvmNetwork } from "./runtimeConfig";
10
13
  const ACTIVE_WALLET_SESSION_KEY = "cordy_minikit_active_wallet_session";
11
14
  const STELLAR_WALLET_STORAGE_KEY = "cordy_minikit_stellar_wallet";
12
- // First test route: BOT Chain Testnet <-> Ethereum Sepolia, USDT only.
13
- const BOT_TESTNET_CHAIN_ID = 968;
14
- const SEPOLIA_CHAIN_ID = 11155111;
15
- const BOT_TESTNET_BRIDGE_ROUTER = "0x6239404Aa276ba68486E2Fa40E90CDd36ff8ec3A";
16
- const BOT_TESTNET_USDT = "0x75edC9335175Fc0552D51D48439F229c10420fe3";
17
- const SEPOLIA_BRIDGE_GATEWAY = "0xc83AE6F73e8918750b87DD001E36093A1AB7b272";
18
- const SEPOLIA_USDT = "0x7B1e05a39adF207a759EAf89E867dBcC1C615130";
19
- const USDT_RESOURCE_ID = "0xac589789ed8c9d2c61f17b13369864b5f181e58eba230a6ee4ec4c3e7750cd1d";
15
+ // Bridge deployments and tokens are supplied through the app's bridge configuration.
20
16
  const BRIDGE_ERC20_ABI = [
21
17
  "function allowance(address owner,address spender) view returns (uint256)",
22
18
  "function approve(address spender,uint256 amount) returns (bool)",
@@ -29,13 +25,26 @@ const BOT_BRIDGE_ABI = [
29
25
  let configuredAssets;
30
26
  export function configureCordyAssets({ assets }) {
31
27
  if (!assets || (assets.networks !== undefined && !Array.isArray(assets.networks)) ||
32
- (assets.evm !== undefined && !Array.isArray(assets.evm)) ||
28
+ (assets.evm !== undefined && (Array.isArray(assets.evm) || typeof assets.evm !== "object")) ||
33
29
  (assets.stellar !== undefined && !Array.isArray(assets.stellar))) {
34
- throw new Error('Cordy Minikit: "networks", "evm", and "stellar" must be arrays when provided.');
30
+ throw new Error('Cordy Minikit: "networks" and "stellar" must be arrays; "evm" must be grouped by chain ID.');
35
31
  }
36
32
  configuredAssets = {
37
33
  networks: (assets.networks ?? []).map((network) => ({ ...network, nativeCurrency: { ...network.nativeCurrency } })),
38
- evm: (assets.evm ?? []).map((asset) => ({ ...asset })),
34
+ evm: Object.fromEntries(Object.entries(assets.evm ?? {}).map(([chainId, entries]) => [
35
+ chainId,
36
+ entries.map((asset) => ({ ...asset })),
37
+ ])),
38
+ bridge: assets.bridge ? {
39
+ ...assets.bridge,
40
+ internal: assets.bridge.internal ? { ...assets.bridge.internal } : undefined,
41
+ external: assets.bridge.external ? { ...assets.bridge.external } : undefined,
42
+ routes: assets.bridge.routes?.map((route) => ({
43
+ ...route,
44
+ internal: { ...route.internal },
45
+ external: { ...route.external },
46
+ })),
47
+ } : undefined,
39
48
  stellar: (assets.stellar ?? []).map((asset) => ({ ...asset })),
40
49
  walletConnectProjectId: assets.walletConnectProjectId,
41
50
  stellarNetwork: assets.stellarNetwork ? { ...assets.stellarNetwork } : undefined,
@@ -49,9 +58,6 @@ function requireStellarNetwork() {
49
58
  }
50
59
  return network;
51
60
  }
52
- function getDefaultEvmChainId() {
53
- return configuredAssets?.networks?.[0]?.chainId;
54
- }
55
61
  function normalizedAmount(amount) {
56
62
  const value = String(amount).trim();
57
63
  if (!/^\d+(\.\d+)?$/.test(value) || !Number.isFinite(Number(value)) || Number(value) <= 0) {
@@ -60,23 +66,37 @@ function normalizedAmount(amount) {
60
66
  return value;
61
67
  }
62
68
  function resolveEvmAsset(requestedSymbol, chainId, networkName) {
63
- const defaultChainId = getDefaultEvmChainId();
64
- const chainAssets = configuredAssets?.evm?.filter((asset) => (asset.chainId ?? defaultChainId) === chainId) ?? [];
69
+ const network = configuredAssets?.networks?.find((candidate) => candidate.chainId === chainId);
70
+ const chainAssets = getConfiguredEvmAssets(configuredAssets).filter((asset) => asset.chainId === chainId) ?? [];
71
+ if (requestedSymbol && network?.nativeCurrency.symbol.toLowerCase() === requestedSymbol.toLowerCase()) {
72
+ return {
73
+ symbol: network.nativeCurrency.symbol,
74
+ type: "native",
75
+ decimals: network.nativeCurrency.decimals,
76
+ };
77
+ }
65
78
  const symbol = requestedSymbol || chainAssets.find((asset) => asset.contractAddress)?.symbol || chainAssets[0]?.symbol;
66
79
  if (!symbol)
67
80
  return undefined;
68
- const sameSymbol = (configuredAssets?.evm ?? []).filter((asset) => asset.symbol.toLowerCase() === symbol.toLowerCase());
69
- const matchingNetwork = sameSymbol.find((asset) => (asset.chainId ?? defaultChainId) === chainId);
81
+ const sameSymbol = getConfiguredEvmAssets(configuredAssets).filter((asset) => asset.symbol.toLowerCase() === symbol.toLowerCase());
82
+ const matchingNetwork = sameSymbol.find((asset) => asset.chainId === chainId);
70
83
  if (sameSymbol.length > 0 && !matchingNetwork) {
71
- const chainIds = [...new Set(sameSymbol.map((asset) => asset.chainId ?? defaultChainId))].join(", ");
84
+ const chainIds = [...new Set(sameSymbol.map((asset) => asset.chainId))].join(", ");
72
85
  throw new Error(`${symbol} is configured for chain ID ${chainIds}, but the connected wallet is on ${networkName} (chain ID ${chainId}). Switch networks or add an asset entry for this chain.`);
73
86
  }
74
87
  return matchingNetwork;
75
88
  }
76
89
  function resolveConfiguredEvmSwapAsset(symbol, chainId) {
77
- const configuredChainId = getDefaultEvmChainId();
78
- const matches = (configuredAssets?.evm ?? []).filter((asset) => asset.symbol.toLowerCase() === symbol.toLowerCase() &&
79
- (asset.chainId ?? configuredChainId) === chainId);
90
+ const network = configuredAssets?.networks?.find((candidate) => candidate.chainId === chainId);
91
+ if (network?.nativeCurrency.symbol.toLowerCase() === symbol.toLowerCase()) {
92
+ return {
93
+ symbol: network.nativeCurrency.symbol,
94
+ type: "native",
95
+ decimals: network.nativeCurrency.decimals,
96
+ };
97
+ }
98
+ const matches = getConfiguredEvmAssets(configuredAssets).filter((asset) => asset.symbol.toLowerCase() === symbol.toLowerCase() &&
99
+ asset.chainId === chainId);
80
100
  if (matches.length > 1) {
81
101
  throw new Error(`More than one ${symbol} asset is configured for chain ID ${chainId}. Keep one entry per asset and network.`);
82
102
  }
@@ -100,6 +120,19 @@ const V2_SWAP_ROUTER_ABI = [
100
120
  "function swapExactETHForTokens(uint amountOutMin,address[] calldata path,address to,uint deadline) external payable returns (uint[] memory amounts)",
101
121
  "function swapExactTokensForETH(uint amountIn,uint amountOutMin,address[] calldata path,address to,uint deadline) external returns (uint[] memory amounts)",
102
122
  ];
123
+ const V3_QUOTER_V2_ABI = [
124
+ "function quoteExactInputSingle((address tokenIn,address tokenOut,uint256 amountIn,uint24 fee,uint160 sqrtPriceLimitX96) params) returns (uint256 amountOut,uint160 sqrtPriceX96After,uint32 initializedTicksCrossed,uint256 gasEstimate)",
125
+ ];
126
+ const V3_ROUTER_ABI = [
127
+ "function exactInputSingle((address tokenIn,address tokenOut,uint24 fee,address recipient,uint256 deadline,uint256 amountIn,uint256 amountOutMinimum,uint160 sqrtPriceLimitX96) params) payable returns (uint256 amountOut)",
128
+ "function multicall(bytes[] data) payable returns (bytes[] results)",
129
+ "function unwrapWETH9(uint256 amountMinimum,address recipient) payable",
130
+ ];
131
+ const V3_ROUTER_02_ABI = [
132
+ "function exactInputSingle((address tokenIn,address tokenOut,uint24 fee,address recipient,uint256 amountIn,uint256 amountOutMinimum,uint160 sqrtPriceLimitX96) params) payable returns (uint256 amountOut)",
133
+ "function multicall(bytes[] data) payable returns (bytes[] results)",
134
+ "function unwrapWETH9(uint256 amountMinimum,address recipient) payable",
135
+ ];
103
136
  const ERC20_SWAP_ABI = [
104
137
  "function approve(address spender,uint256 amount) returns (bool)",
105
138
  "function allowance(address owner,address spender) view returns (uint256)",
@@ -158,7 +191,38 @@ function getActiveWallet() {
158
191
  }
159
192
  throw new Error("Connect an EVM or Stellar wallet first.");
160
193
  }
161
- async function bridgeEvm(amount, from, to, recipient) {
194
+ function resolveBridgeRoute(bridgeConfig, routeId) {
195
+ if (!bridgeConfig)
196
+ throw new Error("Bridge is not configured. Add bridge routes to the assets JSON.");
197
+ if (bridgeConfig.routes?.length) {
198
+ const routeIds = bridgeConfig.routes.map((route) => route.id);
199
+ if (routeIds.some((id) => !id) || new Set(routeIds).size !== routeIds.length) {
200
+ throw new Error("Bridge route IDs must be present and unique in assets.bridge.routes.");
201
+ }
202
+ if (!routeId && bridgeConfig.routes.length > 1) {
203
+ throw new Error(`Choose a bridge route. Available route IDs: ${bridgeConfig.routes.map((route) => route.id).join(", ")}.`);
204
+ }
205
+ const route = routeId
206
+ ? bridgeConfig.routes.find((candidate) => candidate.id === routeId)
207
+ : bridgeConfig.routes[0];
208
+ if (!route)
209
+ throw new Error(`Bridge route "${routeId}" is not configured.`);
210
+ return route;
211
+ }
212
+ if (bridgeConfig.resourceId && bridgeConfig.internal && bridgeConfig.external) {
213
+ if (routeId && routeId !== "default")
214
+ throw new Error(`Bridge route "${routeId}" is not configured.`);
215
+ return {
216
+ id: "default",
217
+ name: `${bridgeConfig.internal.networkName} ↔ ${bridgeConfig.external.networkName}`,
218
+ resourceId: bridgeConfig.resourceId,
219
+ internal: bridgeConfig.internal,
220
+ external: bridgeConfig.external,
221
+ };
222
+ }
223
+ throw new Error("Add at least one complete route to assets.bridge.routes.");
224
+ }
225
+ async function bridgeEvm(amount, from, to, recipient, options = {}) {
162
226
  if (from !== "internal" && from !== "external")
163
227
  throw new Error("Source must be internal or external.");
164
228
  if (to !== "internal" && to !== "external")
@@ -176,31 +240,70 @@ async function bridgeEvm(amount, from, to, recipient) {
176
240
  const provider = new BrowserProvider(rawProvider);
177
241
  const chain = await provider.getNetwork();
178
242
  const chainId = Number(chain.chainId);
179
- const expectedSourceChainId = from === "internal" ? BOT_TESTNET_CHAIN_ID : SEPOLIA_CHAIN_ID;
180
- const destinationChainId = to === "internal" ? BOT_TESTNET_CHAIN_ID : SEPOLIA_CHAIN_ID;
243
+ const route = resolveBridgeRoute(configuredAssets?.bridge, options.routeId);
244
+ if (!route.id || !route.name)
245
+ throw new Error("Each bridge route must have an id and name.");
246
+ if (!route.resourceId || !/^0x[\da-fA-F]{64}$/.test(route.resourceId)) {
247
+ throw new Error("The configured bridge resourceId must be a 32-byte hex value.");
248
+ }
249
+ const sourceConfig = route[from];
250
+ const destinationConfig = route[to];
251
+ if (!sourceConfig || !destinationConfig || !Number.isInteger(sourceConfig.chainId) || !Number.isInteger(destinationConfig.chainId)) {
252
+ throw new Error("Bridge internal and external settings must include valid chain IDs.");
253
+ }
254
+ for (const [side, networkConfig] of [[from, sourceConfig], [to, destinationConfig]]) {
255
+ const bridgeAddress = networkConfig.bridgeAddress;
256
+ const tokenAddress = networkConfig.tokenAddress;
257
+ if (!networkConfig.networkName || !networkConfig.assetSymbol ||
258
+ !bridgeAddress || !tokenAddress || !isAddress(bridgeAddress) || !isAddress(tokenAddress)) {
259
+ throw new Error(`Configure a networkName, assetSymbol, valid bridgeAddress, and valid tokenAddress for the ${side} bridge side.`);
260
+ }
261
+ if (!walletConfig.chains.some((network) => network.id === networkConfig.chainId)) {
262
+ throw new Error(`Configure ${networkConfig.networkName} (chain ID ${networkConfig.chainId}) in the provider's EVM networks.`);
263
+ }
264
+ }
265
+ if (sourceConfig.assetSymbol.toLowerCase() !== destinationConfig.assetSymbol.toLowerCase()) {
266
+ throw new Error("The bridge asset symbols must match on the internal and external networks.");
267
+ }
268
+ if (sourceConfig.chainId === destinationConfig.chainId) {
269
+ throw new Error("The internal and external bridge sides must use different chain IDs.");
270
+ }
271
+ const expectedSourceChainId = sourceConfig.chainId;
272
+ const destinationChainId = destinationConfig.chainId;
181
273
  if (chainId !== expectedSourceChainId) {
182
- const expectedNetwork = from === "internal" ? "BOT Chain Testnet" : "Ethereum Sepolia";
274
+ const expectedNetwork = sourceConfig.networkName;
183
275
  throw new Error(`Connect your wallet to ${expectedNetwork} (chain ID ${expectedSourceChainId}) to bridge from ${from}. The connected wallet is on ${chain.name} (chain ID ${chainId}).`);
184
276
  }
185
277
  const inputAmount = normalizedAmount(amount);
186
- if (from === "internal" && Number(inputAmount) <= 10) {
187
- throw new Error("BOT Chain Testnet bridge-out requires more than 10 USDT.");
188
- }
189
- const tokenAddress = from === "internal" ? BOT_TESTNET_USDT : SEPOLIA_USDT;
190
- const bridgeAddress = from === "internal" ? BOT_TESTNET_BRIDGE_ROUTER : SEPOLIA_BRIDGE_GATEWAY;
191
278
  const signer = await provider.getSigner(connection.accounts[0]);
192
279
  const sender = await signer.getAddress();
280
+ const bridgeAddress = sourceConfig.bridgeAddress;
281
+ const tokenAddress = sourceConfig.tokenAddress;
282
+ if (!bridgeAddress || !tokenAddress)
283
+ throw new Error("The EVM bridge route is missing bridge and token addresses.");
193
284
  const token = new Contract(tokenAddress, BRIDGE_ERC20_ABI, signer);
194
285
  const code = await provider.getCode(bridgeAddress);
195
286
  if (code === "0x")
196
- throw new Error(`No bridge contract is deployed at the configured ${from === "internal" ? "BOT Chain Testnet" : "Sepolia"} testnet address.`);
287
+ throw new Error(`No bridge contract is deployed at the configured ${sourceConfig.networkName} address.`);
197
288
  const decimals = Number(await token.decimals());
198
289
  if (!Number.isInteger(decimals) || decimals < 0 || decimals > 18)
199
- throw new Error("The configured test USDT token returned invalid decimals.");
290
+ throw new Error(`The configured ${sourceConfig.assetSymbol} token returned invalid decimals.`);
200
291
  const amountIn = parseUnits(inputAmount, decimals);
292
+ if (sourceConfig.minimumAmountExclusive !== undefined) {
293
+ let minimumAmount;
294
+ try {
295
+ minimumAmount = parseUnits(normalizedAmount(sourceConfig.minimumAmountExclusive), decimals);
296
+ }
297
+ catch {
298
+ throw new Error(`The configured minimumAmountExclusive for ${sourceConfig.networkName} is invalid.`);
299
+ }
300
+ if (amountIn <= minimumAmount) {
301
+ throw new Error(`${sourceConfig.networkName} bridge-out requires more than ${sourceConfig.minimumAmountExclusive} ${sourceConfig.assetSymbol}.`);
302
+ }
303
+ }
201
304
  const tokenBalance = BigInt((await token.balanceOf(sender)).toString());
202
305
  if (tokenBalance < amountIn)
203
- throw new Error(`Insufficient test USDT on ${from === "internal" ? "BOT Chain Testnet" : "Sepolia"}.`);
306
+ throw new Error(`Insufficient ${sourceConfig.assetSymbol} on ${sourceConfig.networkName}.`);
204
307
  const allowance = BigInt((await token.allowance(sender, bridgeAddress)).toString());
205
308
  let approvalTransactionHash;
206
309
  if (allowance < amountIn) {
@@ -208,39 +311,191 @@ async function bridgeEvm(amount, from, to, recipient) {
208
311
  const reset = await token.approve(bridgeAddress, 0n);
209
312
  const resetReceipt = await reset.wait();
210
313
  if (!resetReceipt || resetReceipt.status !== 1)
211
- throw new Error("Could not reset the USDT bridge allowance.");
314
+ throw new Error(`Could not reset the ${sourceConfig.assetSymbol} bridge allowance.`);
212
315
  }
213
316
  const approval = await token.approve(bridgeAddress, amountIn);
214
317
  const approvalReceipt = await approval.wait();
215
318
  if (!approvalReceipt || approvalReceipt.status !== 1)
216
- throw new Error("Could not approve USDT for the bridge.");
319
+ throw new Error(`Could not approve ${sourceConfig.assetSymbol} for the bridge.`);
217
320
  approvalTransactionHash = approvalReceipt.hash || approval.hash;
218
321
  }
219
322
  const bridge = new Contract(bridgeAddress, BOT_BRIDGE_ABI, signer);
220
- const transaction = await bridge.deposit(destinationChainId, USDT_RESOURCE_ID, recipient, amountIn);
323
+ const transaction = await bridge.deposit(destinationChainId, route.resourceId, recipient, amountIn);
221
324
  const receipt = await transaction.wait();
222
325
  if (!receipt || receipt.status !== 1)
223
326
  throw new Error("The source-chain bridge deposit failed.");
327
+ const { disconnect } = await import("wagmi/actions");
328
+ for (const activeConnection of Array.from(walletConfig.state.connections.values())) {
329
+ await disconnect(walletConfig, { connector: activeConnection.connector });
330
+ }
224
331
  return {
225
332
  success: true,
226
- asset: "USDT",
333
+ asset: sourceConfig.assetSymbol,
227
334
  from,
228
335
  to,
229
- fromNetwork: from === "internal" ? "BOT Chain Testnet" : "Ethereum Sepolia",
230
- toNetwork: to === "internal" ? "BOT Chain Testnet" : "Ethereum Sepolia",
336
+ fromNetwork: sourceConfig.networkName,
337
+ toNetwork: destinationConfig.networkName,
338
+ routeId: route.id,
339
+ routeName: route.name,
231
340
  amount: inputAmount,
232
341
  ...(approvalTransactionHash ? { approvalTransactionHash } : {}),
233
342
  transactionHash: receipt.hash || transaction.hash,
234
343
  status: "submitted",
235
344
  };
236
345
  }
237
- /** Bridge test USDT between BOT Chain Testnet (internal) and Ethereum Sepolia (external). */
238
- export async function cordy_bridge(amount, from, to, recipient) {
346
+ async function bridgeStellar(amount, from, to, recipient, options = {}) {
347
+ if (from !== "internal" && from !== "external")
348
+ throw new Error("Source must be internal or external.");
349
+ if (to !== "internal" && to !== "external")
350
+ throw new Error("Destination must be internal or external.");
351
+ if (from === to)
352
+ throw new Error("Choose different source and destination sides.");
353
+ if (!StrKey.isValidEd25519PublicKey(recipient))
354
+ throw new Error("Recipient must be a valid Stellar public address.");
355
+ if (!/^\d+(\.\d{1,7})?$/.test(amount))
356
+ throw new Error("Stellar amounts support up to 7 decimal places.");
357
+ const stellarConfig = requireStellarNetwork();
358
+ const access = await requestAccess();
359
+ const sourceAddress = access.address;
360
+ if (!sourceAddress)
361
+ throw new Error("Could not access the connected Stellar wallet.");
362
+ const networkDetails = await getNetworkDetails();
363
+ const networkPassphrase = networkDetails.networkPassphrase || stellarConfig.networkPassphrase;
364
+ if (networkDetails.networkPassphrase && networkDetails.networkPassphrase !== stellarConfig.networkPassphrase) {
365
+ throw new Error(`Stellar network mismatch. Expected ${stellarConfig.networkPassphrase}, got ${networkDetails.networkPassphrase}.`);
366
+ }
367
+ const route = resolveBridgeRoute(configuredAssets?.bridge, options.routeId);
368
+ if (!route.id || !route.name)
369
+ throw new Error("Each bridge route must have an id and name.");
370
+ if (!route.resourceId || !/^0x[\da-fA-F]{64}$/.test(route.resourceId)) {
371
+ throw new Error("The configured bridge resourceId must be a 32-byte hex value.");
372
+ }
373
+ const sourceConfig = route[from];
374
+ const destinationConfig = route[to];
375
+ if (!sourceConfig || !destinationConfig || sourceConfig.networkType !== "stellar" || destinationConfig.networkType !== "stellar") {
376
+ throw new Error("Bridge internal and external settings must include valid Stellar network types.");
377
+ }
378
+ if (!sourceConfig.networkName || !sourceConfig.assetSymbol || !sourceConfig.bridgeAddress || !StrKey.isValidEd25519PublicKey(sourceConfig.bridgeAddress)) {
379
+ throw new Error(`Configure a networkName, assetSymbol, and valid bridgeAddress for the ${from} bridge side.`);
380
+ }
381
+ if (!destinationConfig.networkName || !destinationConfig.assetSymbol) {
382
+ throw new Error(`Configure a networkName and assetSymbol for the ${to} bridge side.`);
383
+ }
384
+ if (sourceConfig.assetSymbol.toLowerCase() !== destinationConfig.assetSymbol.toLowerCase()) {
385
+ throw new Error("The bridge asset symbols must match on the internal and external networks.");
386
+ }
387
+ const server = new Horizon.Server(stellarConfig.horizonUrl);
388
+ const sourceAccount = await server.loadAccount(sourceAddress);
389
+ const assetConfig = (configuredAssets?.stellar ?? []).find((asset) => asset.symbol.toLowerCase() === sourceConfig.assetSymbol.toLowerCase() &&
390
+ (!asset.networkPassphrase || asset.networkPassphrase === networkPassphrase)) ?? (sourceConfig.assetSymbol.toLowerCase() === "xlm" ? { symbol: "XLM", type: "native" } : undefined);
391
+ if (!assetConfig)
392
+ throw new Error(`No ${sourceConfig.assetSymbol} asset is configured for this Stellar network.`);
393
+ const stellarAsset = assetConfig.type === "native"
394
+ ? Asset.native()
395
+ : new Asset(assetConfig.code, assetConfig.issuer);
396
+ const assetBalance = assetConfig.type === "native"
397
+ ? sourceAccount.balances.find((item) => item.asset_type === "native")
398
+ : sourceAccount.balances.find((item) => (item.asset_type === "credit_alphanum4" || item.asset_type === "credit_alphanum12") &&
399
+ item.asset_code === assetConfig.code &&
400
+ item.asset_issuer === assetConfig.issuer);
401
+ if (!assetBalance) {
402
+ throw new Error(assetConfig.type === "native"
403
+ ? `The connected Stellar account has no ${sourceConfig.assetSymbol} balance.`
404
+ : `The connected Stellar account has no ${sourceConfig.assetSymbol} trustline from the configured issuer.`);
405
+ }
406
+ const requiredBalance = Number(amount) + (assetConfig.type === "native" ? 0.00001 : 0);
407
+ if (Number(assetBalance.balance) < requiredBalance)
408
+ throw new Error(`Insufficient ${sourceConfig.assetSymbol} balance for this transfer.`);
409
+ const builder = new TransactionBuilder(sourceAccount, { fee: BASE_FEE, networkPassphrase })
410
+ .addOperation(Operation.payment({
411
+ destination: sourceConfig.bridgeAddress,
412
+ asset: stellarAsset,
413
+ amount: Number(amount).toFixed(7),
414
+ }));
415
+ if (sourceConfig.stellarMemo)
416
+ builder.addMemo(Memo.text(sourceConfig.stellarMemo));
417
+ builder.setTimeout(180);
418
+ const unsignedTx = builder.build();
419
+ const { signedTxXdr, error } = await freighterSignTransaction(unsignedTx.toXDR(), {
420
+ networkPassphrase,
421
+ address: sourceAddress,
422
+ });
423
+ if (error || !signedTxXdr)
424
+ throw new Error(error?.message || "Stellar wallet signing was rejected.");
425
+ const signedTx = TransactionBuilder.fromXDR(signedTxXdr, networkPassphrase);
426
+ const receipt = await server.submitTransaction(signedTx);
427
+ if (!receipt.successful || !receipt.hash)
428
+ throw new Error("Stellar bridge deposit did not complete successfully.");
429
+ return {
430
+ success: true,
431
+ asset: sourceConfig.assetSymbol,
432
+ from,
433
+ to,
434
+ fromNetwork: sourceConfig.networkName,
435
+ toNetwork: destinationConfig.networkName,
436
+ routeId: route.id,
437
+ routeName: route.name,
438
+ amount: amount,
439
+ transactionHash: receipt.hash,
440
+ status: "submitted",
441
+ };
442
+ }
443
+ /** Bridge a configured ERC-20 asset between the configured internal and external EVM sides. */
444
+ export async function cordy_bridge(amount, from, to, recipient, options = {}) {
239
445
  try {
240
- return await bridgeEvm(normalizedAmount(amount), from, to, recipient);
446
+ const normalized = normalizedAmount(amount);
447
+ const route = resolveBridgeRoute(configuredAssets?.bridge, options.routeId);
448
+ const sourceConfig = route[from];
449
+ if (!sourceConfig) {
450
+ throw new Error(`Bridge source configuration for '${from}' is missing.`);
451
+ }
452
+ const destinationConfig = route[to];
453
+ if (!destinationConfig) {
454
+ throw new Error(`Bridge destination configuration for '${to}' is missing.`);
455
+ }
456
+ const needsEvmWallet = sourceConfig.networkType === "evm"
457
+ || (route.protocol === "cctp" && sourceConfig.networkType === "stellar" && destinationConfig.networkType === "evm");
458
+ if (needsEvmWallet) {
459
+ const walletConfig = getActiveWagmiConfig();
460
+ const current = walletConfig.state.current;
461
+ const connection = current ? walletConfig.state.connections.get(current) : undefined;
462
+ let connectedAddress = connection?.accounts[0];
463
+ if (!connectedAddress) {
464
+ connectedAddress = await waitForBridgeEvmWallet({
465
+ routeId: route.id,
466
+ amount: normalized,
467
+ from,
468
+ to,
469
+ recipient,
470
+ sourceChainId: sourceConfig.networkType === "evm" ? sourceConfig.chainId : destinationConfig.chainId,
471
+ sourceNetworkType: sourceConfig.networkType,
472
+ destinationNetworkType: destinationConfig.networkType,
473
+ });
474
+ }
475
+ if (!recipient && destinationConfig.networkType === "evm") {
476
+ recipient = connectedAddress;
477
+ }
478
+ }
479
+ if (route.protocol === "cctp") {
480
+ return await cctpBridge(normalized, from, to, recipient, route);
481
+ }
482
+ else if (sourceConfig.networkType === "stellar") {
483
+ return await bridgeStellar(normalized, from, to, recipient, options);
484
+ }
485
+ else if (sourceConfig.networkType === "evm") {
486
+ return await bridgeEvm(normalized, from, to, recipient, options);
487
+ }
488
+ else {
489
+ throw new Error(`Unsupported network type for bridging: ${sourceConfig.networkType}.`);
490
+ }
241
491
  }
242
492
  catch (error) {
243
- return { success: false, error: error instanceof Error ? error.message : "Could not submit the bridge deposit." };
493
+ const errorDetail = error instanceof Error ? error.message : String(error);
494
+ return {
495
+ success: false,
496
+ error: errorDetail,
497
+ errorDetail,
498
+ };
244
499
  }
245
500
  }
246
501
  async function transferEvm(amount, recipient, requestedSymbol) {
@@ -255,6 +510,7 @@ async function transferEvm(amount, recipient, requestedSymbol) {
255
510
  const provider = new BrowserProvider(rawProvider);
256
511
  const chain = await provider.getNetwork();
257
512
  const chainId = Number(chain.chainId);
513
+ requireConfiguredEvmNetwork(configuredAssets, chainId, chain.name);
258
514
  const tokenConfig = resolveEvmAsset(requestedSymbol, chainId, chain.name);
259
515
  const contractAddress = tokenConfig?.contractAddress || "";
260
516
  if (!contractAddress) {
@@ -298,6 +554,7 @@ async function readEvmBalance(requestedSymbol) {
298
554
  const provider = new BrowserProvider(rawProvider);
299
555
  const chain = await provider.getNetwork();
300
556
  const chainId = Number(chain.chainId);
557
+ requireConfiguredEvmNetwork(configuredAssets, chainId, chain.name);
301
558
  const tokenConfig = resolveEvmAsset(requestedSymbol, chainId, chain.name);
302
559
  const readProvider = await getEvmReadProvider(provider, chainId, chain.name, tokenConfig?.rpcUrl);
303
560
  const walletAddress = connection.accounts[0];
@@ -436,7 +693,7 @@ async function transferStellar(amount, recipient, requestedSymbol, memo) {
436
693
  throw new Error("Stellar transfer did not complete successfully.");
437
694
  return { success: true, asset: symbol, network: "stellar", transactionHash: receipt.hash };
438
695
  }
439
- async function swapEvm(amount, fromSymbol, toSymbol, tolerancePercent) {
696
+ async function swapEvm(amount, fromSymbol, toSymbol, tolerancePercent, options = {}) {
440
697
  const walletConfig = getActiveWagmiConfig();
441
698
  const current = walletConfig.state.current;
442
699
  const connection = current ? walletConfig.state.connections.get(current) : undefined;
@@ -446,15 +703,15 @@ async function swapEvm(amount, fromSymbol, toSymbol, tolerancePercent) {
446
703
  const provider = new BrowserProvider(rawProvider);
447
704
  const chain = await provider.getNetwork();
448
705
  const chainId = Number(chain.chainId);
706
+ requireConfiguredEvmNetwork(configuredAssets, chainId, chain.name);
449
707
  const networkConfig = resolveEvmSwapNetworkConfig(chainId);
450
708
  const networkName = networkConfig?.name || chain.name;
451
709
  const fromAsset = resolveConfiguredEvmSwapAsset(fromSymbol, chainId);
452
710
  const toAsset = resolveConfiguredEvmSwapAsset(toSymbol, chainId);
453
711
  if (fromSymbol.toLowerCase() === toSymbol.toLowerCase())
454
712
  throw new Error("Choose two different assets to swap.");
455
- if (!networkConfig?.swapRouterAddress || !isAddress(networkConfig.swapRouterAddress)) {
456
- throw new Error(`No valid Uniswap V2-compatible swap router is configured for ${networkName} (chain ID ${chainId}). Add swapRouterAddress to its network entry in assets JSON.`);
457
- }
713
+ if (!networkConfig)
714
+ throw new Error(`No swap network configuration found for ${networkName} (chain ID ${chainId}).`);
458
715
  const isNative = (asset) => asset.type === "native" || !asset.contractAddress;
459
716
  const fromNative = isNative(fromAsset);
460
717
  const toNative = isNative(toAsset);
@@ -466,42 +723,134 @@ async function swapEvm(amount, fromSymbol, toSymbol, tolerancePercent) {
466
723
  const toAddress = toNative ? wrappedNative : toAsset.contractAddress;
467
724
  if (!isAddress(fromAddress) || !isAddress(toAddress))
468
725
  throw new Error("A configured swap asset has an invalid token contract address.");
726
+ if (fromAddress.toLowerCase() === toAddress.toLowerCase())
727
+ throw new Error("These assets resolve to the same token contract and cannot be swapped.");
469
728
  const signer = await provider.getSigner(connection.accounts[0]);
470
729
  const sender = await signer.getAddress();
471
730
  const inputAmount = normalizedAmount(amount);
472
731
  const inputDecimals = fromNative ? 18 : fromAsset.decimals ?? Number(await new Contract(fromAddress, ERC20_SWAP_ABI, provider).decimals());
473
732
  const outputDecimals = toNative ? 18 : toAsset.decimals ?? Number(await new Contract(toAddress, ERC20_SWAP_ABI, provider).decimals());
474
733
  const amountIn = parseUnits(inputAmount, inputDecimals);
475
- const router = new Contract(networkConfig.swapRouterAddress, V2_SWAP_ROUTER_ABI, signer);
476
- const path = [fromAddress, toAddress];
477
- const amounts = await router.getAmountsOut(amountIn, path);
478
- const quotedOut = BigInt(amounts[amounts.length - 1].toString());
479
- if (quotedOut <= 0n)
480
- throw new Error(`No swap quote is available for ${fromSymbol} to ${toSymbol} on ${networkName}.`);
734
+ const version = options.version ?? "auto";
735
+ if (version !== "auto" && version !== "v2" && version !== "v3")
736
+ throw new Error("Swap version must be auto, v2, or v3.");
737
+ const candidates = [];
738
+ const v2RouterAddress = networkConfig.swapRouterAddress;
739
+ if ((version === "auto" || version === "v2") && v2RouterAddress && isAddress(v2RouterAddress)) {
740
+ try {
741
+ const router = new Contract(v2RouterAddress, V2_SWAP_ROUTER_ABI, provider);
742
+ const amounts = await router.getFunction("getAmountsOut").staticCall(amountIn, [fromAddress, toAddress]);
743
+ const quotedOut = BigInt(amounts[amounts.length - 1].toString());
744
+ if (quotedOut > 0n)
745
+ candidates.push({ version: "v2", quotedOut });
746
+ }
747
+ catch {
748
+ // A missing pool or unsupported route should not prevent trying V3 in auto mode.
749
+ }
750
+ }
751
+ const v3 = networkConfig.swapV3;
752
+ if ((version === "auto" || version === "v3") && v3 && isAddress(v3.routerAddress) && isAddress(v3.quoterAddress)) {
753
+ const feeTiers = options.feeTiers ?? (v3.feeTiers?.length ? v3.feeTiers : [500, 3000, 10000]);
754
+ if (options.feeTiers && (!options.feeTiers.length || options.feeTiers.some((feeTier) => !Number.isInteger(feeTier) || feeTier <= 0 || feeTier >= 1000000))) {
755
+ throw new Error("Per-swap feeTiers must be a non-empty array of integer pool fee values between 1 and 999999.");
756
+ }
757
+ const quoter = new Contract(v3.quoterAddress, V3_QUOTER_V2_ABI, provider);
758
+ for (const feeTier of feeTiers) {
759
+ if (!Number.isInteger(feeTier) || feeTier <= 0 || feeTier >= 1000000)
760
+ continue;
761
+ try {
762
+ const quote = await quoter.getFunction("quoteExactInputSingle").staticCall({
763
+ tokenIn: fromAddress,
764
+ tokenOut: toAddress,
765
+ amountIn,
766
+ fee: feeTier,
767
+ sqrtPriceLimitX96: 0,
768
+ });
769
+ const quotedOut = BigInt(quote[0].toString());
770
+ if (quotedOut > 0n)
771
+ candidates.push({ version: "v3", quotedOut, feeTier });
772
+ }
773
+ catch {
774
+ // This fee tier may not have a pool or may not be enabled on this deployment.
775
+ }
776
+ }
777
+ }
778
+ const candidate = candidates
779
+ .filter((item) => version === "auto" || item.version === version)
780
+ .sort((a, b) => a.quotedOut === b.quotedOut ? 0 : a.quotedOut > b.quotedOut ? -1 : 1)[0];
781
+ if (!candidate) {
782
+ if (version === "v2" && (!v2RouterAddress || !isAddress(v2RouterAddress))) {
783
+ throw new Error(`No valid V2 swap router is configured for ${networkName}. Add swapRouterAddress to its network entry.`);
784
+ }
785
+ if (version === "v3" && (!v3 || !isAddress(v3.routerAddress) || !isAddress(v3.quoterAddress))) {
786
+ throw new Error(`No valid V3 router and QuoterV2 are configured for ${networkName}. Add swapV3 to its network entry.`);
787
+ }
788
+ throw new Error(`No V2 or V3 quote is available for ${fromSymbol} to ${toSymbol} on ${networkName}. Check the router configuration, fee tiers, and pool liquidity.`);
789
+ }
790
+ const quotedOut = candidate.quotedOut;
481
791
  const minOut = quotedOut * swapMinimumOutputBps(tolerancePercent) / SWAP_BPS_DENOMINATOR;
482
792
  const deadline = Math.floor(Date.now() / 1000) + 20 * 60;
483
793
  let transaction;
484
- if (fromNative) {
485
- transaction = await router.swapExactETHForTokens(minOut, path, sender, deadline, { value: amountIn });
794
+ let selectedRouterAddress;
795
+ if (candidate.version === "v2") {
796
+ selectedRouterAddress = v2RouterAddress;
797
+ const router = new Contract(selectedRouterAddress, V2_SWAP_ROUTER_ABI, signer);
798
+ const path = [fromAddress, toAddress];
799
+ if (fromNative) {
800
+ transaction = await router.getFunction("swapExactETHForTokens").send(minOut, path, sender, deadline, { value: amountIn });
801
+ }
802
+ else {
803
+ const token = new Contract(fromAddress, ERC20_SWAP_ABI, signer);
804
+ const allowance = BigInt((await token.allowance(sender, selectedRouterAddress)).toString());
805
+ if (allowance < amountIn) {
806
+ if (allowance > 0n) {
807
+ const reset = await token.approve(selectedRouterAddress, 0n);
808
+ const resetReceipt = await reset.wait();
809
+ if (!resetReceipt || resetReceipt.status !== 1)
810
+ throw new Error(`Could not reset the ${fromSymbol} swap allowance.`);
811
+ }
812
+ const approval = await token.approve(selectedRouterAddress, amountIn);
813
+ const approvalReceipt = await approval.wait();
814
+ if (!approvalReceipt || approvalReceipt.status !== 1)
815
+ throw new Error(`Could not approve ${fromSymbol} for the swap.`);
816
+ }
817
+ transaction = toNative
818
+ ? await router.getFunction("swapExactTokensForETH").send(amountIn, minOut, path, sender, deadline)
819
+ : await router.getFunction("swapExactTokensForTokens").send(amountIn, minOut, path, sender, deadline);
820
+ }
486
821
  }
487
822
  else {
488
- const token = new Contract(fromAddress, ERC20_SWAP_ABI, signer);
489
- const allowance = BigInt((await token.allowance(sender, networkConfig.swapRouterAddress)).toString());
490
- if (allowance < amountIn) {
491
- if (allowance > 0n) {
492
- const reset = await token.approve(networkConfig.swapRouterAddress, 0n);
493
- const resetReceipt = await reset.wait();
494
- if (!resetReceipt || resetReceipt.status !== 1)
495
- throw new Error(`Could not reset the ${fromSymbol} swap allowance.`);
823
+ selectedRouterAddress = v3.routerAddress;
824
+ const routerAbi = v3.routerType === "swapRouter02" ? V3_ROUTER_02_ABI : V3_ROUTER_ABI;
825
+ const router = new Contract(selectedRouterAddress, routerAbi, signer);
826
+ if (!fromNative) {
827
+ const token = new Contract(fromAddress, ERC20_SWAP_ABI, signer);
828
+ const allowance = BigInt((await token.allowance(sender, selectedRouterAddress)).toString());
829
+ if (allowance < amountIn) {
830
+ if (allowance > 0n) {
831
+ const reset = await token.approve(selectedRouterAddress, 0n);
832
+ const resetReceipt = await reset.wait();
833
+ if (!resetReceipt || resetReceipt.status !== 1)
834
+ throw new Error(`Could not reset the ${fromSymbol} swap allowance.`);
835
+ }
836
+ const approval = await token.approve(selectedRouterAddress, amountIn);
837
+ const approvalReceipt = await approval.wait();
838
+ if (!approvalReceipt || approvalReceipt.status !== 1)
839
+ throw new Error(`Could not approve ${fromSymbol} for the swap.`);
496
840
  }
497
- const approval = await token.approve(networkConfig.swapRouterAddress, amountIn);
498
- const approvalReceipt = await approval.wait();
499
- if (!approvalReceipt || approvalReceipt.status !== 1)
500
- throw new Error(`Could not approve ${fromSymbol} for the swap.`);
501
841
  }
842
+ const routerRecipient = toNative ? selectedRouterAddress : sender;
843
+ const params = v3.routerType === "swapRouter02"
844
+ ? [fromAddress, toAddress, candidate.feeTier, routerRecipient, amountIn, minOut, 0n]
845
+ : [fromAddress, toAddress, candidate.feeTier, routerRecipient, deadline, amountIn, minOut, 0n];
846
+ const swapData = router.interface.encodeFunctionData("exactInputSingle", [params]);
847
+ const overrides = fromNative ? { value: amountIn } : {};
502
848
  transaction = toNative
503
- ? await router.swapExactTokensForETH(amountIn, minOut, path, sender, deadline)
504
- : await router.swapExactTokensForTokens(amountIn, minOut, path, sender, deadline);
849
+ ? await router.getFunction("multicall").send([
850
+ swapData,
851
+ router.interface.encodeFunctionData("unwrapWETH9", [minOut, sender]),
852
+ ], overrides)
853
+ : await router.getFunction("exactInputSingle").send(params, overrides);
505
854
  }
506
855
  const receipt = await transaction.wait();
507
856
  if (!receipt || receipt.status !== 1)
@@ -513,6 +862,8 @@ async function swapEvm(amount, fromSymbol, toSymbol, tolerancePercent) {
513
862
  to: toAsset.symbol,
514
863
  amountIn: inputAmount,
515
864
  estimatedAmountOut: formatUnits(quotedOut, outputDecimals),
865
+ version: candidate.version,
866
+ ...(candidate.feeTier ? { feeTier: candidate.feeTier } : {}),
516
867
  transactionHash: receipt.hash || transaction.hash,
517
868
  };
518
869
  }
@@ -575,14 +926,14 @@ async function swapStellar(amount, fromSymbol, toSymbol, tolerancePercent) {
575
926
  };
576
927
  }
577
928
  /** Swap two configured assets using the active EVM or Stellar wallet. */
578
- export async function cordy_swap(amount, from, to, tolerancePercent = DEFAULT_SWAP_TOLERANCE_PERCENT) {
929
+ export async function cordy_swap(amount, from, to, tolerancePercent = DEFAULT_SWAP_TOLERANCE_PERCENT, options = {}) {
579
930
  try {
580
931
  swapMinimumOutputBps(tolerancePercent);
581
932
  const normalized = normalizedAmount(amount);
582
933
  const activeWallet = getActiveWallet();
583
934
  return activeWallet === "stellar"
584
935
  ? await swapStellar(normalized, from, to, tolerancePercent)
585
- : await swapEvm(normalized, from, to, tolerancePercent);
936
+ : await swapEvm(normalized, from, to, tolerancePercent, options);
586
937
  }
587
938
  catch (error) {
588
939
  return { success: false, error: error instanceof Error ? error.message : "Could not swap the selected assets." };