With a configured Wormhole object, we have the ability to do things like; parse addresses for the platforms we passed, get a ChainContext object, or fetch VAAs.
// Grab a ChainContext object from our configured Wormhole instanceconstctx=wh.getChain("Solana");
// Get the VAA from the wormhole message idconstvaa=awaitwh.getVaa(// Wormhole Message ID whm!,// Protocol:Payload name to use for decoding the VAA payload"TokenBridge:Transfer",// Timeout in milliseconds, depending on the chain and network, the VAA may take some time to be available60_000, );
Understanding several higher level concepts of the SDK will help in using it effectively.
Platforms
Every chain is its own special snowflake but many of them share similar functionality. The Platform modules provide a consistent interface for interacting with the chains that share a platform.
Each platform can be installed separately so that dependencies can stay as slim as possible.
Chain Context
The Wormhole class provides a getChain method that returns a ChainContext object for a given chain. This object provides access to the chain specific methods and utilities. Much of the functionality in the ChainContext is provided by the Platform methods but the specific chain may have overridden methods.
The ChainContext object is also responsible for holding a cached rpc client and protocol clients.
// Get the chain context for the source and destination chains// This is useful to grab direct clients for the protocolsconstsrcChain=wh.getChain(senderAddress.chain);constdstChain=wh.getChain(receiverAddress.chain);consttb=awaitsrcChain.getTokenBridge(); // => TokenBridge<'Evm'>srcChain.getRpcClient(); // => RpcClient<'Evm'>
Addresses
Within the Wormhole context, addresses are often normalized to 32 bytes and referred to in this SDK as a UniversalAddresses.
Each platform comes with an address type that understands the native address formats, unsurprisingly referred to as NativeAddress. This abstraction allows the SDK to work with addresses in a consistent way regardless of the underlying chain.
// Its possible to convert a string address to its Native addressconstethAddr:NativeAddress<"Evm"> =toNative("Ethereum","0xbeef...");// A common type in the SDK is the `ChainAddress` which provides// the additional context of the `Chain` this address is relevant for.constsenderAddress:ChainAddress=Wormhole.chainAddress("Ethereum","0xbeef...");constreceiverAddress:ChainAddress=Wormhole.chainAddress("Solana","Sol1111...");// Convert the ChainAddress back to its canonical string address formatconststrAddress=Wormhole.canonicalAddress(senderAddress); // => '0xbeef...'// Or if the ethAddr above is for an emitter and you need the UniversalAddressconstemitterAddr=ethAddr.toUniversalAddress().toString()
Tokens
Similar to the ChainAddress type, the TokenId type provides the Chain and Address of a given Token.
// Returns a TokenId constsourceToken:TokenId=Wormhole.tokenId("Ethereum","0xbeef...");// Whereas the ChainAddress is limited to valid addresses, a TokenId may// have the string literal 'native' to consistently denote the native// gas token of the chainconstgasToken:TokenId=Wormhole.tokenId("Ethereum","native");// the same method can be used to convert the TokenId back to its canonical string address formatconststrAddress=Wormhole.canonicalAddress(senderAddress); // => '0xbeef...'
Signers
In order to sign transactions, an object that fulfils the Signer interface is required. This is a simple interface that can be implemented by wrapping a web wallet or other signing mechanism.
// A Signer is an interface that must be provided to certain methods// in the SDK to sign transactions. It can be either a SignOnlySigner// or a SignAndSendSigner depending on circumstances.// A Signer can be implemented by wrapping an existing offline wallet// or a web walletexporttypeSigner=SignOnlySigner|SignAndSendSigner;// A SignOnlySender is for situations where the signer is not// connected to the network or does not wish to broadcast the// transactions themselvesexportinterfaceSignOnlySigner {chain():ChainName;address():string;// Accept an array of unsigned transactions and return// an array of signed and serialized transactions.// The transactions may be inspected or altered before// signing.// Note: The serialization is chain specific, if in doubt,// see the example implementations linked belowsign(tx:UnsignedTransaction[]):Promise<SignedTx[]>;}// A SignAndSendSigner is for situations where the signer is// connected to the network and wishes to broadcast the// transactions themselvesexportinterfaceSignAndSendSigner {chain():ChainName;address():string;// Accept an array of unsigned transactions and return// an array of transaction ids in the same order as the// UnsignedTransactions array.signAndSend(tx:UnsignedTransaction[]):Promise<TxHash[]>;}
See the testing signers (Evm, Solana, ...) for an example of how to implement a signer for a specific chain or platform.
Protocols
While Wormhole itself is a Generic Message Passing protocol, a number of protocols have been built on top of it to provide specific functionality.
Each Protocol, if available, will have a Platform specific implementation. These implementations provide methods to generate transactions or read state from the contract on-chain.
Wormhole Core
The protocol that underlies all Wormhole activity is the Core protocol. This protocol is responsible for emitting the message containing the information necessary to perform bridging including Emitter address, the Sequence number for the message and the Payload of the message itself.
constwh=awaitwormhole("Testnet", [solana]);constchain=wh.getChain("Solana");const { signer,address } =awaitgetSigner(chain);// Get a reference to the core messaging bridgeconstcoreBridge=awaitchain.getWormholeCore();// Generate transactions, sign and send themconstpublishTxs=coreBridge.publishMessage(// Address of sender (emitter in VAA)address.address,// Message to send (payload in VAA)encoding.bytes.encode("lol"),// Nonce (user defined, no requirement for a specific value, useful to provide a unique identifier for the message)0,// ConsistencyLevel (ie finality of the message, see wormhole docs for more)0, );// Send the transaction(s) to publish the messageconsttxids=awaitsignSendWait(chain, publishTxs, signer);// Take the last txid in case multiple were sent// the last one should be the one containing the relevant// event or log infoconsttxid= txids[txids.length-1];// Grab the wormhole message id from the transaction logs or storageconst [whm] =awaitchain.parseTransaction(txid!.txid);// Or pull the full message content as an Unsigned VAA// const msgs = await coreBridge.parseMessages(txid!.txid);// console.log(msgs);// Wait for the vaa to be signed and available with a timeoutconstvaa=awaitwh.getVaa(whm!,"Uint8Array",60_000);console.log(vaa);// Also possible to search by txid but it takes longer to show up// console.log(await wh.getVaaByTxHash(txid!.txid, "Uint8Array"));constverifyTxs=coreBridge.verifyMessage(address.address, vaa!);console.log(awaitsignSendWait(chain, verifyTxs, signer));
Within the payload is the information necessary to perform whatever action is required based on the Protocol that uses it.
Token Bridge
The most familiar protocol built on Wormhole is the Token Bridge.
Every chain has a TokenBridge protocol client that provides a consistent interface for interacting with the Token Bridge. This includes methods to generate the transactions required to transfer tokens, as well as methods to generate and redeem attestations.
Using the WormholeTransfer abstractions is the recommended way to interact with these protocols but it is possible to use them directly
While using the ChainContext and Protocol clients directly is possible, to do things like transfer tokens, the SDK provides some helpful abstractions.
The WormholeTransfer interface provides a convenient abstraction to encapsulate the steps involved in a cross-chain transfer.
Token Transfers
Performing a Token Transfer is trivial for any source and destination chains.
We can create a new Wormhole object and use it to to create TokenTransfer, CircleTransfer, GatewayTransfer, etc. objects to transfer tokens between chains. The transfer object is responsible for tracking the transfer through the process and providing updates on its status.
// Create a TokenTransfer object to track the state of the transfer over timeconstxfer=awaitwh.tokenTransfer(route.token,route.amount,route.source.address,route.destination.address,route.delivery?.automatic ??false,route.payload,route.delivery?.nativeGas, );constquote=awaitTokenTransfer.quoteTransfer( wh,route.source.chain,route.destination.chain,xfer.transfer, );console.log(quote);if (xfer.transfer.automatic &"e.destinationToken.amount <0)throw"The amount requested is too low to cover the fee and any native gas requested.";// 1) Submit the transactions to the source chain, passing a signer to sign any txnsconsole.log("Starting transfer");constsrcTxids=awaitxfer.initiateTransfer(route.source.signer);console.log(`Started transfer: `, srcTxids);// If automatic, we're doneif (route.delivery?.automatic) return xfer;// 2) Wait for the VAA to be signed and ready (not required for auto transfer)console.log("Getting Attestation");constattestIds=awaitxfer.fetchAttestation(60_000);console.log(`Got Attestation: `, attestIds);// 3) Redeem the VAA on the dest chainconsole.log("Completing Transfer");constdestTxids=awaitxfer.completeTransfer(route.destination.signer);console.log(`Completed Transfer: `, destTxids);
Internally, this uses the TokenBridge protocol client to transfer tokens. The TokenBridge protocol, like other Protocols, provides a consistent set of methods across all chains to generate a set of transactions for that specific chain.
Native USDC Transfers
We can also transfer native USDC using Circle's CCTP
constxfer=awaitwh.circleTransfer(// amount as bigint (base units)req.amount,// sender chain/addresssrc.address,// receiver chain/addressdst.address,// automatic delivery booleanreq.automatic,// payload to be sent with the transferundefined,// If automatic, native gas can be requested to be sent to the receiverreq.nativeGas, );// Note, if the transfer is requested to be Automatic, a fee for performing the relay// will be present in the quote. The fee comes out of the amount requested to be sent.// If the user wants to receive 1.0 on the destination, the amount to send should be 1.0 + fee.// The same applies for native gas dropoffconstquote=awaitCircleTransfer.quoteTransfer(src.chain,dst.chain,xfer.transfer);console.log("Quote", quote);console.log("Starting Transfer");constsrcTxids=awaitxfer.initiateTransfer(src.signer);console.log(`Started Transfer: `, srcTxids);if (req.automatic) {constrelayStatus=awaitwaitForRelay(srcTxids[srcTxids.length-1]!);console.log(`Finished relay: `, relayStatus);return; }// Note: Depending on chain finality, this timeout may need to be increased.// See https://developers.circle.com/stablecoin/docs/cctp-technical-reference#mainnet for moreconsole.log("Waiting for Attestation");constattestIds=awaitxfer.fetchAttestation(60_000);console.log(`Got Attestation: `, attestIds);console.log("Completing Transfer");constdstTxids=awaitxfer.completeTransfer(dst.signer);console.log(`Completed Transfer: `, dstTxids);
Gateway transfers are transfers that are passed through the Wormhole Gateway to or from Cosmos chains.
A transfer into Cosmos from outside cosmos will be automatically delivered to the destination via IBC from the Gateway chain (fka Wormchain)
console.log(`Beginning transfer into Cosmos from ${src.chain.chain}:${src.address.address.toString()} to ${dst.chain.chain}:${dst.address.address.toString()}`, );constxfer=awaitGatewayTransfer.from(wh, { token: token, amount: amount, from:src.address, to:dst.address, } asGatewayTransferDetails);console.log("Created GatewayTransfer: ",xfer.transfer);constsrcTxIds=awaitxfer.initiateTransfer(src.signer);console.log("Started transfer on source chain", srcTxIds);constattests=awaitxfer.fetchAttestation(600_000);console.log("Got Attestations", attests);
A transfer within Cosmos will use IBC to transfer from the origin to the Gateway chain, then out from the Gateway to the destination chain
console.log(`Beginning transfer within cosmos from ${src.chain.chain}:${src.address.address.toString()} to ${dst.chain.chain}:${dst.address.address.toString()}`, );constxfer=awaitGatewayTransfer.from(wh, { token: token, amount: amount, from:src.address, to:dst.address, } asGatewayTransferDetails);console.log("Created GatewayTransfer: ",xfer.transfer);constsrcTxIds=awaitxfer.initiateTransfer(src.signer);console.log("Started transfer on source chain", srcTxIds);constattests=awaitxfer.fetchAttestation(60_000);console.log("Got attests: ", attests);
A transfer leaving Cosmos will produce a VAA from the Gateway that must be manually redeemed on the destination chain
console.log(`Beginning transfer out of cosmos from ${src.chain.chain}:${src.address.address.toString()} to ${dst.chain.chain}:${dst.address.address.toString()}`, );constxfer=awaitGatewayTransfer.from(wh, { token: token, amount: amount, from:src.address, to:dst.address, } asGatewayTransferDetails);console.log("Created GatewayTransfer: ",xfer.transfer);constsrcTxIds=awaitxfer.initiateTransfer(src.signer);console.log("Started transfer on source chain", srcTxIds);constattests=awaitxfer.fetchAttestation(600_000);console.log("Got attests", attests);// Since we're leaving cosmos, this is required to complete the transferconstdstTxIds=awaitxfer.completeTransfer(dst.signer);console.log("Completed transfer on destination chain", dstTxIds);
It may be necessary to recover a transfer that was abandoned before being completed. This can be done by instantiating the Transfer class with the from static method and passing one of several types of identifiers.
A TransactionId or WormholeMessageId may be used to recover the transfer
// Rebuild the transfer from the source txidconstxfer=awaitCircleTransfer.from(wh, txid);constattestIds=awaitxfer.fetchAttestation(60*60*1000);console.log("Got attestation: ", attestIds);constdstTxIds=awaitxfer.completeTransfer(signer);console.log("Completed transfer: ", dstTxIds);
While a specific WormholeTransfer may be used (TokenTransfer, CCTPTransfer, ...), it requires the developer know exactly which transfer type to use for a given request.
To provide a more flexible and generic interface, the Wormhole class provides a method to produce a RouteResolver that can be configured with a set of possible routes to be supported.
// create new resolver, passing the set of routes to considerconstresolver=wh.resolver([routes.TokenBridgeRoute,// manual token bridgeroutes.AutomaticTokenBridgeRoute,// automatic token bridgeroutes.CCTPRoute,// manual CCTProutes.AutomaticCCTPRoute,// automatic CCTProutes.AutomaticPorticoRoute,// Native eth transfers ]);
Once created, the resolver can be used to provide a list of input and possible output tokens.
// what tokens are available on the source chain?constsrcTokens=awaitresolver.supportedSourceTokens(sendChain);console.log("Allowed source tokens: ",srcTokens.map((t) =>canonicalAddress(t)), );// Grab the first one for the example// const sendToken = srcTokens[0]!;constsendToken=Wormhole.tokenId(sendChain.chain,"native");// given the send token, what can we possibly get on the destination chain?constdestTokens=awaitresolver.supportedDestinationTokens(sendToken, sendChain, destChain);console.log("For the given source token and routes configured, the following tokens may be receivable: ",destTokens.map((t) =>canonicalAddress(t)), );//grab the first one for the exampleconstdestinationToken= destTokens[0]!;
Once the tokens are selected, a RouteTransferRequest may be created to provide a list of routes that can fulfil the request
// creating a transfer request fetches token details// since all routes will need to know about the tokensconsttr=awaitroutes.RouteTransferRequest.create(wh, { from:sender.address, to:receiver.address, source: sendToken, destination: destinationToken, });// resolve the transfer request to a set of routes that can perform itconstfoundRoutes=awaitresolver.findRoutes(tr);console.log("For the transfer parameters, we found these routes: ", foundRoutes);
Choosing the best route is currently left to the developer but strategies might include sorting by output amount or expected time to complete the transfer (no estimate currently provided).
After choosing the best route, extra parameters like amount, nativeGasDropoff, and slippage can be passed, depending on the specific route selected and a quote can be retrieved with the validated request.
console.log("This route offers the following default options",bestRoute.getDefaultOptions());// Specify the amount as a decimal stringconstamt="0.001";// Create the transfer params for this requestconsttransferParams= { amount: amt, options: { nativeGas:0 } };// validate the transfer params passed, this returns a new type of ValidatedTransferParams// which (believe it or not) is a validated version of the input params// this new var must be passed to the next step, quoteconstvalidated=awaitbestRoute.validate(transferParams);if (!validated.valid) throwvalidated.error;console.log("Validated parameters: ",validated.params);// get a quote for the transfer, this too returns a new type that must// be passed to the next step, execute (if you like the quote)constquote=awaitbestRoute.quote(validated.params);if (!quote.success) throwquote.error;console.log("Best route quote: ", quote);
Finally, assuming the quote looks good, the route can initiate the request with the quote and the signer
// Now the transfer may be initiated// A receipt will be returned, guess what you gotta do with that?constreceipt=awaitbestRoute.initiate(sender.signer, quote);console.log("Initiated transfer with receipt: ", receipt);