Unlocking the Immense Possibilities with Wormhole: A Guide to Integrating It into Your Project
1. What is wormhole ?
Firstly, let me provide an introduction to the concept of a wormhole and delve into the origins and evolution of wormholes:
Wormhole V1 was introduced in 2020 by Certus One and was initially conceived as a traditional token bridge between Ethereum and Solana. It served as the first bridge on Solana and was responsible for bootstrapping a large amount of the liquidity in the early Solana and Serum ecosystems. Wormhole v2 launched in August 2021 as a decentralized generic interoperability protocol for multiple blockchain ecosystems with initial support for Solana, Terra, Ethereum and Binance Smart Chai. (https://book.wormhole.com/wormhole/1_whatIsWormhole.html)
So basically Wormhole is a bridge between chains. With a wormhole you can interact with different chains without worrying about security. For example: ‘Wormhole’ serves as a vital link between two nations, much like a conduit for monetary transactions. Imagine you’re in Vietnam and your friend is in the United States. You both want to send money to each other, just as people did in the old days, but you’re separated by vast distances and your friend urgently needs the funds. How do you navigate this situation? This is where the ‘Wormhole’ comes into play.
Wormhole facilitate the smooth transfer of your funds from one country to the other. When you want to send money to your friend in the US, ‘Wormhole’ will accept your payment in Vietnam, then alert their US branch. The US branch will then arrange for the transfer of the funds to your friend. This simple process ensures that your money reaches its destination swiftly and securely, even across international borders.
But in blockchain things will not be so simple but to understand in general what Wormhole is and how Wormhole will work, this is a good example to visualize. So let’s go to the following section to better understand what Wormhole really has that they can ensure security between chains.
2. Wormhole architecture
When I first encountered Wormhole, I struggled to grasp its significance. I’d find myself asking, “Why on earth would I need a wormhole?” At the time, it seemed straightforward to interact between blockchains like Solana and Ethereum. I imagined all I had to do was establish a smart contract on each chain and set up a relayer to monitor events. If Solana initiated an action, I could utilize the relayer to transmit the corresponding message to Ethereum for processing, and vice versa. However, a friend posed a hypothetical scenario that shifted my perspective. They asked, “What if a hacker breached your relayer system and tampered with the messages between Solana and Ethereum? How would you counteract this?” It was in that moment I truly understood the value of Wormhole. Wormhole serves as a safeguard, validating that the ‘messages’ originate from my Solana program and not from an unauthorized source. So the question is, what does Wormhole have?
Some basic concepts you need to grasp are as follows:
On-Chain Components
- xDapp Contracts — Contracts developed by xDapp developers. They receive transactions from the end user and then interact with other xDapp contracts and Wormhole Ecosystem Contracts in order to provide their service.
- Ecosystem Contracts — Contracts subject to Wormhole governance which live inside the Wormhole Ecosystem. Their job is to provide the feature suite of Wormhole to xDapp developers.
- Core Contracts — Primary ecosystem contracts. These are the contracts which the Guardians observe and which fundamentally allow for cross-chain communication.
- xAsset Contracts — Contracts that allow normal tokens to be converted to xAssets and enable these xAssets to be bridged.
- Relay Contracts — in development* — Contracts that allow xDapps to send messages to a specific blockchain via the decentralized Generic Relayer network.
- Gas Oracle — in development* — Oracle for recommended fair gas prices across the ecosystem.
- Worm Router Contracts — in development* — Contracts that allow developers to make their Dapp an xDapp that users on any Wormhole supported chain can interact with purely through client-side code.
Off-Chain Components
- Guardian Network — Validators that exist in their own p2p network. Guardians observe the Core Contract on each supported chain and produce VAAs (signed messages) when those contracts receive an interaction.
- Guardian — One of 19 validators in the Guardian Network that contributes to the VAA multisig.
- Spy — Validators on the Guardian Network which are not part of the Guardian set. A spy can observe and forward network traffic, which helps scale up VAA distribution.
- VAAs — Verifiable Action Approvals (VAAs) are the key piece of data in the Wormhole ecosystem, containing the messages emitted by xDapps along with information such as what contract emitted the message. The VAAs are signed by the Guardians and need 13/19 signatures to be considered authentic.
- Specialized Relayers — Relayers that only handle VAAs for a specific protocol or xDapp. They can execute custom logic off-chain, which can reduce gas costs and increase cross-chain compatibility. Currently, xDapp developers are responsible for developing and hosting specialized relayers.
- Generic Relayers — in development* — A decentralized relayer network which delivers messages that are requested on-chain via the Wormhole Relay Contract.
- Wormchain — in development* — A purpose-built cosmos blockchain which aids the Guardian Network and allows for formal interaction with the Guardians.
The definitions can seem a bit complex, can’t they? To ensure a deeper understanding, let’s delve into the next section.
3. How wormhole works ?
This segment of the article draws its insights directly from the following image, so let’s direct our attention towards it. This part I will divide into 3 small stages:
- Source chain
- Off chain
- Dest chain
Soure chain
- In the source chain, there are two key smart contracts at play: the Wormhole smart contract and your custom smart contract. Your interaction with the system will primarily occur via your own smart contract, which will be used to issue a “Calls” to the Wormhole smart contract.
- Once this call is received, the Wormhole smart contract will execute the necessary processing and subsequently “Emmits” a unique communication known as the ‘Wormhole Message’.
Off chain
- When Wormhole Message is created, it undergoes immediate scrutiny by the Guardians of the Wormhole Network for validation purposes. If deemed valid, the Guardians will endorse the message. Subsequently, when the message secures the approval of 13 out of 19 Guardians, indicated by their ‘Agree’ responses, it transitions into a signed VAA.
- Following this, the relayer undertakes its role of retrieving the signed VAA. It then initiates a “Calls” to your smart contract (Itergrator Contract) located on the destination chain.”
Dest chain
- The role of the Integrator contract is to process the signed VAA. It forwards this VAA to the Wormhole Contract on the destination chain, which then determines the validity of your VAA.
- If the VAA is deemed invalid, no action is taken. However, if it is deemed valid, we proceed to decode the VAA, interpret the embedded message, and decide the subsequent course of action based on the contained instructions or simply display it as necessary.
Indeed, we are now at the halfway point in our journey to fully grasp the concept of a Wormhole, its structure, and its functionality. Before we venture into the next section, let’s take a moment to ponder over potential applications of the Wormhole, beyond its evident use for cross-chain financial transfers. Could there be other significant applications that leverage the vast potential offered by cross-chain capabilities? Let’s brainstorm and explore these possibilities.
4. The Potential of Wormhole
The Wormhole SDK of Solana holds immense potential for developers and projects seeking to integrate cross-chain functionality into their applications. By leveraging the power of Wormhole, developers can bridge assets and data across different blockchain networks, opening up a world of possibilities. Here are some key aspects of the Wormhole SDK and its potential applications:
a. Interoperability:
One of the significant advantages of the Wormhole SDK is its ability to establish interoperability between different blockchain ecosystems. It enables seamless asset transfers and data communication between Solana and other compatible blockchains. This interoperability allows developers to tap into the strengths and features of multiple networks, expanding the capabilities of their projects.
b. Cross-Chain Asset Transfers:
With the Wormhole SDK, developers can facilitate the transfer of assets between Solana and other supported blockchains. This feature is particularly valuable for projects looking to enable token swaps, decentralized exchanges, or cross-chain liquidity pools. By integrating Wormhole, developers can create a seamless experience for users to transfer assets across different chains, unlocking new avenues for liquidity and trading opportunities.
c. Cross-Chain Data Transfer:
In addition to asset transfers, the Wormhole SDK enables the transfer of data across blockchains. This capability allows projects to access and utilize information from multiple blockchain networks, enhancing the scope and functionality of their applications. For instance, developers can build decentralized applications (DApps) that leverage data from various sources, creating innovative solutions that harness the collective power of different blockchains.
d. Ecosystem Expansion:
The Wormhole SDK contributes to the growth and expansion of the Solana ecosystem by attracting developers and projects from other blockchain networks. By providing a seamless bridge for asset and data transfers, it encourages collaboration between different communities and facilitates the adoption of Solana as a preferred blockchain platform. This expansion of the ecosystem fosters innovation, diversity, and increased utility for Solana-based projects.
e. DeFi and Beyond:
The potential of the Wormhole SDK extends beyond the realms of decentralized finance (DeFi). While DeFi applications can greatly benefit from cross-chain asset transfers and data communication, other sectors such as gaming, non-fungible tokens (NFTs), supply chain, and more can also leverage the Wormhole SDK to unlock new possibilities. Developers have the opportunity to explore unique use cases and create novel applications that transcend the limitations of a single blockchain.
5. Wormhole SDK
How the Core Wormhole Bridge Works
The core Wormhole bridge operates by running smart contracts on both the Source Chain (where the data currently resides) and the Target Chain (where the data will be moved), and generally follows this workflow:
1) An end user or another smart contract publishes a message using the Bridge Contract on the Source Chain.
2) The Wormhole Network observes this transaction and issues a SignedVAA once it crosses its confirmation threshold.
3) An off-chain process collects the SignedVAA and submits it in a transaction to the Bridge Contract on the Target Chain, which can parse and verify the message.
How the Wormhole Token Bridge Works
It is important to note that the Wormhole Token Bridge is not, strictly speaking, part of the Wormhole protocol, but rather a bridge on top of it. However, as token transfers are such an important use-case of the bridge, it is built and packaged as part of the Wormhole SDK.
The Token Bridge works in the same fashion as above, leveraging the Core Bridge to publish messages. However, there are actually two different functions in the token bridge: Attest and Transfer.
Attest
Attestation is the process by which a token is ‘registered’ with the token bridge. Before being transferred, tokens must first be attested on their Origin Chain and have corresponding wrapped tokens created on the Foreign Chain to which they will be transferred. Attesting on the Origin Chain will create requisite addresses and metadata that will allow the wrapped asset to exist on Foreign Chains.
Transfer
Once attested, tokens are mapped from their Native Chain to ‘wrapped’ assets on the Foreign Chains. Transferring an Ethereum-native token to Solana will result in a ‘wrapped asset’ on Solana, and transferring that same asset back to Ethereum will restore the native token.
It is important to note that Wormhole wrapped tokens are distinct from and incompatible with tokens wrapped by other bridges. Transferring a token which was wrapped by a different bridge will not redeem the native token, but rather will result in a ‘double-wrapped’ token.
6. Coding
Let’s consider a practical example where you utilize the Wormhole SDK to transfer your custom token from a Solana Wallet to an Ethereum Wallet. This process involves two main steps:
Step 1: Registering your token on the Ethereum network. To begin, you need to register your token within the Ethereum network. This step ensures that the Ethereum Wallet recognizes and can interact with your token effectively.
Step 2: Transferring and redeeming your token via the Wormhole Token Bridge. Once your token is registered, you can proceed to send the desired amount of your token to the Wormhole Token Bridge in Solana. This bridge acts as an intermediary, facilitating the secure transfer of tokens between the Solana and Ethereum networks. After sending your token to the bridge, you will then need to redeem it on the Ethereum network, allowing it to be accessed and utilized within your Ethereum Wallet.
So for more clarity on how to use Wormhole SDK, follow my code below:
Import
import { Connection, Keypair, PublicKey, clusterApiUrl } from '@solana/web3.js';
import { ethers } from 'ethers';
import {
CHAIN_ID_ETH,
CHAIN_ID_SOLANA,
CONTRACTS,
attestFromSolana,
createWrappedOnEth,
getEmitterAddressSolana,
getIsTransferCompletedEth,
parseSequenceFromLogSolana,
redeemOnEth,
transferFromSolana,
tryNativeToUint8Array,
} from '@certusone/wormhole-sdk';
import {
getAssociatedTokenAddress,
} from '@solana/spl-token';
Constant
// Solana constant
const connection = new Connection(clusterApiUrl('devnet'), 'confirmed');
const SOLANA_SPL_TOKEN = new Publickey('HyC6H4E2sEJGQoVMhapw1WLnSb51Mnapeh3Eqke68WCM'); // SPL Token publicKey in Solana Devnet
// Keypair that you sign the transaction from Solana
const keypair = Keypair.fromSecretKey(
Uint8Array.from([
13, 82, 117, 67, 249, 64, 150, 31, 116, 67, 234, 152, 255, 109, 62, 111,
35, 170, 11, 56, 65, 18, 157, 242, 80, 97, 246, 84, 1, 65, 149, 181, 67,
249, 215, 33, 158, 135, 96, 152, 226, 28, 89, 211, 255, 248, 42, 118, 35,
1, 14, 106, 86, 195, Ï183, 2, 96, 13, 139, 199, 238, 239, 157, 74,
])
); // Your keypair
// Ethereum constant
const ETH_NODE_URL = ''; // Websocket link from Alchemy
const ETH_PRIVATE_KEY = 'Your private key'
const provider = new ethers.providers.WebSockerProvider(ETH_NODE_URL);
const signer = new ethers.Wallet(ETH_PRIVATE_KEY);
// Wormhole
const WORMHOLE_RPC_HOST = 'https://wormhole-v2-testnet-api.certus.one';
const SOL_BRIDGE_ADDRESS = new PublicKey(CONTRACTS.TESTNET.solana.core);
const SOL_TOKEN_BRIDGE_ADDRESS = new PublicKey(CONTRACTS.TESTNET.solana.token_bridge);
const ETH_TOKEN_BRIDGE_ADDRESS = CONTRACTS.TESTNET.ethereum.token_bridge;
Attest
// Submit transaction - results in a Wormhole message being published
const transaction = await attestFromSolana(
connection, // Solana devnet
SOL_BRIDGE_ADDRESS,
SOL_TOKEN_BRIDGE_ADDRESS,
keypair.publicKey,
SOLANA_SPL_TOKEN,
);
// Sign the transacion
transaction.partialSign(keypair);
// Set the feePayer is you
transaction.feePayer = keypair.publicKey;
const txid = await connection.sendRawTransaction(transaction.serialize(), {
skipPreflix: true,
maxRetries: 5,
})
// Confirm the transaction
await connection.confirmTransaction(txid);
// Get the sequence number and emitter address required to fetch the signedVAA of our message
const info = await connection.getTransaction(txid);
if (info != null) {
const sequence = parseSequenceFromLogSolana(info);
const emitterAddress = await getEmitterAddressSolana(
SOL_TOKEN_BRIDGE_ADDRESS
);
const vaaURL = `${WORMHOLE_RPC_HOST}/v1/signed_vaa/${CHAIN_ID_SOLANA}/${emitterAddress}/${sequence}`;
// Get the VaaBytes from this api of Wormhole Network
let vaaBytes= await (await fetch(vaaURL)).json();
while (!vaaBytes.vaaBytes) {
// If don't get the VaaBytes yet, must fetch again
await new Promise((r) => setTimeout()r, 5000);
vaaBytes= await (await fetch(vaaURL)).json();
}
// Part 2: Ethereum sid
// Convert vaaBytes object to Uint8Array
const signedVAA = new Uint8Array(Buffer.from(vaaBytes.vaaBytes, 'base64'));
// Create the wrapped token on Ethereum
await createWrappedOnEth(ETH_TOKEN_BRIDGE_ADDRESS, signer, signedVAA);
provider.destroy();
};
Transfer
// Your publicKey of your Ethereum wallet
const targetAddress = signer.getAddress();
// Transfer token `SOLANA_SPL_TOKEN` from `fromAddress` with `amount`
const fromAddess = {
await getAssociatedTokenAddress(
new PublicKey(SOLANA_SPL_TOKEN),
keypair.publicKey
).toString();
const amount: bigint = ethers.utils.parseUints('1', 9).toBigInt();
// Submit transaction - results in a Wormhole message being published
const transaction = await transferFromSolana(
connection,
SOL_BRIDGE_ADDRESS,
SOL_TOKEN_BRIDGE_ADDRESS,
keypair.publicKey, // payer address
fromAddress,
SOLANA_SPL_TOKEN,
amount,
tryNativeToUint8Array(targetAddress, CHAIN_ID_ETH),
CHAIN_ID_ETH, // target chain
);
// Sign the transacion
transaction.partialSign(keypair);
// Set the feePayer is you
transaction.feePayer = keypair.publicKey;
const txid = await connection.sendRawTransaction(transaction.serialize(), {
skipPreflix: true,
maxRetries: 5,
})
// Confirm the transaction
await connection.confirmTransaction(txid);
// Get the sequence number and emitter address required to fetch the signedVAA of our message
const info = await connection.getTransaction(txid);
if (info != null) {
const sequence = parseSequenceFromLogSolana(info);
const emitterAddress = await getEmitterAddressSolana(
SOL_TOKEN_BRIDGE_ADDRESS
);
const vaaURL = `${WORMHOLE_RPC_HOST}/v1/signed_vaa/${CHAIN_ID_SOLANA}/${emitterAddress}/${sequence}`;
// Get the VaaBytes from this api of Wormhole Network
let vaaBytes= await (await fetch(vaaURL)).json();
while (!vaaBytes.vaaBytes) {
// If don't get the VaaBytes yet, must fetch again
await new Promise((r) => setTimeout()r, 5000);
vaaBytes= await (await fetch(vaaURL)).json();
}
// Convert vaaBytes object to Uint8Array
const signedVAA = new Uint8Array(Buffer.from(vaaBytes.vaaBytes, 'base64'));
// Create the wrapped token on Ethereum
await createWrappedOnEth(ETH_TOKEN_BRIDGE_ADDRESS, signer, signedVAA);
// Redeem on Ethereum
await redeemOnEth(ETH_TOKEN_BRIDGE_ADDRESS, signer, signedVAA);
// Confirm that transaction is successfull
let transferCompleted = await getIsTransferCompletedEth(
ETH_TOKEN_BRIDGE_ADDRESS,
provider,
signedVAA,
);
// if true, the transfer transaction is completed
console.log('Completed: ', transferCompleted);
provider.destroy();
};
};
7. Conclusion
In conclusion, Wormhole presents an incredible opportunity to unlock the vast potential of cross-chain interoperability. By acting as a secure bridge between different blockchain ecosystems, Wormhole enables seamless asset transfers, data communication, and collaboration across chains. Its architecture, comprising on-chain and off-chain components, ensures the integrity and validity of messages transmitted between blockchains.
The Wormhole SDK, particularly within the Solana ecosystem, offers developers a powerful toolkit to integrate cross-chain functionality into their projects. With Wormhole, developers can achieve interoperability, enabling asset transfers and data exchange between Solana and other supported blockchains. This opens up a wide range of possibilities, including decentralized exchanges, liquidity pools, and innovative applications that leverage the strengths of multiple networks.
Beyond decentralized finance (DeFi), Wormhole’s potential extends to various sectors such as gaming, NFTs, supply chain, and more. Developers have the opportunity to explore unique use cases and create novel applications that transcend the limitations of individual blockchains. The growth of the Wormhole ecosystem contributes to the expansion of Solana’s reach, attracting developers and projects from diverse blockchain communities.
By delving into the coding aspect, we have provided a comprehensive guide to integrating Wormhole into your project. With code examples and instructions for the Source Chain, Relayer, and Dest Chain, we aim to simplify the process of utilizing Wormhole and harnessing its capabilities.
In summary, Wormhole revolutionizes cross-chain communication, fostering collaboration, innovation, and enhanced functionality across blockchain ecosystems. As blockchain technology continues to evolve, Wormhole paves the way for a more connected and inclusive future of decentralized applications.