-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
mod.ts
100 lines (87 loc) · 2.18 KB
/
mod.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
export type Network = 'mainnet' | 'bsc' | 'ropsten' | 'polygon' | 'avax'
export const endpoints = {
mainnet: 'https://api.0x.org',
bsc: 'https://bsc.api.0x.org',
ropsten: 'https://ropsten.api.0x.org',
polygon: 'https://polygon.api.0x.org',
avax: 'https://avalanche.api.0x.org',
}
export type SwapOptions =
& {
from: string
to: string
amount: number
}
& Partial<{
slippage: string
takerAddress: string
affiliateAddress: string
feeRecipient: string
tokenFee: string
}>
export type SwapTransaction = {
price: string
guaranteedPrice: string
to: string
data: string
value: string
gas: string
estimatedGas: string
gasPrice: string
protocolFee: string
minimumProtocolFee: string
buyTokenAddress: string
sellTokenAddress: string
buyAmount: string
sellAmount: string
estimatedGasTokenRefund: string
sources: {
name: string
proportion: string
}[]
allowanceTarget: string
}
export class Zrx {
network: Network = 'mainnet'
base = endpoints[this.network]
constructor(network: Network = 'mainnet') {
this.network = network
this.base = endpoints[network]
}
switchNetwork(network: Network) {
this.network = network
this.base = endpoints[network]
}
async quote({ from, to, amount, ...opts }: SwapOptions): Promise<SwapTransaction> {
const params = new URLSearchParams({
...opts,
buyToken: to,
sellToken: from,
sellAmount: amount.toString(),
})
const res = await fetch(`${this.base}/swap/v1/quote?${params.toString()}`)
const json = await res.json()
return json
}
async prices(token: string): Promise<
{
symbol: string
price: string
}[]
> {
const res = await fetch(`${this.base}/swap/v1/prices?sellToken=${token}`)
const { records } = await res.json()
return records
}
async price({ from, to, amount, ...opts }: SwapOptions): Promise<SwapTransaction> {
const params = new URLSearchParams({
...opts,
buyToken: to,
sellToken: from,
sellAmount: amount.toString(),
})
const res = await fetch(`${this.base}/swap/v1/price?${params.toString()}`)
const json = await res.json()
return json
}
}