> ## Documentation Index
> Fetch the complete documentation index at: https://www.helius.dev/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# 与发送方进行土地交易

> 通过Helius Sender构建低延迟发送循环：区域端点、连接预热、动态优先费用、小费和可重试的着陆确认。

发送方同时通过每条高速路径（Helius、Jito、Harmonic、Rakurai）提交您的交易，并且不消耗API积分。您通过发送每笔交易支付一个SOL小费。本指南构建了一个具有预热连接、实时价格费用和重试策略确认的生产发送循环。

## 选择您的等级

[Sender Max](/docs/zh/sending-transactions/sender-max)（最低0.001 SOL小费）通过所有路径路由，并进入优先小费缓冲区，其中较大的小费优先着陆。

[SWQOS-only](/docs/zh/sending-transactions/sender-swqos-only)（0.000005 SOL）选择单一路径以优化成本。将`?swqos_only=true`添加到端点URL。

在两个最低值之间的小费通过较少的路径尽力而为，因此请选择其中一个等级。

## 选择您的端点

后端应使用最靠近其服务器的区域HTTP端点（`http://ewr-sender.helius-rpc.com/fast`, `fra`, `slc`, `ams`, `lon`, `sg`, `tyo`）。

浏览器应使用全球HTTPS端点`https://sender.helius-rpc.com/fast`，自动路由并避免CORS问题。

## 预热连接

在空闲期后首次发送时，冷TCP/TLS握手会增加延迟。

如果您的系统发送之间可能间隔超过5秒，请使用ping端点保持连接热。

```typescript theme={"system"}
const SENDER = 'http://ewr-sender.helius-rpc.com';

setInterval(async () => {
  try {
    await fetch(`${SENDER}/ping`);
  } catch (e) {
    console.warn('warm-up failed:', e);
  }
}, 5_000);
```

## 构建交易

每个发送方交易必须包括向指定小费账户的提示转账和计算单价。发送方拒绝缺少任何一项的交易。

硬编码优先费用会在市场安静时造成支付过高，在繁忙时竞赛失败，因此从[Priority Fee API](/docs/zh/priority-fee-api)获取价格：

```typescript send.ts theme={"system"}
import {
  Connection, TransactionMessage, VersionedTransaction,
  SystemProgram, PublicKey, Keypair, ComputeBudgetProgram, LAMPORTS_PER_SOL
} from '@solana/web3.js';

const RPC = 'https://mainnet.helius-rpc.com/?api-key=YOUR_API_KEY';
const TIP_ACCOUNTS = [
  '4ACfpUFoaSD9bfPdeu6DBt89gB6ENTeHBXCAi87NhDEE',
  'D2L6yPZ2FmmmTKPgzaMKdhu6EWZcTpLy1Vhx8uvZe7NZ',
  '9bnz4RShgq1hAnLnZbP8kbgBg1kEmcJBYQq3gQbmnSta'
];

async function buildTransaction(keypair: Keypair, tradeInstructions: any[]) {
  const connection = new Connection(RPC);
  const { blockhash } = await connection.getLatestBlockhash('confirmed');

  // Price the fee against the accounts the trade touches
  const feeRes = await fetch(RPC, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({
      jsonrpc: '2.0', id: '1', method: 'getPriorityFeeEstimate',
      params: [{
        accountKeys: tradeInstructions.flatMap(ix => ix.keys.map((k: any) => k.pubkey.toBase58())),
        options: { recommended: true }
      }]
    })
  });
  const { result } = await feeRes.json();

  const tx = new VersionedTransaction(
    new TransactionMessage({
      instructions: [
        ComputeBudgetProgram.setComputeUnitLimit({ units: 100_000 }),
        ComputeBudgetProgram.setComputeUnitPrice({ microLamports: result.priorityFeeEstimate }),
        ...tradeInstructions,
        SystemProgram.transfer({
          fromPubkey: keypair.publicKey,
          toPubkey: new PublicKey(TIP_ACCOUNTS[Math.floor(Math.random() * TIP_ACCOUNTS.length)]),
          lamports: 0.001 * LAMPORTS_PER_SOL // Sender Max minimum; tip more to land first
        })
      ],
      payerKey: keypair.publicKey,
      recentBlockhash: blockhash
    }).compileToV0Message()
  );
  tx.sign([keypair]);
  return tx;
}
```

小费决定您的交易可以选择哪些路径，而优先费用提升其在验证器队列中的位置。它们一起最大化包含概率。

## 发送，然后确认

使用`skipPreflight: true`提交以进行客户端验证以换取延迟，然后通过您的RPC连接确认。

发送方立即返回签名，这不是着陆的证明：

```typescript theme={"system"}
async function sendAndConfirm(tx: VersionedTransaction): Promise<string> {
  const signature = await send(tx);

  const connection = new Connection(RPC);
  for (let i = 0; i < 30; i++) {
    const { value } = await connection.getSignatureStatuses([signature]);
    const status = value[0];
    if (status?.err) throw new Error(`Transaction failed: ${JSON.stringify(status.err)}`);
    if (status?.confirmationStatus === 'confirmed' || status?.confirmationStatus === 'finalized') {
      return signature;
    }
    await new Promise(r => setTimeout(r, 1_000));
  }
  throw new Error('Not confirmed within 30s: rebuild with a fresh blockhash and resend');
}

async function send(tx: VersionedTransaction): Promise<string> {
  const res = await fetch(`${SENDER}/fast`, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({
      jsonrpc: '2.0',
      id: Date.now().toString(),
      method: 'sendTransaction',
      params: [
        Buffer.from(tx.serialize()).toString('base64'),
        { encoding: 'base64', skipPreflight: true, maxRetries: 0 }
      ]
    })
  });
  const json = await res.json();
  if (json.error) throw new Error(json.error.message);
  return json.result;
}
```

使用`maxRetries: 0`您掌控重试策略：当确认超时时，用新的blockhash和重新定价的费用重建，而不是重新发送过时的交易。

默认吞吐量为50 TPS。专业计划可以[请求更高的限制](https://www.helius.dev/contact)。

## 可选：绕过夹层攻击者路由

将`?mev-protect=true`添加到端点URL中，以避免与夹层攻击统计相关的验证器。请求主体不变，并适用于两个等级：

```text theme={"system"}
http://ewr-sender.helius-rpc.com/fast?mev-protect=true
```

查看[MEV Protect](/docs/zh/sending-transactions/mev-protect)以了解权衡。对于原子多交易执行（最多4笔交易，全部或无），在同一端点使用[`sendBundle`](/docs/zh/sending-transactions/sender-max#批处理)。

## 相关指南

<CardGroup cols={2}>
  <Card title="Sender概述" icon="paper-plane" href="/docs/zh/sending-transactions/sender">
    完整的等级、端点、小费账户和速率限制
  </Card>

  <Card title="在预确认上进行交易" icon="stopwatch" href="/docs/zh/pre-confirmations/guides/trade-on-preconfirmations">
    将最快的发送路径与最早的交易信号配对
  </Card>
</CardGroup>
