Skip to main content

Making a swap via cast command

The swap function that needs to be called has the following signature:
function swap(
        address _tokenIn,
        uint256 _amountIn,
        uint256 _minOut,
        address _recipient,
        uint256 _expires
    ) external returns (uint256 amountOut, uint256 lpFeeAmount, uint256 protocolFeeAmount)
ParameterTypeDescription
_tokenInaddressThe address of the token you’re swapping into the pool.
This can be either side of the token pair.
_amountInuint256The amount of _tokenIn to exchange.
_minOutuint256Minimum amount of output token to accept. This is slippage protection, see below for more details.
_recipientaddressAddress that will receive the output tokens
_expiresuint256Block timestamp expiration.

Determine the _minOut argument

The _minOut parameter in the swap() function protects your transactions from unfavorable price movements by setting a minimum acceptable output amount. If the actual output falls below this threshold, the transaction will revert, preventing execution at a worse price than you’re willing to accept. Depending on your use case, you’ll calculate _minOut differently:

Scenario 1: Specify how much you want to receive

Use case: You want to receive a specific amount of tokens (e.g., “I want exactly 100 $TEST”). Steps:
  1. Call simSwapReversed(_tokenOut, _amountOut) where _amountOut is your desired output amount
  2. This returns the amountIn you need to pay
  3. Calculate _minOut = _amountOut × slippageTolerance

Scenario 2: Specify how much you want to spend

Use case: You have a fixed amount to spend (e.g., “I want to spend 100 USDC”). Steps:
  1. Call simSwap(_tokenIn, _amountIn) where _amountIn is what you’re paying
  2. This returns the expected amountOut you’ll receive
  3. Calculate _minOut = amountOut × slippageTolerance
// for example, to allow 5% slippage
_minOut = _amountOut * 0.95;

Send the transaction with cast

First, you’ll probably want to save some values to your environment for use in the command.
.env
RPC_URL=
POOL_ADDRESS=
PRIV_KEY=
TOKEN_IN=
RECIPIENT=
EXPIRES=1798761600 # Jan 1, 2027 - adjust as desired
Then make these value available to the shell:
source .env
And finally, send the transaction!
cast send $POOL_ADDRESS "swap(address,uint256,uint256,address,uint256)(uint256,uint256,uint256)" $TOKEN_IN <AMOUNT_IN> <MIN_OUT> $RECIPIENT $EXPIRES --rpc-url $RPC_URL --private-key $PRIV_KEY

Integrating a swap UI into your App

This is a more involved integration process, but enables you to keep users within your own app ecosystem. You can see an example of this in our Martian Mining demo site.
Martian Mining demo site
If you’d like access to the code repository for this demo site, contact us!