@cordystackx/cordy_minikit 3.0.5 → 3.0.10
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +61 -11
- package/dist/client/runtimeConfig.d.ts +51 -3
- package/dist/client/runtimeConfig.d.ts.map +1 -1
- package/dist/client/runtimeConfig.js +15 -1
- package/dist/client/transfer.d.ts +21 -5
- package/dist/client/transfer.d.ts.map +1 -1
- package/dist/client/transfer.js +423 -72
- package/dist/client.d.ts +1 -1
- package/dist/client.d.ts.map +1 -1
- package/dist/client__provider.d.ts.map +1 -1
- package/dist/client__provider.js +2 -4
- package/dist/components/Connect_wallet_bt.d.ts +3 -3
- package/dist/components/Connect_wallet_bt.d.ts.map +1 -1
- package/dist/components/Connect_wallet_bt.js +13 -13
- package/dist/components/UI_Comp.js +8 -8
- package/dist/config/Image.json +6 -6
- package/dist/controllers/BridgeEvmWalletModal.d.ts +11 -0
- package/dist/controllers/BridgeEvmWalletModal.d.ts.map +1 -0
- package/dist/controllers/BridgeEvmWalletModal.js +154 -0
- package/dist/controllers/Get_Balance.d.ts.map +1 -1
- package/dist/controllers/Get_Balance.js +3 -2
- package/dist/controllers/StellarButton.d.ts.map +1 -1
- package/dist/controllers/StellarButton.js +3 -1
- package/dist/controllers/Transactions.js +2 -2
- package/dist/controllers/bridgeWalletSession.d.ts +13 -0
- package/dist/controllers/bridgeWalletSession.d.ts.map +1 -0
- package/dist/controllers/bridgeWalletSession.js +37 -0
- package/dist/controllers/cctpBridge.d.ts +6 -0
- package/dist/controllers/cctpBridge.d.ts.map +1 -0
- package/dist/controllers/cctpBridge.js +326 -0
- package/dist/controllers/index.d.ts +4 -0
- package/dist/controllers/index.d.ts.map +1 -1
- package/dist/controllers/index.js +2 -0
- package/dist/controllers/useBridgeEvmWallet.d.ts +23 -0
- package/dist/controllers/useBridgeEvmWallet.d.ts.map +1 -0
- package/dist/controllers/useBridgeEvmWallet.js +83 -0
- package/dist/css/UI_Comp/styles.module.css +10 -0
- package/dist/index.d.ts +3 -2
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1 -1
- package/dist/package.json +8 -7
- package/dist/tsconfig.tsbuildinfo +1 -1
- package/dist/wagmi__providers.d.ts +2 -2
- package/dist/wagmi__providers.d.ts.map +1 -1
- package/dist/wagmi__providers.js +4 -4
- package/package.json +8 -7
|
@@ -0,0 +1,154 @@
|
|
|
1
|
+
"use client";
|
|
2
|
+
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
|
|
3
|
+
import { useEffect, useSyncExternalStore, useState } from "react";
|
|
4
|
+
import { useConnect } from "wagmi";
|
|
5
|
+
import Images from "../config/Image.json";
|
|
6
|
+
import { UI_Comp__css } from "../css";
|
|
7
|
+
import { isEvmEnvironmentConfigured } from "../config/walletConfig";
|
|
8
|
+
import { getConfiguredEvmAssets, getCordyRuntimeConfig } from "../client/runtimeConfig";
|
|
9
|
+
import { getBridgeWalletSession, rejectBridgeWalletSession, resolveBridgeWalletSession, subscribeBridgeWalletSession, } from "./bridgeWalletSession";
|
|
10
|
+
const ALWAYS_AVAILABLE_CONNECTOR_NAMES = new Set([
|
|
11
|
+
"WalletConnect",
|
|
12
|
+
"MetaMask",
|
|
13
|
+
"Coinbase Wallet",
|
|
14
|
+
"Trust Wallet",
|
|
15
|
+
]);
|
|
16
|
+
async function prepareConnectedWallet(connector, routeId, from, to) {
|
|
17
|
+
const runtimeConfig = getCordyRuntimeConfig();
|
|
18
|
+
const route = runtimeConfig?.bridge?.routes?.find((candidate) => candidate.id === routeId);
|
|
19
|
+
const source = route?.[from ?? "internal"];
|
|
20
|
+
const destination = route?.[to ?? "external"];
|
|
21
|
+
const target = source?.networkType === "evm" ? source : destination?.networkType === "evm" ? destination : undefined;
|
|
22
|
+
const targetChainId = target?.chainId ?? runtimeConfig?.networks?.[0]?.chainId;
|
|
23
|
+
if (targetChainId === undefined)
|
|
24
|
+
return;
|
|
25
|
+
const network = runtimeConfig?.networks?.find((candidate) => candidate.chainId === targetChainId);
|
|
26
|
+
if (!network) {
|
|
27
|
+
throw new Error(`Chain ${targetChainId} is not configured in Cordy Minikit.`);
|
|
28
|
+
}
|
|
29
|
+
const provider = await connector.getProvider();
|
|
30
|
+
const chainId = `0x${targetChainId.toString(16)}`;
|
|
31
|
+
try {
|
|
32
|
+
await provider.request({ method: "wallet_switchEthereumChain", params: [{ chainId }] });
|
|
33
|
+
}
|
|
34
|
+
catch (error) {
|
|
35
|
+
const code = typeof error === "object" && error !== null && "code" in error
|
|
36
|
+
? error.code
|
|
37
|
+
: undefined;
|
|
38
|
+
if (code !== 4902) {
|
|
39
|
+
throw new Error(`The wallet could not switch to ${network.name}. ${error instanceof Error ? error.message : "The request was rejected."}`);
|
|
40
|
+
}
|
|
41
|
+
await provider.request({
|
|
42
|
+
method: "wallet_addEthereumChain",
|
|
43
|
+
params: [{
|
|
44
|
+
chainId,
|
|
45
|
+
chainName: network.name,
|
|
46
|
+
nativeCurrency: network.nativeCurrency,
|
|
47
|
+
rpcUrls: [network.rpcUrl],
|
|
48
|
+
...(network.blockExplorerUrl ? { blockExplorerUrls: [network.blockExplorerUrl] } : {}),
|
|
49
|
+
}],
|
|
50
|
+
});
|
|
51
|
+
await provider.request({ method: "wallet_switchEthereumChain", params: [{ chainId }] });
|
|
52
|
+
}
|
|
53
|
+
const token = target?.tokenAddress && target.assetSymbol
|
|
54
|
+
? getConfiguredEvmAssets(runtimeConfig).find((asset) => asset.chainId === targetChainId &&
|
|
55
|
+
asset.contractAddress?.toLowerCase() === target.tokenAddress?.toLowerCase())
|
|
56
|
+
: undefined;
|
|
57
|
+
if (target?.tokenAddress && target.assetSymbol) {
|
|
58
|
+
await provider.request({
|
|
59
|
+
method: "wallet_watchAsset",
|
|
60
|
+
params: {
|
|
61
|
+
type: "ERC20",
|
|
62
|
+
options: {
|
|
63
|
+
address: target.tokenAddress,
|
|
64
|
+
symbol: target.assetSymbol,
|
|
65
|
+
decimals: token?.decimals ?? 18,
|
|
66
|
+
},
|
|
67
|
+
},
|
|
68
|
+
});
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
export default function BridgeEvmWalletModal({ open: controlledOpen, onClose: controlledOnClose, onConnected, onConnectionError, targetChainName, title, note, }) {
|
|
72
|
+
const sessionRequest = useSyncExternalStore(subscribeBridgeWalletSession, getBridgeWalletSession, () => undefined);
|
|
73
|
+
const open = controlledOpen ?? Boolean(sessionRequest);
|
|
74
|
+
const onClose = controlledOnClose ?? (() => rejectBridgeWalletSession());
|
|
75
|
+
const route = getCordyRuntimeConfig()?.bridge?.routes?.find((candidate) => candidate.id === sessionRequest?.routeId);
|
|
76
|
+
const source = route?.[sessionRequest?.from ?? "internal"];
|
|
77
|
+
const destination = route?.[sessionRequest?.to ?? "external"];
|
|
78
|
+
const resolvedTargetChain = targetChainName
|
|
79
|
+
?? (source?.networkType === "evm" ? source.networkName : destination?.networkName)
|
|
80
|
+
?? "the destination network";
|
|
81
|
+
const resolvedTitle = title
|
|
82
|
+
?? (source?.networkType === "evm" ? "Connect the source EVM wallet" : "Connect the destination EVM wallet");
|
|
83
|
+
const { connectors, connectAsync } = useConnect();
|
|
84
|
+
const [pendingConnector, setPendingConnector] = useState();
|
|
85
|
+
const [error, setError] = useState();
|
|
86
|
+
const description = note ?? `Connect your EVM wallet. The bridge continues automatically on ${resolvedTargetChain}.`;
|
|
87
|
+
useEffect(() => {
|
|
88
|
+
if (!open) {
|
|
89
|
+
setPendingConnector(undefined);
|
|
90
|
+
setError(undefined);
|
|
91
|
+
}
|
|
92
|
+
}, [open]);
|
|
93
|
+
if (!open)
|
|
94
|
+
return null;
|
|
95
|
+
const connect = async (connector) => {
|
|
96
|
+
setPendingConnector(connector.uid);
|
|
97
|
+
setError(undefined);
|
|
98
|
+
try {
|
|
99
|
+
if (!isEvmEnvironmentConfigured()) {
|
|
100
|
+
throw new Error("EVM is not configured. Add an EVM network and asset to the provider configuration.");
|
|
101
|
+
}
|
|
102
|
+
const connection = await connectAsync({ connector });
|
|
103
|
+
const connectedAddress = connection.accounts?.[0];
|
|
104
|
+
await prepareConnectedWallet(connector, sessionRequest?.routeId, sessionRequest?.from, sessionRequest?.to);
|
|
105
|
+
onConnected?.(connectedAddress);
|
|
106
|
+
if (connectedAddress && sessionRequest)
|
|
107
|
+
resolveBridgeWalletSession(connectedAddress);
|
|
108
|
+
onClose();
|
|
109
|
+
}
|
|
110
|
+
catch (connectionError) {
|
|
111
|
+
const message = connectionError instanceof Error ? connectionError.message : "EVM wallet connection failed.";
|
|
112
|
+
setError(message);
|
|
113
|
+
onConnectionError?.(message);
|
|
114
|
+
if (sessionRequest)
|
|
115
|
+
rejectBridgeWalletSession(message);
|
|
116
|
+
}
|
|
117
|
+
finally {
|
|
118
|
+
setPendingConnector(undefined);
|
|
119
|
+
}
|
|
120
|
+
};
|
|
121
|
+
return (_jsx("div", { className: UI_Comp__css.bridge_modal_container, role: "presentation", children: _jsxs("section", { className: UI_Comp__css.bridge_modal, role: "dialog", "aria-modal": "true", "aria-labelledby": "cordy-bridge-wallet-title", children: [_jsxs("div", { className: UI_Comp__css.bridge_modal_header, children: [_jsxs("div", { children: [_jsx("p", { className: UI_Comp__css.eyebrow, children: "CORDY MINIKIT \u00B7 EVM DESTINATION" }), _jsx("h2", { id: "cordy-bridge-wallet-title", children: resolvedTitle })] }), _jsx("button", { className: UI_Comp__css.close_button, type: "button", onClick: onClose, "aria-label": "Close EVM wallet connection dialog", children: "\u00D7" })] }), _jsx("p", { className: UI_Comp__css.modal_description, children: description }), _jsx("div", { className: UI_Comp__css.bridge_wallet_options, children: connectors.map((connector) => {
|
|
122
|
+
const isTrustWallet = connector.name.toLowerCase().includes("trust");
|
|
123
|
+
const imageSource = Images[connector.name]
|
|
124
|
+
|| (isTrustWallet ? Images["Trust Wallet"] : undefined);
|
|
125
|
+
const displayName = isTrustWallet ? "Trust Wallet" : connector.name;
|
|
126
|
+
const imageUnavailable = connector.type === "injected"
|
|
127
|
+
&& !ALWAYS_AVAILABLE_CONNECTOR_NAMES.has(connector.name)
|
|
128
|
+
&& !isTrustWallet;
|
|
129
|
+
return (_jsx(BridgeWalletOption, { connector: connector, displayName: displayName, imageSource: imageSource, imageUnavailable: imageUnavailable, isPending: pendingConnector === connector.uid, disabled: Boolean(pendingConnector), onClick: () => void connect(connector) }, connector.uid));
|
|
130
|
+
}) }), error && _jsx("div", { className: UI_Comp__css.error_message, role: "alert", children: error }), _jsxs("p", { className: UI_Comp__css.panel_note, children: ["Connect your EVM wallet. The bridge continues automatically on ", resolvedTargetChain, "."] })] }) }));
|
|
131
|
+
}
|
|
132
|
+
function BridgeWalletOption({ connector, displayName, imageSource, imageUnavailable, isPending, disabled, onClick, }) {
|
|
133
|
+
const [installed, setInstalled] = useState(!imageUnavailable);
|
|
134
|
+
const [imageFailed, setImageFailed] = useState(false);
|
|
135
|
+
const fallbackInitial = displayName.trim().charAt(0).toUpperCase() || "?";
|
|
136
|
+
useEffect(() => {
|
|
137
|
+
if (!imageUnavailable)
|
|
138
|
+
return;
|
|
139
|
+
let active = true;
|
|
140
|
+
void connector.getProvider().then((provider) => {
|
|
141
|
+
if (active)
|
|
142
|
+
setInstalled(Boolean(provider));
|
|
143
|
+
}).catch(() => {
|
|
144
|
+
if (active)
|
|
145
|
+
setInstalled(false);
|
|
146
|
+
});
|
|
147
|
+
return () => {
|
|
148
|
+
active = false;
|
|
149
|
+
};
|
|
150
|
+
}, [connector, imageUnavailable]);
|
|
151
|
+
return (_jsxs("button", { className: UI_Comp__css.bridge_wallet_option, type: "button", disabled: !installed || disabled, onClick: onClick, children: [imageSource && !imageFailed
|
|
152
|
+
? _jsx("img", { src: imageSource, alt: "", "aria-hidden": "true", width: 23, height: 23, onError: () => setImageFailed(true) })
|
|
153
|
+
: _jsx("span", { className: UI_Comp__css.wallet_icon_fallback, "aria-hidden": "true", children: fallbackInitial }), isPending ? `Connecting ${displayName}…` : !installed ? `${displayName} (Not installed)` : displayName] }));
|
|
154
|
+
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"Get_Balance.d.ts","sourceRoot":"","sources":["../../controllers/Get_Balance.tsx"],"names":[],"mappings":"AAAA,OAAO,EAAqD,KAAK,QAAQ,EAAE,MAAM,QAAQ,CAAC;AAI1F,MAAM,MAAM,mBAAmB,GAAG;IAChC,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,QAAQ,CAAC,EAAE,QAAQ,CAAC;IACpB,gBAAgB,CAAC,EAAE,QAAQ,CAAC;IAC5B,eAAe,CAAC,EAAE,MAAM,CAAC;IACzB,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,QAAQ,CAAC,EAAE,MAAM,CAAC;CACnB,CAAC;AAEF,MAAM,MAAM,kBAAkB,GAAG;IAC/B,OAAO,EAAE,MAAM,CAAC;IAChB,UAAU,EAAE,MAAM,CAAC;IACnB,MAAM,EAAE,MAAM,CAAC;IACf,QAAQ,EAAE,MAAM,CAAC;IACjB,OAAO,EAAE,MAAM,CAAC;IAChB,OAAO,EAAE,MAAM,CAAC;CACjB,CAAC;AAEF,4EAA4E;AAC5E,wBAAsB,gBAAgB,CACpC,OAAO,EAAE,MAAM,EACf,OAAO,GAAE,mBAAwB,GAChC,OAAO,CAAC,kBAAkB,CAAC,
|
|
1
|
+
{"version":3,"file":"Get_Balance.d.ts","sourceRoot":"","sources":["../../controllers/Get_Balance.tsx"],"names":[],"mappings":"AAAA,OAAO,EAAqD,KAAK,QAAQ,EAAE,MAAM,QAAQ,CAAC;AAI1F,MAAM,MAAM,mBAAmB,GAAG;IAChC,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,QAAQ,CAAC,EAAE,QAAQ,CAAC;IACpB,gBAAgB,CAAC,EAAE,QAAQ,CAAC;IAC5B,eAAe,CAAC,EAAE,MAAM,CAAC;IACzB,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,QAAQ,CAAC,EAAE,MAAM,CAAC;CACnB,CAAC;AAEF,MAAM,MAAM,kBAAkB,GAAG;IAC/B,OAAO,EAAE,MAAM,CAAC;IAChB,UAAU,EAAE,MAAM,CAAC;IACnB,MAAM,EAAE,MAAM,CAAC;IACf,QAAQ,EAAE,MAAM,CAAC;IACjB,OAAO,EAAE,MAAM,CAAC;IAChB,OAAO,EAAE,MAAM,CAAC;CACjB,CAAC;AAEF,4EAA4E;AAC5E,wBAAsB,gBAAgB,CACpC,OAAO,EAAE,MAAM,EACf,OAAO,GAAE,mBAAwB,GAChC,OAAO,CAAC,kBAAkB,CAAC,CA0F7B;AAED,0FAA0F;AAC1F,wBAA8B,eAAe,CAC3C,OAAO,EAAE,MAAM,EACf,QAAQ,CAAC,EAAE,MAAM,GAChB,OAAO,CAAC;IAAE,OAAO,EAAE,MAAM,CAAC;IAAC,MAAM,EAAE,MAAM,CAAA;CAAE,CAAC,CAQ9C"}
|
|
@@ -1,11 +1,11 @@
|
|
|
1
1
|
import { Contract, formatUnits, isAddress, JsonRpcProvider } from "ethers";
|
|
2
2
|
import ERC20_ABI from "../config/ERC20_ABI.json";
|
|
3
|
-
import { getCordyRuntimeConfig } from "../client/runtimeConfig";
|
|
3
|
+
import { getConfiguredEvmAssets, getCordyRuntimeConfig, requireConfiguredEvmNetwork } from "../client/runtimeConfig";
|
|
4
4
|
/** Shared ERC-20 balance reader used by wallet status and the Cordy API. */
|
|
5
5
|
export async function readTokenBalance(address, options = {}) {
|
|
6
6
|
const assets = getCordyRuntimeConfig();
|
|
7
7
|
const configuredChainId = options.expectedChainId ?? assets?.networks?.[0]?.chainId;
|
|
8
|
-
const chainAssets = assets
|
|
8
|
+
const chainAssets = getConfiguredEvmAssets(assets).filter((asset) => asset.chainId === configuredChainId) ?? [];
|
|
9
9
|
const defaultAsset = chainAssets.find((asset) => asset.contractAddress) || chainAssets[0];
|
|
10
10
|
const tokenAddress = options.tokenAddress || defaultAsset?.contractAddress;
|
|
11
11
|
const rpcUrl = options.rpcUrl || defaultAsset?.rpcUrl || assets?.networks?.find((network) => network.chainId === configuredChainId)?.rpcUrl;
|
|
@@ -24,6 +24,7 @@ export async function readTokenBalance(address, options = {}) {
|
|
|
24
24
|
throw new Error("Could not connect to the configured EVM RPC endpoint.");
|
|
25
25
|
}
|
|
26
26
|
const chainId = Number(network.chainId);
|
|
27
|
+
requireConfiguredEvmNetwork(assets, chainId, network.name);
|
|
27
28
|
if (options.expectedChainId !== undefined && chainId !== options.expectedChainId) {
|
|
28
29
|
throw new Error(`The EVM RPC is on chain ID ${chainId}, but the wallet is on ${options.networkName || "another network"} (chain ID ${options.expectedChainId}).`);
|
|
29
30
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"StellarButton.d.ts","sourceRoot":"","sources":["../../controllers/StellarButton.tsx"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"StellarButton.d.ts","sourceRoot":"","sources":["../../controllers/StellarButton.tsx"],"names":[],"mappings":"AAoBA,MAAM,CAAC,OAAO,UAAU,mBAAmB,CAAC,EAC1C,SAAS,EACT,cAAc,GACf,EAAE;IACD,SAAS,CAAC,EAAE,CAAC,OAAO,EAAE,MAAM,KAAK,IAAI,CAAC;IACtC,cAAc,CAAC,EAAE,CAAC,MAAM,EAAE;QACxB,SAAS,EAAE,OAAO,CAAC;QACnB,KAAK,CAAC,EAAE,MAAM,CAAC;QACf,OAAO,CAAC,EAAE,MAAM,CAAC;QACjB,OAAO,CAAC,EAAE,MAAM,CAAC;KAClB,KAAK,IAAI,CAAC;CACZ,+BAqFA"}
|
|
@@ -3,6 +3,7 @@ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
|
|
|
3
3
|
import { useState } from "react";
|
|
4
4
|
import { requestAccess, getNetworkDetails, isConnected, } from "@stellar/freighter-api";
|
|
5
5
|
import img_src from "../config/Image.json";
|
|
6
|
+
import { UI_Comp__css } from "../css";
|
|
6
7
|
import { isStellarEnvironmentConfigured } from "./loadStellarBalance";
|
|
7
8
|
const FREIGHTER_DOWNLOAD_URL = "https://www.freighter.app/";
|
|
8
9
|
function isMobileDevice() {
|
|
@@ -15,6 +16,7 @@ export default function StellarWalletButton({ onConnect, onStatusChange, }) {
|
|
|
15
16
|
const [isPending, setIsPending] = useState(false);
|
|
16
17
|
const [errorMsg, setErrorMsg] = useState();
|
|
17
18
|
const [network, setNetwork] = useState();
|
|
19
|
+
const [imageFailed, setImageFailed] = useState(false);
|
|
18
20
|
const connect = async () => {
|
|
19
21
|
setIsPending(true);
|
|
20
22
|
setErrorMsg(undefined);
|
|
@@ -63,7 +65,7 @@ export default function StellarWalletButton({ onConnect, onStatusChange, }) {
|
|
|
63
65
|
setIsPending(false);
|
|
64
66
|
}
|
|
65
67
|
};
|
|
66
|
-
return (_jsxs("button", { onClick: connect, disabled: isPending, children: [_jsx("img", { src: img_src.Freighter, alt: "
|
|
68
|
+
return (_jsxs("button", { onClick: connect, disabled: isPending, children: [img_src.Freighter && !imageFailed ? (_jsx("img", { src: img_src.Freighter, alt: "", "aria-hidden": "true", title: "Freighter", width: 18, height: 18, onError: () => setImageFailed(true) })) : _jsx("span", { className: UI_Comp__css.wallet_icon_fallback, "aria-hidden": "true", children: "F" }), isPending
|
|
67
69
|
? "Connecting..."
|
|
68
70
|
: address
|
|
69
71
|
? `Connected: ${address.slice(0, 6)}...`
|
|
@@ -3,7 +3,7 @@ import { ethers, parseUnits } from 'ethers';
|
|
|
3
3
|
import { Horizon, Asset, BASE_FEE, Memo, Operation, TransactionBuilder } from "@stellar/stellar-sdk";
|
|
4
4
|
import { getNetworkDetails, requestAccess, signTransaction as freighterSignTransaction } from "@stellar/freighter-api";
|
|
5
5
|
import tokenAbi from '../config/ERC20_ABI.json';
|
|
6
|
-
import { getCordyRuntimeConfig } from '../client/runtimeConfig';
|
|
6
|
+
import { getConfiguredEvmAssets, getCordyRuntimeConfig } from '../client/runtimeConfig';
|
|
7
7
|
/** @deprecated Use `cordy.transfer(amount, recipient, { asset })` instead. */
|
|
8
8
|
export default async function CordyStackTrans(address, cost) {
|
|
9
9
|
if (!address) {
|
|
@@ -13,7 +13,7 @@ export default async function CordyStackTrans(address, cost) {
|
|
|
13
13
|
try {
|
|
14
14
|
const runtimeConfig = getCordyRuntimeConfig();
|
|
15
15
|
const defaultNetwork = runtimeConfig?.networks?.[0];
|
|
16
|
-
const defaultAsset = runtimeConfig
|
|
16
|
+
const defaultAsset = getConfiguredEvmAssets(runtimeConfig).find((asset) => asset.chainId === defaultNetwork?.chainId && asset.contractAddress);
|
|
17
17
|
const tokenAddress = defaultAsset?.contractAddress || "";
|
|
18
18
|
const rpcEndpoint = defaultAsset?.rpcUrl || defaultNetwork?.rpcUrl || "";
|
|
19
19
|
const ethereum = window?.ethereum;
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import type { BridgeEvmWalletRequest } from "./useBridgeEvmWallet";
|
|
2
|
+
type PendingSession = {
|
|
3
|
+
request: BridgeEvmWalletRequest;
|
|
4
|
+
resolve: (address: string) => void;
|
|
5
|
+
reject: (error: Error) => void;
|
|
6
|
+
};
|
|
7
|
+
export declare function subscribeBridgeWalletSession(listener: () => void): () => void;
|
|
8
|
+
export declare function getBridgeWalletSession(): PendingSession["request"] | undefined;
|
|
9
|
+
export declare function waitForBridgeEvmWallet(request: BridgeEvmWalletRequest): Promise<string>;
|
|
10
|
+
export declare function resolveBridgeWalletSession(address: string): void;
|
|
11
|
+
export declare function rejectBridgeWalletSession(message?: string): void;
|
|
12
|
+
export {};
|
|
13
|
+
//# sourceMappingURL=bridgeWalletSession.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"bridgeWalletSession.d.ts","sourceRoot":"","sources":["../../controllers/bridgeWalletSession.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,sBAAsB,EAAE,MAAM,sBAAsB,CAAC;AAEnE,KAAK,cAAc,GAAG;IACpB,OAAO,EAAE,sBAAsB,CAAC;IAChC,OAAO,EAAE,CAAC,OAAO,EAAE,MAAM,KAAK,IAAI,CAAC;IACnC,MAAM,EAAE,CAAC,KAAK,EAAE,KAAK,KAAK,IAAI,CAAC;CAChC,CAAC;AASF,wBAAgB,4BAA4B,CAAC,QAAQ,EAAE,MAAM,IAAI,GAAG,MAAM,IAAI,CAG7E;AAED,wBAAgB,sBAAsB,IAAI,cAAc,CAAC,SAAS,CAAC,GAAG,SAAS,CAE9E;AAED,wBAAgB,sBAAsB,CAAC,OAAO,EAAE,sBAAsB,GAAG,OAAO,CAAC,MAAM,CAAC,CAQvF;AAED,wBAAgB,0BAA0B,CAAC,OAAO,EAAE,MAAM,GAAG,IAAI,CAMhE;AAED,wBAAgB,yBAAyB,CAAC,OAAO,SAAyC,GAAG,IAAI,CAMhG"}
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
let pendingSession;
|
|
2
|
+
const listeners = new Set();
|
|
3
|
+
function notify() {
|
|
4
|
+
listeners.forEach((listener) => listener());
|
|
5
|
+
}
|
|
6
|
+
export function subscribeBridgeWalletSession(listener) {
|
|
7
|
+
listeners.add(listener);
|
|
8
|
+
return () => listeners.delete(listener);
|
|
9
|
+
}
|
|
10
|
+
export function getBridgeWalletSession() {
|
|
11
|
+
return pendingSession?.request;
|
|
12
|
+
}
|
|
13
|
+
export function waitForBridgeEvmWallet(request) {
|
|
14
|
+
if (pendingSession) {
|
|
15
|
+
return Promise.reject(new Error("Another bridge wallet connection is already in progress."));
|
|
16
|
+
}
|
|
17
|
+
return new Promise((resolve, reject) => {
|
|
18
|
+
pendingSession = { request, resolve, reject };
|
|
19
|
+
notify();
|
|
20
|
+
});
|
|
21
|
+
}
|
|
22
|
+
export function resolveBridgeWalletSession(address) {
|
|
23
|
+
const session = pendingSession;
|
|
24
|
+
if (!session)
|
|
25
|
+
return;
|
|
26
|
+
pendingSession = undefined;
|
|
27
|
+
notify();
|
|
28
|
+
session.resolve(address);
|
|
29
|
+
}
|
|
30
|
+
export function rejectBridgeWalletSession(message = "EVM wallet connection was cancelled.") {
|
|
31
|
+
const session = pendingSession;
|
|
32
|
+
if (!session)
|
|
33
|
+
return;
|
|
34
|
+
pendingSession = undefined;
|
|
35
|
+
notify();
|
|
36
|
+
session.reject(new Error(message));
|
|
37
|
+
}
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
import type { CordyBridgeRouteConfig } from "../client/runtimeConfig";
|
|
2
|
+
import type { CordyBridgeResult } from "../client/transfer";
|
|
3
|
+
type CordyBridgeSide = "internal" | "external";
|
|
4
|
+
export declare function cctpBridge(amount: string, from: CordyBridgeSide, to: CordyBridgeSide, recipient: string, route: CordyBridgeRouteConfig): Promise<CordyBridgeResult>;
|
|
5
|
+
export {};
|
|
6
|
+
//# sourceMappingURL=cctpBridge.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"cctpBridge.d.ts","sourceRoot":"","sources":["../../controllers/cctpBridge.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EACV,sBAAsB,EACvB,MAAM,yBAAyB,CAAC;AACjC,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,oBAAoB,CAAC;AAG5D,KAAK,eAAe,GAAG,UAAU,GAAG,UAAU,CAAC;AAyP/C,wBAAsB,UAAU,CAC9B,MAAM,EAAE,MAAM,EACd,IAAI,EAAE,eAAe,EACrB,EAAE,EAAE,eAAe,EACnB,SAAS,EAAE,MAAM,EACjB,KAAK,EAAE,sBAAsB,GAC5B,OAAO,CAAC,iBAAiB,CAAC,CAyH5B"}
|
|
@@ -0,0 +1,326 @@
|
|
|
1
|
+
import { BrowserProvider, Contract, isAddress, parseUnits } from "ethers";
|
|
2
|
+
import { Address, Contract as StellarContract, nativeToScVal, rpc, StrKey, TransactionBuilder, xdr } from "@stellar/stellar-sdk";
|
|
3
|
+
import { getNetworkDetails, requestAccess, signTransaction as freighterSignTransaction } from "@stellar/freighter-api";
|
|
4
|
+
import { getCordyRuntimeConfig } from "../client/runtimeConfig";
|
|
5
|
+
import { getActiveWagmiConfig } from "../config/walletConfig";
|
|
6
|
+
async function evmStep(step, action) {
|
|
7
|
+
try {
|
|
8
|
+
return await action();
|
|
9
|
+
}
|
|
10
|
+
catch (error) {
|
|
11
|
+
const detail = error instanceof Error ? error.message : String(error);
|
|
12
|
+
throw new Error(`Could not ${step}. Check your wallet network and RPC access. ${detail}`);
|
|
13
|
+
}
|
|
14
|
+
}
|
|
15
|
+
function requireEvmValue(value, step) {
|
|
16
|
+
if (value === null || value === undefined) {
|
|
17
|
+
throw new Error(`Could not ${step}. The connected wallet provider returned no value.`);
|
|
18
|
+
}
|
|
19
|
+
return value;
|
|
20
|
+
}
|
|
21
|
+
const CCTP_TOKEN_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 CCTP_MESSENGER_ABI = [
|
|
28
|
+
"function depositForBurn(uint256 amount,uint32 destinationDomain,bytes32 mintRecipient,address burnToken,bytes32 destinationCaller,uint256 maxFee,uint32 minFinalityThreshold)",
|
|
29
|
+
"function depositForBurnWithHook(uint256 amount,uint32 destinationDomain,bytes32 mintRecipient,address burnToken,bytes32 destinationCaller,uint256 maxFee,uint32 minFinalityThreshold,bytes hookData)",
|
|
30
|
+
];
|
|
31
|
+
const MESSAGE_TRANSMITTER_ABI = [
|
|
32
|
+
"function receiveMessage(bytes message,bytes attestation)",
|
|
33
|
+
];
|
|
34
|
+
const EMPTY_DESTINATION_CALLER = `0x${"00".repeat(32)}`;
|
|
35
|
+
function toBytes32(value) {
|
|
36
|
+
if (!isAddress(value))
|
|
37
|
+
throw new Error("CCTP EVM recipients must be valid EVM addresses.");
|
|
38
|
+
return `0x${value.slice(2).padStart(64, "0")}`;
|
|
39
|
+
}
|
|
40
|
+
function stellarContractToBytes32(value) {
|
|
41
|
+
if (!StrKey.isValidContract(value)) {
|
|
42
|
+
throw new Error("CCTP Stellar recipients require a valid CctpForwarder contract address.");
|
|
43
|
+
}
|
|
44
|
+
return `0x${Buffer.from(StrKey.decodeContract(value)).toString("hex")}`;
|
|
45
|
+
}
|
|
46
|
+
function buildForwarderHook(recipient) {
|
|
47
|
+
if (!StrKey.isValidEd25519PublicKey(recipient) &&
|
|
48
|
+
!StrKey.isValidContract(recipient) &&
|
|
49
|
+
!StrKey.isValidMed25519PublicKey(recipient)) {
|
|
50
|
+
throw new Error("CCTP Stellar recipients must be valid G..., M..., or C... addresses.");
|
|
51
|
+
}
|
|
52
|
+
const encoded = Buffer.from(recipient, "utf8");
|
|
53
|
+
const hook = Buffer.alloc(32 + encoded.length);
|
|
54
|
+
hook.writeUInt32BE(0, 24);
|
|
55
|
+
hook.writeUInt32BE(encoded.length, 28);
|
|
56
|
+
encoded.copy(hook, 32);
|
|
57
|
+
return `0x${hook.toString("hex")}`;
|
|
58
|
+
}
|
|
59
|
+
function requireCctpArgument(value, name) {
|
|
60
|
+
if (value === "" || value === null || value === undefined) {
|
|
61
|
+
throw new Error(`CCTP ${name} is missing.`);
|
|
62
|
+
}
|
|
63
|
+
return value;
|
|
64
|
+
}
|
|
65
|
+
function evmAddressBytes32(value) {
|
|
66
|
+
if (!isAddress(value))
|
|
67
|
+
throw new Error("CCTP EVM recipients must be valid EVM addresses.");
|
|
68
|
+
return xdr.ScVal.scvBytes(Buffer.from(value.slice(2).padStart(64, "0"), "hex"));
|
|
69
|
+
}
|
|
70
|
+
async function submitStellarSorobanTransaction(server, contractId, method, args, networkPassphrase, sourceAddress) {
|
|
71
|
+
const account = await server.getAccount(sourceAddress);
|
|
72
|
+
const transaction = new TransactionBuilder(account, {
|
|
73
|
+
fee: "10000000",
|
|
74
|
+
networkPassphrase,
|
|
75
|
+
})
|
|
76
|
+
.addOperation(new StellarContract(contractId).call(method, ...args))
|
|
77
|
+
.setTimeout(120)
|
|
78
|
+
.build();
|
|
79
|
+
const simulation = await server.simulateTransaction(transaction);
|
|
80
|
+
if (rpc.Api.isSimulationError(simulation)) {
|
|
81
|
+
throw new Error(`Stellar Soroban simulation failed: ${JSON.stringify(simulation)}`);
|
|
82
|
+
}
|
|
83
|
+
const prepared = rpc.assembleTransaction(transaction, simulation).build();
|
|
84
|
+
const signed = await freighterSignTransaction(prepared.toXDR(), {
|
|
85
|
+
networkPassphrase,
|
|
86
|
+
address: sourceAddress,
|
|
87
|
+
});
|
|
88
|
+
if (signed.error || !signed.signedTxXdr) {
|
|
89
|
+
throw new Error(signed.error?.message || "Stellar wallet signing was rejected.");
|
|
90
|
+
}
|
|
91
|
+
const result = await server.sendTransaction(TransactionBuilder.fromXDR(signed.signedTxXdr, networkPassphrase));
|
|
92
|
+
if (result.status === "ERROR")
|
|
93
|
+
throw new Error(`Stellar transaction submission failed: ${JSON.stringify(result)}`);
|
|
94
|
+
let completed = await server.getTransaction(result.hash);
|
|
95
|
+
while (completed.status === "NOT_FOUND") {
|
|
96
|
+
await new Promise((resolve) => setTimeout(resolve, 2000));
|
|
97
|
+
completed = await server.getTransaction(result.hash);
|
|
98
|
+
}
|
|
99
|
+
if (completed.status !== "SUCCESS")
|
|
100
|
+
throw new Error(`Stellar transaction failed: ${JSON.stringify(completed)}`);
|
|
101
|
+
return result.hash;
|
|
102
|
+
}
|
|
103
|
+
async function waitForCctpAttestation(sourceDomain, transactionHash) {
|
|
104
|
+
const baseUrl = "https://iris-api-sandbox.circle.com/v2/messages";
|
|
105
|
+
for (let attempt = 0; attempt < 60; attempt += 1) {
|
|
106
|
+
const response = await fetch(`${baseUrl}/${sourceDomain}?transactionHash=${encodeURIComponent(transactionHash)}`);
|
|
107
|
+
if (response.ok) {
|
|
108
|
+
const data = await response.json();
|
|
109
|
+
const message = data.messages?.[0];
|
|
110
|
+
if (message?.status === "complete" && message.message && message.attestation) {
|
|
111
|
+
return { message: message.message, attestation: message.attestation };
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
else if (response.status !== 404) {
|
|
115
|
+
throw new Error(`Circle attestation request failed with HTTP ${response.status}.`);
|
|
116
|
+
}
|
|
117
|
+
await new Promise((resolve) => setTimeout(resolve, 5000));
|
|
118
|
+
}
|
|
119
|
+
throw new Error("Circle attestation was not available within five minutes.");
|
|
120
|
+
}
|
|
121
|
+
async function getDestinationEvmWallet(destination) {
|
|
122
|
+
const walletConfig = getActiveWagmiConfig();
|
|
123
|
+
const current = walletConfig.state.current;
|
|
124
|
+
const connection = current ? walletConfig.state.connections.get(current) : undefined;
|
|
125
|
+
if (!connection) {
|
|
126
|
+
throw new Error("Connect an EVM wallet on the destination network before starting the Stellar CCTP transfer.");
|
|
127
|
+
}
|
|
128
|
+
const rawProvider = await connection.connector.getProvider();
|
|
129
|
+
let provider = new BrowserProvider(rawProvider);
|
|
130
|
+
const chain = await evmStep(`read the connected wallet chain for ${destination.networkName}`, () => provider.getNetwork());
|
|
131
|
+
if (destination.chainId === undefined || Number(chain.chainId) !== destination.chainId) {
|
|
132
|
+
try {
|
|
133
|
+
await provider.send("wallet_switchEthereumChain", [{
|
|
134
|
+
chainId: `0x${destination.chainId.toString(16)}`,
|
|
135
|
+
}]);
|
|
136
|
+
}
|
|
137
|
+
catch (error) {
|
|
138
|
+
const message = error instanceof Error ? error.message : "The wallet rejected the network switch.";
|
|
139
|
+
throw new Error(`Switch the connected EVM wallet to ${destination.networkName} to continue: ${message}`);
|
|
140
|
+
}
|
|
141
|
+
const switchedChain = await provider.getNetwork();
|
|
142
|
+
if (Number(switchedChain.chainId) !== destination.chainId) {
|
|
143
|
+
throw new Error(`The connected EVM wallet is not on ${destination.networkName}.`);
|
|
144
|
+
}
|
|
145
|
+
provider = new BrowserProvider(rawProvider);
|
|
146
|
+
}
|
|
147
|
+
if (!connection.accounts[0]) {
|
|
148
|
+
throw new Error("The connected EVM wallet has no active account.");
|
|
149
|
+
}
|
|
150
|
+
return { walletConfig, connection, provider };
|
|
151
|
+
}
|
|
152
|
+
async function disconnectEvmWallets(walletConfig) {
|
|
153
|
+
const { disconnect } = await import("wagmi/actions");
|
|
154
|
+
const connections = Array.from(walletConfig.state.connections.values());
|
|
155
|
+
for (const connection of connections) {
|
|
156
|
+
await disconnect(walletConfig, { connector: connection.connector });
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
async function bridgeStellarToEvm(amount, from, to, recipient, route) {
|
|
160
|
+
const source = route[from];
|
|
161
|
+
const destination = route[to];
|
|
162
|
+
const stellarConfig = getCordyRuntimeConfig()?.stellarNetwork;
|
|
163
|
+
if (!source || !destination || source.networkType !== "stellar" || destination.networkType !== "evm") {
|
|
164
|
+
throw new Error("CCTP Stellar source requires a Stellar source and EVM destination.");
|
|
165
|
+
}
|
|
166
|
+
if (!isAddress(recipient))
|
|
167
|
+
throw new Error("The CCTP destination must be a valid EVM address.");
|
|
168
|
+
if (source.domain === undefined || !source.tokenMessengerMinter || !source.tokenAddress ||
|
|
169
|
+
destination.domain === undefined || !destination.messageTransmitter) {
|
|
170
|
+
throw new Error("Configure Stellar tokenAddress/tokenMessengerMinter and EVM domain/messageTransmitter for CCTP.");
|
|
171
|
+
}
|
|
172
|
+
if (!stellarConfig?.sorobanRpcUrl) {
|
|
173
|
+
throw new Error("Configure stellarNetwork.sorobanRpcUrl for Stellar CCTP.");
|
|
174
|
+
}
|
|
175
|
+
const destinationWallet = await getDestinationEvmWallet(destination);
|
|
176
|
+
const access = await requestAccess();
|
|
177
|
+
const sourceAddress = access.address;
|
|
178
|
+
if (!sourceAddress)
|
|
179
|
+
throw new Error("No Stellar wallet account is available.");
|
|
180
|
+
const network = await getNetworkDetails();
|
|
181
|
+
const networkPassphrase = network.networkPassphrase || stellarConfig.networkPassphrase;
|
|
182
|
+
if (networkPassphrase !== stellarConfig.networkPassphrase) {
|
|
183
|
+
throw new Error(`Stellar network mismatch. Expected ${stellarConfig.networkPassphrase}.`);
|
|
184
|
+
}
|
|
185
|
+
const server = new rpc.Server(stellarConfig.sorobanRpcUrl);
|
|
186
|
+
const latestLedger = await server.getLatestLedger();
|
|
187
|
+
const amountIn = parseUnits(amount, 7);
|
|
188
|
+
const owner = new Address(sourceAddress).toScVal();
|
|
189
|
+
const messenger = new Address(source.tokenMessengerMinter).toScVal();
|
|
190
|
+
const approveHash = await submitStellarSorobanTransaction(server, source.tokenAddress, "approve", [
|
|
191
|
+
owner,
|
|
192
|
+
messenger,
|
|
193
|
+
nativeToScVal(amountIn, { type: "i128" }),
|
|
194
|
+
nativeToScVal(latestLedger.sequence + 100000, { type: "u32" }),
|
|
195
|
+
], networkPassphrase, sourceAddress);
|
|
196
|
+
const burnHash = await submitStellarSorobanTransaction(server, source.tokenMessengerMinter, "deposit_for_burn", [
|
|
197
|
+
owner,
|
|
198
|
+
nativeToScVal(amountIn, { type: "i128" }),
|
|
199
|
+
nativeToScVal(destination.domain, { type: "u32" }),
|
|
200
|
+
evmAddressBytes32(recipient),
|
|
201
|
+
new Address(source.tokenAddress).toScVal(),
|
|
202
|
+
xdr.ScVal.scvBytes(Buffer.alloc(32)),
|
|
203
|
+
nativeToScVal(0n, { type: "i128" }),
|
|
204
|
+
nativeToScVal(2000, { type: "u32" }),
|
|
205
|
+
], networkPassphrase, sourceAddress);
|
|
206
|
+
const attestation = await waitForCctpAttestation(source.domain, burnHash);
|
|
207
|
+
const signer = await destinationWallet.provider.getSigner(destinationWallet.connection.accounts[0]);
|
|
208
|
+
const transmitter = new Contract(destination.messageTransmitter, MESSAGE_TRANSMITTER_ABI, signer);
|
|
209
|
+
const mintTransaction = await transmitter.receiveMessage(attestation.message, attestation.attestation);
|
|
210
|
+
const receipt = await mintTransaction.wait();
|
|
211
|
+
if (!receipt || receipt.status !== 1)
|
|
212
|
+
throw new Error("EVM CCTP mint transaction failed.");
|
|
213
|
+
await disconnectEvmWallets(destinationWallet.walletConfig);
|
|
214
|
+
return {
|
|
215
|
+
success: true,
|
|
216
|
+
asset: source.assetSymbol,
|
|
217
|
+
from,
|
|
218
|
+
to,
|
|
219
|
+
fromNetwork: source.networkName,
|
|
220
|
+
toNetwork: destination.networkName,
|
|
221
|
+
routeId: route.id,
|
|
222
|
+
routeName: route.name,
|
|
223
|
+
amount,
|
|
224
|
+
transactionHash: receipt.hash || mintTransaction.hash,
|
|
225
|
+
status: "submitted",
|
|
226
|
+
approvalTransactionHash: approveHash,
|
|
227
|
+
};
|
|
228
|
+
}
|
|
229
|
+
export async function cctpBridge(amount, from, to, recipient, route) {
|
|
230
|
+
const source = route[from];
|
|
231
|
+
const destination = route[to];
|
|
232
|
+
if (!source || !destination)
|
|
233
|
+
throw new Error("CCTP route source and destination are required.");
|
|
234
|
+
if (source.networkType === "stellar")
|
|
235
|
+
return bridgeStellarToEvm(amount, from, to, recipient, route);
|
|
236
|
+
if (source.networkType !== "evm" || source.chainId === undefined || source.domain === undefined || !source.tokenAddress || !source.tokenMessenger) {
|
|
237
|
+
throw new Error("Configure the CCTP EVM source with chainId, domain, tokenAddress, and tokenMessenger.");
|
|
238
|
+
}
|
|
239
|
+
if (destination.networkType === "evm" && (destination.domain === undefined || !isAddress(destination.tokenAddress || ""))) {
|
|
240
|
+
throw new Error("Configure the CCTP EVM destination with domain and a valid tokenAddress.");
|
|
241
|
+
}
|
|
242
|
+
if (destination.networkType === "stellar" && !destination.cctpForwarder) {
|
|
243
|
+
throw new Error("Configure the Stellar CctpForwarder contract for EVM-to-Stellar CCTP.");
|
|
244
|
+
}
|
|
245
|
+
const walletConfig = getActiveWagmiConfig();
|
|
246
|
+
const current = walletConfig.state.current;
|
|
247
|
+
const connection = current ? walletConfig.state.connections.get(current) : undefined;
|
|
248
|
+
if (!connection)
|
|
249
|
+
throw new Error("No EVM wallet is currently connected.");
|
|
250
|
+
const rawProvider = await connection.connector.getProvider();
|
|
251
|
+
let provider = new BrowserProvider(rawProvider);
|
|
252
|
+
let chain = await evmStep(`read the connected wallet chain for ${source.networkName}`, () => provider.getNetwork());
|
|
253
|
+
if (Number(chain.chainId) !== source.chainId) {
|
|
254
|
+
await evmStep(`switch the connected wallet to ${source.networkName}`, () => provider.send("wallet_switchEthereumChain", [{
|
|
255
|
+
chainId: `0x${source.chainId.toString(16)}`,
|
|
256
|
+
}]));
|
|
257
|
+
provider = new BrowserProvider(rawProvider);
|
|
258
|
+
chain = await evmStep(`verify the connected wallet is on ${source.networkName}`, () => provider.getNetwork());
|
|
259
|
+
if (Number(chain.chainId) !== source.chainId) {
|
|
260
|
+
throw new Error(`The connected EVM wallet is not on ${source.networkName}.`);
|
|
261
|
+
}
|
|
262
|
+
}
|
|
263
|
+
const signer = await evmStep("access the connected EVM signer", () => provider.getSigner(connection.accounts[0]));
|
|
264
|
+
const sender = await evmStep("read the connected EVM account", () => signer.getAddress());
|
|
265
|
+
const token = new Contract(source.tokenAddress, CCTP_TOKEN_ABI, signer);
|
|
266
|
+
const messenger = new Contract(source.tokenMessenger, CCTP_MESSENGER_ABI, signer);
|
|
267
|
+
const decimalsValue = await evmStep(`read ${source.assetSymbol} decimals`, () => token.decimals());
|
|
268
|
+
const decimals = Number(requireEvmValue(decimalsValue, `read ${source.assetSymbol} decimals`));
|
|
269
|
+
if (!Number.isInteger(decimals) || decimals < 0 || decimals > 18)
|
|
270
|
+
throw new Error("The CCTP token returned invalid decimals.");
|
|
271
|
+
const amountIn = parseUnits(amount, decimals);
|
|
272
|
+
const balance = requireEvmValue(await evmStep(`read ${source.assetSymbol} balance`, () => token.balanceOf(sender)), `read ${source.assetSymbol} balance`);
|
|
273
|
+
if (BigInt(balance.toString()) < amountIn) {
|
|
274
|
+
throw new Error(`Insufficient ${source.assetSymbol} balance for CCTP.`);
|
|
275
|
+
}
|
|
276
|
+
const allowanceValue = requireEvmValue(await evmStep(`read ${source.assetSymbol} allowance`, () => token.allowance(sender, source.tokenMessenger)), `read ${source.assetSymbol} allowance`);
|
|
277
|
+
const allowance = BigInt(allowanceValue.toString());
|
|
278
|
+
let approvalTransactionHash;
|
|
279
|
+
if (allowance < amountIn) {
|
|
280
|
+
const approval = await evmStep(`submit ${source.assetSymbol} approval`, () => token.approve(source.tokenMessenger, amountIn));
|
|
281
|
+
const receipt = await evmStep("wait for the EVM approval receipt", () => approval.wait());
|
|
282
|
+
if (!receipt || receipt.status !== 1)
|
|
283
|
+
throw new Error("CCTP token approval failed.");
|
|
284
|
+
approvalTransactionHash = receipt.hash || approval.hash;
|
|
285
|
+
}
|
|
286
|
+
let transaction;
|
|
287
|
+
const destinationDomain = requireCctpArgument(destination.domain, "destination domain");
|
|
288
|
+
const maxFee = 0n;
|
|
289
|
+
const minFinalityThreshold = 2000;
|
|
290
|
+
if (destination.networkType === "stellar") {
|
|
291
|
+
const forwarder = stellarContractToBytes32(destination.cctpForwarder);
|
|
292
|
+
const hookData = buildForwarderHook(recipient);
|
|
293
|
+
transaction = await evmStep("submit the EVM-to-Stellar CCTP burn", () => messenger.depositForBurnWithHook(amountIn, destinationDomain, forwarder, source.tokenAddress, EMPTY_DESTINATION_CALLER, maxFee, minFinalityThreshold, hookData));
|
|
294
|
+
}
|
|
295
|
+
else {
|
|
296
|
+
const mintRecipient = toBytes32(recipient);
|
|
297
|
+
transaction = await evmStep("submit the EVM CCTP burn", () => messenger.depositForBurn(amountIn, destinationDomain, mintRecipient, source.tokenAddress, EMPTY_DESTINATION_CALLER, maxFee, minFinalityThreshold));
|
|
298
|
+
}
|
|
299
|
+
const receipt = await evmStep("wait for the EVM burn receipt", () => transaction.wait());
|
|
300
|
+
if (!receipt || receipt.status !== 1)
|
|
301
|
+
throw new Error("CCTP burn transaction failed.");
|
|
302
|
+
let disconnectWarning;
|
|
303
|
+
try {
|
|
304
|
+
await disconnectEvmWallets(walletConfig);
|
|
305
|
+
}
|
|
306
|
+
catch (error) {
|
|
307
|
+
disconnectWarning = error instanceof Error
|
|
308
|
+
? `The bridge completed, but the EVM wallet could not be disconnected: ${error.message}`
|
|
309
|
+
: "The bridge completed, but the EVM wallet could not be disconnected.";
|
|
310
|
+
}
|
|
311
|
+
return {
|
|
312
|
+
success: true,
|
|
313
|
+
asset: source.assetSymbol,
|
|
314
|
+
from,
|
|
315
|
+
to,
|
|
316
|
+
fromNetwork: source.networkName,
|
|
317
|
+
toNetwork: destination.networkName,
|
|
318
|
+
routeId: route.id,
|
|
319
|
+
routeName: route.name,
|
|
320
|
+
amount,
|
|
321
|
+
...(approvalTransactionHash ? { approvalTransactionHash } : {}),
|
|
322
|
+
transactionHash: receipt.hash || transaction.hash,
|
|
323
|
+
status: "pending",
|
|
324
|
+
...(disconnectWarning ? { warning: disconnectWarning } : {}),
|
|
325
|
+
};
|
|
326
|
+
}
|
|
@@ -1,4 +1,8 @@
|
|
|
1
1
|
export { default as WalletButton } from "./WagmiButton";
|
|
2
|
+
export { default as BridgeEvmWalletModal } from "./BridgeEvmWalletModal";
|
|
3
|
+
export type { BridgeEvmWalletModalProps } from "./BridgeEvmWalletModal";
|
|
4
|
+
export { bridgeRequestNeedsEvmWallet, useBridgeEvmWallet } from "./useBridgeEvmWallet";
|
|
5
|
+
export type { BridgeEvmWalletRequest, UseBridgeEvmWalletOptions } from "./useBridgeEvmWallet";
|
|
2
6
|
export { default as CordyStackTrans } from "./Transactions";
|
|
3
7
|
export { CordyStackTransStellar } from "./Transactions";
|
|
4
8
|
export { default as getTokenBalance } from "./Get_Balance";
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../controllers/index.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,OAAO,IAAI,YAAY,EAAE,MAAM,eAAe,CAAC;
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../controllers/index.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,OAAO,IAAI,YAAY,EAAE,MAAM,eAAe,CAAC;AACxD,OAAO,EAAE,OAAO,IAAI,oBAAoB,EAAE,MAAM,wBAAwB,CAAC;AACzE,YAAY,EAAE,yBAAyB,EAAE,MAAM,wBAAwB,CAAC;AACxE,OAAO,EAAE,2BAA2B,EAAE,kBAAkB,EAAE,MAAM,sBAAsB,CAAC;AACvF,YAAY,EAAE,sBAAsB,EAAE,yBAAyB,EAAE,MAAM,sBAAsB,CAAC;AAE9F,OAAO,EAAE,OAAO,IAAI,eAAe,EAAE,MAAM,gBAAgB,CAAC;AAC5D,OAAO,EAAE,sBAAsB,EAAE,MAAM,gBAAgB,CAAC;AAExD,OAAO,EAAE,OAAO,IAAI,eAAe,EAAE,MAAM,eAAe,CAAC;AAE3D,OAAO,EAAE,OAAO,IAAI,gBAAgB,EAAE,MAAM,oBAAoB,CAAC;AAEjE,OAAO,EAAE,OAAO,IAAI,mBAAmB,EAAE,MAAM,iBAAiB,CAAC;AAEjE,OAAO,EAAE,OAAO,IAAI,kBAAkB,EAAE,MAAM,sBAAsB,CAAC;AAErE,OAAO,EAAE,OAAO,IAAI,oBAAoB,EAAE,MAAM,cAAc,CAAC;AAE/D,OAAO,EAAE,OAAO,IAAI,eAAe,EAAE,MAAM,oBAAoB,CAAC"}
|