@cordystackx/cordy_minikit 2.0.11 → 3.0.1

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 (67) hide show
  1. package/README.md +58 -752
  2. package/dist/client/jwt.d.ts +32 -0
  3. package/dist/client/jwt.d.ts.map +1 -0
  4. package/dist/client/jwt.js +84 -0
  5. package/dist/client/transfer.d.ts +104 -0
  6. package/dist/client/transfer.d.ts.map +1 -0
  7. package/dist/client/transfer.js +613 -0
  8. package/dist/client.d.ts +5 -0
  9. package/dist/client.d.ts.map +1 -0
  10. package/dist/client.js +2 -0
  11. package/dist/client__provider.d.ts +3 -1
  12. package/dist/client__provider.d.ts.map +1 -1
  13. package/dist/client__provider.js +29 -2
  14. package/dist/components/Connect_wallet_bt.d.ts +9 -3
  15. package/dist/components/Connect_wallet_bt.d.ts.map +1 -1
  16. package/dist/components/Connect_wallet_bt.js +63 -47
  17. package/dist/components/UI_Comp.d.ts.map +1 -1
  18. package/dist/components/UI_Comp.js +51 -60
  19. package/dist/config/Image.json +2 -2
  20. package/dist/config/walletConfig.d.ts +3 -0
  21. package/dist/config/walletConfig.d.ts.map +1 -1
  22. package/dist/config/walletConfig.js +43 -2
  23. package/dist/controllers/Get_Balance.d.ts +22 -0
  24. package/dist/controllers/Get_Balance.d.ts.map +1 -1
  25. package/dist/controllers/Get_Balance.js +90 -28
  26. package/dist/controllers/StellarButton.d.ts.map +1 -1
  27. package/dist/controllers/StellarButton.js +4 -0
  28. package/dist/controllers/Transactions.d.ts +2 -0
  29. package/dist/controllers/Transactions.d.ts.map +1 -1
  30. package/dist/controllers/Transactions.js +2 -0
  31. package/dist/controllers/WagmiButton.d.ts +2 -1
  32. package/dist/controllers/WagmiButton.d.ts.map +1 -1
  33. package/dist/controllers/WagmiButton.js +32 -32
  34. package/dist/controllers/index.d.ts +0 -1
  35. package/dist/controllers/index.d.ts.map +1 -1
  36. package/dist/controllers/index.js +0 -1
  37. package/dist/controllers/loadStellarBalance.d.ts +23 -1
  38. package/dist/controllers/loadStellarBalance.d.ts.map +1 -1
  39. package/dist/controllers/loadStellarBalance.js +47 -14
  40. package/dist/css/UI_Comp/styles.module.css +121 -314
  41. package/dist/demo/next.config.d.ts +4 -0
  42. package/dist/demo/next.config.d.ts.map +1 -0
  43. package/dist/demo/next.config.js +12 -0
  44. package/dist/demo/src/app/layout.d.ts +5 -0
  45. package/dist/demo/src/app/layout.d.ts.map +1 -0
  46. package/dist/demo/src/app/layout.js +9 -0
  47. package/dist/demo/src/app/page.d.ts +2 -0
  48. package/dist/demo/src/app/page.d.ts.map +1 -0
  49. package/dist/demo/src/app/page.js +9 -0
  50. package/dist/index.d.ts +4 -0
  51. package/dist/index.d.ts.map +1 -1
  52. package/dist/index.js +3 -0
  53. package/dist/package.json +28 -14
  54. package/dist/server/jwt.d.ts +18 -0
  55. package/dist/server/jwt.d.ts.map +1 -0
  56. package/dist/server/jwt.js +35 -0
  57. package/dist/server.d.ts +3 -0
  58. package/dist/server.d.ts.map +1 -0
  59. package/dist/server.js +1 -0
  60. package/dist/tsconfig.tsbuildinfo +1 -1
  61. package/dist/wagmi__providers.d.ts +7 -2
  62. package/dist/wagmi__providers.d.ts.map +1 -1
  63. package/dist/wagmi__providers.js +24 -5
  64. package/package.json +28 -14
  65. package/dist/controllers/AirDrop_Faucet.d.ts +0 -2
  66. package/dist/controllers/AirDrop_Faucet.d.ts.map +0 -1
  67. package/dist/controllers/AirDrop_Faucet.js +0 -93
@@ -0,0 +1,613 @@
1
+ "use client";
2
+ import { Asset, BASE_FEE, Horizon, Memo, Networks, Operation, StrKey, TransactionBuilder } from "@stellar/stellar-sdk";
3
+ import { getNetworkDetails, requestAccess, signTransaction as freighterSignTransaction } from "@stellar/freighter-api";
4
+ import { BrowserProvider, Contract, formatUnits, isAddress, JsonRpcProvider, parseUnits } from "ethers";
5
+ import { getActiveWagmiConfig } from "../config/walletConfig";
6
+ import { readTokenBalance } from "../controllers/Get_Balance";
7
+ import loadStellarBalance from "../controllers/loadStellarBalance";
8
+ import tokenAbi from "../config/ERC20_ABI.json";
9
+ const ACTIVE_WALLET_SESSION_KEY = "cordy_minikit_active_wallet_session";
10
+ const STELLAR_WALLET_STORAGE_KEY = "cordy_minikit_stellar_wallet";
11
+ const stellarRpc = process.env.NEXT_PUBLIC_STELLAR_HORIZON || "https://horizon-testnet.stellar.org";
12
+ const stellarNetwork = process.env.NEXT_PUBLIC_STELLAR_NETWORK_PASSPHRASE || Networks.TESTNET;
13
+ // First test route: BOT Chain Testnet <-> Ethereum Sepolia, USDT only.
14
+ const BOT_TESTNET_CHAIN_ID = 968;
15
+ const SEPOLIA_CHAIN_ID = 11155111;
16
+ const BOT_TESTNET_BRIDGE_ROUTER = "0x6239404Aa276ba68486E2Fa40E90CDd36ff8ec3A";
17
+ const BOT_TESTNET_USDT = "0x75edC9335175Fc0552D51D48439F229c10420fe3";
18
+ const SEPOLIA_BRIDGE_GATEWAY = "0xc83AE6F73e8918750b87DD001E36093A1AB7b272";
19
+ const SEPOLIA_USDT = "0x7B1e05a39adF207a759EAf89E867dBcC1C615130";
20
+ const USDT_RESOURCE_ID = "0xac589789ed8c9d2c61f17b13369864b5f181e58eba230a6ee4ec4c3e7750cd1d";
21
+ const BRIDGE_ERC20_ABI = [
22
+ "function allowance(address owner,address spender) view returns (uint256)",
23
+ "function approve(address spender,uint256 amount) returns (bool)",
24
+ "function balanceOf(address owner) view returns (uint256)",
25
+ "function decimals() view returns (uint8)",
26
+ ];
27
+ const BOT_BRIDGE_ABI = [
28
+ "function deposit(uint256 destinationChainId,bytes32 resourceId,address recipient,uint256 amount) payable",
29
+ ];
30
+ let configuredAssets;
31
+ export function configureCordyAssets({ assets }) {
32
+ if (!assets || (assets.networks !== undefined && !Array.isArray(assets.networks)) ||
33
+ (assets.evm !== undefined && !Array.isArray(assets.evm)) ||
34
+ (assets.stellar !== undefined && !Array.isArray(assets.stellar))) {
35
+ throw new Error('Cordy Minikit: "networks", "evm", and "stellar" must be arrays when provided.');
36
+ }
37
+ configuredAssets = {
38
+ networks: (assets.networks ?? []).map((network) => ({ ...network, nativeCurrency: { ...network.nativeCurrency } })),
39
+ evm: (assets.evm ?? []).map((asset) => ({ ...asset })),
40
+ stellar: (assets.stellar ?? []).map((asset) => ({ ...asset })),
41
+ };
42
+ }
43
+ function normalizedAmount(amount) {
44
+ const value = String(amount).trim();
45
+ if (!/^\d+(\.\d+)?$/.test(value) || !Number.isFinite(Number(value)) || Number(value) <= 0) {
46
+ throw new Error("Amount must be a positive decimal number.");
47
+ }
48
+ return value;
49
+ }
50
+ function resolveEvmAsset(requestedSymbol, chainId, networkName) {
51
+ if (!requestedSymbol)
52
+ return undefined;
53
+ const sameSymbol = (configuredAssets?.evm ?? []).filter((asset) => asset.symbol.toLowerCase() === requestedSymbol.toLowerCase());
54
+ const configuredChainId = Number(process.env.NEXT_PUBLIC_CHAIN_ID);
55
+ const matchingNetwork = sameSymbol.find((asset) => (asset.chainId ?? configuredChainId) === chainId);
56
+ if (sameSymbol.length > 0 && !matchingNetwork) {
57
+ const chainIds = [...new Set(sameSymbol.map((asset) => asset.chainId ?? configuredChainId))].join(", ");
58
+ throw new Error(`${requestedSymbol} 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.`);
59
+ }
60
+ return matchingNetwork;
61
+ }
62
+ function resolveConfiguredEvmSwapAsset(symbol, chainId) {
63
+ const configuredChainId = Number(process.env.NEXT_PUBLIC_CHAIN_ID);
64
+ const matches = (configuredAssets?.evm ?? []).filter((asset) => asset.symbol.toLowerCase() === symbol.toLowerCase() &&
65
+ (asset.chainId ?? configuredChainId) === chainId);
66
+ if (matches.length > 1) {
67
+ throw new Error(`More than one ${symbol} asset is configured for chain ID ${chainId}. Keep one entry per asset and network.`);
68
+ }
69
+ if (matches.length === 1)
70
+ return matches[0];
71
+ const envTokenSymbol = process.env.NEXT_PUBLIC_TOKEN_SYMBOL?.trim();
72
+ const envTokenAddress = process.env.NEXT_PUBLIC_TOKENADDRESS?.trim();
73
+ const envChainId = Number(process.env.NEXT_PUBLIC_CHAIN_ID);
74
+ if (envTokenSymbol?.toLowerCase() === symbol.toLowerCase() &&
75
+ envTokenAddress &&
76
+ Number.isSafeInteger(envChainId) &&
77
+ envChainId === chainId) {
78
+ if (!isAddress(envTokenAddress))
79
+ throw new Error("NEXT_PUBLIC_TOKENADDRESS is not a valid EVM token address.");
80
+ return {
81
+ symbol: envTokenSymbol,
82
+ chainId,
83
+ contractAddress: envTokenAddress,
84
+ rpcUrl: process.env.NEXT_PUBLIC_RPC_ENDPOINT,
85
+ };
86
+ }
87
+ throw new Error(`${symbol} is not configured for EVM chain ID ${chainId}. Add it to the assets JSON or configure it with NEXT_PUBLIC_TOKEN_SYMBOL and NEXT_PUBLIC_TOKENADDRESS for this chain.`);
88
+ }
89
+ function resolveConfiguredStellarSwapAsset(symbol, networkPassphrase) {
90
+ const matches = (configuredAssets?.stellar ?? []).filter((asset) => asset.symbol.toLowerCase() === symbol.toLowerCase() &&
91
+ (!asset.networkPassphrase || asset.networkPassphrase === networkPassphrase));
92
+ if (matches.length !== 1) {
93
+ throw new Error(matches.length > 1
94
+ ? `More than one ${symbol} asset is configured for this Stellar network. Keep one entry per asset and network.`
95
+ : `${symbol} is not configured for this Stellar network. Add it to the assets JSON before swapping.`);
96
+ }
97
+ return matches[0];
98
+ }
99
+ const V2_SWAP_ROUTER_ABI = [
100
+ "function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts)",
101
+ "function swapExactTokensForTokens(uint amountIn,uint amountOutMin,address[] calldata path,address to,uint deadline) external returns (uint[] memory amounts)",
102
+ "function swapExactETHForTokens(uint amountOutMin,address[] calldata path,address to,uint deadline) external payable returns (uint[] memory amounts)",
103
+ "function swapExactTokensForETH(uint amountIn,uint amountOutMin,address[] calldata path,address to,uint deadline) external returns (uint[] memory amounts)",
104
+ ];
105
+ const ERC20_SWAP_ABI = [
106
+ "function approve(address spender,uint256 amount) returns (bool)",
107
+ "function allowance(address owner,address spender) view returns (uint256)",
108
+ "function decimals() view returns (uint8)",
109
+ ];
110
+ function resolveEvmSwapNetworkConfig(chainId, fallbackName) {
111
+ const registered = configuredAssets?.networks?.find((network) => network.chainId === chainId);
112
+ if (registered)
113
+ return registered;
114
+ const envChainId = Number(process.env.NEXT_PUBLIC_CHAIN_ID);
115
+ const rpcUrl = process.env.NEXT_PUBLIC_RPC_ENDPOINT;
116
+ if (!rpcUrl || !Number.isSafeInteger(envChainId) || envChainId !== chainId)
117
+ return undefined;
118
+ return {
119
+ chainId,
120
+ name: process.env.NEXT_PUBLIC_CHAIN_NAME || fallbackName,
121
+ rpcUrl,
122
+ swapRouterAddress: process.env.NEXT_PUBLIC_SWAP_ROUTER_ADDRESS,
123
+ wrappedNativeTokenAddress: process.env.NEXT_PUBLIC_WRAPPED_NATIVE_TOKEN_ADDRESS,
124
+ };
125
+ }
126
+ async function getEvmReadProvider(walletProvider, chainId, networkName, assetRpcUrl) {
127
+ const rpcUrl = assetRpcUrl || configuredAssets?.networks?.find((network) => network.chainId === chainId)?.rpcUrl || process.env.NEXT_PUBLIC_RPC_ENDPOINT;
128
+ if (!rpcUrl)
129
+ return walletProvider;
130
+ const rpcProvider = new JsonRpcProvider(rpcUrl);
131
+ let rpcNetwork;
132
+ try {
133
+ rpcNetwork = await rpcProvider.getNetwork();
134
+ }
135
+ catch {
136
+ if (!assetRpcUrl && !configuredAssets?.networks?.some((network) => network.rpcUrl === rpcUrl))
137
+ return walletProvider;
138
+ throw new Error(`Could not reach the configured EVM RPC endpoint for ${networkName}. Check its URL and availability.`);
139
+ }
140
+ if (Number(rpcNetwork.chainId) !== chainId) {
141
+ throw new Error(`The configured EVM RPC is on chain ID ${rpcNetwork.chainId}, but the wallet is on ${networkName} (chain ID ${chainId}). Use an RPC for the connected network.`);
142
+ }
143
+ return rpcProvider;
144
+ }
145
+ function getActiveWallet() {
146
+ if (typeof window === "undefined")
147
+ throw new Error("Transfers must be started in the browser.");
148
+ const selected = window.localStorage.getItem(ACTIVE_WALLET_SESSION_KEY);
149
+ if (selected === "stellar")
150
+ return "stellar";
151
+ if (selected === "evm")
152
+ return "evm";
153
+ const walletConfig = getActiveWagmiConfig();
154
+ const current = walletConfig.state.current;
155
+ if (current && walletConfig.state.connections.has(current))
156
+ return "evm";
157
+ try {
158
+ const stored = JSON.parse(window.localStorage.getItem(STELLAR_WALLET_STORAGE_KEY) || "null");
159
+ if (stored?.address)
160
+ return "stellar";
161
+ }
162
+ catch {
163
+ // Ignore invalid stale wallet state and report that no wallet is active below.
164
+ }
165
+ throw new Error("Connect an EVM or Stellar wallet first.");
166
+ }
167
+ async function bridgeEvm(amount, from, to, recipient) {
168
+ if (from !== "internal" && from !== "external")
169
+ throw new Error("Source must be internal or external.");
170
+ if (to !== "internal" && to !== "external")
171
+ throw new Error("Destination must be internal or external.");
172
+ if (from === to)
173
+ throw new Error("Choose different source and destination sides.");
174
+ if (!isAddress(recipient))
175
+ throw new Error("Recipient must be a valid EVM address.");
176
+ const walletConfig = getActiveWagmiConfig();
177
+ const current = walletConfig.state.current;
178
+ const connection = current ? walletConfig.state.connections.get(current) : undefined;
179
+ if (!connection)
180
+ throw new Error("No EVM wallet is currently connected.");
181
+ const rawProvider = await connection.connector.getProvider();
182
+ const provider = new BrowserProvider(rawProvider);
183
+ const chain = await provider.getNetwork();
184
+ const chainId = Number(chain.chainId);
185
+ const expectedSourceChainId = from === "internal" ? BOT_TESTNET_CHAIN_ID : SEPOLIA_CHAIN_ID;
186
+ const destinationChainId = to === "internal" ? BOT_TESTNET_CHAIN_ID : SEPOLIA_CHAIN_ID;
187
+ if (chainId !== expectedSourceChainId) {
188
+ const expectedNetwork = from === "internal" ? "BOT Chain Testnet" : "Ethereum Sepolia";
189
+ 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}).`);
190
+ }
191
+ const inputAmount = normalizedAmount(amount);
192
+ if (from === "internal" && Number(inputAmount) <= 10) {
193
+ throw new Error("BOT Chain Testnet bridge-out requires more than 10 USDT.");
194
+ }
195
+ const tokenAddress = from === "internal" ? BOT_TESTNET_USDT : SEPOLIA_USDT;
196
+ const bridgeAddress = from === "internal" ? BOT_TESTNET_BRIDGE_ROUTER : SEPOLIA_BRIDGE_GATEWAY;
197
+ const signer = await provider.getSigner(connection.accounts[0]);
198
+ const sender = await signer.getAddress();
199
+ const token = new Contract(tokenAddress, BRIDGE_ERC20_ABI, signer);
200
+ const code = await provider.getCode(bridgeAddress);
201
+ if (code === "0x")
202
+ throw new Error(`No bridge contract is deployed at the configured ${from === "internal" ? "BOT Chain Testnet" : "Sepolia"} testnet address.`);
203
+ const decimals = Number(await token.decimals());
204
+ if (!Number.isInteger(decimals) || decimals < 0 || decimals > 18)
205
+ throw new Error("The configured test USDT token returned invalid decimals.");
206
+ const amountIn = parseUnits(inputAmount, decimals);
207
+ const tokenBalance = BigInt((await token.balanceOf(sender)).toString());
208
+ if (tokenBalance < amountIn)
209
+ throw new Error(`Insufficient test USDT on ${from === "internal" ? "BOT Chain Testnet" : "Sepolia"}.`);
210
+ const allowance = BigInt((await token.allowance(sender, bridgeAddress)).toString());
211
+ let approvalTransactionHash;
212
+ if (allowance < amountIn) {
213
+ if (allowance > 0n) {
214
+ const reset = await token.approve(bridgeAddress, 0n);
215
+ const resetReceipt = await reset.wait();
216
+ if (!resetReceipt || resetReceipt.status !== 1)
217
+ throw new Error("Could not reset the USDT bridge allowance.");
218
+ }
219
+ const approval = await token.approve(bridgeAddress, amountIn);
220
+ const approvalReceipt = await approval.wait();
221
+ if (!approvalReceipt || approvalReceipt.status !== 1)
222
+ throw new Error("Could not approve USDT for the bridge.");
223
+ approvalTransactionHash = approvalReceipt.hash || approval.hash;
224
+ }
225
+ const bridge = new Contract(bridgeAddress, BOT_BRIDGE_ABI, signer);
226
+ const transaction = await bridge.deposit(destinationChainId, USDT_RESOURCE_ID, recipient, amountIn);
227
+ const receipt = await transaction.wait();
228
+ if (!receipt || receipt.status !== 1)
229
+ throw new Error("The source-chain bridge deposit failed.");
230
+ return {
231
+ success: true,
232
+ asset: "USDT",
233
+ from,
234
+ to,
235
+ fromNetwork: from === "internal" ? "BOT Chain Testnet" : "Ethereum Sepolia",
236
+ toNetwork: to === "internal" ? "BOT Chain Testnet" : "Ethereum Sepolia",
237
+ amount: inputAmount,
238
+ ...(approvalTransactionHash ? { approvalTransactionHash } : {}),
239
+ transactionHash: receipt.hash || transaction.hash,
240
+ status: "submitted",
241
+ };
242
+ }
243
+ /** Bridge test USDT between BOT Chain Testnet (internal) and Ethereum Sepolia (external). */
244
+ export async function cordy_bridge(amount, from, to, recipient) {
245
+ try {
246
+ return await bridgeEvm(normalizedAmount(amount), from, to, recipient);
247
+ }
248
+ catch (error) {
249
+ return { success: false, error: error instanceof Error ? error.message : "Could not submit the bridge deposit." };
250
+ }
251
+ }
252
+ async function transferEvm(amount, recipient, requestedSymbol) {
253
+ if (!isAddress(recipient))
254
+ throw new Error("Recipient must be a valid EVM address.");
255
+ const walletConfig = getActiveWagmiConfig();
256
+ const current = walletConfig.state.current;
257
+ const connection = current ? walletConfig.state.connections.get(current) : undefined;
258
+ if (!connection)
259
+ throw new Error("No EVM wallet is currently connected.");
260
+ const rawProvider = await connection.connector.getProvider();
261
+ const provider = new BrowserProvider(rawProvider);
262
+ const chain = await provider.getNetwork();
263
+ const chainId = Number(chain.chainId);
264
+ const tokenConfig = resolveEvmAsset(requestedSymbol, chainId, chain.name);
265
+ const fallbackAddress = process.env.NEXT_PUBLIC_TOKENADDRESS || "";
266
+ const contractAddress = tokenConfig?.contractAddress || fallbackAddress;
267
+ if (!contractAddress) {
268
+ throw new Error(`No ${requestedSymbol || "default"} EVM token configured. Add it to the asset JSON or set NEXT_PUBLIC_TOKENADDRESS.`);
269
+ }
270
+ if (!isAddress(contractAddress))
271
+ throw new Error("The configured EVM token contract address is invalid.");
272
+ const readProvider = await getEvmReadProvider(provider, chainId, chain.name, tokenConfig?.rpcUrl);
273
+ const signer = await provider.getSigner(connection.accounts[0]);
274
+ const from = await signer.getAddress();
275
+ const balance = await readTokenBalance(from, {
276
+ tokenAddress: contractAddress,
277
+ rpcUrl: tokenConfig?.rpcUrl || configuredAssets?.networks?.find((network) => network.chainId === chainId)?.rpcUrl,
278
+ provider: readProvider,
279
+ fallbackProvider: provider,
280
+ expectedChainId: chainId,
281
+ networkName: chain.name,
282
+ symbol: tokenConfig?.symbol,
283
+ decimals: tokenConfig?.decimals,
284
+ });
285
+ if (requestedSymbol && balance.symbol.toLowerCase() !== requestedSymbol.toLowerCase()) {
286
+ throw new Error(`The configured token is ${balance.symbol}, not ${requestedSymbol}. Add ${requestedSymbol} to the asset JSON.`);
287
+ }
288
+ const value = parseUnits(amount, balance.decimals);
289
+ if (BigInt(balance.rawBalance) < value)
290
+ throw new Error(`Insufficient ${balance.symbol} balance for this transfer.`);
291
+ const writeToken = new Contract(contractAddress, tokenAbi, signer);
292
+ const transaction = await writeToken.transfer(recipient, value);
293
+ const receipt = await transaction.wait();
294
+ if (!receipt || receipt.status !== 1)
295
+ throw new Error("EVM transfer did not complete successfully.");
296
+ return { success: true, asset: balance.symbol, network: "evm", transactionHash: receipt.hash || transaction.hash };
297
+ }
298
+ async function readEvmBalance(requestedSymbol) {
299
+ const walletConfig = getActiveWagmiConfig();
300
+ const current = walletConfig.state.current;
301
+ const connection = current ? walletConfig.state.connections.get(current) : undefined;
302
+ if (!connection)
303
+ throw new Error("No EVM wallet is currently connected.");
304
+ const rawProvider = await connection.connector.getProvider();
305
+ const provider = new BrowserProvider(rawProvider);
306
+ const chain = await provider.getNetwork();
307
+ const chainId = Number(chain.chainId);
308
+ const tokenConfig = resolveEvmAsset(requestedSymbol, chainId, chain.name);
309
+ const readProvider = await getEvmReadProvider(provider, chainId, chain.name, tokenConfig?.rpcUrl);
310
+ const walletAddress = connection.accounts[0];
311
+ if (!walletAddress)
312
+ throw new Error("No EVM wallet account is currently connected.");
313
+ if (tokenConfig?.type === "native") {
314
+ return {
315
+ success: true,
316
+ network: chain.name,
317
+ balance: formatUnits(await readProvider.getBalance(walletAddress), 18),
318
+ asset: tokenConfig.symbol,
319
+ };
320
+ }
321
+ const contractAddress = tokenConfig?.contractAddress || process.env.NEXT_PUBLIC_TOKENADDRESS || "";
322
+ if (!contractAddress) {
323
+ throw new Error(`No ${requestedSymbol || "default"} EVM token configured. Add it to the asset JSON or set NEXT_PUBLIC_TOKENADDRESS.`);
324
+ }
325
+ if (!isAddress(contractAddress))
326
+ throw new Error("The configured EVM token contract address is invalid.");
327
+ const balance = await readTokenBalance(walletAddress, {
328
+ tokenAddress: contractAddress,
329
+ rpcUrl: tokenConfig?.rpcUrl || configuredAssets?.networks?.find((network) => network.chainId === chainId)?.rpcUrl,
330
+ provider: readProvider,
331
+ fallbackProvider: provider,
332
+ expectedChainId: chainId,
333
+ networkName: chain.name,
334
+ symbol: tokenConfig?.symbol,
335
+ decimals: tokenConfig?.decimals,
336
+ });
337
+ if (requestedSymbol && balance.symbol.toLowerCase() !== requestedSymbol.toLowerCase()) {
338
+ throw new Error(`The configured token is ${balance.symbol}, not ${requestedSymbol}. Add ${requestedSymbol} to the asset JSON.`);
339
+ }
340
+ return {
341
+ success: true,
342
+ network: chain.name,
343
+ balance: balance.balance,
344
+ asset: balance.symbol,
345
+ };
346
+ }
347
+ async function readStellarBalance(requestedSymbol) {
348
+ const symbol = requestedSymbol || "XLM";
349
+ const access = await requestAccess();
350
+ const address = access.address;
351
+ if (!address)
352
+ throw new Error("Could not access the connected Stellar wallet.");
353
+ const balance = await loadStellarBalance(address, {
354
+ assetSymbol: symbol,
355
+ assets: configuredAssets?.stellar,
356
+ horizonUrl: stellarRpc,
357
+ networkPassphrase: stellarNetwork,
358
+ });
359
+ return {
360
+ success: true,
361
+ network: balance.network,
362
+ balance: balance.balance,
363
+ asset: balance.asset,
364
+ };
365
+ }
366
+ /** Read the full-precision balance for the active wallet and selected asset. */
367
+ export async function cordy_balance(options = {}) {
368
+ try {
369
+ const activeWallet = getActiveWallet();
370
+ return activeWallet === "stellar"
371
+ ? await readStellarBalance(options.asset)
372
+ : await readEvmBalance(options.asset);
373
+ }
374
+ catch (error) {
375
+ return {
376
+ success: false,
377
+ error: error instanceof Error ? error.message : "Could not read wallet balance.",
378
+ };
379
+ }
380
+ }
381
+ async function transferStellar(amount, recipient, requestedSymbol, memo) {
382
+ if (!StrKey.isValidEd25519PublicKey(recipient))
383
+ throw new Error("Recipient must be a valid Stellar public address.");
384
+ if (!/^\d+(\.\d{1,7})?$/.test(amount))
385
+ throw new Error("Stellar amounts support up to 7 decimal places.");
386
+ const symbol = requestedSymbol || "XLM";
387
+ const access = await requestAccess();
388
+ const sourceAddress = access.address;
389
+ if (!sourceAddress)
390
+ throw new Error("Could not access the connected Stellar wallet.");
391
+ const networkDetails = await getNetworkDetails();
392
+ const networkPassphrase = networkDetails.networkPassphrase || stellarNetwork;
393
+ if (networkDetails.networkPassphrase && networkDetails.networkPassphrase !== stellarNetwork) {
394
+ throw new Error(`Stellar network mismatch. Expected ${stellarNetwork}, got ${networkDetails.networkPassphrase}.`);
395
+ }
396
+ const candidates = (configuredAssets?.stellar ?? []).filter((asset) => asset.symbol.toLowerCase() === symbol.toLowerCase() &&
397
+ (!asset.networkPassphrase || asset.networkPassphrase === networkPassphrase));
398
+ if (candidates.length > 1)
399
+ throw new Error(`More than one ${symbol} asset matches this Stellar network; make the JSON entries unique.`);
400
+ const assetConfig = candidates[0] ??
401
+ (symbol.toLowerCase() === "xlm" ? { symbol: "XLM", type: "native" } : undefined);
402
+ if (!assetConfig)
403
+ throw new Error(`No ${symbol} asset is configured for this Stellar network.`);
404
+ const stellarAsset = assetConfig.type === "native"
405
+ ? Asset.native()
406
+ : new Asset(assetConfig.code, assetConfig.issuer);
407
+ const server = new Horizon.Server(stellarRpc);
408
+ const sourceAccount = await server.loadAccount(sourceAddress);
409
+ const assetBalance = assetConfig.type === "native"
410
+ ? sourceAccount.balances.find((item) => item.asset_type === "native")
411
+ : sourceAccount.balances.find((item) => (item.asset_type === "credit_alphanum4" || item.asset_type === "credit_alphanum12") &&
412
+ item.asset_code === assetConfig.code &&
413
+ item.asset_issuer === assetConfig.issuer);
414
+ if (!assetBalance) {
415
+ throw new Error(assetConfig.type === "native"
416
+ ? `The connected Stellar account has no ${symbol} balance.`
417
+ : `The connected Stellar account has no ${symbol} trustline from the configured issuer.`);
418
+ }
419
+ const requiredBalance = Number(amount) + (assetConfig.type === "native" ? 0.00001 : 0);
420
+ if (Number(assetBalance.balance) < requiredBalance)
421
+ throw new Error(`Insufficient ${symbol} balance for this transfer.`);
422
+ const builder = new TransactionBuilder(sourceAccount, { fee: BASE_FEE, networkPassphrase })
423
+ .addOperation(Operation.payment({ destination: recipient, asset: stellarAsset, amount: Number(amount).toFixed(7) }))
424
+ .setTimeout(180);
425
+ const memoText = memo?.trim();
426
+ if (memoText) {
427
+ if (new TextEncoder().encode(memoText).length > 28)
428
+ throw new Error("Stellar text memos must be 28 bytes or fewer.");
429
+ builder.addMemo(Memo.text(memoText));
430
+ }
431
+ const unsignedTx = builder.build();
432
+ const { signedTxXdr, error } = await freighterSignTransaction(unsignedTx.toXDR(), {
433
+ networkPassphrase,
434
+ address: sourceAddress,
435
+ });
436
+ if (error || !signedTxXdr)
437
+ throw new Error(error?.message || "Stellar wallet signing was rejected.");
438
+ const signedTx = TransactionBuilder.fromXDR(signedTxXdr, networkPassphrase);
439
+ const receipt = await server.submitTransaction(signedTx);
440
+ if (!receipt.successful || !receipt.hash)
441
+ throw new Error("Stellar transfer did not complete successfully.");
442
+ return { success: true, asset: symbol, network: "stellar", transactionHash: receipt.hash };
443
+ }
444
+ async function swapEvm(amount, fromSymbol, toSymbol) {
445
+ const walletConfig = getActiveWagmiConfig();
446
+ const current = walletConfig.state.current;
447
+ const connection = current ? walletConfig.state.connections.get(current) : undefined;
448
+ if (!connection)
449
+ throw new Error("No EVM wallet is currently connected.");
450
+ const rawProvider = await connection.connector.getProvider();
451
+ const provider = new BrowserProvider(rawProvider);
452
+ const chain = await provider.getNetwork();
453
+ const chainId = Number(chain.chainId);
454
+ const networkConfig = resolveEvmSwapNetworkConfig(chainId, chain.name);
455
+ const networkName = networkConfig?.name || chain.name;
456
+ const fromAsset = resolveConfiguredEvmSwapAsset(fromSymbol, chainId);
457
+ const toAsset = resolveConfiguredEvmSwapAsset(toSymbol, chainId);
458
+ if (fromSymbol.toLowerCase() === toSymbol.toLowerCase())
459
+ throw new Error("Choose two different assets to swap.");
460
+ if (!networkConfig?.swapRouterAddress || !isAddress(networkConfig.swapRouterAddress)) {
461
+ throw new Error(`No valid Uniswap V2-compatible swap router is configured for ${networkName} (chain ID ${chainId}). Set NEXT_PUBLIC_SWAP_ROUTER_ADDRESS or add the network to assets JSON.`);
462
+ }
463
+ const isNative = (asset) => asset.type === "native" || !asset.contractAddress;
464
+ const fromNative = isNative(fromAsset);
465
+ const toNative = isNative(toAsset);
466
+ const wrappedNative = networkConfig.wrappedNativeTokenAddress;
467
+ if ((fromNative || toNative) && (!wrappedNative || !isAddress(wrappedNative))) {
468
+ throw new Error(`Set NEXT_PUBLIC_WRAPPED_NATIVE_TOKEN_ADDRESS or configure wrappedNativeTokenAddress for ${networkName} to swap its native currency.`);
469
+ }
470
+ const fromAddress = fromNative ? wrappedNative : fromAsset.contractAddress;
471
+ const toAddress = toNative ? wrappedNative : toAsset.contractAddress;
472
+ if (!isAddress(fromAddress) || !isAddress(toAddress))
473
+ throw new Error("A configured swap asset has an invalid token contract address.");
474
+ const signer = await provider.getSigner(connection.accounts[0]);
475
+ const sender = await signer.getAddress();
476
+ const inputAmount = normalizedAmount(amount);
477
+ const inputDecimals = fromNative ? 18 : fromAsset.decimals ?? Number(await new Contract(fromAddress, ERC20_SWAP_ABI, provider).decimals());
478
+ const outputDecimals = toNative ? 18 : toAsset.decimals ?? Number(await new Contract(toAddress, ERC20_SWAP_ABI, provider).decimals());
479
+ const amountIn = parseUnits(inputAmount, inputDecimals);
480
+ const router = new Contract(networkConfig.swapRouterAddress, V2_SWAP_ROUTER_ABI, signer);
481
+ const path = [fromAddress, toAddress];
482
+ const amounts = await router.getAmountsOut(amountIn, path);
483
+ const quotedOut = BigInt(amounts[amounts.length - 1].toString());
484
+ if (quotedOut <= 0n)
485
+ throw new Error(`No swap quote is available for ${fromSymbol} to ${toSymbol} on ${networkName}.`);
486
+ const minOut = quotedOut * 9900n / 10000n;
487
+ const deadline = Math.floor(Date.now() / 1000) + 20 * 60;
488
+ let transaction;
489
+ if (fromNative) {
490
+ transaction = await router.swapExactETHForTokens(minOut, path, sender, deadline, { value: amountIn });
491
+ }
492
+ else {
493
+ const token = new Contract(fromAddress, ERC20_SWAP_ABI, signer);
494
+ const allowance = BigInt((await token.allowance(sender, networkConfig.swapRouterAddress)).toString());
495
+ if (allowance < amountIn) {
496
+ if (allowance > 0n) {
497
+ const reset = await token.approve(networkConfig.swapRouterAddress, 0n);
498
+ const resetReceipt = await reset.wait();
499
+ if (!resetReceipt || resetReceipt.status !== 1)
500
+ throw new Error(`Could not reset the ${fromSymbol} swap allowance.`);
501
+ }
502
+ const approval = await token.approve(networkConfig.swapRouterAddress, amountIn);
503
+ const approvalReceipt = await approval.wait();
504
+ if (!approvalReceipt || approvalReceipt.status !== 1)
505
+ throw new Error(`Could not approve ${fromSymbol} for the swap.`);
506
+ }
507
+ transaction = toNative
508
+ ? await router.swapExactTokensForETH(amountIn, minOut, path, sender, deadline)
509
+ : await router.swapExactTokensForTokens(amountIn, minOut, path, sender, deadline);
510
+ }
511
+ const receipt = await transaction.wait();
512
+ if (!receipt || receipt.status !== 1)
513
+ throw new Error(`The ${fromSymbol} to ${toSymbol} swap failed on ${networkName}.`);
514
+ return {
515
+ success: true,
516
+ network: "evm",
517
+ from: fromAsset.symbol,
518
+ to: toAsset.symbol,
519
+ amountIn: inputAmount,
520
+ estimatedAmountOut: formatUnits(quotedOut, outputDecimals),
521
+ transactionHash: receipt.hash || transaction.hash,
522
+ };
523
+ }
524
+ function stellarAssetFromConfig(asset) {
525
+ return asset.type === "native" ? Asset.native() : new Asset(asset.code, asset.issuer);
526
+ }
527
+ async function swapStellar(amount, fromSymbol, toSymbol) {
528
+ if (fromSymbol.toLowerCase() === toSymbol.toLowerCase())
529
+ throw new Error("Choose two different assets to swap.");
530
+ if (!/^\d+(\.\d{1,7})?$/.test(amount))
531
+ throw new Error("Stellar swap amounts support up to 7 decimal places.");
532
+ const access = await requestAccess();
533
+ const source = access.address;
534
+ if (!source)
535
+ throw new Error("Could not access the connected Stellar wallet.");
536
+ const networkDetails = await getNetworkDetails();
537
+ const passphrase = networkDetails.networkPassphrase || stellarNetwork;
538
+ if (passphrase !== stellarNetwork)
539
+ throw new Error(`Stellar network mismatch. Expected ${stellarNetwork}, got ${passphrase}.`);
540
+ const fromAsset = resolveConfiguredStellarSwapAsset(fromSymbol, passphrase);
541
+ const toAsset = resolveConfiguredStellarSwapAsset(toSymbol, passphrase);
542
+ const stellarFrom = stellarAssetFromConfig(fromAsset);
543
+ const stellarTo = stellarAssetFromConfig(toAsset);
544
+ const server = new Horizon.Server(stellarRpc);
545
+ const sourceAccount = await server.loadAccount(source);
546
+ const paths = await server.strictSendPaths(stellarFrom, amount, [stellarTo]).call();
547
+ const route = paths.records[0];
548
+ if (!route)
549
+ throw new Error(`No Stellar path is available to swap ${fromSymbol} to ${toSymbol}.`);
550
+ const minOut = (Number(route.destination_amount) * 0.99).toFixed(7);
551
+ const routeAssets = route.path.map((item) => item.asset_type === "native"
552
+ ? Asset.native()
553
+ : new Asset(item.asset_code, item.asset_issuer));
554
+ const transaction = new TransactionBuilder(sourceAccount, { fee: BASE_FEE, networkPassphrase: passphrase })
555
+ .addOperation(Operation.pathPaymentStrictSend({
556
+ sendAsset: stellarFrom,
557
+ sendAmount: amount,
558
+ destination: source,
559
+ destAsset: stellarTo,
560
+ destMin: minOut,
561
+ path: routeAssets,
562
+ }))
563
+ .setTimeout(180)
564
+ .build();
565
+ const signed = await freighterSignTransaction(transaction.toXDR(), { networkPassphrase: passphrase, address: source });
566
+ if (signed.error || !signed.signedTxXdr)
567
+ throw new Error(signed.error?.message || "Stellar wallet signing was rejected.");
568
+ const receipt = await server.submitTransaction(TransactionBuilder.fromXDR(signed.signedTxXdr, passphrase));
569
+ if (!receipt.successful || !receipt.hash)
570
+ throw new Error("The Stellar swap did not complete successfully.");
571
+ return {
572
+ success: true,
573
+ network: "stellar",
574
+ from: fromAsset.symbol,
575
+ to: toAsset.symbol,
576
+ amountIn: amount,
577
+ estimatedAmountOut: route.destination_amount,
578
+ transactionHash: receipt.hash,
579
+ };
580
+ }
581
+ /** Swap two configured assets using the active EVM or Stellar wallet. */
582
+ export async function cordy_swap(amount, from, to) {
583
+ try {
584
+ const normalized = normalizedAmount(amount);
585
+ const activeWallet = getActiveWallet();
586
+ return activeWallet === "stellar"
587
+ ? await swapStellar(normalized, from, to)
588
+ : await swapEvm(normalized, from, to);
589
+ }
590
+ catch (error) {
591
+ return { success: false, error: error instanceof Error ? error.message : "Could not swap the selected assets." };
592
+ }
593
+ }
594
+ /** Configure a caller-owned JSON asset registry before requesting transfers. */
595
+ export function cordy_configure(options) {
596
+ configureCordyAssets(options);
597
+ }
598
+ /** Send a selected JSON-configured asset using Minikit's active wallet. */
599
+ export async function cordy_transfer(amount, recipient, options = {}) {
600
+ try {
601
+ const normalized = normalizedAmount(amount);
602
+ const activeWallet = getActiveWallet();
603
+ return activeWallet === "stellar"
604
+ ? await transferStellar(normalized, recipient, options.asset, options.memo)
605
+ : await transferEvm(normalized, recipient, options.asset);
606
+ }
607
+ catch (error) {
608
+ return {
609
+ success: false,
610
+ error: error instanceof Error ? error.message : "Transfer failed.",
611
+ };
612
+ }
613
+ }
@@ -0,0 +1,5 @@
1
+ export { cordy, jwt_confirm, jwt_verify, jwt_disconnect } from "./client/jwt";
2
+ export type { JwtDisconnectResult, JwtSessionRequestOptions, JwtSessionResult } from "./client/jwt";
3
+ export { configureCordyAssets, cordy_configure, cordy_bridge, cordy_swap, cordy_transfer } from "./client/transfer";
4
+ export type { CordyAssetsConfig, CordyBridgeResult, CordyBridgeSide, CordyTransferOptions, CordyTransferResult, CordySwapResult, EvmAssetConfig, EvmNetworkConfig, StellarAssetConfig } from "./client/transfer";
5
+ //# sourceMappingURL=client.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"client.d.ts","sourceRoot":"","sources":["../client.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,EAAE,WAAW,EAAE,UAAU,EAAE,cAAc,EAAE,MAAM,cAAc,CAAC;AAC9E,YAAY,EAAE,mBAAmB,EAAE,wBAAwB,EAAE,gBAAgB,EAAE,MAAM,cAAc,CAAC;AAEpG,OAAO,EAAE,oBAAoB,EAAE,eAAe,EAAE,YAAY,EAAE,UAAU,EAAE,cAAc,EAAE,MAAM,mBAAmB,CAAC;AACpH,YAAY,EAAE,iBAAiB,EAAE,iBAAiB,EAAE,eAAe,EAAE,oBAAoB,EAAE,mBAAmB,EAAE,eAAe,EAAE,cAAc,EAAE,gBAAgB,EAAE,kBAAkB,EAAE,MAAM,mBAAmB,CAAC"}
package/dist/client.js ADDED
@@ -0,0 +1,2 @@
1
+ export { cordy, jwt_confirm, jwt_verify, jwt_disconnect } from "./client/jwt";
2
+ export { configureCordyAssets, cordy_configure, cordy_bridge, cordy_swap, cordy_transfer } from "./client/transfer";
@@ -1,5 +1,7 @@
1
1
  import { ReactNode } from 'react';
2
- export default function ProvidersClientWrapper({ children }: {
2
+ import { type CordyAssetsConfig } from './client/transfer';
3
+ export default function ProvidersClientWrapper({ children, assets, }: {
3
4
  children: ReactNode;
5
+ assets?: CordyAssetsConfig;
4
6
  }): import("react").JSX.Element;
5
7
  //# sourceMappingURL=client__provider.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"client__provider.d.ts","sourceRoot":"","sources":["../client__provider.tsx"],"names":[],"mappings":"AACA,OAAO,EAAE,SAAS,EAAE,MAAM,OAAO,CAAC;AAQlC,MAAM,CAAC,OAAO,UAAU,sBAAsB,CAAC,EAAE,QAAQ,EAAE,EAAE;IAAE,QAAQ,EAAE,SAAS,CAAA;CAAE,+BAEnF"}
1
+ {"version":3,"file":"client__provider.d.ts","sourceRoot":"","sources":["../client__provider.tsx"],"names":[],"mappings":"AACA,OAAO,EAAE,SAAS,EAAsB,MAAM,OAAO,CAAC;AACtD,OAAO,EAAwB,KAAK,iBAAiB,EAAE,MAAM,mBAAmB,CAAC;AAUjF,MAAM,CAAC,OAAO,UAAU,sBAAsB,CAAC,EAC7C,QAAQ,EACR,MAAM,GACP,EAAE;IACD,QAAQ,EAAE,SAAS,CAAC;IACpB,MAAM,CAAC,EAAE,iBAAiB,CAAC;CAC5B,+BAyBA"}