@cowprotocol/cow-sdk 2.0.0-alpha.6 → 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 +88 -74
- package/dist/README.md +88 -74
- package/dist/index-5242792d.js +29 -0
- package/dist/{index-c9cad3d4.js.map → index-5242792d.js.map} +1 -1
- package/dist/index.js +2 -2
- package/dist/index.js.map +1 -1
- package/dist/index.modern.mjs +1 -1
- package/dist/index.module.js +2 -2
- package/dist/index.module.js.map +1 -1
- package/dist/order-book/api.d.ts +1 -0
- package/dist/order-signing/orderSigningUtils.d.ts +1 -1
- package/dist/order-signing/types.d.ts +1 -1
- package/dist/order-signing/utils.d.ts +1 -1
- package/dist/package.json +3 -1
- package/dist/{utils-474dc9c3.js → utils-1a21c973.js} +2 -2
- package/dist/utils-1a21c973.js.map +1 -0
- package/dist/utils-72280006.js +2 -0
- package/dist/utils-72280006.js.map +1 -0
- package/dist/utils-f7284bac.js +2 -0
- package/dist/utils-f7284bac.js.map +1 -0
- package/package.json +3 -1
- package/dist/index-c9cad3d4.js +0 -29
- package/dist/utils-204fe1d3.js +0 -2
- package/dist/utils-204fe1d3.js.map +0 -1
- package/dist/utils-474dc9c3.js.map +0 -1
- package/dist/utils-fa9c8b98.js +0 -2
- package/dist/utils-fa9c8b98.js.map +0 -1
package/README.md
CHANGED
|
@@ -4,6 +4,8 @@
|
|
|
4
4
|
|
|
5
5
|
# CoW SDK
|
|
6
6
|
|
|
7
|
+
## 📚 [SDK docs website](https://docs.cow.fi/cow-sdk)
|
|
8
|
+
|
|
7
9
|
## Test coverage
|
|
8
10
|
|
|
9
11
|
| Statements | Branches | Functions | Lines |
|
|
@@ -12,121 +14,133 @@
|
|
|
12
14
|
|
|
13
15
|
## Getting started
|
|
14
16
|
|
|
15
|
-
|
|
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)**
|
|
18
|
+
|
|
19
|
+
### Installation
|
|
16
20
|
|
|
17
21
|
```bash
|
|
18
22
|
yarn add @cowprotocol/cow-sdk
|
|
19
23
|
```
|
|
20
24
|
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
```js
|
|
24
|
-
import { CowSdk } from '@cowprotocol/cow-sdk'
|
|
25
|
-
|
|
26
|
-
const chainId = 100 // Gnosis chain
|
|
27
|
-
const cowSdk = new CowSdk(chainId)
|
|
28
|
-
```
|
|
25
|
+
### Content
|
|
29
26
|
|
|
30
|
-
|
|
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
|
|
31
30
|
|
|
32
|
-
- The CoW API (`cowSdk.cowApi`)
|
|
33
|
-
- The CoW Subgraph (`cowSdk.cowSubgraphApi`)
|
|
34
|
-
- Convenient method to facilitate signing orders (i.e `cowSdk.signOrder`)
|
|
35
31
|
|
|
36
|
-
|
|
32
|
+
```typescript
|
|
33
|
+
import { OrderBookApi, OrderSigningUtils, SubgraphApi } from '@cowprotocol/cow-sdk'
|
|
37
34
|
|
|
38
|
-
|
|
35
|
+
const chainId = 100 // Gnosis chain
|
|
39
36
|
|
|
40
|
-
|
|
37
|
+
const orderBookApi = new OrderBookApi({ chainId })
|
|
38
|
+
const subgraphApi = new SubgraphApi({ chainId })
|
|
39
|
+
const orderSigningUtils = new OrderSigningUtils()
|
|
40
|
+
```
|
|
41
41
|
|
|
42
|
-
|
|
43
|
-
- Get fee quotes
|
|
44
|
-
- Get order details
|
|
45
|
-
- Get history of orders: i.e. filtering by account, transaction hash, etc.
|
|
42
|
+
## Quick start
|
|
46
43
|
|
|
47
|
-
|
|
44
|
+
### Sign, fetch, post and cancel order
|
|
48
45
|
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
const trades = await cowSdk.cowApi.getOrders({
|
|
52
|
-
owner: '0x00000000005ef87f8ca7014309ece7260bbcdaeb', // Trader
|
|
53
|
-
limit: 5,
|
|
54
|
-
offset: 0,
|
|
55
|
-
})
|
|
56
|
-
console.log(trades)
|
|
57
|
-
```
|
|
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.
|
|
58
48
|
|
|
59
|
-
|
|
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)
|
|
60
56
|
|
|
61
|
-
|
|
62
|
-
- The CoW Subgraph (`cowSdk.cowSubgraphApi`)
|
|
63
|
-
- Convenient method to facilitate signing orders (i.e `cowSdk.signOrder`)
|
|
57
|
+
[You also can check this code in the CRA example](./examples/cra/src/pages/quickStart/index.tsx)
|
|
64
58
|
|
|
65
|
-
> ✨ For a quick snippet with the full process on posting an order see the [Post an Order Example](./docs/post-order-example.ts)
|
|
66
59
|
|
|
67
|
-
|
|
60
|
+
```typescript
|
|
61
|
+
import { OrderBookApi, OrderSigningUtils, SupportedChainId } from '@cowprotocol/cow-sdk'
|
|
62
|
+
import { Web3Provider } from '@ethersproject/providers'
|
|
68
63
|
|
|
69
|
-
|
|
64
|
+
const account = 'YOUR_WALLET_ADDRESS'
|
|
65
|
+
const chainId = 5 // Goerli
|
|
66
|
+
const provider = new Web3Provider(window.ethereum)
|
|
67
|
+
const signer = provider.getSigner()
|
|
70
68
|
|
|
71
|
-
|
|
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,
|
|
76
|
+
}
|
|
72
77
|
|
|
73
|
-
|
|
78
|
+
const orderBookApi = new OrderBookApi({ chainId: SupportedChainId.GOERLI })
|
|
74
79
|
|
|
75
|
-
|
|
80
|
+
async function main() {
|
|
81
|
+
const { quote } = await orderBookApi.getQuote(quoteRequest)
|
|
76
82
|
|
|
77
|
-
|
|
83
|
+
const orderSigningResult = await OrderSigningUtils.signOrder(quote, chainId, signer)
|
|
78
84
|
|
|
79
|
-
|
|
80
|
-
- Get fee quotes
|
|
81
|
-
- Get order details
|
|
82
|
-
- Get history of orders: i.e. filtering by account, transaction hash, etc.
|
|
85
|
+
const orderId = await orderBookApi.sendOrder({ ...quote, ...orderSigningResult })
|
|
83
86
|
|
|
84
|
-
|
|
87
|
+
const order = await orderBookApi.getOrder(orderId)
|
|
85
88
|
|
|
86
|
-
|
|
89
|
+
const trades = await orderBookApi.getTrades({ orderId })
|
|
87
90
|
|
|
88
|
-
|
|
91
|
+
const orderCancellationSigningResult = await OrderSigningUtils.signOrderCancellations([orderId], chainId, signer)
|
|
89
92
|
|
|
90
|
-
|
|
91
|
-
most common ways to do it is by created offchain signed messages (meta-transactions, uses `EIP-712` or `EIP-1271`).
|
|
93
|
+
const cancellationResult = await orderBookApi.sendSignedOrderCancellations({...orderCancellationSigningResult, orderUids: [orderId] })
|
|
92
94
|
|
|
93
|
-
|
|
95
|
+
console.log('Results: ', { orderId, order, trades, orderCancellationSigningResult, cancellationResult })
|
|
96
|
+
}
|
|
97
|
+
```
|
|
98
|
+
### Querying the Cow Subgraph
|
|
94
99
|
|
|
95
|
-
|
|
96
|
-
- 2. **Sign the order**: Using off-chain signing or Meta-transactions
|
|
97
|
-
- 3. **Post the signed order to the API**: So, the order becomes `OPEN`
|
|
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.
|
|
98
101
|
|
|
99
|
-
The
|
|
102
|
+
The SDK provides just an easy way to access all this information.
|
|
100
103
|
|
|
101
|
-
|
|
104
|
+
You can query the Cow Subgraph either by running some common queries exposed by the `CowSubgraphApi` or by building your own ones:
|
|
102
105
|
|
|
103
|
-
|
|
106
|
+
```typescript
|
|
107
|
+
import { SubgraphApi, SupportedChainId } from '@cowprotocol/cow-sdk'
|
|
104
108
|
|
|
105
|
-
|
|
109
|
+
const subgraphApi = new SubgraphApi({ chainId: SupportedChainId.MAINNET })
|
|
106
110
|
|
|
107
|
-
|
|
111
|
+
// Get CoW Protocol totals
|
|
112
|
+
const { tokens, orders, traders, settlements, volumeUsd, volumeEth, feesUsd, feesEth } =
|
|
113
|
+
await csubgraphApi.getTotals()
|
|
114
|
+
console.log({ tokens, orders, traders, settlements, volumeUsd, volumeEth, feesUsd, feesEth })
|
|
108
115
|
|
|
109
|
-
|
|
116
|
+
// Get last 24 hours volume in usd
|
|
117
|
+
const { hourlyTotals } = await cowSubgraphApi.getLastHoursVolume(24)
|
|
118
|
+
console.log(hourlyTotals)
|
|
110
119
|
|
|
111
|
-
|
|
120
|
+
// Get last week volume in usd
|
|
121
|
+
const { dailyTotals } = await cowSubgraphApi.getLastDaysVolume(7)
|
|
122
|
+
console.log(dailyTotals)
|
|
112
123
|
|
|
113
|
-
|
|
114
|
-
const
|
|
115
|
-
|
|
116
|
-
|
|
124
|
+
// Get the last 5 batches
|
|
125
|
+
const query = `
|
|
126
|
+
query LastBatches($n: Int!) {
|
|
127
|
+
settlements(orderBy: firstTradeTimestamp, orderDirection: desc, first: $n) {
|
|
128
|
+
txHash
|
|
129
|
+
firstTradeTimestamp
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
`
|
|
133
|
+
const variables = { n: 5 }
|
|
134
|
+
const response = await cowSubgraphApi.runQuery(query, variables)
|
|
135
|
+
console.log(response)
|
|
117
136
|
```
|
|
118
137
|
|
|
119
|
-
This will create a document similar to:
|
|
120
138
|
|
|
121
|
-
|
|
122
|
-
{
|
|
123
|
-
"version": "0.4.0",
|
|
124
|
-
"appCode": "YourApp",
|
|
125
|
-
"metadata": {}
|
|
126
|
-
}
|
|
127
|
-
```
|
|
139
|
+
## Architecture
|
|
128
140
|
|
|
129
|
-
|
|
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)
|
|
130
144
|
|
|
131
145
|
## Development
|
|
132
146
|
|
package/dist/README.md
CHANGED
|
@@ -4,6 +4,8 @@
|
|
|
4
4
|
|
|
5
5
|
# CoW SDK
|
|
6
6
|
|
|
7
|
+
## 📚 [SDK docs website](https://docs.cow.fi/cow-sdk)
|
|
8
|
+
|
|
7
9
|
## Test coverage
|
|
8
10
|
|
|
9
11
|
| Statements | Branches | Functions | Lines |
|
|
@@ -12,121 +14,133 @@
|
|
|
12
14
|
|
|
13
15
|
## Getting started
|
|
14
16
|
|
|
15
|
-
|
|
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)**
|
|
18
|
+
|
|
19
|
+
### Installation
|
|
16
20
|
|
|
17
21
|
```bash
|
|
18
22
|
yarn add @cowprotocol/cow-sdk
|
|
19
23
|
```
|
|
20
24
|
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
```js
|
|
24
|
-
import { CowSdk } from '@cowprotocol/cow-sdk'
|
|
25
|
-
|
|
26
|
-
const chainId = 100 // Gnosis chain
|
|
27
|
-
const cowSdk = new CowSdk(chainId)
|
|
28
|
-
```
|
|
25
|
+
### Content
|
|
29
26
|
|
|
30
|
-
|
|
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
|
|
31
30
|
|
|
32
|
-
- The CoW API (`cowSdk.cowApi`)
|
|
33
|
-
- The CoW Subgraph (`cowSdk.cowSubgraphApi`)
|
|
34
|
-
- Convenient method to facilitate signing orders (i.e `cowSdk.signOrder`)
|
|
35
31
|
|
|
36
|
-
|
|
32
|
+
```typescript
|
|
33
|
+
import { OrderBookApi, OrderSigningUtils, SubgraphApi } from '@cowprotocol/cow-sdk'
|
|
37
34
|
|
|
38
|
-
|
|
35
|
+
const chainId = 100 // Gnosis chain
|
|
39
36
|
|
|
40
|
-
|
|
37
|
+
const orderBookApi = new OrderBookApi({ chainId })
|
|
38
|
+
const subgraphApi = new SubgraphApi({ chainId })
|
|
39
|
+
const orderSigningUtils = new OrderSigningUtils()
|
|
40
|
+
```
|
|
41
41
|
|
|
42
|
-
|
|
43
|
-
- Get fee quotes
|
|
44
|
-
- Get order details
|
|
45
|
-
- Get history of orders: i.e. filtering by account, transaction hash, etc.
|
|
42
|
+
## Quick start
|
|
46
43
|
|
|
47
|
-
|
|
44
|
+
### Sign, fetch, post and cancel order
|
|
48
45
|
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
const trades = await cowSdk.cowApi.getOrders({
|
|
52
|
-
owner: '0x00000000005ef87f8ca7014309ece7260bbcdaeb', // Trader
|
|
53
|
-
limit: 5,
|
|
54
|
-
offset: 0,
|
|
55
|
-
})
|
|
56
|
-
console.log(trades)
|
|
57
|
-
```
|
|
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.
|
|
58
48
|
|
|
59
|
-
|
|
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)
|
|
60
56
|
|
|
61
|
-
|
|
62
|
-
- The CoW Subgraph (`cowSdk.cowSubgraphApi`)
|
|
63
|
-
- Convenient method to facilitate signing orders (i.e `cowSdk.signOrder`)
|
|
57
|
+
[You also can check this code in the CRA example](./examples/cra/src/pages/quickStart/index.tsx)
|
|
64
58
|
|
|
65
|
-
> ✨ For a quick snippet with the full process on posting an order see the [Post an Order Example](./docs/post-order-example.ts)
|
|
66
59
|
|
|
67
|
-
|
|
60
|
+
```typescript
|
|
61
|
+
import { OrderBookApi, OrderSigningUtils, SupportedChainId } from '@cowprotocol/cow-sdk'
|
|
62
|
+
import { Web3Provider } from '@ethersproject/providers'
|
|
68
63
|
|
|
69
|
-
|
|
64
|
+
const account = 'YOUR_WALLET_ADDRESS'
|
|
65
|
+
const chainId = 5 // Goerli
|
|
66
|
+
const provider = new Web3Provider(window.ethereum)
|
|
67
|
+
const signer = provider.getSigner()
|
|
70
68
|
|
|
71
|
-
|
|
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,
|
|
76
|
+
}
|
|
72
77
|
|
|
73
|
-
|
|
78
|
+
const orderBookApi = new OrderBookApi({ chainId: SupportedChainId.GOERLI })
|
|
74
79
|
|
|
75
|
-
|
|
80
|
+
async function main() {
|
|
81
|
+
const { quote } = await orderBookApi.getQuote(quoteRequest)
|
|
76
82
|
|
|
77
|
-
|
|
83
|
+
const orderSigningResult = await OrderSigningUtils.signOrder(quote, chainId, signer)
|
|
78
84
|
|
|
79
|
-
|
|
80
|
-
- Get fee quotes
|
|
81
|
-
- Get order details
|
|
82
|
-
- Get history of orders: i.e. filtering by account, transaction hash, etc.
|
|
85
|
+
const orderId = await orderBookApi.sendOrder({ ...quote, ...orderSigningResult })
|
|
83
86
|
|
|
84
|
-
|
|
87
|
+
const order = await orderBookApi.getOrder(orderId)
|
|
85
88
|
|
|
86
|
-
|
|
89
|
+
const trades = await orderBookApi.getTrades({ orderId })
|
|
87
90
|
|
|
88
|
-
|
|
91
|
+
const orderCancellationSigningResult = await OrderSigningUtils.signOrderCancellations([orderId], chainId, signer)
|
|
89
92
|
|
|
90
|
-
|
|
91
|
-
most common ways to do it is by created offchain signed messages (meta-transactions, uses `EIP-712` or `EIP-1271`).
|
|
93
|
+
const cancellationResult = await orderBookApi.sendSignedOrderCancellations({...orderCancellationSigningResult, orderUids: [orderId] })
|
|
92
94
|
|
|
93
|
-
|
|
95
|
+
console.log('Results: ', { orderId, order, trades, orderCancellationSigningResult, cancellationResult })
|
|
96
|
+
}
|
|
97
|
+
```
|
|
98
|
+
### Querying the Cow Subgraph
|
|
94
99
|
|
|
95
|
-
|
|
96
|
-
- 2. **Sign the order**: Using off-chain signing or Meta-transactions
|
|
97
|
-
- 3. **Post the signed order to the API**: So, the order becomes `OPEN`
|
|
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.
|
|
98
101
|
|
|
99
|
-
The
|
|
102
|
+
The SDK provides just an easy way to access all this information.
|
|
100
103
|
|
|
101
|
-
|
|
104
|
+
You can query the Cow Subgraph either by running some common queries exposed by the `CowSubgraphApi` or by building your own ones:
|
|
102
105
|
|
|
103
|
-
|
|
106
|
+
```typescript
|
|
107
|
+
import { SubgraphApi, SupportedChainId } from '@cowprotocol/cow-sdk'
|
|
104
108
|
|
|
105
|
-
|
|
109
|
+
const subgraphApi = new SubgraphApi({ chainId: SupportedChainId.MAINNET })
|
|
106
110
|
|
|
107
|
-
|
|
111
|
+
// Get CoW Protocol totals
|
|
112
|
+
const { tokens, orders, traders, settlements, volumeUsd, volumeEth, feesUsd, feesEth } =
|
|
113
|
+
await csubgraphApi.getTotals()
|
|
114
|
+
console.log({ tokens, orders, traders, settlements, volumeUsd, volumeEth, feesUsd, feesEth })
|
|
108
115
|
|
|
109
|
-
|
|
116
|
+
// Get last 24 hours volume in usd
|
|
117
|
+
const { hourlyTotals } = await cowSubgraphApi.getLastHoursVolume(24)
|
|
118
|
+
console.log(hourlyTotals)
|
|
110
119
|
|
|
111
|
-
|
|
120
|
+
// Get last week volume in usd
|
|
121
|
+
const { dailyTotals } = await cowSubgraphApi.getLastDaysVolume(7)
|
|
122
|
+
console.log(dailyTotals)
|
|
112
123
|
|
|
113
|
-
|
|
114
|
-
const
|
|
115
|
-
|
|
116
|
-
|
|
124
|
+
// Get the last 5 batches
|
|
125
|
+
const query = `
|
|
126
|
+
query LastBatches($n: Int!) {
|
|
127
|
+
settlements(orderBy: firstTradeTimestamp, orderDirection: desc, first: $n) {
|
|
128
|
+
txHash
|
|
129
|
+
firstTradeTimestamp
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
`
|
|
133
|
+
const variables = { n: 5 }
|
|
134
|
+
const response = await cowSubgraphApi.runQuery(query, variables)
|
|
135
|
+
console.log(response)
|
|
117
136
|
```
|
|
118
137
|
|
|
119
|
-
This will create a document similar to:
|
|
120
138
|
|
|
121
|
-
|
|
122
|
-
{
|
|
123
|
-
"version": "0.4.0",
|
|
124
|
-
"appCode": "YourApp",
|
|
125
|
-
"metadata": {}
|
|
126
|
-
}
|
|
127
|
-
```
|
|
139
|
+
## Architecture
|
|
128
140
|
|
|
129
|
-
|
|
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)
|
|
130
144
|
|
|
131
145
|
## Development
|
|
132
146
|
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import"cross-fetch/polyfill";import{gql as e,request as t}from"graphql-request";var r;!function(e){e[e.MAINNET=1]="MAINNET",e[e.GOERLI=5]="GOERLI",e[e.GNOSIS_CHAIN=100]="GNOSIS_CHAIN"}(r||(r={}));const s=["prod","staging"],o={env:"prod",chainId:r.MAINNET};class n extends Error{constructor(e,t){super(e),this.error_code=void 0,this.error_code=t}}const i="cow-sdk:",a="https://gnosis.mypinata.cloud/ipfs",c="https://api.pinata.cloud";function d(){return d=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var s in r)Object.prototype.hasOwnProperty.call(r,s)&&(e[s]=r[s])}return e},d.apply(this,arguments)}class u{constructor(e){this.config=void 0,this.config=e}}class l extends Error{constructor(e,t,r){super(r),this.url=void 0,this.status=void 0,this.statusText=void 0,this.body=void 0,this.request=void 0,this.name="ApiError",this.url=t.url,this.status=t.status,this.statusText=t.statusText,this.body=t.body,this.request=e}}let h;class p extends Error{constructor(e){super(e),this.name="CancelError"}get isCancelled(){return!0}}h=Symbol.toStringTag;class E{constructor(e){this[h]=void 0,this._isResolved=void 0,this._isRejected=void 0,this._isCancelled=void 0,this._cancelHandlers=void 0,this._promise=void 0,this._resolve=void 0,this._reject=void 0,this._isResolved=!1,this._isRejected=!1,this._isCancelled=!1,this._cancelHandlers=[],this._promise=new Promise((t,r)=>{this._resolve=t,this._reject=r;const s=e=>{this._isResolved||this._isRejected||this._isCancelled||this._cancelHandlers.push(e)};return Object.defineProperty(s,"isResolved",{get:()=>this._isResolved}),Object.defineProperty(s,"isRejected",{get:()=>this._isRejected}),Object.defineProperty(s,"isCancelled",{get:()=>this._isCancelled}),e(e=>{var t;this._isResolved||this._isRejected||this._isCancelled||(this._isResolved=!0,null==(t=this._resolve)||t.call(this,e))},e=>{var t;this._isResolved||this._isRejected||this._isCancelled||(this._isRejected=!0,null==(t=this._reject)||t.call(this,e))},s)})}then(e,t){return this._promise.then(e,t)}catch(e){return this._promise.catch(e)}finally(e){return this._promise.finally(e)}cancel(){var e;if(!(this._isResolved||this._isRejected||this._isCancelled)){if(this._isCancelled=!0,this._cancelHandlers.length)try{for(const e of this._cancelHandlers)e()}catch(e){return void console.warn("Cancellation threw an error",e)}this._cancelHandlers.length=0,null==(e=this._reject)||e.call(this,new p("Request aborted"))}}get isCancelled(){return this._isCancelled}}const T=e=>null!=e,O=e=>"string"==typeof e,N=e=>O(e)&&""!==e,_=e=>"object"==typeof e&&"string"==typeof e.type&&"function"==typeof e.stream&&"function"==typeof e.arrayBuffer&&"function"==typeof e.constructor&&"string"==typeof e.constructor.name&&/^(Blob|File)$/.test(e.constructor.name)&&/^(Blob|File)$/.test(e[Symbol.toStringTag]),I=e=>e instanceof FormData,A=async(e,t)=>"function"==typeof t?t(e):t,f=async(e,t)=>{const r=await A(t,e.TOKEN),s=await A(t,e.USERNAME),o=await A(t,e.PASSWORD),n=await A(t,e.HEADERS),i=Object.entries(d({Accept:"application/json"},n,t.headers)).filter(([e,t])=>T(t)).reduce((e,[t,r])=>d({},e,{[t]:String(r)}),{});if(N(r)&&(i.Authorization=`Bearer ${r}`),N(s)&&N(o)){const e=(e=>{try{return btoa(e)}catch(t){return Buffer.from(e).toString("base64")}})(`${s}:${o}`);i.Authorization=`Basic ${e}`}return t.body&&(t.mediaType?i["Content-Type"]=t.mediaType:_(t.body)?i["Content-Type"]=t.body.type||"application/octet-stream":O(t.body)?i["Content-Type"]="text/plain":I(t.body)||(i["Content-Type"]="application/json")),new Headers(i)},R=(e,t)=>new E(async(r,s,o)=>{try{const s=((e,t)=>{const r=e.ENCODE_PATH||encodeURI,s=t.url.replace("{api-version}",e.VERSION).replace(/{(.*?)}/g,(e,s)=>{var o;return null!=(o=t.path)&&o.hasOwnProperty(s)?r(String(t.path[s])):e}),o=`${e.BASE}${s}`;return t.query?`${o}${(e=>{const t=[],r=(e,s)=>{T(s)&&(Array.isArray(s)?s.forEach(t=>{r(e,t)}):"object"==typeof s?Object.entries(s).forEach(([t,s])=>{r(`${e}[${t}]`,s)}):((e,r)=>{t.push(`${encodeURIComponent(e)}=${encodeURIComponent(String(r))}`)})(e,s))};return Object.entries(e).forEach(([e,t])=>{r(e,t)}),t.length>0?`?${t.join("&")}`:""})(t.query)}`:o})(e,t),n=(e=>{if(e.formData){const t=new FormData,r=(e,r)=>{O(r)||_(r)?t.append(e,r):t.append(e,JSON.stringify(r))};return Object.entries(e.formData).filter(([e,t])=>T(t)).forEach(([e,t])=>{Array.isArray(t)?t.forEach(t=>r(e,t)):r(e,t)}),t}})(t),i=(e=>{var t;if(e.body)return null!=(t=e.mediaType)&&t.includes("/json")?JSON.stringify(e.body):O(e.body)||_(e.body)||I(e.body)?e.body:JSON.stringify(e.body)})(t),a=await f(e,t);if(!o.isCancelled){const c=await(async(e,t,r,s,o,n,i)=>{const a=new AbortController,c={headers:n,body:null!=s?s:o,method:t.method,signal:a.signal};return e.WITH_CREDENTIALS&&(c.credentials=e.CREDENTIALS),i(()=>a.abort()),await fetch(r,c)})(e,t,s,i,n,a,o),u=await(async e=>{if(204!==e.status)try{const t=e.headers.get("Content-Type");if(t)return t.toLowerCase().startsWith("application/json")?await e.json():await e.text()}catch(e){console.error(e)}})(c),h=((e,t)=>{if(t){const r=e.headers.get(t);if(O(r))return r}})(c,t.responseHeader),p={url:s,ok:c.ok,status:c.status,statusText:c.statusText,body:null!=h?h:u};((e,t)=>{const r=d({400:"Bad Request",401:"Unauthorized",403:"Forbidden",404:"Not Found",500:"Internal Server Error",502:"Bad Gateway",503:"Service Unavailable"},e.errors)[t.status];if(r)throw new l(e,t,r);if(!t.ok)throw new l(e,t,"Generic Error")})(t,p),r(p.body)}}catch(e){s(e)}});class g extends u{constructor(e){super(e)}request(e){return R(this.config,e)}}class S{constructor(e){this.httpRequest=void 0,this.httpRequest=e}postApiV1Orders(e){return this.httpRequest.request({method:"POST",url:"/api/v1/orders",body:e,mediaType:"application/json",errors:{400:"Error during order validation",403:"Forbidden, your account is deny-listed",429:"Too many order placements",500:"Error adding an order"}})}deleteApiV1Orders(e){return this.httpRequest.request({method:"DELETE",url:"/api/v1/orders",body:e,mediaType:"application/json",errors:{400:"Malformed signature",401:"Invalid signature",404:"One or more orders were not found and no orders were cancelled."}})}getApiV1Orders(e){return this.httpRequest.request({method:"GET",url:"/api/v1/orders/{UID}",path:{UID:e},errors:{404:"Order was not found"}})}deleteApiV1Orders1(e,t){return this.httpRequest.request({method:"DELETE",url:"/api/v1/orders/{UID}",path:{UID:e},body:t,mediaType:"application/json",errors:{400:"Malformed signature",401:"Invalid signature",404:"Order was not found"}})}patchApiV1Orders(e,t){return this.httpRequest.request({method:"PATCH",url:"/api/v1/orders/{UID}",path:{UID:e},body:t,mediaType:"application/json",errors:{400:"Error cancelling and replacing new order with an old one.",401:"Invalid replacement order. This can happen if the old and new orders have\n different signers, the new order's app data is not an encoded cancellation of\n the old order, or the new order is based on presign or EIP-1271 signatures.\n ",403:"Forbidden",404:"Order was not found"}})}getApiV1TransactionsOrders(e){return this.httpRequest.request({method:"GET",url:"/api/v1/transactions/{txHash}/orders",path:{txHash:e}})}getApiV1Trades(e,t){return this.httpRequest.request({method:"GET",url:"/api/v1/trades",query:{owner:e,orderUid:t}})}getApiV1Auction(){return this.httpRequest.request({method:"GET",url:"/api/v1/auction"})}getApiV1AccountOrders(e,t,r){return this.httpRequest.request({method:"GET",url:"/api/v1/account/{owner}/orders",path:{owner:e},query:{offset:t,limit:r},errors:{400:"Problem with parameters like limit being too large."}})}getApiV1TokenNativePrice(e){return this.httpRequest.request({method:"GET",url:"/api/v1/token/{token}/native_price",path:{token:e},errors:{400:"Error finding the price.",404:"No liquidity was found",500:"Unexpected error"}})}postApiV1Quote(e){return this.httpRequest.request({method:"POST",url:"/api/v1/quote",body:e,mediaType:"application/json",errors:{400:"Error quoting order.",403:"Forbidden, your account is deny-listed",429:"Too many order quotes",500:"Unexpected error quoting an order"}})}getApiV1SolverCompetition(e){return this.httpRequest.request({method:"GET",url:"/api/v1/solver_competition/{auction_id}",path:{auction_id:e},errors:{404:"No competition information available for this auction id."}})}getApiV1SolverCompetitionByTxHash(e){return this.httpRequest.request({method:"GET",url:"/api/v1/solver_competition/by_tx_hash/{tx_hash}",path:{tx_hash:e},errors:{404:"No competition information available for this tx hash."}})}getApiV1Version(){return this.httpRequest.request({method:"GET",url:"/api/v1/version"})}}class y{constructor(e,t=g){var r,s,o,n;this.default=void 0,this.request=void 0,this.request=new t({BASE:null!==(r=null==e?void 0:e.BASE)&&void 0!==r?r:"https://api.cow.fi/mainnet",VERSION:null!==(s=null==e?void 0:e.VERSION)&&void 0!==s?s:"0.0.1",WITH_CREDENTIALS:null!==(o=null==e?void 0:e.WITH_CREDENTIALS)&&void 0!==o&&o,CREDENTIALS:null!==(n=null==e?void 0:e.CREDENTIALS)&&void 0!==n?n:"include",TOKEN:null==e?void 0:e.TOKEN,USERNAME:null==e?void 0:e.USERNAME,PASSWORD:null==e?void 0:e.PASSWORD,HEADERS:null==e?void 0:e.HEADERS,ENCODE_PATH:null==e?void 0:e.ENCODE_PATH}),this.default=new S(this.request)}}const v={BASE:"https://api.cow.fi/mainnet",VERSION:"0.0.1",WITH_CREDENTIALS:!1,CREDENTIALS:"include",TOKEN:void 0,USERNAME:void 0,PASSWORD:void 0,HEADERS:void 0,ENCODE_PATH:void 0};var m,C,U,D,w,L,b,P,F,q,x,V,j,k;!function(e){e.ERC20="erc20",e.INTERNAL="internal"}(m||(m={})),function(e){e.EIP712="eip712",e.ETHSIGN="ethsign"}(C||(C={})),function(e){var t;(t=e.errorType||(e.errorType={})).NO_LIQUIDITY="NoLiquidity",t.UNSUPPORTED_TOKEN="UnsupportedToken",t.AMOUNT_IS_ZERO="AmountIsZero",t.SELL_AMOUNT_DOES_NOT_COVER_FEE="SellAmountDoesNotCoverFee"}(U||(U={})),function(e){var t;(t=e.placementError||(e.placementError={})).QUOTE_NOT_FOUND="QuoteNotFound",t.VALID_TO_TOO_FAR_IN_FUTURE="ValidToTooFarInFuture",t.PRE_VALIDATION_ERROR="PreValidationError"}(D||(D={})),function(e){var t;(t=e.errorType||(e.errorType={})).INVALID_SIGNATURE="InvalidSignature",t.WRONG_OWNER="WrongOwner",t.ORDER_NOT_FOUND="OrderNotFound",t.ALREADY_CANCELLED="AlreadyCancelled",t.ORDER_FULLY_EXECUTED="OrderFullyExecuted",t.ORDER_EXPIRED="OrderExpired",t.ON_CHAIN_ORDER="OnChainOrder"}(w||(w={})),function(e){e.MARKET="market",e.LIMIT="limit",e.LIQUIDITY="liquidity"}(L||(L={})),function(e){e.BUY="buy",e.SELL="sell"}(b||(b={})),function(e){var t;(t=e.errorType||(e.errorType={})).DUPLICATE_ORDER="DuplicateOrder",t.INSUFFICIENT_FEE="InsufficientFee",t.INSUFFICIENT_ALLOWANCE="InsufficientAllowance",t.INSUFFICIENT_BALANCE="InsufficientBalance",t.INSUFFICIENT_VALID_TO="InsufficientValidTo",t.EXCESSIVE_VALID_TO="ExcessiveValidTo",t.INVALID_SIGNATURE="InvalidSignature",t.TRANSFER_ETH_TO_CONTRACT="TransferEthToContract",t.TRANSFER_SIMULATION_FAILED="TransferSimulationFailed",t.UNSUPPORTED_TOKEN="UnsupportedToken",t.WRONG_OWNER="WrongOwner",t.MISSING_FROM="MissingFrom",t.SAME_BUY_AND_SELL_TOKEN="SameBuyAndSellToken",t.ZERO_AMOUNT="ZeroAmount",t.UNSUPPORTED_BUY_TOKEN_DESTINATION="UnsupportedBuyTokenDestination",t.UNSUPPORTED_SELL_TOKEN_SOURCE="UnsupportedSellTokenSource",t.UNSUPPORTED_ORDER_TYPE="UnsupportedOrderType",t.UNSUPPORTED_SIGNATURE="UnsupportedSignature",t.TOO_MANY_LIMIT_ORDERS="TooManyLimitOrders"}(P||(P={})),function(e){(e.kind||(e.kind={})).SELL="sell"}(F||(F={})),function(e){e.PRESIGNATURE_PENDING="presignaturePending",e.OPEN="open",e.FULFILLED="fulfilled",e.CANCELLED="cancelled",e.EXPIRED="expired"}(q||(q={})),function(e){e.FAST="fast",e.OPTIMAL="optimal"}(x||(x={})),function(e){var t;(t=e.errorType||(e.errorType={})).ALREADY_CANCELLED="AlreadyCancelled",t.ORDER_FULLY_EXECUTED="OrderFullyExecuted",t.ORDER_EXPIRED="OrderExpired",t.ON_CHAIN_ORDER="OnChainOrder",t.DUPLICATE_ORDER="DuplicateOrder",t.INSUFFICIENT_FEE="InsufficientFee",t.INSUFFICIENT_ALLOWANCE="InsufficientAllowance",t.INSUFFICIENT_BALANCE="InsufficientBalance",t.INSUFFICIENT_VALID_TO="InsufficientValidTo",t.EXCESSIVE_VALID_TO="ExcessiveValidTo",t.INVALID_SIGNATURE="InvalidSignature",t.TRANSFER_ETH_TO_CONTRACT="TransferEthToContract",t.TRANSFER_SIMULATION_FAILED="TransferSimulationFailed",t.UNSUPPORTED_TOKEN="UnsupportedToken",t.WRONG_OWNER="WrongOwner",t.SAME_BUY_AND_SELL_TOKEN="SameBuyAndSellToken",t.ZERO_AMOUNT="ZeroAmount",t.UNSUPPORTED_BUY_TOKEN_DESTINATION="UnsupportedBuyTokenDestination",t.UNSUPPORTED_SELL_TOKEN_SOURCE="UnsupportedSellTokenSource",t.UNSUPPORTED_ORDER_TYPE="UnsupportedOrderType",t.UNSUPPORTED_SIGNATURE="UnsupportedSignature"}(V||(V={})),function(e){e.ERC20="erc20",e.INTERNAL="internal",e.EXTERNAL="external"}(j||(j={})),function(e){e.EIP712="eip712",e.ETHSIGN="ethsign",e.PRESIGN="presign",e.EIP1271="eip1271"}(k||(k={}));const H="0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE";function G(e){return function(e){const{ethflowData:t}=e;if(!t)return e;const{userValidTo:r}=t;return d({},e,{validTo:r,owner:e.onchainUser||e.owner,sellToken:H})}(function(e){const{executedFeeAmount:t,executedSurplusFee:r}=e;return d({},e,{totalFee:null!=r?r:t})}(e))}const B={[r.MAINNET]:"https://api.cow.fi/mainnet",[r.GNOSIS_CHAIN]:"https://api.cow.fi/xdai",[r.GOERLI]:"https://api.cow.fi/goerli"},M={[r.MAINNET]:"https://barn.api.cow.fi/mainnet",[r.GNOSIS_CHAIN]:"https://barn.api.cow.fi/xdai",[r.GOERLI]:"https://barn.api.cow.fi/goerli"};class W extends u{constructor(e){super(e)}request(e){return R(this.config,d({},e,{headers:d({},e.headers,{"Content-Type":"application/json"})}))}}class ${constructor(e={}){this.context=void 0,this.servicePerNetwork={},this.context=d({},o,e)}getTrades({owner:e,orderId:t},r={}){return e&&t?new E((e,t)=>{t(new n("Cannot specify both owner and orderId"))}):this.getServiceForNetwork(r).getApiV1Trades(e,t)}getOrders({owner:e,offset:t=0,limit:r=1e3},s={}){return this.getServiceForNetwork(s).getApiV1AccountOrders(e,t,r).then(e=>e.map(G))}getTxOrders(e,t={}){return this.getServiceForNetwork(t).getApiV1TransactionsOrders(e).then(e=>e.map(G))}getOrder(e,t={}){return this.getServiceForNetwork(t).getApiV1Orders(e).then(e=>G(e))}getOrderMultiEnv(e,t={}){const{env:r}=this.getContextWithOverride(t),o=s.filter(e=>e!==r);let n=0;const i=r=>{const s=o[n];return r instanceof l&&404===r.status&&s?(n++,this.getOrder(e,d({},t,{env:s})).catch(i)):Promise.reject(r)};return this.getOrder(e,d({},t,{env:r})).catch(i)}getQuote(e,t={}){return this.getServiceForNetwork(t).postApiV1Quote(e)}sendSignedOrderCancellations(e,t={}){return this.getServiceForNetwork(t).deleteApiV1Orders(e)}sendOrder(e,t={}){return this.getServiceForNetwork(t).postApiV1Orders(e).catch(e=>{const t=e.body;if(null!=t&&t.errorType)throw new Error(t.errorType);throw e})}getNativePrice(e,t={}){return this.getServiceForNetwork(t).getApiV1TokenNativePrice(e)}getOrderLink(e,t){const{chainId:r,env:s}=this.getContextWithOverride(t);return this.getApiBaseUrls(s)[r]+`/api/v1/orders/${e}`}getServiceForNetwork(e){const{chainId:t,env:r}=this.getContextWithOverride(e),s=`${r}|${t}`,o=this.servicePerNetwork[s];if(o)return o.default;const n=new y({BASE:this.getApiBaseUrls(r)[t]},W);return this.servicePerNetwork[s]=n,n.default}getContextWithOverride(e={}){return d({},this.context,e)}getApiBaseUrls(e){return this.context.baseUrls?this.context.baseUrls:"prod"===e?B:M}}let K,Y,Q,X=e=>e;const Z=e(K||(K=X`
|
|
2
|
+
query Totals {
|
|
3
|
+
totals {
|
|
4
|
+
tokens
|
|
5
|
+
orders
|
|
6
|
+
traders
|
|
7
|
+
settlements
|
|
8
|
+
volumeUsd
|
|
9
|
+
volumeEth
|
|
10
|
+
feesUsd
|
|
11
|
+
feesEth
|
|
12
|
+
}
|
|
13
|
+
}
|
|
14
|
+
`)),J=e(Y||(Y=X`
|
|
15
|
+
query LastDaysVolume($days: Int!) {
|
|
16
|
+
dailyTotals(orderBy: timestamp, orderDirection: desc, first: $days) {
|
|
17
|
+
timestamp
|
|
18
|
+
volumeUsd
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
`)),z=e(Q||(Q=X`
|
|
22
|
+
query LastHoursVolume($hours: Int!) {
|
|
23
|
+
hourlyTotals(orderBy: timestamp, orderDirection: desc, first: $hours) {
|
|
24
|
+
timestamp
|
|
25
|
+
volumeUsd
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
`)),ee={[r.MAINNET]:"https://api.thegraph.com/subgraphs/name/cowprotocol/cow",[r.GNOSIS_CHAIN]:"https://api.thegraph.com/subgraphs/name/cowprotocol/cow-gc",[r.GOERLI]:"https://api.thegraph.com/subgraphs/name/cowprotocol/cow-goerli"},te={[r.MAINNET]:"https://api.thegraph.com/subgraphs/name/cowprotocol/cow-staging",[r.GNOSIS_CHAIN]:"https://api.thegraph.com/subgraphs/name/cowprotocol/cow-gc-staging",[r.GOERLI]:""};class re{constructor(e={}){this.API_NAME="CoW Protocol Subgraph",this.context=void 0,this.context=d({},o,e)}async getTotals(e={}){return(await this.runQuery(Z,void 0,e)).totals[0]}async getLastDaysVolume(e,t={}){return this.runQuery(J,{days:e},t)}async getLastHoursVolume(e,t={}){return this.runQuery(z,{hours:e},t)}async runQuery(e,r=undefined,s={}){const{chainId:o,env:i}=this.getContextWithOverride(s),a=this.getEnvConfigs(i)[o];try{return await t(a,e,r)}catch(t){throw console.error(`[subgraph:${this.API_NAME}]`,t),new n(`Error running query: ${e}. Variables: ${JSON.stringify(r)}. API: ${a}. Inner Error: ${t}`)}}getContextWithOverride(e={}){return d({},this.context,e)}getEnvConfigs(e){return this.context.baseUrls?this.context.baseUrls:"prod"===e?ee:te}}const se=()=>import("./utils-f7284bac.js");class oe{static async signOrder(e,t,r){const{signOrder:s}=await se();return s(e,t,r)}static async signOrderCancellation(e,t,r){const{signOrderCancellation:s}=await se();return s(e,t,r)}static async signOrderCancellations(e,t,r){const{signOrderCancellations:s}=await se();return s(e,t,r)}static async getDomain(e){const{getDomain:t}=await se();return t(e)}}export{l as A,u as B,n as C,o as D,C as E,U as F,B as O,x as P,V as R,r as S,d as _,s as a,a as b,c,M as d,$ as e,y as f,E as g,p as h,v as i,m as j,D as k,i as l,w as m,L as n,b as o,P as p,F as q,q as r,j as s,k as t,S as u,ee as v,te as w,re as x,oe as y};
|
|
29
|
+
//# sourceMappingURL=index-5242792d.js.map
|