How to bridge to and from Solana
This guide shows you how to bridge USDC to and from Solana with Fast Bridge. The steps bridge from Solana to an EVM chain, and Bridge to Solana covers the other direction.
Prerequisites
- A Pimlico API key with Fast Bridge enabled.
- A Solana account holding USDC.
Steps
Set up a bridge client
Create the account, a Solana RPC client and the functions that call the Fast Bridge API: one to get the bridge's Solana addresses, and one to bridge the tokens.
import {
address,
appendTransactionMessageInstructions,
createKeyPairSignerFromBytes,
createNoopSigner,
createSolanaRpc,
createTransactionMessage,
getBase64EncodedWireTransaction,
partiallySignTransactionMessageWithSigners,
pipe,
setTransactionMessageFeePayerSigner,
setTransactionMessageLifetimeUsingBlockhash,
} from "@solana/kit"
import {
findAssociatedTokenPda,
getTransferCheckedInstruction,
TOKEN_PROGRAM_ADDRESS,
} from "@solana-program/token"
import type {
BridgeRequest,
BridgeStatus,
Eip3009Authorization,
SolanaBridgeAddresses,
} from "./types"
const apiKey = "YOUR_PIMLICO_API_KEY"
const SOLANA_CHAIN_ID = 101
const BASE_CHAIN_ID = 8453
const USDC_SOLANA = address("EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v")
const USDC_BASE = "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913"
// The account that holds the USDC on Solana
const user = await createKeyPairSignerFromBytes(
new Uint8Array(JSON.parse(process.env.USER_SECRET_KEY as string)),
)
const rpc = createSolanaRpc("https://api.mainnet-beta.solana.com")
// Throws the bridge's { code, message } if it rejected the request
const readResponse = async (response: Response) => {
const body = await response.json()
if (!response.ok) {
throw new Error(`${body.code}: ${body.message}`)
}
return body
}
// The fee payer and reserve token accounts a Solana transaction is built with
const getSolanaBridgeAddresses = async (): Promise<SolanaBridgeAddresses> => {
const response = await fetch(
`https://api.pimlico.io/v1/bridge/addresses/solana?apikey=${apiKey}`,
)
return readResponse(response)
}
// Bridges the tokens to the recipient and waits for the outcome
const bridgeTokens = async (request: BridgeRequest): Promise<BridgeStatus> => {
const response = await fetch(
`https://api.pimlico.io/v1/bridge/execute/sync?apikey=${apiKey}`,
{
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(request),
},
)
return readResponse(response)
}type Hex = `0x${string}`
export type SolanaBridgeAddresses = {
feePayer: string
executor: string
reserveTokenAccounts: { token: string; address: string }[]
}
export type SolanaAuthorization = {
type: "solana-transaction"
// The signed transaction, base64 encoded
transaction: string
}
export type Eip3009Authorization = {
type: "eip3009"
token: Hex
from: Hex
to: Hex
amount: string
validAfter: number
validBefore: number
nonce: Hex
signature: Hex
}
export type BridgeRequest = {
originChainId: number
destinationChainId: number
originToken: string
destinationToken: string
authorization: SolanaAuthorization | Eip3009Authorization
// Required when either chain is Solana
recipient: string
}
export type BridgeStatus = {
requestId: string
status: "pending" | "success" | "failed" | "refunded"
amountIn: string
fee: string
amountOut: string
origin: { chainId: number; status: string; transactionHash?: string }
destination: {
chainId: number
recipient: string
status: string
transactionHash?: string
error?: { code: string; message: string }
}
}Sign the transfer
Build a transaction that makes one transfer of the USDC into the bridge's reserve token account, with the bridge's feePayer as its fee payer, and sign it. Leave the fee payer's signature empty.
const { feePayer, reserveTokenAccounts } = await getSolanaBridgeAddresses()
const reserve = reserveTokenAccounts.find(
(account) => account.token === USDC_SOLANA,
)
if (!reserve) {
throw new Error("The bridge has no reserve token account for USDC")
}
const amount = 25_000_000n // 25 USDC
const [source] = await findAssociatedTokenPda({
owner: user.address,
mint: USDC_SOLANA,
tokenProgram: TOKEN_PROGRAM_ADDRESS,
})
const { value: latestBlockhash } = await rpc.getLatestBlockhash().send()
const message = pipe(
createTransactionMessage({ version: 0 }),
// The bridge pays the fee. It signs later, so a noop signer leaves its signature empty
(m) =>
setTransactionMessageFeePayerSigner(createNoopSigner(address(feePayer)), m),
(m) => setTransactionMessageLifetimeUsingBlockhash(latestBlockhash, m),
// One transfer of the USDC into the bridge's reserve
(m) =>
appendTransactionMessageInstructions(
[
getTransferCheckedInstruction({
source,
mint: USDC_SOLANA,
destination: address(reserve.address),
authority: user,
amount,
decimals: 6,
}),
],
m,
),
)
// The user signs as the transfer's authority
const transaction = getBase64EncodedWireTransaction(
await partiallySignTransactionMessageWithSigners(message),
)Send the request
Send the signed transaction as a solana-transaction authorization, with the origin and destination chains, the tokens and an EVM recipient. Send it within about a minute, before the transaction's blockhash expires. bridgeTokens returns once the bridge has finished, and throws if the request is rejected. See the error codes.
const result = await bridgeTokens({
originChainId: SOLANA_CHAIN_ID,
destinationChainId: BASE_CHAIN_ID,
originToken: USDC_SOLANA,
destinationToken: USDC_BASE,
authorization: { type: "solana-transaction", transaction },
// The EVM address that receives the USDC
recipient: "YOUR_EVM_ADDRESS",
})Check the result
Read status from the response:
success: the USDC was delivered indestination.transactionHash.failed: nothing was bridged, and the USDC is still on Solana.pending: the bridge hasn't finished. See How to check a bridge's status.
if (result.status === "success") {
console.log("Delivered:", result.destination.transactionHash)
} else if (result.status === "failed") {
console.log("Nothing was bridged")
} else {
console.log("Still pending")
}Bridge to Solana
To bridge from an EVM chain to Solana, sign the authorization as in How to bridge to a recipient. Then set destinationChainId to 101, destinationToken to the USDC mint and recipient to a Solana address.
const toSolana = await bridgeTokens({
originChainId: BASE_CHAIN_ID,
destinationChainId: SOLANA_CHAIN_ID,
originToken: USDC_BASE,
destinationToken: USDC_SOLANA,
authorization,
// The Solana account that receives the USDC
recipient: user.address,
})