-
Notifications
You must be signed in to change notification settings - Fork 26
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
dawnkelly09
wants to merge
6
commits into
main
Choose a base branch
from
dawn/manual-token-bridge-evm
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from 5 commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
9375cd4
adds "transfer wrapped assets" guide, snippets, and updated llm files
dawnkelly09 88d8938
refactored code, updated guide to match
dawnkelly09 2af44b9
update terminal output, llms
dawnkelly09 6f1e062
minor tweaks, llms
dawnkelly09 2d0cd2f
Merge branch 'main' into dawn/manual-token-bridge-evm
dawnkelly09 88a8344
adds link, updates url, llms
dawnkelly09 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
75 changes: 75 additions & 0 deletions
75
.snippets/code/products/token-bridge/guides/transfer-wrapped-assets/helpers.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | ||
} |
5 changes: 5 additions & 0 deletions
5
.snippets/code/products/token-bridge/guides/transfer-wrapped-assets/terminal01.html
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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> |
36 changes: 36 additions & 0 deletions
36
.snippets/code/products/token-bridge/guides/transfer-wrapped-assets/terminal02.html
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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> |
56 changes: 56 additions & 0 deletions
56
.snippets/code/products/token-bridge/guides/transfer-wrapped-assets/terminal03.html
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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> |
174 changes: 174 additions & 0 deletions
174
.snippets/code/products/token-bridge/guides/transfer-wrapped-assets/transfer01.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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), | ||
dawnkelly09 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
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); | ||
}); |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.