A Decentralized Exchange (DEX) is an application that allows users to trade tokens (native & fungible tokens) through smart contracts.
In brief, DEXs work by having pools of token pairs (e.g. NEAR-USDC) that users can deposit tokens into.
The ratio of the tokens in the pool determines the exchange rate for a swap. Indeed, swapping is adding tokens to one side of the pool while removing tokens from the other side of the pool.
This docs refer to Ref Finance, a community built DEX in NEAR.
Please check their docs for more information.
Query Token Exchange Rate
One can query the exchange rate of a token pair by calling the get-token-price
method on the DEX contract.
Query Whitelisted Tokens
Anyone list tokens for sale in the DEX. This is why, in order to protect users, the DEX contract has a list of whitelisted tokens that can be traded.
“`bash
near view v2.ref-finance.near get_whitelisted_tokens
“`
Examples Response
“`bash
‘wrap.near’,
‘usdt.tether-token.near’,
‘berryclub.ek.near’,
‘farm.berryclub.ek.near’,
‘token.v2.ref-finance.near’,
‘token.paras.near’,
‘marmaj.tkn.near’,
‘meta-pool.near’,
…
“`
Register in the DEX
In order to use the contract, make sure to register your account in the DEX by paying for the storage you will use in order to keep track of your balances.
“`bash
near call v2.ref-finance.near storage_deposit ” –accountId
“`
Deposit funds
In order to swap tokens, one must first deposit tokens into the DEX. For this, you will need to transfer the FT you want to swap to the DEX contract.
“`bash
near call token.v2.ref-finance.near ft_transfer_call {“receiver_id”: “v2.ref-finance.near”, “amount”: “1000000000000”, “msg”: “”} –gas 300000000000000 –depositYocto 1 –accountId
“`
:::danger
Do NOT transfer NEAR tokens to Ref Finance. Instead, call near_deposit
in the wrap.near
contract, attaching the amount of NEAR you want to swap.
- This will mint
wrap.near
for you, which you can then transfer to Ref Finance. -
::
Get Deposit Balances
Query your deposit balances by calling the get_deposits
method:
Query Pools
DEXs work by having multiple pools of token pairs (e.g. NEAR-USDC) that users can deposit tokens into.
Swap tokens
In order to swap a token for another, you need to have funds, and there needs to exist a pool that has both tokens on it.
Additional Resources
- Claim Fungible Tokens from Lockup – the example how to claim locked tokens from the
lockup.burrow.near
contract. - BSC Dex Collection – the example of how to build simple swap page for a DEX.