Skip to content

Commit cc5e8ce

Browse files
committed
feat: add 0x API key in the swap requests
1 parent 3bea301 commit cc5e8ce

File tree

9 files changed

+69
-32
lines changed

9 files changed

+69
-32
lines changed

Diff for: .gitignore

+1
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
# editors
22

33
.idea
4+
.vscode
45
.DS_Store
56
.eslintcache
67
*-lock.*

Diff for: src/common/utils/request.ts

+5-4
Original file line numberDiff line numberDiff line change
@@ -112,10 +112,11 @@ const sendRequest = (options) => {
112112
const opts = { ...defaultOptions, ...options }
113113
const req = request[opts.method](opts.endpoint)
114114

115-
// req.set({
116-
// 'Content-Type': opts.formData ? 'application/x-www-form-urlencoded; charset=UTF-8' : 'application/json',
117-
// ...(opts.headers || {}),
118-
// })
115+
if (opts.headers) {
116+
req.set({
117+
...opts.headers,
118+
})
119+
}
119120

120121
if (opts.timeout) {
121122
req.timeout({

Diff for: src/front/config/mainnet/api.js

+1
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ export default {
44
zeroxPolygon: 'https://polygon.api.0x.org',
55
zeroxFantom: 'https://fantom.api.0x.org',
66
zeroxAvalanche: 'https://avalanche.api.0x.org',
7+
zeroxArbitrum: 'https://arbitrum.api.0x.org',
78
oneinch: 'https://api.1inch.exchange/v3.0',
89
limitOrders: 'https://limit-orders.1inch.exchange/v1.0',
910
horizon: 'https://horizon.stellar.org',

Diff for: src/front/config/mainnet/swapContract.js

+1-1
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@ export default {
88
protectedBtcKey: '025c8ee352e8b0d12aecd8b3d9ac3bd93cae1b2cc5de7ac56c2995ab506ac800bd',
99
btcPinKey: '032aec5d20f9a0bb913a9835330259748392927c9a812299c4498a9e2ed3e78d3f',
1010
zerox: '0xdef1c0ded9bec7f1a1670819833240f027b25eff',
11-
11+
zeroxFantom: '0xdef189deaef76e379df891899eb5a00a94cbc250',
1212
uniswapRouter: '0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D', // Ethereum
1313
uniswapFactory: '0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f',
1414
pancakeswapRouter: '0x10ED43C718714eb63d5aA57B78B54704E256024E', // BSC

Diff for: src/front/shared/pages/Exchange/QuickSwap/Feedback.tsx

+2-2
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@ import { FormattedMessage } from 'react-intl'
33
import CSSModules from 'react-css-modules'
44
import styles from './index.scss'
55
import { BlockReasons, Actions } from './types'
6-
import { API_NAME } from './constants'
6+
import { SWAP_API } from './constants'
77

88
function Feedback(props) {
99
const {
@@ -25,7 +25,7 @@ function Feedback(props) {
2525

2626
return (
2727
<section>
28-
{!isSourceMode && !API_NAME[network?.networkVersion] ? (
28+
{!isSourceMode && !SWAP_API[network?.networkVersion] ? (
2929
<p styleName="dangerousNotice">
3030
<FormattedMessage
3131
id="aggregatorCannotUseThisNetwork"

Diff for: src/front/shared/pages/Exchange/QuickSwap/Footer.tsx

+2
Original file line numberDiff line numberDiff line change
@@ -98,6 +98,8 @@ function Footer(props: FooterProps) {
9898
const apiSwap = async () => {
9999
if (isSourceMode) return
100100

101+
// TODO Check the correct proxy contract in the final data
102+
101103
const baseCurrency = fromWallet.standard ? fromWallet.baseCurrency : fromWallet.currency
102104
const assetName = fromWallet.standard ? fromWallet.tokenKey : fromWallet.currency
103105

Diff for: src/front/shared/pages/Exchange/QuickSwap/constants.ts

+25-6
Original file line numberDiff line numberDiff line change
@@ -11,12 +11,31 @@ export const GWEI_DECIMALS = 9
1111
export const MAX_PERCENT = 100
1212
export const SEC_PER_MINUTE = 60
1313

14-
export const API_NAME = {
15-
1: 'zeroxEthereum',
16-
56: 'zeroxBsc',
17-
137: 'zeroxPolygon',
18-
250: 'zeroxFantom',
19-
43114: 'zeroxAvalanche',
14+
export const SWAP_API = {
15+
1: {
16+
name: 'zeroxEthereum',
17+
spender: 'zerox',
18+
},
19+
56: {
20+
name: 'zeroxBsc',
21+
spender: 'zerox',
22+
},
23+
137: {
24+
name: 'zeroxPolygon',
25+
spender: 'zerox',
26+
},
27+
250: {
28+
name: 'zeroxFantom',
29+
spender: 'zeroxFantom',
30+
},
31+
43114: {
32+
name: 'zeroxAvalanche',
33+
spender: 'zerox',
34+
},
35+
42161: {
36+
name: 'zeroxArbitrum',
37+
spender: 'zerox',
38+
},
2039
}
2140

2241
export const API_GAS_LIMITS = {

Diff for: src/front/shared/pages/Exchange/QuickSwap/index.tsx

+31-19
Original file line numberDiff line numberDiff line change
@@ -31,7 +31,7 @@ import {
3131
CurrencyMenuItem,
3232
} from './types'
3333
import {
34-
API_NAME,
34+
SWAP_API,
3535
GWEI_DECIMALS,
3636
COIN_DECIMALS,
3737
API_GAS_LIMITS,
@@ -192,6 +192,7 @@ class QuickSwap extends PureComponent<IUniversalObj, ComponentState> {
192192
gasLimit: '',
193193
blockReason: undefined,
194194
serviceFee: false,
195+
zeroxApiKey: window.zeroxApiKey || '',
195196
}
196197
}
197198

@@ -314,7 +315,7 @@ class QuickSwap extends PureComponent<IUniversalObj, ComponentState> {
314315
const { coin, blockchain } = getCoinInfo(currency.value)
315316
const network = externalConfig.evmNetworks[blockchain || coin]
316317

317-
return !!API_NAME[network?.networkVersion]
318+
return !!SWAP_API[network?.networkVersion]
318319
})
319320
}
320321

@@ -346,7 +347,7 @@ class QuickSwap extends PureComponent<IUniversalObj, ComponentState> {
346347

347348
const feeOptsKey = fromWallet?.standard || fromWallet?.currency
348349
const currentFeeOpts = externalConfig.opts.fee[feeOptsKey?.toLowerCase()]
349-
const correctFeeRepresentation = !Number.isNaN(window?.zeroxFeePercent)
350+
const correctFeeRepresentation = !Number.isNaN(window?.zeroxFeePercent)
350351
&& window.zeroxFeePercent >= 0
351352
&& window.zeroxFeePercent <= 100
352353

@@ -502,8 +503,8 @@ class QuickSwap extends PureComponent<IUniversalObj, ComponentState> {
502503
}))
503504
}
504505

505-
createSwapRequest = (skipValidation = false) => {
506-
const { slippage, spendedAmount, fromWallet, toWallet, serviceFee } = this.state
506+
buildSwapParams = (route: '/price' | '/quote', skipValidation = false) => {
507+
const { slippage, spendedAmount, fromWallet, toWallet, serviceFee, zeroxApiKey } = this.state
507508

508509
const sellToken = fromWallet?.contractAddress || EVM_COIN_ADDRESS
509510
const buyToken = toWallet?.contractAddress || EVM_COIN_ADDRESS
@@ -516,7 +517,7 @@ class QuickSwap extends PureComponent<IUniversalObj, ComponentState> {
516517
const enoughBalanceForSwap = new BigNumber(fromWallet.balance).isGreaterThan(new BigNumber(spendedAmount))
517518

518519
const request = [
519-
`/swap/v1/quote?`,
520+
`/swap/v1${route}?`,
520521
`buyToken=${buyToken}&`,
521522
`sellToken=${sellToken}&`,
522523
`sellAmount=${sellAmount}`,
@@ -531,7 +532,6 @@ class QuickSwap extends PureComponent<IUniversalObj, ComponentState> {
531532

532533
if (serviceFee) {
533534
const { address, percent } = serviceFee
534-
535535
request.push(`&feeRecipient=${address}`)
536536
request.push(`&buyTokenPercentageFee=${percent}`)
537537
}
@@ -544,11 +544,13 @@ class QuickSwap extends PureComponent<IUniversalObj, ComponentState> {
544544
// allow users to enter an amount up to 100, because it's more easy then enter the amount from 0 to 1
545545
// and now convert it into the api format
546546
const correctValue = new BigNumber(slippage).dividedBy(MAX_PERCENT)
547-
548547
request.push(`&slippagePercentage=${correctValue}`)
549548
}
550549

551-
return request.join('')
550+
return {
551+
headers: { '0x-api-key': zeroxApiKey },
552+
endpoint: request.join(''),
553+
}
552554
}
553555

554556
onInputDataChange = async () => {
@@ -640,7 +642,11 @@ class QuickSwap extends PureComponent<IUniversalObj, ComponentState> {
640642
}
641643

642644
fetchSwapAPIData = async () => {
643-
const { network, spendedAmount, isPending } = this.state
645+
const { isSourceMode, network, spendedAmount, isPending, zeroxApiKey } = this.state
646+
647+
if (!isSourceMode && !zeroxApiKey) {
648+
return console.log('%c0x API key is not set', 'color:red')
649+
}
644650

645651
const dontFetch = (
646652
new BigNumber(spendedAmount).isNaN()
@@ -656,31 +662,37 @@ class QuickSwap extends PureComponent<IUniversalObj, ComponentState> {
656662
}))
657663

658664
let repeatRequest = true
659-
let swapRequest = this.createSwapRequest()
665+
// TODO Send basic requests to /price to avoid exceeding API limits
666+
const params = this.buildSwapParams('/quote')
667+
let { headers, endpoint } = params
660668

661669
while (repeatRequest) {
662-
const swap: any = await apiLooper.get(API_NAME[network.networkVersion], swapRequest, {
663-
reportErrors: (error) => {
670+
const swap: any = await apiLooper.get(SWAP_API[network.networkVersion].name, endpoint, {
671+
headers,
672+
sourceError: true,
673+
reportErrors: (error: IError) => {
664674
if (!repeatRequest) {
665675
this.reportError(error)
666676
}
667677
},
668-
sourceError: true,
669678
})
670679

680+
console.table(swap)
681+
671682
if (!(swap instanceof Error)) {
672683
repeatRequest = false
673684

674685
await this.calculateDataFromSwap({
675686
swap,
676-
withoutValidation: swapRequest.match(/skipValidation/),
687+
withoutValidation: endpoint.match(/skipValidation/),
677688
})
678689
} else if (this.tryToSkipValidation(swap)) {
679690
// it's a special error. Will be a new request
680-
swapRequest = this.createSwapRequest(true)
691+
const p = this.buildSwapParams('/quote', true)
692+
headers = p.headers
693+
endpoint = p.endpoint
681694
} else {
682695
this.reportError(swap)
683-
684696
repeatRequest = false
685697
}
686698
}
@@ -828,9 +840,9 @@ class QuickSwap extends PureComponent<IUniversalObj, ComponentState> {
828840
wallet = toWallet
829841
}
830842

831-
const spender = isSourceMode
843+
const spender: `0x${number}` = isSourceMode
832844
? LIQUIDITY_SOURCE_DATA[network.networkVersion]?.router
833-
: externalConfig.swapContract.zerox
845+
: externalConfig.swapContract[SWAP_API[network.networkVersion].spender]
834846

835847
if (!wallet.isToken) {
836848
this.setNeedApprove(direction, false)

Diff for: src/front/shared/pages/Exchange/QuickSwap/types.ts

+1
Original file line numberDiff line numberDiff line change
@@ -93,4 +93,5 @@ export type ComponentState = {
9393
blockReason: BlockReasons | undefined
9494
liquidityErrorMessage: string
9595
serviceFee: ServiceFee | false
96+
zeroxApiKey: string
9697
}

0 commit comments

Comments
 (0)