📤Swapping

Overview of token swapping

Preface

Amity recently adopted a reworked the swap function to offer Coin -> Token, Token -> Token and Token -> Coin swaps. Swapping can be done through any DEX a user chooses; by default, the four supported swapping networks, Harmony, Ethereum, Avalanche, and Polygon, each have their own set of 2-3 DEX's that a user can choose from when engaging in a swap. Additionally, all four networks have an extra "Custom" option for a DEX, in which the user is prompted to provide a routing address of their choosing to execute the swap in. This opens up the possibility of swaps through any DEX on all four supported swapping networks.

How this works

DEX's have router smart contracts to handle transactions such as these; routers are accessed by initializing a contract with a Checksum address and a unique ABI, and then calling functions on that contract.

web3.eth.contract(address=Web3.toChecksumAddress(routerAddress), abi=ABI)

This address field will change depending on either the DEX a user chooses or the router a user supplies to Amity. For DEX's built in to Amity, some may use a custom ABI (Trader Joe on Avalanche for example) but the vast majority of routers (custom ones included) will use the Uniswap ABI by default as it's pretty universal and will work with most routers.

Transaction building

Once a router is initialized, depending on the parameters a user fills out, Amity will build either a swapExactETHForTokens, swapExactTokensForTokens, or a swapExactTokensForETH transaction (for unique ABI's like Trader Joe's, these may be along the lines of swapExactAVAXForTokens instead of ETH);

router.functions.swapExactETHForTokens(0, [wrappedETH, Web3.toChecksumAddress(tokenToBuy)], Web3.toChecksumAddress(address), 17426800000).buildTransaction({
      'from': Web3.toChecksumAddress(address),
      'value': web3.toWei(value, 'ether'),
      'gas': estimate,
      'gasPrice': web3.eth.gasPrice,
      'nonce': nonce,
      'chainId': chainId
    })
router.functions.swapExactTokensForTokensSupportingFeeOnTransferTokens(amount, 0, [Web3.toChecksumAddress(token1), Web3.toChecksumAddress(token2)], Web3.toChecksumAddress(address[0]), 17426800000).buildTransaction({
      'from': Web3.toChecksumAddress(address[0]),
      'gas': estimate,
      'gasPrice': web3.eth.gas_price,
      'nonce': nonce,
      'chainId': chainId
      })
router.functions.swapExactTokensForETH(amount, 0, [Web3.toChecksumAddress(token1), wrap], Web3.toChecksumAddress(address[0]), 17426800000).buildTransaction({
      'from': Web3.toChecksumAddress(address[0]),
      'gas': estimate,
      'gasPrice': web3.eth.gas_price,
      'nonce': nonce,
      'chainId': chainId
    })

Last updated