SDK

Execute Swaps

Execute token swaps using the SDK after getting a quote.

Swap Flow

  1. Ensure wallet is connected
  2. Check token balance
  3. Get allowance and approve if needed
  4. Get swap quote with account address
  5. Execute the swap transaction

Token Approval

Before swapping, you need to approve the contract to spend your tokens:

Terminal
JS
1
async approve(approveContract) {
2
let approve = await swapSdk.approve({
3
chain: this.chainName,
4
tokenAddress: this.inToken.address,
5
approveContract: approveContract,
6
gasPrice: this.gasPrice,
7
decimals: this.inToken.decimals,
8
amount: this.inAmount
9
})
10
11
if (!approve.code) {
12
approve
13
.on('error', (error) => { console.error(error) })
14
.on('transactionHash', (hash) => { console.log('Approval tx:', hash) })
15
.on('receipt', (data) => { console.log('Approved') })
16
.on('success', (data) => { console.log('Success') })
17
}
18
}

Execute Swap

Terminal
JS
1
async swap() {
2
if (!this.myWallet) {
3
alert('Please connect the wallet.')
4
return
5
}
6
7
if (this.inTokenBalance < this.inAmount) {
8
alert(this.inToken.symbol + ' Insufficient balance.')
9
return
10
}
11
12
// Get exchange info for approve contract
13
let { data } = await api.exchange({ chain: this.chainName })
14
15
// Check allowance
16
let allowance = await this.getAllowance(data.approveContract)
17
if (new BigNumber(allowance).lt(this.inAmount)) {
18
await this.approve(data.approveContract)
19
return
20
}
21
22
// Get swap quote with account
23
let response = await swapSdk.swapQuote({
24
chain: this.chainName,
25
inTokenAddress: this.inToken.address,
26
outTokenAddress: this.outToken.address,
27
amount: this.inAmount,
28
gasPrice: this.gasPrice,
29
slippage: 1,
30
account: this.myWallet.address,
31
})
32
33
if (response.code == 200) {
34
swapSdk.swap(response.data)
35
.on('error', (error) => { console.error(error) })
36
.on('transactionHash', (hash) => { console.log('Swap tx:', hash) })
37
.on('receipt', (data) => { this.getBalance() })
38
.on('success', (data) => { console.log('Swap complete') })
39
} else {
40
alert('Error:' + response.message)
41
}
42
}

Check Allowance

Terminal
JS
1
async getAllowance(approveContract) {
2
return await swapSdk.getAllowance({
3
chain: this.chainName,
4
decimals: this.inToken.decimals,
5
tokenAddress: this.inToken.address,
6
approveContract,
7
account: this.myWallet.address
8
})
9
}

Next Steps