@cowprotocol/cow-sdk 2.0.0-alpha.5 → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -4,375 +4,121 @@
4
4
 
5
5
  # CoW SDK
6
6
 
7
- [![Styled With Prettier](https://img.shields.io/badge/code_style-prettier-ff69b4.svg)](https://prettier.io/)
8
- [![Coverage Status](https://coveralls.io/repos/github/cowprotocol/cow-sdk/badge.svg?branch=main)](https://coveralls.io/github/cowprotocol/cow-sdk?branch=main)
7
+ ## 📚 [SDK docs website](https://docs.cow.fi/cow-sdk)
9
8
 
10
- ## Getting started
11
-
12
- Install the SDK:
13
-
14
- ```bash
15
- yarn add @cowprotocol/cow-sdk
16
- ```
17
-
18
- Instantiate the SDK:
19
-
20
- ```js
21
- import { CowSdk } from '@cowprotocol/cow-sdk'
22
-
23
- const chainId = 100 // Gnosis chain
24
- const cowSdk = new CowSdk(chainId)
25
- ```
26
-
27
- The SDK will expose:
28
-
29
- - The CoW API (`cowSdk.cowApi`)
30
- - The CoW Subgraph (`cowSdk.cowSubgraphApi`)
31
- - Convenient method to facilitate signing orders (i.e `cowSdk.signOrder`)
32
-
33
- > For a quick snippet with the full process on posting an order see the [Post an Order Example](./docs/post-order-example.ts)
34
-
35
- ## CoW API
36
-
37
- The SDK provides access to the CoW API. The CoW API allows you:
38
-
39
- - Post orders
40
- - Get fee quotes
41
- - Get order details
42
- - Get history of orders: i.e. filtering by account, transaction hash, etc.
43
-
44
- For example, you can easily get the last 5 order of a trader:
45
-
46
- ```js
47
- // i.e. Get last 5 orders for a given trader
48
- const trades = await cowSdk.cowApi.getOrders({
49
- owner: '0x00000000005ef87f8ca7014309ece7260bbcdaeb', // Trader
50
- limit: 5,
51
- offset: 0,
52
- })
53
- console.log(trades)
54
- ```
55
-
56
- > For more information about the API methods, you can check [api.cow.fi/docs](https://api.cow.fi/docs).
57
-
58
- ## Sign and Post orders
59
-
60
- In order to trade, you will need to create a valid order first.
61
-
62
- On the contraty to other decentralised exchanges, creating orders is free in CoW Protocol. This is because, one of the
63
- most common ways to do it is by created offchain signed messages (meta-transactions, uses `EIP-712` or `EIP-1271`).
64
-
65
- Posting orders is a three steps process:
66
-
67
- - 1. **Get Market Pricea**: Fee & Price
68
- - 2. **Sign the order**: Using off-chain signing or Meta-transactions
69
- - 3. **Post the signed order to the API**: So, the order becomes `OPEN`
70
-
71
- The next sections will guide you through the process of creating a valid order.
72
-
73
- > For a quick snippet with the full process on posting an order see the [Post an Order Example](./docs/post-order-example.ts).
9
+ ## Test coverage
74
10
 
75
- ### Enable tokens (token approval)
76
- Because of the use of off-chain signing (meta-transactions), users will need to **Enable the sell token** before signed
77
- orders can be considered as valid ones.
11
+ | Statements | Branches | Functions | Lines |
12
+ | ------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------ | ---------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------- |
13
+ | ![Statements](https://img.shields.io/badge/statements-94.77%25-brightgreen.svg?style=flat) | ![Branches](https://img.shields.io/badge/branches-76.78%25-red.svg?style=flat) | ![Functions](https://img.shields.io/badge/functions-97.43%25-brightgreen.svg?style=flat) | ![Lines](https://img.shields.io/badge/lines-97.67%25-brightgreen.svg?style=flat) |
78
14
 
79
- This enabling is technically an `ERC-20` approval, and is something that needs to be done only once. After this all
80
- order creation can be done for free using offchain signing.
81
-
82
- > For more details see https://docs.cow.fi/tutorials/how-to-submit-orders-via-the-api/1.-set-allowance-for-the-sell-token
83
-
84
- ### Instantiate SDK with a signer
85
-
86
- Before you can sign any transaction, you have to instantiate the SDK with a [Ethers.JS signer](https://docs.ethers.io/v5/api/signer/):
87
-
88
- ```js
89
- import { Wallet } from 'ethers'
90
- import { CowSdk, OrderKind } from '@cowprotocol/cow-sdk'
91
-
92
- const mnemonic = 'fall dirt bread cactus...'
93
- const wallet = Wallet.fromMnemonic(mnemonic)
94
-
95
- const cowSdk = new CowSdk(
96
- 100, { // Leaving chainId empty will default to MAINNET
97
- signer: wallet // Provide a signer, so you can sign order
98
- })
99
- ```
100
-
101
- ### STEP 1: Get Market Price
102
-
103
- To create an order, you need to get a price/fee quote first:
104
-
105
- * The SDK will give you easy access to the API, which returns the `Market Price` and the `Fee` for any given trade you intent to do.
106
- * The returned `Market Price` is not strictly needed, you can use your own pricing logic.
107
- * You can choose a price that is below this Market price (**Market Order**), or above Market Price (**Limit Order**).
108
- * The `Fee` however is very important.
109
- * It is the required amount in sell token the trader agrees on paying for executing the order onchain.
110
- * Normally, its value is proportional to the current Gas Price of the network.
111
- * This fee is never charged if you don't trade.
112
-
113
- To get the quote, you simply specify the trade you intent to do:
114
-
115
- ```js
116
- const quoteResponse = await cowSdk.cowApi.getQuote({
117
- kind: OrderKind.SELL, // Sell order (could also be BUY)
118
- sellToken: '0xc778417e063141139fce010982780140aa0cd5ab', // WETH
119
- buyToken: '0x4dbcdf9b62e891a7cec5a2568c3f4faf9e8abe2b', // USDC
120
- amount: '1000000000000000000', // 1 WETH
121
- userAddress: '0x1811be0994930fe9480eaede25165608b093ad7a', // Trader
122
- validTo: 2524608000,
123
- })
124
-
125
- const { sellToken, buyToken, validTo, buyAmount, sellAmount, receiver, feeAmount } = quoteResponse.quote
126
- ```
127
-
128
- ### STEP 2: Sign the order
129
-
130
- Once you know the price and fee, we can create the order and sign it:
131
-
132
- - Technically the order is just a signed message with your intent to trade, and contains your `Limit Price` and `Fee`.
133
- - As explained before, you can choose your `Limit Price`, but some general approach is to take the current Market Price
134
- and apply some slippage tolerance to it. `Received Amount = Expected Amount * (1 - Slippage Tolerance)`
135
- - The SDK will provide an easy way to sign orders given the raw data
136
-
137
- ```js
138
- const { sellToken, buyToken, validTo, buyAmount, sellAmount, receiver, feeAmount } = quoteResponse.quote
139
-
140
- // Prepare the RAW order
141
- const order = {
142
- kind: OrderKind.SELL, // SELL || BUY
143
- receiver, // Your account or any other
144
- sellToken,
145
- buyToken,
146
-
147
- partiallyFillable: false, // ("false" is for a "Fill or Kill" order, "true" for allowing "Partial execution" which is not supported yet)
148
-
149
- // Deadline
150
- validTo,
151
-
152
- // Limit Price
153
- // You can apply some slippage tolerance here to make sure the trade is executed.
154
- // CoW protocol protects from MEV, so it can work with higher slippages
155
- sellAmount,
156
- buyAmount,
15
+ ## Getting started
157
16
 
158
- // Use the fee you received from the API
159
- feeAmount,
17
+ **Usage examples: [VanillaJS](./examples/vanilla/src/index.ts), [Create React App](./examples/cra/src/pages/getOrders/index.tsx), [NodeJS](./examples/nodejs/src/index.ts)**
160
18
 
161
- // The appData allows you to attach arbitrary information (meta-data) to the order. Its explained in their own section. For now, you can use this 0x0 value
162
- appData: '0x0000000000000000000000000000000000000000000000000000000000000000',
163
- }
19
+ ### Installation
164
20
 
165
- // Sign the order
166
- const signedOrder = await cowSdk.signOrder(order)
21
+ ```bash
22
+ yarn add @cowprotocol/cow-sdk
167
23
  ```
168
24
 
169
- At this point, you have a signed order. So next step will be to post it to the API so it's considered by the solvers and executed.
170
-
171
- ## STEP 3: **Post the signed order to the API**:
25
+ ### Content
172
26
 
173
- Once you have a signed order, last step is to send it to the API.
27
+ - `OrderBookApi` - provides the ability to retrieve orders and trades from the CowSap order-book, as well as add and cancel them
28
+ - `OrderSigningUtils` - serves to sign orders and cancel them using [EIP-712](https://eips.ethereum.org/EIPS/eip-712)
29
+ - `SubgraphApi` - provides statistics data about CoW protocol from [Subgraph](https://github.com/cowprotocol/subgraph), such as trading volume, trades count and others
174
30
 
175
- - The API will accept the order if its correctly signed, the deadline is correct, and the fee is enough to settle it
176
- - Once accepted, the order will be `OPEN` until the specified `validTo` date (expiration)
177
- - The possible outcomes once accepted is:
178
- - The order is `EXECUTED`: you will pay the signed fee, and get at least the `buyAmount` tokens you specified, although you will probably get more! (you will probably get a so-called **Surplus**).
179
- - The order `EXPIRES`: If your price is not good enough, and the order is out of the market price before
180
- expiration, your order will expire. This doesn't have any cost to the user, which **only pays the fee if the trade is executed**.
181
- - You cancel the order, so it becomes `CANCELLED`. Cancelling an order can be done both as a free meta-transaction
182
- (**soft cancelations**) or as a regular on-chain transaction (**hard cancelations**).
183
- - The API will return an `orderId` which identifies the order, and is created as a summary (hash) of it. In other words, the `orderId` is deterministic given all the order parameters.
184
31
 
185
- Post an order using the SDK:
32
+ ```typescript
33
+ import { OrderBookApi, OrderSigningUtils, SubgraphApi } from '@cowprotocol/cow-sdk'
186
34
 
187
- ```js
188
- const orderId = await cowSdk.cowApi.sendOrder({
189
- order: { ...order, ...signedOrder },
190
- owner: '0x1811be0994930fe9480eaede25165608b093ad7a',
191
- })
192
- ```
193
-
194
- ### BONUS: Show link to Explorer
195
- Once the order is posted, its good to allow to check the state of it.
196
-
197
- One easy is to check in the CoW Explorer. You can create a CoW Explorer link if you have the `orderId`:
35
+ const chainId = 100 // Gnosis chain
198
36
 
199
- ```js
200
- // View order in explorer
201
- console.log(`https://explorer.cow.fi/gc/orders/${orderId}`)
37
+ const orderBookApi = new OrderBookApi({ chainId })
38
+ const subgraphApi = new SubgraphApi({ chainId })
39
+ const orderSigningUtils = new OrderSigningUtils()
202
40
  ```
203
41
 
204
- ## Create a meta-data document for attaching to an order
205
-
206
- Orders in CoW Protocol can contain arbitrary data in a field called `AppData`.
207
-
208
- The SDK facilitates the creation of these documents, and getting the `AppData` Hex number that summarizes it.
209
-
210
- The most important thing to define in the meta-data is the name of your app, so the order-flow can be credited to it.
42
+ ## Quick start
211
43
 
212
- ```js
213
- const appDataDoc = cowSdk.metadataApi.generateAppDataDoc({
214
- appDataParams: { appCode: 'YourApp' },
215
- })
216
- ```
44
+ ### Sign, fetch, post and cancel order
217
45
 
218
- This will create a document similar to:
46
+ For clarity, let's look at the use of the API with a practical example:
47
+ Exchanging `0.4 GNO` to `WETH` on `Goerli` network.
219
48
 
220
- ```json
221
- {
222
- "version": "0.4.0",
223
- "appCode": "YourApp",
224
- "metadata": {}
225
- }
226
- ```
49
+ We will do the following operations:
50
+ 1. Get a quote
51
+ 2. Sign the order
52
+ 3. Send the order to the order-book
53
+ 4. Get the data of the created order
54
+ 5. Get trades of the order
55
+ 6. Cancel the order (signing + sending)
227
56
 
228
- After creating the most basic document, you can see how to attach additional meta-data items.
57
+ [You also can check this code in the CRA example](./examples/cra/src/pages/quickStart/index.tsx)
229
58
 
230
- For example, you could give information about who referred the user creating the order.
231
59
 
232
- ```js
233
- const appDataDoc = cowSdk.metadataApi.generateAppDataDoc({
234
- appDataParams: { appCode: 'YourApp' },
235
- metadataParas: {
236
- referrerParams: {
237
- address: '0x1f5B740436Fc5935622e92aa3b46818906F416E9',
238
- },
239
- },
240
- })
241
- ```
60
+ ```typescript
61
+ import { OrderBookApi, OrderSigningUtils, SupportedChainId } from '@cowprotocol/cow-sdk'
62
+ import { Web3Provider } from '@ethersproject/providers'
242
63
 
243
- This will create a document similar to:
64
+ const account = 'YOUR_WALLET_ADDRESS'
65
+ const chainId = 5 // Goerli
66
+ const provider = new Web3Provider(window.ethereum)
67
+ const signer = provider.getSigner()
244
68
 
245
- ```json
246
- {
247
- "version": "0.4.0",
248
- "appCode": "YourApp",
249
- "metadata": {
250
- "referrer": {
251
- "address": "0x1f5B740436Fc5935622e92aa3b46818906F416E9",
252
- "version": "0.1.0"
253
- }
254
- }
69
+ const quoteRequest = {
70
+ sellToken: '0xb4fbf271143f4fbf7b91a5ded31805e42b2208d6', // WETH goerli
71
+ buyToken: '0x02abbdbaaa7b1bb64b5c878f7ac17f8dda169532', // GNO goerli
72
+ from: account,
73
+ receiver: account,
74
+ sellAmountBeforeFee: (0.4 * 10 ** 18).toString(), // 0.4 WETH
75
+ kind: OrderQuoteSide.kind.SELL,
255
76
  }
256
- ```
257
77
 
258
- The method `cowSdk.metadataApi.generateAppDataDoc` will always create the latest schema version.
78
+ const orderBookApi = new OrderBookApi({ chainId: SupportedChainId.GOERLI })
259
79
 
260
- For a complete list of metadata that can be attached and for previous versions
261
- check `@cowprotocol/app-data` [repository](https://github.com/cowprotocol/app-data)
262
- and [NPM package](https://www.npmjs.com/package/@cowprotocol/app-data)
80
+ async function main() {
81
+ const { quote } = await orderBookApi.getQuote(quoteRequest)
263
82
 
264
- ## Get the AppData Hex
83
+ const orderSigningResult = await OrderSigningUtils.signOrder(quote, chainId, signer)
265
84
 
266
- The `AppData` Hex points to an IPFS document with the meta-data attached to the order.
85
+ const orderId = await orderBookApi.sendOrder({ ...quote, ...orderSigningResult })
267
86
 
268
- You can calculate the `AppData` Hex, and its corresponding `cidV0` using the SDK:
87
+ const order = await orderBookApi.getOrder(orderId)
269
88
 
270
- ```js
271
- const { appDataHash, cidv0 } = await cowSdk.metadataApi.calculateAppDataHash(appDataDoc)
272
- ```
273
-
274
- Note how this operation is deterministic, so given the same document, it will always generate the same hash.
89
+ const trades = await orderBookApi.getTrades({ orderId })
275
90
 
276
- This method can be used to calculate the actual hash before uploading the document to IPFS.
91
+ const orderCancellationSigningResult = await OrderSigningUtils.signOrderCancellations([orderId], chainId, signer)
277
92
 
278
- ## Get meta-data document uploaded to IPFS from AppData
93
+ const cancellationResult = await orderBookApi.sendSignedOrderCancellations({...orderCancellationSigningResult, orderUids: [orderId] })
279
94
 
280
- Given the `AppData` of a document that has been uploaded to IPFS, you can easily retrieve the document.
281
-
282
- ```js
283
- const appDataDoc = await cowSdk.metadataApi.decodeAppData(
284
- '0x5ddb2c8207c10b96fac92cb934ef9ba004bc007a073c9e5b13edc422f209ed80'
285
- )
286
- ```
287
-
288
- This will return a document similar to:
289
-
290
- ```json
291
- {
292
- "version": "0.1.0",
293
- "appCode": "YourApp",
294
- "metadata": {
295
- "referrer": {
296
- "address": "0x1f5B740436Fc5935622e92aa3b46818906F416E9",
297
- "version": "0.1.0"
298
- }
299
- }
95
+ console.log('Results: ', { orderId, order, trades, orderCancellationSigningResult, cancellationResult })
300
96
  }
301
97
  ```
98
+ ### Querying the Cow Subgraph
302
99
 
303
- ## Upload document to IPFS
304
-
305
- The SDK uses Pinata to upload it to IPFS, so you will need an API Key in order to upload it using the SDK.
100
+ The [Subgraph](https://github.com/cowprotocol/subgraph) is constantly indexing the protocol, making all the information more accessible. It provides information about trades, users, tokens and settlements. Additionally, it has some data aggregations which provides insights on the hourly/daily/totals USD volumes, trades, users, etc.
306
101
 
307
- Alternatively, you can upload the document on your own using any other service.
308
-
309
- ```js
310
- // Make sure you provide the IPFS params when instantiating the SDK
311
- const cowSdk = new CowSdk(100, {
312
- ipfs: {
313
- pinataApiKey: 'YOUR_PINATA_API_KEY',
314
- pinataApiSecret: 'YOUR_PINATA_API_SECRET',
315
- },
316
- })
317
-
318
- // Upload to IPFS
319
- const uploadedAppDataHash = await cowSdk.metadataApi.uploadMetadataDocToIpfs(appDataDoc)
320
- ```
321
-
322
- ## Convert IPFS CIDv0 to AppData (and back)
323
- Given an IPFS CIDv0 you can convert it to an `AppData`
324
-
325
- ```js
326
- const decodedAppDataHex = await cowSdk.metadataApi.cidToAppDataHex('QmUf2TrpSANVXdgcYfAAACe6kg551cY3rAemB7xfEMjYvs')
327
- ```
328
-
329
- This will return an `AppData` hex: `0x5ddb2c8207c10b96fac92cb934ef9ba004bc007a073c9e5b13edc422f209ed80`
330
-
331
- > This might be handy if you decide to upload the document to IPFS yourself and then you need the AppData to post your order
332
-
333
- Similarly, you can do the opposite and convert an `AppData` into an IPFS document:
334
-
335
- ```js
336
- const decodedAppDataHex = await cowSdk.metadataApi.appDataHexToCid(hash)
337
- ```
338
-
339
- This will return an IPFS CIDv0: `QmUf2TrpSANVXdgcYfAAACe6kg551cY3rAemB7xfEMjYvs`
340
-
341
- ## Getting appData schema files
342
-
343
- It's possible to get schema files directly for each exported version using `getAppDataSchema`
344
-
345
- ```js
346
- const schema = await cowSdk.metadataApi.getAppDataSchema('0.4.0')
347
- ```
348
-
349
- ## Validating appDataDocs
350
-
351
- If for some reason you decide to create an `appDataDoc` without using the helper function, you can use `validateAppDataDoc` to validate it against the schema
352
-
353
- ```js
354
- const { success, error } = await cowSdk.metadataApi.validateAppDataDoc({ version: '0.1.0', ... })
355
- ```
356
-
357
- ## Querying the Cow Subgraph
102
+ The SDK provides just an easy way to access all this information.
358
103
 
359
104
  You can query the Cow Subgraph either by running some common queries exposed by the `CowSubgraphApi` or by building your own ones:
360
105
 
361
- ```js
362
- const chainId = 1 // Mainnet
363
- const cowSdk = new CowSdk(chainId)
106
+ ```typescript
107
+ import { SubgraphApi, SupportedChainId } from '@cowprotocol/cow-sdk'
364
108
 
365
- // Get Cow Protocol totals
109
+ const subgraphApi = new SubgraphApi({ chainId: SupportedChainId.MAINNET })
110
+
111
+ // Get CoW Protocol totals
366
112
  const { tokens, orders, traders, settlements, volumeUsd, volumeEth, feesUsd, feesEth } =
367
- await cowSdk.cowSubgraphApi.getTotals()
113
+ await csubgraphApi.getTotals()
368
114
  console.log({ tokens, orders, traders, settlements, volumeUsd, volumeEth, feesUsd, feesEth })
369
115
 
370
116
  // Get last 24 hours volume in usd
371
- const { hourlyTotals } = await cowSdk.cowSubgraphApi.getLastHoursVolume(24)
117
+ const { hourlyTotals } = await cowSubgraphApi.getLastHoursVolume(24)
372
118
  console.log(hourlyTotals)
373
119
 
374
120
  // Get last week volume in usd
375
- const { dailyTotals } = await cowSdk.cowSubgraphApi.getLastDaysVolume(7)
121
+ const { dailyTotals } = await cowSubgraphApi.getLastDaysVolume(7)
376
122
  console.log(dailyTotals)
377
123
 
378
124
  // Get the last 5 batches
@@ -385,10 +131,19 @@ const query = `
385
131
  }
386
132
  `
387
133
  const variables = { n: 5 }
388
- const response = await cowSdk.cowSubgraphApi.runQuery(query, variables)
134
+ const response = await cowSubgraphApi.runQuery(query, variables)
389
135
  console.log(response)
390
136
  ```
391
137
 
138
+
139
+ ## Architecture
140
+
141
+ One way to make the most out of the SDK is to get familiar to its architecture.
142
+
143
+ > See [SDK Architecture](./docs/architecture.md)
144
+
145
+ ## Development
146
+
392
147
  ### Install Dependencies
393
148
 
394
149
  ```bash
@@ -409,3 +164,12 @@ yarn start
409
164
  ```bash
410
165
  yarn test
411
166
  ```
167
+
168
+ ### Code generation
169
+
170
+ Some parets of the SDK are automatically generated. This is the case for the Order Book APU and the Subgraph API
171
+
172
+ ```bash
173
+ # Re-create automatically generated code
174
+ yarn codegen
175
+ ```