Skip to content

Adds Transfer Wrapped Assets guide to Token Bridge section #461

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 6 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 5 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
import {
Chain,
ChainAddress,
ChainContext,
isTokenId,
Wormhole,
Network,
Signer,
TokenId,
} from '@wormhole-foundation/sdk';
import type { SignAndSendSigner } from '@wormhole-foundation/sdk';
import evm from '@wormhole-foundation/sdk/evm';
import solana from '@wormhole-foundation/sdk/solana';
import sui from '@wormhole-foundation/sdk/sui';

/**
* Returns a signer for the given chain using locally scoped credentials.
* The required values (EVM_PRIVATE_KEY, SOL_PRIVATE_KEY, SUI_MNEMONIC) must
* be loaded securely beforehand, for example via a keystore, secrets
* manager, or environment variables (not recommended).
*/
export async function getSigner<N extends Network, C extends Chain>(
chain: ChainContext<N, C>
): Promise<{
chain: ChainContext<N, C>;
signer: SignAndSendSigner<N, C>;
address: ChainAddress<C>;
}> {
let signer: Signer<any, any>;
const platform = chain.platform.utils()._platform;

// Customize the signer by adding or removing platforms as needed
// Be sure to import the necessary packages for the platforms you want to support
switch (platform) {
case 'Evm':
signer = await (
await evm()
).getSigner(await chain.getRpc(), EVM_PRIVATE_KEY!);
break;
case 'Solana':
signer = await (
await solana()
).getSigner(await chain.getRpc(), SOL_PRIVATE_KEY!);
break;
case 'Sui':
signer = await (
await sui()
).getSigner(await chain.getRpc(), SUI_MNEMONIC!);
break;
default:
throw new Error(`Unsupported platform: ${platform}`);
}

const typedSigner = signer as SignAndSendSigner<N, C>;

return {
chain,
signer: typedSigner,
address: Wormhole.chainAddress(chain.chain, signer.address()),
};
}

/**
* Get the number of decimals for the token on the source chain.
* This helps convert a user-friendly amount (e.g., '1') into raw units.
*/
export async function getTokenDecimals<N extends Network>(
wh: Wormhole<N>,
token: TokenId,
chain: ChainContext<N, any>
): Promise<number> {
return isTokenId(token)
? Number(await wh.getDecimals(token.chain, token.address))
: chain.config.nativeTokenDecimals;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
<div id="termynal" data-termynal>
<span data-ty="input"><span class="file-path"></span>npx tsx transfer.ts</span>
<span data-ty>⚠️ Token is NOT registered on destination. Running attestation flow...</span>
<span data-ty="input"><span class="file-path"></span></span>
</div>
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
<div id="termynal" data-termynal>
<span data-ty="input"><span class="file-path"></span>npx tsx transfer.ts</span>
<span data-ty>⚠️ Token is NOT registered on destination. Running attestation flow...</span>
<span data-ty>βœ… Attestation transaction sent: [
{
chain: 'Moonbeam',
txid: '0x2b9878e6d8e92d8ecc96d663904312c18a827ccf0b02380074fdbc0fba7e6b68'
}
]</span>
<span data-ty>βœ… Attestation messages: [
{
chain: 'Moonbeam',
emitter: UniversalAddress { address: [Uint8Array] },
sequence: 1505n
}
]
</span>
<span data-ty>Retrying Wormholescan:GetVaaBytes, attempt 0/750</span>
<span data-ty>Retrying Wormholescan:GetVaaBytes, attempt 1/750</span>
<span data-ty>....</span>
<span data-ty>Retrying Wormholescan:GetVaaBytes, attempt 10/750</span>
<span data-ty>βœ… Attestation submitted on destination: [
{
chain: 'Solana',
txid: '3R4oF5P85jK3wKgkRs5jmE8BBLoM4wo2hWSgXXL6kA8efbj2Vj9vfuFSb53xALqYZuv3FnXDwJNuJfiKKDwpDH1r'
}
]</span>
<span data-ty>βœ… Wrapped token is now available on Solana: SolanaAddress {
type: 'Native',
address: PublicKey [PublicKey(2qjSAGrpT2eTb673KuGAR5s6AJfQ1X5Sg177Qzuqt7yB)] {
_bn: <BN: 1b578bb9b7a04a1aab3b5b64b550d8fc4f73ab343c9cf8532d2976b77ec4a8ca>
}
}</span>
<span data-ty>πŸš€ Token attestation complete! Proceeding with transfer...</span>
<span data-ty="input"><span class="file-path"></span></span>
</div>
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
<div id="termynal" data-termynal>
<span data-ty="input"><span class="file-path"></span>npx tsx transfer.ts</span>
<span data-ty>βœ… Token already registered on destination: SolanaAddress {
type: 'Native',
address: PublicKey [PublicKey(2qjSAGrpT2eTb673KuGAR5s6AJfQ1X5Sg177Qzuqt7yB)] {
_bn: <BN: 1b578bb9b7a04a1aab3b5b64b550d8fc4f73ab343c9cf8532d2976b77ec4a8ca>
}
}</span>
<span data-ty>πŸš€ Built transfer object: {
token: {
chain: 'Moonbeam',
address: EvmAddress {
type: 'Native',
address: '0x39F2f26f247CcC223393396755bfde5ecaeb0648'
}
},
amount: 200000000000000000n,
from: {
chain: 'Moonbeam',
address: EvmAddress {
type: 'Native',
address: '0xCD8Bcd9A793a7381b3C66C763c3f463f70De4e12'
}
},
to: {
chain: 'Solana',
address: SolanaAddress {
type: 'Native',
address: [PublicKey [PublicKey(21dmEFTFGBEVoUNjmrxumN6A2xFxNBQXTkK7AmMqNmqD)]]
}
},
automatic: false,
payload: undefined,
nativeGas: 0n
}</span>
<span data-ty>πŸ”— Source chain tx sent: [
'0xf318a1098a81063ac8acc9ca117eeb41ae9abfd9cb550a976721d2fa978f313a'
]</span>
<span data-ty>⏳ Waiting for attestation (VAA) for manual transfer...</span>
<span data-ty>Retrying Wormholescan:GetVaaBytes, attempt 0/30</span>
<span data-ty>Retrying Wormholescan:GetVaaBytes, attempt 1/30</span>
<span data-ty>.....</span>
<span data-ty>Retrying Wormholescan:GetVaaBytes, attempt 15/30</span>
<span data-ty>βœ… Got attestation ID(s): [
{
chain: 'Moonbeam',
emitter: UniversalAddress { address: [Uint8Array] },
sequence: 1506n
}
]</span>
<span data-ty>β†ͺ️ Redeeming transfer on destination...</span>
<span data-ty>πŸŽ‰ Destination tx(s) submitted: [
'23NRfFZyKJTDLppJF4GovdegxYAuW2HeXTEFSKKNeA7V82aqTVYTkKeM8sCHCDWe7gWooLAPHARjbAheXoxbbwPk'
]</span>
<span data-ty="input"><span class="file-path"></span></span>
</div>
Original file line number Diff line number Diff line change
@@ -0,0 +1,174 @@
import {
wormhole,
Wormhole,
TokenId,
TokenAddress,
} from '@wormhole-foundation/sdk';
import evm from '@wormhole-foundation/sdk/evm';
import solana from '@wormhole-foundation/sdk/solana';
import { signSendWait, toNative } from '@wormhole-foundation/sdk-connect';
import { getSigner, getTokenDecimals } from './helpers';

async function transferTokens() {
// Initialize wh instance
const wh = await wormhole('Testnet', [evm, solana]);
// Define sourceChain and destinationChain, get chain contexts
const sourceChain = wh.getChain('Moonbeam');
const destinationChain = wh.getChain('Solana');
// Load signers for both chains
const sourceSigner = await getSigner(sourceChain);
const destinationSigner = await getSigner(destinationChain);

// Define token and amount to transfer
const tokenId: TokenId = Wormhole.tokenId(
sourceChain.chain,
'INSERT_TOKEN_CONTRACT_ADDRESS'
);
// Replace with amount you want to transfer
// This is a human-readable number, e.g., 0.2 for 0.2 tokens
const amount = 0;
// Convert to raw units based on token decimals
const decimals = await getTokenDecimals(wh, tokenId, sourceChain);
const transferAmount = BigInt(Math.floor(amount * 10 ** decimals));

// Check if the token is registered with destinationChain token bridge contract
// Registered = returns the wrapped token ID, continues with transfer
// Not registered = runs the attestation flow to register the token
let wrappedToken: TokenId;
try {
wrappedToken = await wh.getWrappedAsset(destinationChain.chain, tokenId);
console.log(
'βœ… Token already registered on destination:',
wrappedToken.address
);
} catch (e) {
console.log(
'⚠️ Token is NOT registered on destination. Running attestation flow...'
);
// Retrieve the token bridge context for the source chain
// This is where you will send the transaction to attest the token
const tb = await sourceChain.getTokenBridge();
// Define the token to attest and a payer address
const token: TokenAddress<typeof sourceChain.chain> = toNative(
sourceChain.chain,
tokenId.address.toString()
);
const payer = toNative(sourceChain.chain, sourceSigner.signer.address());
// Call the `createAttestation` method to create a new attestation
// and sign and send the transaction
for await (const tx of tb.createAttestation(token, payer)) {
const txids = await signSendWait(
sourceChain,
tb.createAttestation(token),
sourceSigner.signer
);
console.log('βœ… Attestation transaction sent:', txids);
// Parse the transaction to get Wormhole message ID
const messages = await sourceChain.parseTransaction(txids[0].txid);
console.log('βœ… Attestation messages:', messages);
// Set a timeout for fetching the VAA, this can take several minutes
// depending on the source chain network and finality
const timeout = 25 * 60 * 1000;
// Fetch the VAA for the attestation message
const vaa = await wh.getVaa(
messages[0]!,
'TokenBridge:AttestMeta',
timeout
);
if (!vaa) throw new Error('❌ VAA not found before timeout.');
// Get the token bridge context for the destination chain
// and submit the attestation VAA
const destTb = await destinationChain.getTokenBridge();
const payer = toNative(
destinationChain.chain,
destinationSigner.signer.address()
);
const destTxids = await signSendWait(
destinationChain,
destTb.submitAttestation(vaa, payer),
destinationSigner.signer
);
console.log('βœ… Attestation submitted on destination:', destTxids);
}
// Poll for the wrapped token to appear on the destination chain
// before proceeding with the transfer
const maxAttempts = 50; // ~5 minutes with 6s interval
const interval = 6000;
let attempt = 0;
let registered = false;

while (attempt < maxAttempts && !registered) {
attempt++;
try {
const wrapped = await wh.getWrappedAsset(
destinationChain.chain,
tokenId
);
console.log(
`βœ… Wrapped token is now available on ${destinationChain.chain}:`,
wrapped.address
);
registered = true;
} catch {
console.log(
`⏳ Waiting for wrapped token to register on ${destinationChain.chain}...`
);
await new Promise((res) => setTimeout(res, interval));
}
}

if (!registered) {
throw new Error(
`❌ Token attestation did not complete in time on ${destinationChain.chain}`
);
}

console.log('πŸš€ Token attestation complete! Proceeding with transfer...');
}

// Define whether the transfer is automatic or manual
const automatic = false;
// Optional native gas amount for automatic transfers only
const nativeGasAmount = '0.001'; // 0.001 of native gas in human-readable format
// Get the decimals for the source chain
const nativeGasDecimals = destinationChain.config.nativeTokenDecimals;
// If automatic, convert to raw units, otherwise set to 0n
const nativeGas = automatic
? BigInt(Number(nativeGasAmount) * 10 ** nativeGasDecimals)
: 0n;
// Build the token transfer object
const xfer = await wh.tokenTransfer(
tokenId,
transferAmount,
sourceSigner.address,
destinationSigner.address,
automatic,
undefined, // no payload
nativeGas
);
console.log('πŸš€ Built transfer object:', xfer.transfer);

// Initiate, sign, and send the token transfer
const srcTxs = await xfer.initiateTransfer(sourceSigner.signer);
console.log('πŸ”— Source chain tx sent:', srcTxs);

// If automatic, no further action is required. The relayer completes the transfer.
if (automatic) {
console.log('βœ… Automatic transfer: relayer is handling redemption.');
return;
}
// For manual transfers, wait for VAA
console.log('⏳ Waiting for attestation (VAA) for manual transfer...');
const attIds = await xfer.fetchAttestation(120_000); // 2 minutes timeout
console.log('βœ… Got attestation ID(s):', attIds);

// Complete the manual transfer on the destination chain
console.log('β†ͺ️ Redeeming transfer on destination...');
const destTxs = await xfer.completeTransfer(destinationSigner.signer);
console.log('πŸŽ‰ Destination tx(s) submitted:', destTxs);
}

transferTokens().catch((e) => {
console.error('❌ Error in transferTokens', e);
process.exit(1);
});
Loading