小费地址使用示例
大约 2 分钟
在原交易中包含小费地址
功能概述
系统将检查提交的交易中是否存在我们的小费地址,如果未找到将返回错误。本文档提供了如何将小费地址直接整合到您的原交易中的示例(推荐方式)。
实现步骤
- 首先,从
/api/v2/randomTipAddress
端点获取随机小费地址 - 将小费转账直接包含在您的原交易中
- 将包含集成小费的单笔交易提交到批量提交端点
代码示例(转账示例)
// 步骤1:获取随机小费地址
async function createTransferWithTip(fromPrivateKey, toAddress, amountSOL) {
try {
// 1. 获取随机小费地址
const tipAddressResponse = await fetch('https://api.flashblock.trade/api/v2/randomTipAddress', {
method: 'GET',
headers: { 'Authorization': '7ebb9180244b50a47ca1993370dc4d5a' }
});
const tipData = await tipAddressResponse.json();
if (!tipData.success) {
throw new Error(`获取小费地址失败: ${tipData.message}`);
}
const tipAddress = tipData.data.tipAccount;
// 2. 计算金额
const mainLamports = Math.round(amountSOL * 1e9);
const tipLamports = Math.round(mainLamports * 0.001); // 0.1% 小费
// 3. 从私钥创建密钥对
const payer = Keypair.fromSecretKey(bs58.decode(fromPrivateKey));
const toPubkey = new PublicKey(toAddress);
const tipPubkey = new PublicKey(tipAddress);
// 4. 创建包含两个转账的交易
const transaction = new Transaction()
.add(
SystemProgram.transfer({
fromPubkey: payer.publicKey,
toPubkey: toPubkey,
lamports: mainLamports,
})
)
.add(
SystemProgram.transfer({
fromPubkey: payer.publicKey,
toPubkey: tipPubkey,
lamports: tipLamports,
})
);
// 5. 设置最近的区块哈希
const { blockhash } = await connection.getLatestBlockhash();
transaction.recentBlockhash = blockhash;
transaction.feePayer = payer.publicKey;
// 6. 签名交易
transaction.sign(payer);
// 7. 序列化为base64
const serializedTransaction = transaction.serialize();
const base64Transaction = Buffer.from(serializedTransaction).toString('base64');
return base64Transaction;
} catch (error) {
console.error('创建交易时出错:', error);
throw error;
}
}
// 使用示例
async function submitBatchTransactions(transactionsBase64) {
try {
const response = await fetch('http://ams.flashblock.trade/api/v2/submit-batch', {
method: 'POST',
headers: {
'Authorization': '7ebb9180244b50a47ca1993370dc4d5a',
'Content-Type': 'application/json'
},
body: JSON.stringify({
transactions: transactionsBase64
})
});
const result = await response.json();
if (result.success) {
console.log('批量提交成功:', result.data);
return result.data;
} else {
console.error(`错误: ${result.message} (代码: ${result.code})`);
return null;
}
} catch (error) {
console.error('API请求失败:', error);
throw error;
}
}
// 使用示例
const transactions = [
"AaBU8zC90i...MAAAAAAAA=",
"AaN9N7CCvi...MAAAAAAAA="
];
submitBatchTransactions(transactions)
.then(result => {
if (result) {
console.log(`批量ID: ${result.batch_id}`);
result.results.forEach(tx => {
console.log(`交易 ${tx.txid}: ${tx.status}`);
});
}
})
.catch(err => {
console.error('提交批量失败:', err);
});