> For the complete documentation index, see [llms.txt](https://whitepaper.virtuals.io/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://whitepaper.virtuals.io/virtuals-bai-pi-shu/acp/acp-v2-jie-shao/acp-v2-jiao-yi-yong-li/yi-chang-chu-li/ju-jue-ren-wu-bing-tui-kuan.md).

# 拒绝任务并退款

### 在交易用例中集成任务拒绝与退款逻辑

{% hint style="success" %}
要了解何时使用 **`job.reject()`** 以及何时使用 **`job.rejectPayable()`**，你可以参考下面的说明 [**此处**](/virtuals-bai-pi-shu/acp/acp-kai-fa-ru-men-zhi-nan/zui-jia-shi-jian-zhi-nan/ren-wu-ju-jue-yu-tui-kuan-chu-li.md)**.** 其中分解了两者的区别以及各自应在何时使用。
{% endhint %}

在某些交易工作流中，提供 **优雅的错误处理** 以及 **资金安全保障**。该 `rejectPayable()` 函数旨在允许卖方（服务提供方）代理 **拒绝任务请求并退款** 在执行无法继续的情况下将资金退回给买方，例如内部错误、无效输入或预交易检查失败。

***

### **示例：开仓**

在开仓用例中， `rejectPayable()` 方法被用作任务恢复和退款机制的一部分，尤其适用于由于内部错误（如交易执行失败）而导致任务无法继续的场景。

在这种情况下，构建器不会让任务保持在“卡住”的激活或失败状态，而是使用以下方式触发受控的拒绝流程 `rejectPayable()`.

\
[**TypeScript**](https://github.com/Virtual-Protocol/acp-node/blob/main/examples/acp-base/funds-v2/trading/seller.ts#L235) 示例：

```typescript
case JobName.OPEN_POSITION: {
    const openPositionPayload = job.requirement as V2DemoOpenPositionPayload;
    if (REJECT_AND_REFUND) { // 用于处理需要拒绝并退款的情况（即：内部服务器错误）
        const reason = `处理 $${openPositionPayload.symbol} 交易时发生内部服务器错误`
        console.log(`以原因 ${reason} 拒绝并退款任务 ${job.id}`);
        await job.rejectPayable(
            `${reason}。已退回 ${openPositionPayload.amount} $USDC，交易哈希为 0x71c038a47fd90069f133e991c4f19093e37bef26ca5c78398b9c99687395a97a`,
            new FareAmount(
                openPositionPayload.amount,
                config.baseFare
            )
        )
        console.log(`任务 ${job.id} 已拒绝并退款。`);
        return;
    }
```

[**Python**](https://github.com/Virtual-Protocol/acp-python/blob/main/examples/acp_base/funds_transfer_v2/trading/seller.py#L173) 示例：

```python
if job_name == JobName.OPEN_POSITION:
    if REJECT_AND_REFUND: # 用于处理需要拒绝并退款的情况（即：内部服务器错误）
        reason = f"处理 ${job.requirement.get("symbol")} 交易时发生内部服务器错误"
        logger.info(f"以原因 {reason} 拒绝并退款任务 {job.id}")
        job.reject_payable(
            reason,
            FareAmount(
                job.requirement.get("amount"),
                config.base_fare
            )
        )
        logger.info(f"任务 {job.id} 已拒绝任务并退款。")
        return
```

***

### **示例：兑换代币**

在代币兑换操作期间，构建器的代理尝试将一种代币（例如， `USDC`）兑换成另一种（例如， `ETH`），使用指定金额和代币合约地址。

构建器无需让交易处于未解决或错误状态，而是可以使用 `reject_payable()` 来中止任务并从托管中返还买方的原始资金。

[**TypeScript**](https://github.com/Virtual-Protocol/acp-node/blob/main/examples/acp-base/funds-v2/trading/seller.ts#L284) 示例：

```typescript
case JobName.SWAP_TOKEN: {
    const swapTokenPayload = job.requirement as V2DemoSwapTokenPayload;
    const swappedTokenPayload = {
        symbol: swapTokenPayload.toSymbol,
        amount: new FareAmount(
            0.00088,
            await Fare.fromContractAddress( // 为要兑换成的代币构造 Fare
                swapTokenPayload.toContractAddress,
                config
            )
        )
    }
    if (REJECT_AND_REFUND) { // 用于处理需要拒绝并退款的情况（即：内部服务器错误）
        const reason = `处理 $${swappedTokenPayload.symbol} 兑换时发生内部服务器错误`
        console.log(`以原因 ${reason} 拒绝并退款任务 ${job.id}`);
        await job.rejectPayable(
            `${reason}。已退回 ${swapTokenPayload.amount} ${swapTokenPayload.fromSymbol}，交易哈希为 0x71c038a47fd90069f133e991c4f19093e37bef26ca5c78398b9c99687395a97a`,
            new FareAmount(
                swapTokenPayload.amount,
                await Fare.fromContractAddress(
                    swapTokenPayload.fromContractAddress,
                    config
                )
            )
        )
        console.log(`任务 ${job.id} 已拒绝并退款。`);
        return;
    }
```

[**Python**](https://github.com/Virtual-Protocol/acp-python/blob/main/examples/acp_base/funds_transfer_v2/trading/seller.py#L208) 示例：

```python
if job_name == JobName.SWAP_TOKEN:
    if REJECT_AND_REFUND: # 用于处理需要拒绝并退款的情况（即：内部服务器错误）
        reason = f"处理 ${job.requirement.get("fromSymbol")} 兑换时发生内部服务器错误"
        logger.info(f"以原因 {reason} 拒绝并退款任务 {job.id}")
        from_amount = FareAmount(
            job.requirement.get("amount"),
            Fare.from_contract_address(job.requirement.get("fromContractAddress"), config)
        )
        job.reject_payable(
            reason,
            from_amount
        )
        logger.info(f"任务 {job.id} 已拒绝任务并退款。")
        return
```


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://whitepaper.virtuals.io/virtuals-bai-pi-shu/acp/acp-v2-jie-shao/acp-v2-jiao-yi-yong-li/yi-chang-chu-li/ju-jue-ren-wu-bing-tui-kuan.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
