fba2c4"; // Standard address for estimation
const gasLimit = await estimateGasLimit(
solanaChain,
solanaSenderAddress, // Solana sender address (required)
receiverAddress, // Receiver address
encodedData,
[
{
token: "4zMMC9srt5Ri5X14GAgXhaHii3GnPAEERYPJgZJDncDU", // Solana USDC mint
amount: BigInt("12345"),
},
],
"16015286601757825753" // Ethereum Sepolia chain selector
);
console.log(`Estimated gas limit: ${gasLimit.toString()}`);
// Typical result: ~604000-660000 for messages with token transfers
```
{% endcode %}
#### Always Estimate Gas
> **Critical:** Always use `estimateReceiveExecution` to estimate gas limits. Never hardcode gas values as they vary based on message data, token amounts, and receiver contract complexity.
Gas estimation may fail in rare cases (network issues, contract not deployed, etc.). If estimation fails:
1. **Retry the estimation** - Most failures are transient network issues
2. **Check receiver contract** - Ensure the receiver contract is deployed and accessible
3. **Verify parameters** - Ensure sender, receiver, and data are correctly formatted
4. **Use minimum safety value** - Only as a last resort, use a minimum value that ensures the transaction won't fail
{% code expandable="true" %}
```typescript
// Always estimate first
let gasLimit: bigint;
try {
// SDK estimation is the preferred and most accurate method
const gasEstimate = await estimateReceiveExecution({
source: solanaChain,
dest: destEvmChain,
routerOrRamp: routerProgramId,
message: {
sender: senderAddress,
receiver: receiverAddress,
data: encodedData,
tokenAmounts: tokenAmounts.length > 0 ? tokenAmounts : undefined,
},
});
gasLimit = BigInt(gasEstimate);
console.log(`SDK gas estimate: ${gasLimit}`);
} catch (error) {
console.error("Gas estimation failed:", error);
// Fallback should only be used as a last resort
// Always investigate why estimation failed and prefer retrying
const FALLBACK_GAS_LIMIT = 700000n;
gasLimit = FALLBACK_GAS_LIMIT;
console.warn(`Using fallback gas limit: ${gasLimit} - investigate estimation failure`);
}
```
{% endcode %}
**Important Notes:**
* **SDK gas estimation is strongly preferred** - it calculates the exact gas needed for your specific message
* Fallback values are emergency-only and may be too high or too low
* If estimation consistently fails, there may be an issue with your setup
* The fallback 700,000 gas is a conservative safety value, not a recommended value
* Always investigate why estimation failed before using fallback values
### 6. Fee Estimation <a href="#fee-estimation" id="fee-estimation"></a>
Fee estimation calculates the CCIP fee required to send the message across chains.
{% code expandable="true" %}
```typescript
import { SolanaChain } from "@chainlink/ccip-sdk";
async function estimateCCIPFee(
solanaChain: SolanaChain,
routerProgramId: string,
destinationChainSelector: string,
receiverBytes32: string, // bytes32-padded receiver address
encodedData: string,
gasLimit: bigint,
allowOutOfOrder: boolean,
tokenAmounts: Array<{ token: string; amount: bigint }>
): Promise<bigint> {
const message = {
receiver: receiverBytes32, // Use bytes32 format for actual message
data: encodedData,
extraArgs: {
gasLimit: gasLimit,
allowOutOfOrderExecution: allowOutOfOrder,
},
tokenAmounts: tokenAmounts.length > 0 ? tokenAmounts : undefined,
};
const fee = await solanaChain.getFee({
router: routerProgramId,
destChainSelector: BigInt(destinationChainSelector),
message,
});
return fee; // Fee in lamports (1 SOL = 1e9 lamports)
}
// Example usage
const fee = await estimateCCIPFee(
solanaChain,
"Ccip842gzYHhvdDkSyi2YVCoAWPbYJoApMFzSxQroE9C", // Router program ID
"16015286601757825753", // Ethereum Sepolia
receiverBytes32, // bytes32 format
encodedData,
660935n, // Gas limit
true, // Allow out of order
[
{
token: "4zMMC9srt5Ri5X14GAgXhaHii3GnPAEERYPJgZJDncDU",
amount: BigInt("12345"),
},
]
);
console.log(`Estimated fee: ${Number(fee) / 1e9} SOL`);
```
{% endcode %}
### 7. Executing the Transaction <a href="#executing-the-transaction" id="executing-the-transaction"></a>
#### Step 1: Generate Unsigned Transaction
{% code expandable="true" %}
```typescript
import { TransactionMessage, VersionedTransaction } from "@solana/web3.js";
async function generateTransaction(
solanaChain: SolanaChain,
publicKey: PublicKey,
routerProgramId: string,
destinationChainSelector: string,
receiverBytes32: string,
encodedData: string,
gasLimit: bigint,
allowOutOfOrder: boolean,
fee: bigint,
tokenAmounts: Array<{ token: string; amount: bigint }>
) {
const message = {
receiver: receiverBytes32,
data: encodedData,
extraArgs: {
gasLimit: gasLimit,
allowOutOfOrderExecution: allowOutOfOrder,
},
fee: fee,
tokenAmounts: tokenAmounts.length > 0 ? tokenAmounts : undefined,
};
const unsignedTx = await solanaChain.generateUnsignedSendMessage({
sender: publicKey.toBase58(),
router: routerProgramId,
destChainSelector: BigInt(destinationChainSelector),
message,
});
return unsignedTx;
}
```
{% endcode %}
#### Step 2: Convert to Solana Transaction
{% code expandable="true" %}
```typescript
async function convertToSolanaTransaction(
connection: Connection,
publicKey: PublicKey,
unsignedTx: any
): Promise<VersionedTransaction> {
const { instructions, lookupTables } = unsignedTx as {
family: string;
instructions: any[];
lookupTables: any[];
mainIndex: number;
};
// Get recent blockhash
const { blockhash, lastValidBlockHeight } = await connection.getLatestBlockhash("confirmed");
// Build TransactionMessage
const transactionMessage = new TransactionMessage({
payerKey: publicKey,
recentBlockhash: blockhash,
instructions: instructions,
});
// Compile to V0 message with lookup tables (if available)
const messageV0 = lookupTables && lookupTables.length > 0
? transactionMessage.compileToV0Message(lookupTables)
: transactionMessage.compileToV0Message();
// Create VersionedTransaction
return new VersionedTransaction(messageV0);
}
```
{% endcode %}
#### Step 3: Sign and Send
{% code expandable="true" %}
```typescript
async function signAndSendTransaction(
connection: Connection,
versionedTx: VersionedTransaction,
signTransaction: (tx: VersionedTransaction) => Promise<VersionedTransaction>
): Promise<{ signature: string; messageId: string | null }> {
// Sign transaction
const signedTx = await signTransaction(versionedTx);
// Send transaction
const signature = await connection.sendTransaction(signedTx, {
skipPreflight: false,
maxRetries: 3,
});
// Get blockhash for confirmation
const { blockhash, lastValidBlockHeight } = await connection.getLatestBlockhash("confirmed");
// Confirm transaction
await connection.confirmTransaction({
signature,
blockhash,
lastValidBlockHeight,
}, "confirmed");
// Extract message ID from transaction logs
await new Promise(resolve => setTimeout(resolve, 2000)); // Wait for processing
const tx = await connection.getTransaction(signature, {
maxSupportedTransactionVersion: 0,
commitment: "confirmed",
});
let messageId: string | null = null;
if (tx && tx.meta?.logMessages) {
const logs = tx.meta.logMessages;
const routerProgramId = "Ccip842gzYHhvdDkSyi2YVCoAWPbYJoApMFzSxQroE9C";
for (const log of logs) {
if (log.startsWith("Program return:") && log.includes(routerProgramId)) {
const parts = log.split(" ");
if (parts.length >= 4) {
const base64Data = parts[3];
const returnBuffer = Buffer.from(base64Data, "base64");
if (returnBuffer.length === 32) {
messageId = `0x${returnBuffer.toString("hex")}`;
} else if (returnBuffer.length >= 40) {
const messageIdBytes = returnBuffer.subarray(8, 40);
messageId = `0x${messageIdBytes.toString("hex")}`;
}
break;
}
}
}
}
return { signature, messageId };
}
```
{% endcode %}
## Complete Code Example <a href="#complete-code-example" id="complete-code-example"></a>
Here's a complete example integrating all the steps:
{% code expandable="true" %}
```typescript
import { SolanaChain } from "@chainlink/ccip-sdk";
import { EVMChain, estimateReceiveExecution } from "@chainlink/ccip-sdk";
import { fromViemClient } from "@chainlink/ccip-sdk/viem";
import { Connection, PublicKey, TransactionMessage, VersionedTransaction } from "@solana/web3.js";
import { createPublicClient, http, encodeAbiParameters, parseAbiParameters } from "viem";
import { zeroPadValue } from "ethers";
import { useWallet, useConnection } from "@solana/wallet-adapter-react";
// Configuration
const MAPLE_CONFIG = {
// Testnet addresses
receiverAddress: "0x02b6a75c5d1f430f0614dc5ac8ad5f9d35fba2c4",
poolAddress: "0x3EB612858EE843eBb14Df37b9Ec2c7c82B23eE2B",
destinationChainSelector: "16015286601757825753", // Ethereum Sepolia
// Solana Devnet
solanaRpcUrl: "https://api.devnet.solana.com",
routerProgramId: "Ccip842gzYHhvdDkSyi2YVCoAWPbYJoApMFzSxQroE9C",
sourceChainSelector: "16423721717087811551", // Solana Devnet
// Token addresses
solanaUSDC: "4zMMC9srt5Ri5X14GAgXhaHii3GnPAEERYPJgZJDncDU",
// Ethereum Sepolia
ethereumSepoliaRpcUrl: "https://rpc.sepolia.org",
};
// Helper functions
function solanaToBytes32(solanaAddress: string): string {
const publicKey = new PublicKey(solanaAddress);
const hex = "0x" + publicKey.toBuffer().toString("hex");
return zeroPadValue(hex, 32);
}
function evmToBytes32(address: string): string {
if (!address.startsWith("0x")) address = `0x${address}`;
if (address.length === 42) return zeroPadValue(address, 32);
return address;
}
function encodeUniversalMessage(
universalSenderAddress: string, // bytes32 hex string
poolAddress: string, // EVM address
metaData: string = "0x0000000000000000000000000000000000000000000000000000000000000000"
): `0x${string}` {
return encodeAbiParameters(
parseAbiParameters("bytes32, address, bytes32"),
[
universalSenderAddress as `0x${string}`,
poolAddress as `0x${string}`,
metaData as `0x${string}`
]
);
}
// Main function
async function sendMapleCCIPMessage(
solanaAddress: string,
tokenAmount: bigint,
signTransaction: (tx: VersionedTransaction) => Promise<VersionedTransaction>,
connection: Connection
): Promise<{ signature: string; messageId: string | null }> {
// 1. Initialize Solana Chain
const solanaChain = await SolanaChain.fromUrl(MAPLE_CONFIG.solanaRpcUrl);
// 2. Convert Solana address to bytes32
const universalSenderAddress = solanaToBytes32(solanaAddress);
// 3. Encode UniversalMessage struct
const encodedData = encodeUniversalMessage(
universalSenderAddress,
MAPLE_CONFIG.poolAddress
);
// 4. Convert receiver address to bytes32
const receiverBytes32 = evmToBytes32(MAPLE_CONFIG.receiverAddress);
// 5. Estimate gas limit
const destClient = createPublicClient({
chain: {
id: 11155111,
name: "Ethereum Sepolia",
nativeCurrency: { name: "Sepolia ETH", symbol: "ETH", decimals: 18 },
rpcUrls: { default: { http: [MAPLE_CONFIG.ethereumSepoliaRpcUrl] } },
blockExplorers: { default: { name: "Etherscan", url: "https://sepolia.etherscan.io" } },
},
transport: http(MAPLE_CONFIG.ethereumSepoliaRpcUrl),
});
const destEvmChain = await fromViemClient(destClient);
// Always estimate gas - never hardcode values
let gasLimit: bigint;
try {
const gasEstimate = await estimateReceiveExecution({
source: solanaChain,
dest: destEvmChain,
routerOrRamp: MAPLE_CONFIG.routerProgramId,
message: {
sender: solanaAddress, // Solana sender address (required for accurate estimation)
receiver: MAPLE_CONFIG.receiverAddress, // Standard address for estimation
data: encodedData,
tokenAmounts: [
{
token: MAPLE_CONFIG.solanaUSDC,
amount: tokenAmount,
},
],
},
});
gasLimit = BigInt(gasEstimate);
console.log(`SDK gas estimate: ${gasLimit} - using SDK-provided value`);
} catch (error) {
// Gas estimation failed - this should be rare
// SDK estimation is preferred; fallback is for emergency only
console.error("Gas estimation failed:", error);
console.warn("SDK gas estimation is preferred. Investigate why estimation failed.");
// Only use fallback as last resort - this is an emergency case
// In production, you should retry estimation or handle the error appropriately
const FALLBACK_GAS_LIMIT = 700000n;
gasLimit = FALLBACK_GAS_LIMIT;
console.warn(`Using fallback gas limit: ${gasLimit} (investigate estimation failure)`);
}
console.log(`Gas limit: ${gasLimit.toString()}`);
// 6. Estimate fee
const fee = await solanaChain.getFee({
router: MAPLE_CONFIG.routerProgramId,
destChainSelector: BigInt(MAPLE_CONFIG.destinationChainSelector),
message: {
receiver: receiverBytes32,
data: encodedData,
extraArgs: {
gasLimit: gasLimit,
allowOutOfOrderExecution: true,
},
tokenAmounts: [
{
token: MAPLE_CONFIG.solanaUSDC,
amount: tokenAmount,
},
],
},
});
console.log(`Fee: ${Number(fee) / 1e9} SOL`);
// 7. Generate unsigned transaction
const unsignedTx = await solanaChain.generateUnsignedSendMessage({
sender: solanaAddress,
router: MAPLE_CONFIG.routerProgramId,
destChainSelector: BigInt(MAPLE_CONFIG.destinationChainSelector),
message: {
receiver: receiverBytes32,
data: encodedData,
extraArgs: {
gasLimit: gasLimit,
allowOutOfOrderExecution: true,
},
fee: fee,
tokenAmounts: [
{
token: MAPLE_CONFIG.solanaUSDC,
amount: tokenAmount,
},
],
},
});
// 8. Convert to Solana transaction
const { instructions, lookupTables } = unsignedTx as {
family: string;
instructions: any[];
lookupTables: any[];
mainIndex: number;
};
const { blockhash, lastValidBlockHeight } = await connection.getLatestBlockhash("confirmed");
const messageV0 = lookupTables && lookupTables.length > 0
? new TransactionMessage({
payerKey: new PublicKey(solanaAddress),
recentBlockhash: blockhash,
instructions: instructions,
}).compileToV0Message(lookupTables)
: new TransactionMessage({
payerKey: new PublicKey(solanaAddress),
recentBlockhash: blockhash,
instructions: instructions,
}).compileToV0Message();
const versionedTx = new VersionedTransaction(messageV0);
// 9. Sign and send
const signedTx = await signTransaction(versionedTx);
const signature = await connection.sendTransaction(signedTx, {
skipPreflight: false,
maxRetries: 3,
});
await connection.confirmTransaction({
signature,
blockhash,
lastValidBlockHeight,
}, "confirmed");
// 10. Extract message ID
await new Promise(resolve => setTimeout(resolve, 2000));
const tx = await connection.getTransaction(signature, {
maxSupportedTransactionVersion: 0,
commitment: "confirmed",
});
let messageId: string | null = null;
if (tx && tx.meta?.logMessages) {
for (const log of tx.meta.logMessages) {
if (log.startsWith("Program return:") && log.includes(MAPLE_CONFIG.routerProgramId)) {
const parts = log.split(" ");
if (parts.length >= 4) {
const base64Data = parts[3];
const returnBuffer = Buffer.from(base64Data, "base64");
if (returnBuffer.length === 32) {
messageId = `0x${returnBuffer.toString("hex")}`;
} else if (returnBuffer.length >= 40) {
const messageIdBytes = returnBuffer.subarray(8, 40);
messageId = `0x${messageIdBytes.toString("hex")}`;
}
break;
}
}
}
}
return { signature, messageId };
}
// React hook usage example
function useMapleCCIP() {
const { publicKey, signTransaction } = useWallet();
const { connection } = useConnection();
const sendMessage = async (tokenAmount: bigint) => {
if (!publicKey || !signTransaction) {
throw new Error("Wallet not connected");
}
return await sendMapleCCIPMessage(
publicKey.toBase58(),
tokenAmount,
signTransaction,
connection
);
};
return { sendMessage };
}
```
{% endcode %}
## Message Monitoring via API <a href="#message-monitoring" id="message-monitoring"></a>
After sending CCIP messages, you'll want to monitor their status and display message history to users. The CCIP API provides REST endpoints for querying message transactions by sender address, receiver address, or both.
> **Note:** This is a pre-release version of the CCIP API (v2). The public release will be published soon. The Base URL of the production API will be: <https://api.ccip.cldev.cloud/v2/>
#### API Base URL (Staging)
<https://api.ccip.cldev.cloud/v2/>
#### Querying Messages
The API supports querying messages with the following filters:
* **By Receiver Address**: Find all messages sent to the Maple receiver contract
* **By Sender Address**: Find all messages sent by a specific user
* **By Both**: Find messages matching both sender and receiver
#### Basic Query Function
{% code expandable="true" %}
```typescript
const CCIP_API_BASE = "https://api.ccip.cldev.cloud/v2/";
interface NetworkInfo {
name: string;
chainSelector: string;
chainId: string;
chainFamily: "EVM" | "SVM" | "APTOS";
}
type MessageStatus =
| "SENT"
| "SOURCE_FINALIZED"
| "COMMITTED"
| "BLESSED"
| "VERIFYING"
| "VERIFIED"
| "SUCCESS"
| "FAILED";
interface MessageSearchResult {
messageId: string;
sender: string;
receiver: string;
origin?: string | null;
status: MessageStatus;
sourceNetworkInfo: NetworkInfo;
destNetworkInfo: NetworkInfo;
sendTransactionHash: string;
sendTimestamp: string;
receiptTransactionHash?: string | null;
receiptTimestamp?: string | null;
sourceTokenAddress?: string | null;
}
interface MessagesResponse {
data: MessageSearchResult[];
pagination: {
limit: number;
hasNextPage: boolean;
cursor?: string | null;
};
}
async function queryCCIPMessages(
receiverAddress?: string,
senderAddress?: string,
limit: number = 50,
cursor?: string | null
): Promise<MessagesResponse> {
const params = new URLSearchParams();
if (cursor) {
params.set("cursor", cursor);
params.set("limit", limit.toString());
} else {
params.set("limit", limit.toString());
if (receiverAddress) {
params.set("receiver", receiverAddress.toLowerCase());
}
if (senderAddress) {
params.set("sender", senderAddress.toLowerCase());
}
}
const url = `${CCIP_API_BASE}messages?${params.toString()}`;
const response = await fetch(url, {
headers: {
"Accept": "application/json",
},
});
if (!response.ok) {
const error = await response.json().catch(() => ({
error: "Unknown error",
message: `HTTP ${response.status}`,
}));
throw new Error(error.message || error.error);
}
return await response.json();
}
```
{% endcode %}
#### Understanding Message Statuses
The API returns messages with the following status values:
* **`SENT`**: Transaction submitted and waiting for source chain confirmation
* **`SOURCE_FINALIZED`**: Transaction confirmed on source chain and ready for CCIP processing
* **`COMMITTED`**: Message committed to destination chain's commit store (CCIP v1.6 and below)
* **`BLESSED`**: Message approved by CCIP network (CCIP v1.6 and below)
* **`VERIFYING`**: Message is being verified by the CCIP network (CCIP v1.7+)
* **`VERIFIED`**: Message has been verified by the CCIP network (CCIP v1.7+)
* **`SUCCESS`**: Message successfully executed on destination chain
* **`FAILED`**: Message execution failed but can be manually retried
#### Status Display Helpers
{% code expandable="true" %}
```typescript
function getStatusLabel(status: MessageStatus): string {
switch (status) {
case "SENT": return "Sent";
case "SOURCE_FINALIZED": return "Source Finalized";
case "COMMITTED": return "Committed";
case "BLESSED": return "Blessed";
case "VERIFYING": return "Verifying";
case "VERIFIED": return "Verified";
case "SUCCESS": return "Success";
case "FAILED": return "Failed";
default: return "Unknown";
}
}
function getStatusColor(status: MessageStatus): string {
switch (status) {
case "SUCCESS":
return "green";
case "FAILED":
return "red";
case "SENT":
case "SOURCE_FINALIZED":
case "COMMITTED":
case "BLESSED":
case "VERIFYING":
case "VERIFIED":
return "yellow";
default:
return "gray";
}
}
function isStatusComplete(status: MessageStatus): boolean {
return status === "SUCCESS" || status === "FAILED";
}
```
{% endcode %}
#### Best Practices
1. **Cache Results**: Cache messa프로젝트로 돌아가기