Transfer tokens between Cosmos chains using Inter-Blockchain Communication
Transfer tokens between different Cosmos chains using IBC (Inter-Blockchain Communication) with CosmJS.
import { useCosmosClient } from "./useCosmosClient";
import { coins } from "@cosmjs/stargate";
import { MsgTransfer } from "cosmjs-types/ibc/applications/transfer/v1/tx";
import { Height } from "cosmjs-types/ibc/core/client/v1/client";
function IBCTransfer() {
const { signingClient } = useCosmosClient("https://rpc.cosmos.network");
const sendIBCTransfer = async () => {
if (!signingClient) return;
const accounts = await signingClient.signer.getAccounts();
const sender = accounts[0].address;
const currentHeight = await signingClient.getHeight();
const timeoutHeight = Height.fromPartial({
revisionNumber: 1n,
revisionHeight: BigInt(currentHeight + 1000),
});
const msgTransfer = {
typeUrl: "/ibc.applications.transfer.v1.MsgTransfer",
value: MsgTransfer.fromPartial({
sourcePort: "transfer",
sourceChannel: "channel-141", // Osmosis channel
token: {
denom: "uatom",
amount: "1000000", // 1 ATOM
},
sender: sender,
receiver: "osmo1...", // Osmosis address
timeoutHeight: timeoutHeight,
timeoutTimestamp: 0n,
}),
};
const fee = {
amount: coins(5000, "uatom"),
gas: "250000",
};
try {
const result = await signingClient.signAndBroadcast(
sender,
[msgTransfer],
fee,
"IBC transfer via Para"
);
console.log("IBC transfer initiated:", result.transactionHash);
} catch (error) {
console.error("IBC transfer failed:", error);
}
};
return (
<button onClick={sendIBCTransfer}>Send 1 ATOM to Osmosis</button>
);
}