This repository has been archived by the owner on Jun 24, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 55
/
trade.ts
176 lines (150 loc) · 4.95 KB
/
trade.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
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
import { CurrencyAmount, Currency, Token } from '@uniswap/sdk-core'
import { isAddress, shortenAddress } from 'utils'
import { OrderStatus, OrderKind, ChangeOrderStatusParams, Order } from 'state/orders/actions'
import { AddUnserialisedPendingOrderParams } from 'state/orders/hooks'
import { signOrder, signOrderCancellation, UnsignedOrder } from 'utils/signatures'
import { sendSignedOrderCancellation, sendOrder as sendOrderApi, OrderID } from 'api/gnosisProtocol'
import { Signer } from 'ethers'
import { RADIX_DECIMAL, AMOUNT_PRECISION } from 'constants/index'
import { SupportedChainId as ChainId } from 'constants/chains'
import { formatSmart } from 'utils/format'
import { SigningScheme } from '@gnosis.pm/gp-v2-contracts'
import { getTrades } from 'api/gnosisProtocol/api'
export interface PostOrderParams {
account: string
chainId: ChainId
signer: Signer
kind: OrderKind
inputAmount: CurrencyAmount<Currency>
outputAmount: CurrencyAmount<Currency>
feeAmount: CurrencyAmount<Currency> | undefined
sellToken: Token
buyToken: Token
validTo: number
recipient: string
recipientAddressOrName: string | null
allowsOffchainSigning: boolean
appDataHash: string
}
function _getSummary(params: PostOrderParams): string {
const { kind, account, inputAmount, outputAmount, recipient, recipientAddressOrName, feeAmount } = params
const [inputQuantifier, outputQuantifier] = [
kind === OrderKind.BUY ? 'at most ' : '',
kind === OrderKind.SELL ? 'at least ' : '',
]
const inputSymbol = inputAmount.currency.symbol
const outputSymbol = outputAmount.currency.symbol
const inputAmountValue = formatSmart(feeAmount ? inputAmount.add(feeAmount) : inputAmount, AMOUNT_PRECISION)
const outputAmountValue = formatSmart(outputAmount, AMOUNT_PRECISION)
const base = `Swap ${inputQuantifier}${inputAmountValue} ${inputSymbol} for ${outputQuantifier}${outputAmountValue} ${outputSymbol}`
if (recipient === account) {
return base
} else {
const toAddress =
recipientAddressOrName && isAddress(recipientAddressOrName)
? shortenAddress(recipientAddressOrName)
: recipientAddressOrName
return `${base} to ${toAddress}`
}
}
export async function signAndPostOrder(params: PostOrderParams): Promise<AddUnserialisedPendingOrderParams> {
const {
kind,
chainId,
inputAmount,
outputAmount,
sellToken,
buyToken,
feeAmount,
validTo,
account,
signer,
recipient,
allowsOffchainSigning,
appDataHash,
} = params
// fee adjusted input amount
const sellAmount = inputAmount.quotient.toString(RADIX_DECIMAL)
// slippage adjusted output amount
const buyAmount = outputAmount.quotient.toString(RADIX_DECIMAL)
// Prepare order
const summary = _getSummary(params)
const receiver = recipient
const creationTime = new Date().toISOString()
const unsignedOrder: UnsignedOrder = {
sellToken: sellToken.address,
buyToken: buyToken.address,
sellAmount,
buyAmount,
validTo,
appData: appDataHash,
feeAmount: feeAmount?.quotient.toString() || '0',
kind,
receiver,
partiallyFillable: false, // Always fill or kill
}
let signingScheme: SigningScheme
let signature: string | undefined
if (allowsOffchainSigning) {
const signedOrderInfo = await signOrder(unsignedOrder, chainId, signer)
signingScheme = signedOrderInfo.signingScheme
signature = signedOrderInfo.signature
} else {
signingScheme = SigningScheme.PRESIGN
signature = account
}
// Call API
const orderId = await sendOrderApi({
chainId,
order: {
...unsignedOrder,
receiver,
signingScheme,
// Include the signature
signature,
},
owner: account,
})
const pendingOrderParams: Order = {
...unsignedOrder,
// Basic order params
id: orderId,
owner: account,
summary,
inputToken: sellToken,
outputToken: buyToken,
// Status
status: allowsOffchainSigning ? OrderStatus.PENDING : OrderStatus.PRESIGNATURE_PENDING,
creationTime,
// Signature
signature,
// Additional API info
apiAdditionalInfo: undefined,
}
return {
chainId,
id: orderId,
order: pendingOrderParams,
}
}
type OrderCancellationParams = {
orderId: OrderID
account: string
chainId: ChainId
signer: Signer
cancelPendingOrder: (params: ChangeOrderStatusParams) => void
}
export async function sendOrderCancellation(params: OrderCancellationParams): Promise<void> {
const { orderId, account, chainId, signer, cancelPendingOrder } = params
const { signature, signingScheme } = await signOrderCancellation(orderId, chainId, signer)
await sendSignedOrderCancellation({
chainId,
owner: account,
cancellation: { orderUid: orderId, signature, signingScheme },
})
cancelPendingOrder({ chainId, id: orderId })
}
export async function hasTrades(chainId: ChainId, address: string): Promise<boolean> {
const trades = await getTrades({ chainId, owner: address, limit: 1 })
return trades.length > 0
}