单笔交换
交换是与 SwapX 协议最常见的交互。以下示例向您展示如何使用您创建的两个函数来实现单路径交换合约:
- swapExactInputSingle
- swapExactOutputSingle
该swapExactInputSingle函数用于执行精确输入交换,即将固定数量的一种代币交换为最大可能数量的另一种代币。此函数使用ISwapRouter接口中的ExactInputSingleParams结构和函数。
该swapExactOutputSingle函数用于执行精确输出交换,即将最小可能数量的一种代币交换为固定数量的另一种代币。此函数使用ISwapRouter接口中的ExactOutputSingleParams结构和函数。
为了简化,示例对代币合约地址进行了硬编码,但如下文进一步解释的那样,可以修改合约以根据每个交易更改池和代币。
当通过智能合约进行交易时,最重要的是要记住需要访问外部价格来源。如果没有这个,交易可能会造成相当大的损失。
注意:交换示例不是可用于生产的代码,并且以简单的方式实现以用于学习目的。
签订 声明用于编译合约的 solidity 版本,并abicoder v2允许在 calldata 中对任意嵌套数组和结构进行编码和解码,这是执行交换时使用的功能。
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity =0.7.6;
pragma abicoder v2;
创建一个名为的合约SwapExamples,并声明一个swapRouter类型的不可变公共变量ISwapRouter。这使我们能够调用ISwapRouter接口中的函数。
contract SwapExamples {
// For the scope of these swap examples,
// we will detail the design considerations when using `exactInput`, `exactInputSingle`, `exactOutput`, and `exactOutputSingle`.
// It should be noted that for the sake of these examples we pass in the swap router as a constructor argument instead of inheriting it.
// More advanced example contracts will detail how to inherit the swap router safely.
// This example swaps DAI/WETH9 for single path swaps and DAI/USDC/WETH9 for multi path swaps.
ISwapRouter public immutable swapRouter;