Swap

The entry-point for Validly swaps is the Sovereign Pool's swap function. The following diagram contains more information:

Below is a Solidity example of how to execute a swap against a Validly pool, from the perspective of a smart contract which calls it.

Solidity example:

// Address of Validly's Sovereign Pool to swap against
address pool = 0x123;
// Amount of input token to swap against the pool
uint256 amountIn = 123;
// Minimum amount of output token required after swap
// WARNING: Be sure to set this within safe and reasonable bounds in production!
uint256 amountOutMin = 1;

// token0 and token1 from `pool`
address token0 = ISovereignPool(pool).token0();
address token1 = ISovereignPool(pool).token1();

// Direction of the swap:
// tokenIn=token0 and tokenOut=token1
bool isZeroToOne = true;

// handle tokenIn approval to `pool`
// Assumes that OpenZeppelin's ERC20 SafeTransferLib is used
if (isZeroToOne) {
    token0.safeApprove(pool, amountIn);
} else {
    token1.safeApprove(pool, amountIn);
}

// See: https://github.com/ValantisLabs/valantis-core/blob/main/src/pools/structs/SovereignPoolStructs.sol#L36-L45
SovereignPoolSwapParams memory params;
// Populate inputs to pool's swap function
params.isSwapCallback = false;
params.isZeroToOne = isZeroToOne;
params.amountIn = amountIn;
params.amountOutMin = amountOutMin;
params.deadline = block.timestamp + 1;
params.recipient = address(this);
params.swapTokenOut = isZeroToOne ? address(token1) : address(token0);

// Executes swap against Validly's Sovereign Pool (`pool`)
(uint256 amountInUsed, uint256 amountOut) = ISovereignPool(pool).swap(params);

Last updated