Skip to content

WithdrawSwap

class defipy.process.WithdrawSwap()

Single-sided withdrawal, also called a zap-out. The caller wants to leave the pool holding only one token from the pair. The primitive performs an approximate 50/50 withdrawal, swaps the unwanted side back into the desired token, and returns the user’s full position in the desired token.

Available on Uniswap V2 and Uniswap V3 only. Balancer and Stableswap support is tracked for a later release.

amount_out = WithdrawSwap().apply(pool, token_out, user, amount_out_target)

Withdraw the user’s stake from pool, returning approximately amount_out_target of token_out. The primitive burns LP tokens, removes both sides, swaps the non-target side, and returns the target side.

Parameters

NameTypeDescription
poolexchangePool instance to withdraw from. V2 or V3 only.
token_outERC20The token the user wants to leave with.
userstrUser address (string identifier) whose LP tokens are burned.
amount_out_targetfloatTarget amount of token_out to receive.

Returns

NameTypeDescription
amount_outfloatThe actual amount of token_out returned to the user (slightly less than the target due to swap fees on the rebalancing leg).
from defipy import *
user_nm = 'user'
eth_amount = 1000
tkn_amount = 100000
tkn = ERC20("TKN", "0x111")
eth = ERC20("ETH", "0x09")
exchg_data = UniswapExchangeData(tkn0 = eth, tkn1 = tkn, symbol="LP", address="0x011")
factory = UniswapFactory("ETH pool factory", "0x2")
lp = factory.deploy(exchg_data)
Join().apply(lp, user_nm, eth_amount, tkn_amount)
expected_amount_out = WithdrawSwap().apply(lp, eth, user_nm, 1)
lp.summary()
Exchange ETH-TKN (LP) Reserves: ETH = 999.0, TKN = 100000.0 Liquidity: 9994.991239989282
expected_amount_out = WithdrawSwap().apply(lp, tkn, user_nm, 100)
lp.summary()
Exchange ETH-TKN (LP) Reserves: ETH = 1000.0, TKN = 99900.0 Liquidity: 9994.991239989282
  • The mechanism is: perform 50/50 withdrawal sized to the target → swap remaining 50% → return the consolidated target token.
  • The realized output is less than the target by approximately one swap fee (30 bps on V2; the configured tier on V3) — that’s the cost of consolidating to a single side.