Swap Tokens

Swap tokens.


FunWallets can swap between any pair of fungible assets, including ERC-20s (USDC, DAI, WETH) & base currencies (ETH, MATIC).

FunWallet uses 1inch on chains where 1inch is supported. Otherwise it uses Uniswap.\

Swaps can be done by either specifying the name of the asset to be swapped (e.g "eth") or by the address of the asset (e.g "0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48").


Swap ETH for USDC

The following flow demonstrates how to swap 0.001 ETH for the equivalent amount of DAI on the Göerli testnet.

,
swap.js
const { FunWallet, configureEnvironment } = require("fun-wallet")
const { Eoa } = require("fun-wallet/auth")
const { fundWallet } = require("fun-wallet/utils")
const PRIVATE_KEY = "0x98e9cfb323863bc4bfc094482703f3d4ac0cd407e3af2351c00dde1a6732756a"
const API_KEY = "MYny3w7xJh6PRlRgkJ9604sHouY2MTke6lCPpSHq"
const swap = async () => {
await configureEnvironment({
apiKey: API_KEY
})
const auth = new Eoa({ privateKey: PRIVATE_KEY })
const uniqueId = await auth.getUniqueId()
const wallet = new FunWallet({ uniqueId })
// NOTE: Wallet must be prefunded if not using a sponsor
// await fundWallet(funder_auth, wallet, .005)
// auth: an auth object (see Auth API)
// in: type of token you are swapping with
// amount: amount to swap
// out: type of token swapping to
const receipt = await wallet.swap(auth, {
in: "eth",
amount: .001,
out: "dai",
});
}
swap()

    Important!

  • Ensure your privateKey starts with '0x'.

  • Ensure your account has enough funds to swap with and pay for gas. (ie: USDC, ETH)

See full reference for Swap.