@cowprotocol/cow-sdk 0.0.1 → 0.0.6
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/.eslintrc.json +15 -0
- package/.github/workflows/publish.yml +23 -0
- package/.nvmrc +1 -0
- package/.prettierignore +1 -0
- package/.prettierrc +5 -0
- package/COPYRIGHT.md +13 -0
- package/LICENSE-APACHE +201 -0
- package/LICENSE-MIT +21 -0
- package/README.md +95 -6
- package/dist/src/appData.schema-d44994e0.js +2 -0
- package/dist/src/appData.schema-d44994e0.js.map +1 -0
- package/dist/src/appData.schema-fb2df827.js +2 -0
- package/dist/src/appData.schema-fb2df827.js.map +1 -0
- package/dist/src/cow-sdk.esm.js +2 -0
- package/dist/src/cow-sdk.esm.js.map +1 -0
- package/dist/src/cow-sdk.js +2 -0
- package/dist/src/cow-sdk.js.map +1 -0
- package/dist/src/cow-sdk.modern.js +2 -0
- package/dist/src/cow-sdk.modern.js.map +1 -0
- package/dist/src/src/CowSdk.d.ts +16 -0
- package/dist/src/src/api/cow/errors/OperatorError.d.ts +63 -0
- package/dist/src/src/api/cow/errors/QuoteError.d.ts +32 -0
- package/dist/src/src/api/cow/index.d.ts +38 -0
- package/dist/src/src/api/cow/types.d.ts +73 -0
- package/dist/src/src/api/index.d.ts +1 -0
- package/dist/src/src/constants/chains.d.ts +6 -0
- package/dist/src/src/constants/index.d.ts +3 -0
- package/dist/src/src/constants/tokens.d.ts +5 -0
- package/dist/src/src/index.d.ts +4 -0
- package/dist/src/src/types/index.d.ts +7 -0
- package/dist/src/src/utils/appData.d.ts +7 -0
- package/dist/src/src/utils/common.d.ts +5 -0
- package/dist/src/src/utils/context.d.ts +24 -0
- package/dist/src/src/utils/sign.d.ts +54 -0
- package/dist/src/src/utils/tokens.d.ts +2 -0
- package/package.json +39 -12
- package/src/CowSdk.ts +24 -3
- package/src/api/cow/errors/OperatorError.ts +140 -0
- package/src/api/cow/errors/QuoteError.ts +114 -0
- package/src/api/cow/index.ts +343 -0
- package/src/api/cow/types.ts +82 -0
- package/src/api/index.ts +1 -0
- package/src/constants/chains.ts +11 -0
- package/src/constants/index.ts +14 -0
- package/src/constants/tokens.ts +16 -0
- package/src/index.ts +4 -1
- package/src/schemas/appData.schema.json +7 -23
- package/src/types/index.ts +5 -0
- package/src/utils/appData.spec.ts +39 -41
- package/src/utils/appData.ts +11 -13
- package/src/utils/common.ts +27 -0
- package/src/utils/context.ts +42 -0
- package/src/utils/price.ts +44 -0
- package/src/utils/sign.ts +224 -0
- package/src/utils/tokens.ts +12 -0
- package/src/workflows/publish.sh +77 -0
- package/tsconfig.json +10 -3
package/.eslintrc.json
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
{
|
|
2
|
+
"parser": "@typescript-eslint/parser",
|
|
3
|
+
"extends": [
|
|
4
|
+
"prettier",
|
|
5
|
+
"plugin:prettier/recommended",
|
|
6
|
+
"plugin:@typescript-eslint/recommended",
|
|
7
|
+
"plugin:prettier/recommended"
|
|
8
|
+
],
|
|
9
|
+
"plugins": ["prettier"],
|
|
10
|
+
"rules": {
|
|
11
|
+
"prettier/prettier": "error"
|
|
12
|
+
},
|
|
13
|
+
|
|
14
|
+
"ignorePatterns": ["dist", "node_modules"]
|
|
15
|
+
}
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
name: Publish package to NPM
|
|
2
|
+
|
|
3
|
+
on:
|
|
4
|
+
# https://docs.github.com/en/actions/using-workflows/events-that-trigger-workflows#workflow_dispatch
|
|
5
|
+
workflow_dispatch:
|
|
6
|
+
|
|
7
|
+
jobs:
|
|
8
|
+
deploy:
|
|
9
|
+
runs-on: ubuntu-latest
|
|
10
|
+
steps:
|
|
11
|
+
- uses: actions/checkout@v2
|
|
12
|
+
- uses: actions/setup-node@v1
|
|
13
|
+
with:
|
|
14
|
+
node-version: 14.x
|
|
15
|
+
- run: yarn --frozen-lockfile
|
|
16
|
+
- run: bash src/workflows/publish.sh
|
|
17
|
+
env:
|
|
18
|
+
PUBLISH_SERVER: ${{ secrets.PUBLISH_SERVER }}
|
|
19
|
+
GITLAB_TRIGGER_TOKEN: ${{ secrets.GITLAB_TRIGGER_TOKEN }}
|
|
20
|
+
BUCKET_NAME: ${{ secrets.BUCKET_NAME }}
|
|
21
|
+
AWS_ACCESS_KEY_ID: ${{ secrets.AWS_ACCESS_KEY_ID }}
|
|
22
|
+
AWS_SECRET_ACCESS_KEY: ${{ secrets.AWS_SECRET_ACCESS_KEY }}
|
|
23
|
+
AWS_REGION: ${{ secrets.AWS_REGION }}
|
package/.nvmrc
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
v14.*
|
package/.prettierignore
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
dist/
|
package/.prettierrc
ADDED
package/COPYRIGHT.md
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
# Intellectual Property Notice
|
|
2
|
+
|
|
3
|
+
Copyright 2021 Gnosis Ltd
|
|
4
|
+
|
|
5
|
+
Copyrights in this project are retained by contributors. No copyright assignment
|
|
6
|
+
is required to contribute to this project.
|
|
7
|
+
|
|
8
|
+
Except as otherwise noted (below and/or in individual files), this project is
|
|
9
|
+
licensed under the Apache License, Version 2.0
|
|
10
|
+
([`LICENSE-APACHE`](LICENSE-APACHE) or
|
|
11
|
+
http://www.apache.org/licenses/LICENSE-2.0) or the MIT license,
|
|
12
|
+
([`LICENSE-MIT`](LICENSE-MIT) or http://opensource.org/licenses/MIT), at your
|
|
13
|
+
option.
|
package/LICENSE-APACHE
ADDED
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
|
177
|
+
|
|
178
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
179
|
+
|
|
180
|
+
To apply the Apache License to your work, attach the following
|
|
181
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
182
|
+
replaced with your own identifying information. (Don't include
|
|
183
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
184
|
+
comment syntax for the file format. We also recommend that a
|
|
185
|
+
file or class name and description of purpose be included on the
|
|
186
|
+
same "printed page" as the copyright notice for easier
|
|
187
|
+
identification within third-party archives.
|
|
188
|
+
|
|
189
|
+
Copyright [yyyy] [name of copyright owner]
|
|
190
|
+
|
|
191
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
192
|
+
you may not use this file except in compliance with the License.
|
|
193
|
+
You may obtain a copy of the License at
|
|
194
|
+
|
|
195
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
196
|
+
|
|
197
|
+
Unless required by applicable law or agreed to in writing, software
|
|
198
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
199
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
200
|
+
See the License for the specific language governing permissions and
|
|
201
|
+
limitations under the License.
|
package/LICENSE-MIT
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2021 Gnosis Ltd
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,8 +1,100 @@
|
|
|
1
|
-
# CoW protocol SDK
|
|
2
1
|
<p align="center">
|
|
3
|
-
<img width="400" src="docs/images/CoW.png">
|
|
2
|
+
<img width="400" src="https://raw.githubusercontent.com/gnosis/cow-sdk/main/docs/images/CoW.png">
|
|
4
3
|
</p>
|
|
5
4
|
|
|
5
|
+
# CoW protocol SDK
|
|
6
|
+
[](https://prettier.io/)
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
> ⚠️⚠️ THE SDK IS IN Beta ⚠️⚠️
|
|
10
|
+
> It is being currently develop and is a work in progress, also it's API is subjected to change.
|
|
11
|
+
> If you experience any problems, please open an issue in Github trying to describe your problem.
|
|
12
|
+
|
|
13
|
+
### Getting started
|
|
14
|
+
|
|
15
|
+
Install the SDK:
|
|
16
|
+
|
|
17
|
+
```bash
|
|
18
|
+
yarn add @cowprotocol/cow-sdk
|
|
19
|
+
```
|
|
20
|
+
|
|
21
|
+
Instantiate the SDK:
|
|
22
|
+
|
|
23
|
+
```js
|
|
24
|
+
import { CowSdk } from 'cow-sdk'
|
|
25
|
+
|
|
26
|
+
const chainId = 4 // Rinkeby
|
|
27
|
+
const cowSdk = new CowSdk(chainId)
|
|
28
|
+
```
|
|
29
|
+
|
|
30
|
+
The SDK will expose the CoW API operations (`cowSdk.cowApi`) and some convenient method that will facilitate signing orders (`cowSdk.signOrder`). Future version will provide easy access to The Graph data and some other convenient utils.
|
|
31
|
+
|
|
32
|
+
```js
|
|
33
|
+
// i.e. Get last 5 orders for a given trader
|
|
34
|
+
const trades = await cowSdk.cowApi.getOrders({
|
|
35
|
+
owner: '0x00000000005ef87f8ca7014309ece7260bbcdaeb', // Trader
|
|
36
|
+
limit: 5,
|
|
37
|
+
offset: 0
|
|
38
|
+
})
|
|
39
|
+
console.log(trades)
|
|
40
|
+
```
|
|
41
|
+
|
|
42
|
+
Let's see a full example on how to submit an order to CowSwap.
|
|
43
|
+
|
|
44
|
+
> ⚠️ Before starting, the protocol requires you to approve the sell token before the order can be considered.
|
|
45
|
+
> For more details see https://docs.cow.fi/tutorials/how-to-submit-orders-via-the-api/1.-set-allowance-for-the-sell-token
|
|
46
|
+
|
|
47
|
+
In this example, we will:
|
|
48
|
+
- 1. **Instantiate the SDK and a wallet**: Used for signing orders
|
|
49
|
+
- 2. **Get a price/fee quote from the API**: Get current market price and required protocol fee to settle your trade.
|
|
50
|
+
- 3. **Sign the order using your wallet**: Only signed orders are considered by the protocol.
|
|
51
|
+
- 4. **Post the signed order to the API**: Post the order so it can be executed.
|
|
52
|
+
|
|
53
|
+
```js
|
|
54
|
+
import { Wallet } from 'ethers'
|
|
55
|
+
import { CowSdk, OrderKind } from 'cow-sdk'
|
|
56
|
+
|
|
57
|
+
// 1. Instantiate wallet and SDK
|
|
58
|
+
const mnemonic = 'fall dirt bread cactus...'
|
|
59
|
+
const wallet = Wallet.fromMnemonic(mnemonic)
|
|
60
|
+
const cowSdk = new CowSdk(4, { signer: wallet })
|
|
61
|
+
|
|
62
|
+
// 2. Get a price/fee quote from the API
|
|
63
|
+
// It will return the price and fee to "Sell 1 ETH for USDC"
|
|
64
|
+
const quoteResponse = await cowSdk.cowApi.getQuote({
|
|
65
|
+
kind: OrderKind.SELL, // Sell order (could also be BUY)
|
|
66
|
+
sellToken: '0xc778417e063141139fce010982780140aa0cd5ab', // WETH
|
|
67
|
+
buyToken: '0x4dbcdf9b62e891a7cec5a2568c3f4faf9e8abe2b', // USDC
|
|
68
|
+
amount: '1000000000000000000', // 1 WETH
|
|
69
|
+
userAddress: '0x1811be0994930fe9480eaede25165608b093ad7a', // Trader
|
|
70
|
+
validTo: 2524608000,
|
|
71
|
+
})
|
|
72
|
+
|
|
73
|
+
const { sellToken, buyToken, validTo, buyAmount, sellAmount, receiver, feeAmount } = quoteResponse.quote
|
|
74
|
+
const order = {
|
|
75
|
+
kind: OrderKind.SELL,
|
|
76
|
+
partiallyFillable: false, // Allow partial executions of an order (true would be for a "Fill or Kill" order, which is not yet supported but will be added soon)
|
|
77
|
+
sellToken,
|
|
78
|
+
buyToken,
|
|
79
|
+
validTo,
|
|
80
|
+
buyAmount,
|
|
81
|
+
sellAmount,
|
|
82
|
+
receiver,
|
|
83
|
+
feeAmount,
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
// 3. Sign the order using your wallet
|
|
87
|
+
const signedOrder = await cowSdk.signOrder(order)
|
|
88
|
+
|
|
89
|
+
// 4. Post the signed order to the API
|
|
90
|
+
const orderId = await cowSdk.cowApi.sendOrder({
|
|
91
|
+
order: { ...order, ...signedOrder },
|
|
92
|
+
owner: '0x1811be0994930fe9480eaede25165608b093ad7a',
|
|
93
|
+
})
|
|
94
|
+
|
|
95
|
+
// We can inspect the Order details in the CoW Protocol Explorer
|
|
96
|
+
console.log(`https://explorer.cow.fi/rinkeby/orders/${orderId}`)
|
|
97
|
+
```
|
|
6
98
|
|
|
7
99
|
### Install Dependencies
|
|
8
100
|
|
|
@@ -14,11 +106,8 @@ yarn
|
|
|
14
106
|
|
|
15
107
|
```bash
|
|
16
108
|
yarn build
|
|
17
|
-
```
|
|
18
|
-
|
|
19
|
-
### Run
|
|
20
109
|
|
|
21
|
-
|
|
110
|
+
# Build in watch mode
|
|
22
111
|
yarn start
|
|
23
112
|
```
|
|
24
113
|
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
var e="https://cowswap.exchange/appdata.schema.json",t="http://json-schema.org/draft-07/schema",r="Metadata JSON document for adding information to orders.",i=["version","metadata"],s="AppData Root Schema",o={version:{$id:"#/properties/version",description:"Semantic versioning of document",examples:["1.0.0","1.2.3"],title:"Semantic Versioning",type:"string"},appCode:{$id:"#/properties/appCode",description:"The code identifying the CLI, UI, service generating the order.",examples:["CowSwap"],title:"App Code",type:"string"},metadata:{$id:"#/properties/metadata",default:{},description:"Each metadata will specify one aspect of the order.",required:[],title:"Metadata descriptors",type:"object",properties:{referrer:{$ref:"#/definitions/kindMetadata/referrer"}}}},d={version:{$id:"#/definitions/version",description:"Semantic versioning of document",examples:["1.0.0","1.2.3"],title:"Semantic Versioning",type:"string"},ethereumAddress:{$id:"#/definitions/ethereumAddress",pattern:"^0x[a-fA-F0-9]{40}$",title:"Ethereum compatible address",examples:["0xb6BAd41ae76A11D10f7b0E664C5007b908bC77C9"],type:"string"},kindMetadata:{referrer:{$id:"#/definitions/referrer",required:["version","address"],title:"Referrer",type:"object",properties:{version:{$ref:"#/definitions/version"},address:{$ref:"#/definitions/ethereumAddress",title:"Referrer address"}}}}},a={$id:e,$schema:t,description:r,required:i,title:s,type:"object",properties:o,definitions:d};exports.$id=e,exports.$schema=t,exports.default=a,exports.definitions=d,exports.description=r,exports.properties=o,exports.required=i,exports.title=s,exports.type="object";
|
|
2
|
+
//# sourceMappingURL=appData.schema-d44994e0.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"appData.schema-d44994e0.js","sources":[],"sourcesContent":[],"names":[],"mappings":""}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
var e="https://cowswap.exchange/appdata.schema.json",t="http://json-schema.org/draft-07/schema",i="Metadata JSON document for adding information to orders.",r=["version","metadata"],s="AppData Root Schema",a="object",d={version:{$id:"#/properties/version",description:"Semantic versioning of document",examples:["1.0.0","1.2.3"],title:"Semantic Versioning",type:"string"},appCode:{$id:"#/properties/appCode",description:"The code identifying the CLI, UI, service generating the order.",examples:["CowSwap"],title:"App Code",type:"string"},metadata:{$id:"#/properties/metadata",default:{},description:"Each metadata will specify one aspect of the order.",required:[],title:"Metadata descriptors",type:"object",properties:{referrer:{$ref:"#/definitions/kindMetadata/referrer"}}}},o={version:{$id:"#/definitions/version",description:"Semantic versioning of document",examples:["1.0.0","1.2.3"],title:"Semantic Versioning",type:"string"},ethereumAddress:{$id:"#/definitions/ethereumAddress",pattern:"^0x[a-fA-F0-9]{40}$",title:"Ethereum compatible address",examples:["0xb6BAd41ae76A11D10f7b0E664C5007b908bC77C9"],type:"string"},kindMetadata:{referrer:{$id:"#/definitions/referrer",required:["version","address"],title:"Referrer",type:"object",properties:{version:{$ref:"#/definitions/version"},address:{$ref:"#/definitions/ethereumAddress",title:"Referrer address"}}}}},n={$id:e,$schema:t,description:i,required:r,title:s,type:"object",properties:d,definitions:o};export{e as $id,t as $schema,n as default,o as definitions,i as description,d as properties,r as required,s as title,a as type};
|
|
2
|
+
//# sourceMappingURL=appData.schema-fb2df827.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"appData.schema-fb2df827.js","sources":[],"sourcesContent":[],"names":[],"mappings":""}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{SigningScheme as e,IntChainIdTypedDataV4Signer as r,TypedDataV3Signer as t,domain as n,signOrderCancellation as o,signOrder as i,OrderKind as s}from"@gnosis.pm/gp-v2-contracts";export{OrderKind}from"@gnosis.pm/gp-v2-contracts";import a from"loglevel";import c from"cross-fetch";import u from"@gnosis.pm/gp-v2-contracts/networks.json";import d from"ajv";class h extends Error{constructor(e,r){super(e),this.error_code=void 0,this.error_code=r}}function l(e){if(!e)return"";const r=new URLSearchParams;for(const t of Object.keys(e)){const n=e[t];n&&r.append(t,n)}const t=r.toString();return t?`?${t}`:""}var p;!function(e){e[e.MAINNET=1]="MAINNET",e[e.RINKEBY=4]="RINKEBY",e[e.GNOSIS_CHAIN=100]="GNOSIS_CHAIN"}(p||(p={}));const f=[p.MAINNET,p.RINKEBY,p.GNOSIS_CHAIN];class E{constructor(e,r){this.symbol=void 0,this.address=void 0,this.symbol=e,this.address=r}}const{GPv2Settlement:g}=u,m={[p.MAINNET]:g[p.MAINNET].address,[p.RINKEBY]:g[p.RINKEBY].address,[p.GNOSIS_CHAIN]:g[p.GNOSIS_CHAIN].address},N=function(n,o,i,s="v4"){try{let u;function c(e){return u?e:{signature:p.data.toString(),signingScheme:d}}const d="eth_sign"===s?e.ETHSIGN:e.EIP712;let l,p=null;try{switch(s){case"v3":l=new t(i);break;case"int_v4":l=new r(i);break;default:l=i}}catch(e){throw a.error("Wallet not supported:",e),new h("Wallet not supported")}const f=function(e,r){try{var t=Promise.resolve(o({...n,signer:l,signingScheme:d})).then(function(e){p=e})}catch(e){return r(e)}return t&&t.then?t.then(void 0,r):t}(0,function(e){if(void 0===(r=e).code&&void 0===r.message)throw a.error(e),e;var r;if(e.code===I||w.test(e.message))switch(s){case"v4":const r=N(n,o,i,"v3");return u=1,r;case"v3":const t=N(n,o,i,"eth_sign");return u=1,t;default:throw e}else{if(D.test(e.message)){const e=N(n,o,i,"int_v4");return u=1,e}if(e.code===A){const e=N(n,o,i,"eth_sign");return u=1,e}if(T.test(e.message)){const e=N(n,o,i,"v3");return u=1,e}if(P.test(e.message)){const e=N(n,o,i,"eth_sign");return u=1,e}}});return Promise.resolve(f&&f.then?f.then(c):c(f))}catch(e){return Promise.reject(e)}},v=function(e){try{const{chainId:r,signer:t,signingScheme:n,orderId:i}=e,s=k(r);return Promise.resolve(o(s,i,t,S(n)))}catch(e){return Promise.reject(e)}},y=function(e){try{const{chainId:r,signer:t,order:n,signingScheme:o}=e,s=k(r);return Promise.resolve(i(s,n,t,S(o)))}catch(e){return Promise.reject(e)}},A=-32603,I=-32601,T=/eth_signTypedData_v4 does not exist/i,P=/eth_signTypedData_v3 does not exist/i,w=/RPC request failed/i,D=/provided chainid .* must match the active chainid/i,R=new Map([[e.EIP712,{libraryValue:0,apiValue:"eip712"}],[e.ETHSIGN,{libraryValue:1,apiValue:"ethsign"}],[e.EIP1271,{libraryValue:2,apiValue:"eip1271"}],[e.PRESIGN,{libraryValue:3,apiValue:"presign"}]]);function _(e){const r=R.get(e);if(void 0===r)throw new h("Unknown schema "+e);return r}function O(e){return _(e).apiValue}function S(e){return _(e).libraryValue}function k(e){const r=m[e];if(!r)throw new h("Unsupported network. Settlement contract is not deployed");return n(e,r)}var b,L,U,x;!function(e){e.DuplicateOrder="DuplicateOrder",e.InvalidSignature="InvalidSignature",e.MissingOrderData="MissingOrderData",e.InsufficientValidTo="InsufficientValidTo",e.InsufficientAllowance="InsufficientAllowance",e.InsufficientBalance="InsufficientBalance",e.InsufficientFee="InsufficientFee",e.WrongOwner="WrongOwner",e.NotFound="NotFound",e.OrderNotFound="OrderNotFound",e.AlreadyCancelled="AlreadyCancelled",e.OrderFullyExecuted="OrderFullyExecuted",e.OrderExpired="OrderExpired",e.NoLiquidity="NoLiquidity",e.UnsupportedToken="UnsupportedToken",e.AmountIsZero="AmountIsZero",e.SellAmountDoesNotCoverFee="SellAmountDoesNotCoverFee",e.TransferEthToContract="TransferEthToContract",e.UNHANDLED_GET_ERROR="UNHANDLED_GET_ERROR",e.UNHANDLED_CREATE_ERROR="UNHANDLED_CREATE_ERROR",e.UNHANDLED_DELETE_ERROR="UNHANDLED_DELETE_ERROR"}(b||(b={})),function(e){e.DuplicateOrder="There was another identical order already submitted. Please try again.",e.InsufficientFee="The signed fee is insufficient. It's possible that is higher now due to a change in the gas price, ether price, or the sell token price. Please try again to get an updated fee quote.",e.InvalidSignature="The order signature is invalid. Check whether your Wallet app supports off-chain signing.",e.MissingOrderData="The order has missing information",e.InsufficientValidTo="The order you are signing is already expired. This can happen if you set a short expiration in the settings and waited too long before signing the transaction. Please try again.",e.InsufficientAllowance="The account doesn't have enough funds",e.InsufficientBalance="The account needs to approve the selling token in order to trade",e.WrongOwner="The signature is invalid.\n\nIt's likely that the signing method provided by your wallet doesn't comply with the standards required by CowSwap.\n\nCheck whether your Wallet app supports off-chain signing (EIP-712 or ETHSIGN).",e.NotFound="Token pair selected has insufficient liquidity",e.OrderNotFound="The order you are trying to cancel does not exist",e.AlreadyCancelled="Order is already cancelled",e.OrderFullyExecuted="Order is already filled",e.OrderExpired="Order is expired",e.NoLiquidity="Token pair selected has insufficient liquidity",e.UnsupportedToken="One of the tokens you are trading is unsupported. Please read the FAQ for more info.",e.AmountIsZero="Amount is zero",e.SellAmountDoesNotCoverFee="Sell amount does not sufficiently cover the current fee",e.TransferEthToContract="Sending the native currency to smart contract wallets is not currently supported",e.UNHANDLED_GET_ERROR="Order fetch failed. This may be due to a server or network connectivity issue. Please try again later.",e.UNHANDLED_CREATE_ERROR="The order was not accepted by the network",e.UNHANDLED_DELETE_ERROR="The order cancellation was not accepted by the network"}(L||(L={}));class F extends h{static getErrorMessage(e,r){try{return Promise.resolve(function(r,t){try{var n=Promise.resolve(e.json()).then(function(e){return e.errorType?F.apiErrorDetails[e.errorType]||e.errorType:(a.error("Unknown reason for bad order submission",e),e.description)})}catch(e){return t()}return n&&n.then?n.then(void 0,t):n}(0,function(){return a.error("Error handling a 400 error. Likely a problem deserialising the JSON response"),function(e){switch(e){case"get":return L.UNHANDLED_GET_ERROR;case"create":return L.UNHANDLED_CREATE_ERROR;case"delete":return L.UNHANDLED_DELETE_ERROR;default:return a.error("[OperatorError::_mapActionToErrorDetails] Uncaught error mapping error action type to server error. Please try again later."),"Something failed. Please try again later."}}(r)}))}catch(e){return Promise.reject(e)}}static getErrorFromStatusCode(e,r){try{const t=this;switch(e.status){case 400:case 404:return Promise.resolve(t.getErrorMessage(e,r));case 403:return Promise.resolve(`The order cannot be ${"create"===r?"accepted":"cancelled"}. Your account is deny-listed.`);case 429:return Promise.resolve(`The order cannot be ${"create"===r?"accepted. Too many order placements":"cancelled. Too many order cancellations"}. Please, retry in a minute`);default:return a.error(`[OperatorError::getErrorFromStatusCode] Error ${"create"===r?"creating":"cancelling"} the order, status code:`,e.status||"unknown"),Promise.resolve(`Error ${"create"===r?"creating":"cancelling"} the order`)}return Promise.resolve()}catch(e){return Promise.reject(e)}}constructor(e){super(e.description,e.errorType),this.name="OperatorError",this.description=void 0,this.description=e.description,this.message=L[e.errorType]}}F.apiErrorDetails=L,function(e){e.UnsupportedToken="UnsupportedToken",e.InsufficientLiquidity="InsufficientLiquidity",e.FeeExceedsFrom="FeeExceedsFrom",e.ZeroPrice="ZeroPrice",e.UNHANDLED_ERROR="UNHANDLED_ERROR"}(U||(U={})),function(e){e.UnsupportedToken="One of the tokens you are trading is unsupported. Please read the FAQ for more info.",e.InsufficientLiquidity="Token pair selected has insufficient liquidity",e.FeeExceedsFrom='Current fee exceeds entered "from" amount',e.ZeroPrice="Quoted price is zero. This is likely due to a significant price difference between the two tokens. Please try increasing amounts.",e.UNHANDLED_ERROR="Quote fetch failed. This may be due to a server or network connectivity issue. Please try again later."}(x||(x={}));class H extends h{static getErrorMessage(e){try{return Promise.resolve(function(r,t){try{var n=Promise.resolve(e.json()).then(function(e){return e.errorType?H.quoteErrorDetails[e.errorType]||e.errorType:(a.error("Unknown reason for bad quote fetch",e),e.description)})}catch(e){return t()}return n&&n.then?n.then(void 0,t):n}(0,function(){return a.error("Error handling 400/404 error. Likely a problem deserialising the JSON response"),H.quoteErrorDetails.UNHANDLED_ERROR}))}catch(e){return Promise.reject(e)}}static getErrorFromStatusCode(e){try{const r=this;switch(e.status){case 400:case 404:return Promise.resolve(r.getErrorMessage(e));default:return a.error("[QuoteError::getErrorFromStatusCode] Error fetching quote, status code:",e.status||"unknown"),Promise.resolve("Error fetching quote")}return Promise.resolve()}catch(e){return Promise.reject(e)}}constructor(e){super(e.description,e.errorType),this.name="QuoteErrorObject",this.description=void 0,this.data=void 0,this.description=e.description,this.message=H.quoteErrorDetails[e.errorType],this.data=e?.data}}H.quoteErrorDetails=x;const C={[p.MAINNET]:new E("WETH","0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2"),[p.RINKEBY]:new E("WETH","0xc778417E063141139Fce010982780140Aa0cD5Ab"),[p.GNOSIS_CHAIN]:new E("WXDAI","0xe91D153E0b41518A2Ce8Dd3D7944Fa863463a97d")},j={[p.MAINNET]:"ETH",[p.RINKEBY]:"ETH",[p.GNOSIS_CHAIN]:"XDAI"};function M(e,r){let t=e;return e===j[r]&&(t=C[r].address),t}function $(e,r){try{var t=e()}catch(e){return r(e)}return t&&t.then?t.then(void 0,r):t}const q=function(e,r){try{return e.ok?Promise.resolve(e.json()):Promise.resolve(e.json()).then(function(e){const t=function(e){switch(e?.errorType){case b.NotFound:case b.NoLiquidity:return{errorType:U.InsufficientLiquidity,description:x.InsufficientLiquidity};case b.SellAmountDoesNotCoverFee:return{errorType:U.FeeExceedsFrom,description:x.FeeExceedsFrom,data:e?.data};case b.UnsupportedToken:return{errorType:U.UnsupportedToken,description:e.description};case b.SellAmountDoesNotCoverFee:return{errorType:U.FeeExceedsFrom,description:e.description};default:return{errorType:U.UNHANDLED_ERROR,description:x.UNHANDLED_ERROR}}}(e),n=new H(t);if(r){const{sellToken:e,buyToken:t}=r;a.error(`Error querying fee from API - sellToken: ${e}, buyToken: ${t}`)}throw n})}catch(e){return Promise.reject(e)}},G={errorType:U.UNHANDLED_ERROR,description:x.UNHANDLED_ERROR},B={errorType:b.UNHANDLED_CREATE_ERROR,description:L.UNHANDLED_CREATE_ERROR};class V{constructor(e,r){this.chainId=void 0,this.context=void 0,this.API_NAME="CoW Protocol",this.chainId=e,this.context=r}get DEFAULT_HEADERS(){return{"Content-Type":"application/json","X-AppId":this.context.appDataHash}}get API_BASE_URL(){return this.context.isDevEnvironment?{[p.MAINNET]:"https://barn.api.cow.fi/mainnet/api",[p.RINKEBY]:"https://barn.api.cow.fi/rinkeby/api",[p.GNOSIS_CHAIN]:"https://barn.api.cow.fi/xdai/api"}:{[p.MAINNET]:"https://api.cow.fi/mainnet/api",[p.RINKEBY]:"https://api.cow.fi/rinkeby/api",[p.GNOSIS_CHAIN]:"https://api.cow.fi/xdai/api"}}get PROFILE_API_BASE_URL(){return this.context.isDevEnvironment?{[p.MAINNET]:"https://barn.api.cow.fi/affiliate/api"}:{[p.MAINNET]:"https://api.cow.fi/affiliate/api"}}getProfileData(e){try{const r=this;return a.debug(`[api:${r.API_NAME}] Get profile data for`,r.chainId,e),r.chainId!==p.MAINNET?(a.info("Profile data is only available for mainnet"),Promise.resolve(null)):Promise.resolve(r.getProfile(`/profile/${e}`)).then(function(e){return e.ok?e.json():Promise.resolve(e.json()).then(function(e){throw a.error(e),new h(e?.description)})})}catch(e){return Promise.reject(e)}}getTrades(e){try{const r=this,{owner:t,limit:n,offset:o}=e,i=l({owner:t,limit:n,offset:o});return a.debug("[util:operator] Get trades for",r.chainId,t,{limit:n,offset:o}),Promise.resolve($(function(){return Promise.resolve(r.get(`/trades${i}`)).then(function(e){return e.ok?e.json():Promise.resolve(e.json()).then(function(e){throw new h(e)})})},function(e){throw a.error("Error getting trades:",e),new h("Error getting trades: "+e)}))}catch(e){return Promise.reject(e)}}getOrders(e){try{const r=this,{owner:t,limit:n=1e3,offset:o=0}=e,i=l({limit:n,offset:o});return a.debug(`[api:${r.API_NAME}] Get orders for `,r.chainId,t,n,o),Promise.resolve($(function(){return Promise.resolve(r.get(`/account/${t}/orders/${i}`)).then(function(e){return e.ok?e.json():Promise.resolve(e.json()).then(function(e){throw new F(e)})})},function(e){throw a.error("Error getting orders information:",e),new F(B)}))}catch(e){return Promise.reject(e)}}getOrder(e){try{const r=this;return a.debug(`[api:${r.API_NAME}] Get order for `,r.chainId,e),Promise.resolve($(function(){return Promise.resolve(r.get(`/orders/${e}`)).then(function(e){return e.ok?e.json():Promise.resolve(e.json()).then(function(e){throw new F(e)})})},function(e){throw a.error("Error getting order information:",e),new F(B)}))}catch(e){return Promise.reject(e)}}getPriceQuoteLegacy(e){try{const r=this,{baseToken:t,quoteToken:n,amount:o,kind:i}=e;return a.debug(`[api:${r.API_NAME}] Get price from API`,e),Promise.resolve(r.get(`/markets/${M(t,r.chainId)}-${M(n,r.chainId)}/${i}/${o}`).catch(e=>{throw a.error("Error getting price quote:",e),new H(G)})).then(q)}catch(e){return Promise.reject(e)}}getQuote(e){try{const r=this,t=r.mapNewToLegacyParams(e,r.chainId);return Promise.resolve(r.post("/quote",t)).then(q)}catch(e){return Promise.reject(e)}}sendSignedOrderCancellation(e){try{const r=this,{cancellation:t,owner:n}=e;return a.debug(`[api:${r.API_NAME}] Delete signed order for network`,r.chainId,t),Promise.resolve(r.delete(`/orders/${t.orderUid}`,{signature:t.signature,signingScheme:O(t.signingScheme),from:n})).then(function(e){function n(e){a.debug(`[api:${r.API_NAME}] Cancelled order`,t.orderUid,r.chainId)}const o=function(){if(!e.ok)return Promise.resolve(F.getErrorFromStatusCode(e,"delete")).then(function(e){throw new h(e)})}();return o&&o.then?o.then(n):n()})}catch(e){return Promise.reject(e)}}sendOrder(e){try{const r=this,t={...e.order,appData:r.context.appDataHash},{owner:n}=e;return a.debug(`[api:${r.API_NAME}] Post signed order for network`,r.chainId,t),Promise.resolve(r.post("/orders",{...t,signingScheme:O(t.signingScheme),from:n})).then(function(e){function t(t){return Promise.resolve(e.json()).then(function(e){return a.debug(`[api:${r.API_NAME}] Success posting the signed order`,e),e})}const n=function(){if(!e.ok)return Promise.resolve(F.getErrorFromStatusCode(e,"create")).then(function(e){throw new h(e)})}();return n&&n.then?n.then(t):t()})}catch(e){return Promise.reject(e)}}getOrderLink(e){return this.getApiBaseUrl()+`/orders/${e}`}mapNewToLegacyParams(e,r){const{amount:t,kind:n,userAddress:o,receiver:i,validTo:a,sellToken:c,buyToken:u}=e,d=o||"0x0000000000000000000000000000000000000000",h={sellToken:M(c,r),buyToken:M(u,r),from:d,receiver:i||d,appData:this.context.appDataHash,validTo:a,partiallyFillable:!1};return n===s.SELL?{kind:s.SELL,sellAmountBeforeFee:t,...h}:{kind:s.BUY,buyAmountAfterFee:t,...h}}getApiBaseUrl(){const e=this.API_BASE_URL[this.chainId];if(e)return e+"/v1";throw new h(`Unsupported Network. The ${this.API_NAME} API is not deployed in the Network `+this.chainId)}getProfileApiBaseUrl(){const e=this.PROFILE_API_BASE_URL[this.chainId];if(e)return e+"/v1";throw new h(`Unsupported Network. The ${this.API_NAME} API is not deployed in the Network `+this.chainId)}fetch(e,r,t){const n=this.getApiBaseUrl();return c(n+e,{headers:this.DEFAULT_HEADERS,method:r,body:void 0!==t?JSON.stringify(t):t})}fetchProfile(e,r,t){const n=this.getProfileApiBaseUrl();return c(n+e,{headers:this.DEFAULT_HEADERS,method:r,body:void 0!==t?JSON.stringify(t):t})}post(e,r){return this.fetch(e,"POST",r)}get(e){return this.fetch(e,"GET")}getProfile(e){return this.fetchProfile(e,"GET")}delete(e,r){return this.fetch(e,"DELETE",r)}}const W=function(e){try{return Promise.resolve(Y()).then(function({ajv:r,validate:t}){return Promise.resolve(t(e)).then(function(e){return{result:!!e,errors:r.errors??void 0}})})}catch(e){return Promise.reject(e)}},Y=function(){try{function e(){return{ajv:Q,validate:K}}Q||(Q=new d);const r=function(){if(!K)return Promise.resolve(import("./appData.schema-fb2df827.js")).then(function(e){K=Q.compile(e)})}();return Promise.resolve(r&&r.then?r.then(e):e())}catch(e){return Promise.reject(e)}};let K,Q;const Z={appDataHash:"0x0000000000000000000000000000000000000000000000000000000000000000",isDevEnvironment:!1};class J{constructor(e){this.context=void 0,this.context={...Z,...e}}get appDataHash(){return this.context.appDataHash??Z.appDataHash}get isDevEnvironment(){return this.context.isDevEnvironment??Z.isDevEnvironment}get signer(){if(this.context.signer)return this.context.signer;throw new h("No signer was provided")}}class X{constructor(e,r={}){this.chainId=void 0,this.context=void 0,this.cowApi=void 0,this.validateAppDataDocument=W,this.chainId=e,this.context=new J(r),this.cowApi=new V(e,this.context)}signOrder(e){return function(e,r,t){return N({order:e,chainId:r},y,t)}({...e,appData:this.context.appDataHash},this.chainId,this.context.signer)}signOrderCancellation(e){return function(e,r,t){return N({orderId:e,chainId:r},v,t)}(e,this.chainId,this.context.signer)}}X.version="0.0.6";export{f as ALL_SUPPORTED_CHAIN_IDS,h as CowError,X as CowSdk,E as Token};
|
|
2
|
+
//# sourceMappingURL=cow-sdk.esm.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"cow-sdk.esm.js","sources":["../../src/utils/common.ts","../../src/constants/chains.ts","../../src/types/index.ts","../../src/constants/index.ts","../../src/utils/sign.ts","../../src/api/cow/errors/OperatorError.ts","../../src/api/cow/errors/QuoteError.ts","../../src/constants/tokens.ts","../../src/utils/tokens.ts","../../src/api/cow/index.ts","../../src/utils/appData.ts","../../src/utils/context.ts","../../src/CowSdk.ts"],"sourcesContent":["export class CowError extends Error {\n error_code?: string\n\n constructor(message: string, error_code?: string) {\n super(message)\n this.error_code = error_code\n }\n}\n\nexport function objectToQueryString(o: any): string {\n if (!o) {\n return ''\n }\n\n const qs = new URLSearchParams()\n\n for (const key of Object.keys(o)) {\n const value = o[key]\n if (value) {\n qs.append(key, value)\n }\n }\n\n const qsResult = qs.toString()\n\n return qsResult ? `?${qsResult}` : ''\n}\n","export enum SupportedChainId {\n MAINNET = 1,\n RINKEBY = 4,\n GNOSIS_CHAIN = 100,\n}\n\nexport const ALL_SUPPORTED_CHAIN_IDS: SupportedChainId[] = [\n SupportedChainId.MAINNET,\n SupportedChainId.RINKEBY,\n SupportedChainId.GNOSIS_CHAIN,\n]\n","export * from '/api/cow/types'\nexport { OrderKind } from '@gnosis.pm/gp-v2-contracts'\nexport class Token {\n constructor(public symbol: string, public address: string) {}\n}\n","import contractNetworks from '@gnosis.pm/gp-v2-contracts/networks.json'\nimport { SupportedChainId as ChainId } from './chains'\n\nconst { GPv2Settlement } = contractNetworks\n\nexport const GP_SETTLEMENT_CONTRACT_ADDRESS: Partial<Record<number, string>> = {\n [ChainId.MAINNET]: GPv2Settlement[ChainId.MAINNET].address,\n [ChainId.RINKEBY]: GPv2Settlement[ChainId.RINKEBY].address,\n [ChainId.GNOSIS_CHAIN]: GPv2Settlement[ChainId.GNOSIS_CHAIN].address,\n}\n\nexport const ZERO_ADDRESS = '0x0000000000000000000000000000000000000000'\n\nexport const DEFAULT_APP_DATA_HASH = '0x0000000000000000000000000000000000000000000000000000000000000000'\n","import {\n domain as domainGp,\n signOrder as signOrderGp,\n signOrderCancellation as signOrderCancellationGp,\n EcdsaSignature,\n Order,\n OrderCancellation as OrderCancellationGp,\n Signature,\n TypedDataV3Signer,\n IntChainIdTypedDataV4Signer,\n SigningScheme,\n} from '@gnosis.pm/gp-v2-contracts'\nimport log from 'loglevel'\n\nimport { SupportedChainId as ChainId } from '/constants/chains'\nimport { GP_SETTLEMENT_CONTRACT_ADDRESS } from '/constants'\nimport { TypedDataDomain, Signer } from '@ethersproject/abstract-signer'\nimport { CowError } from './common'\n\n// For error codes, see:\n// - https://eth.wiki/json-rpc/json-rpc-error-codes-improvement-proposal\n// - https://www.jsonrpc.org/specification#error_object\nconst METAMASK_SIGNATURE_ERROR_CODE = -32603\nconst METHOD_NOT_FOUND_ERROR_CODE = -32601\nconst V4_ERROR_MSG_REGEX = /eth_signTypedData_v4 does not exist/i\nconst V3_ERROR_MSG_REGEX = /eth_signTypedData_v3 does not exist/i\nconst RPC_REQUEST_FAILED_REGEX = /RPC request failed/i\nconst METAMASK_STRING_CHAINID_REGEX = /provided chainid .* must match the active chainid/i\n\nexport type UnsignedOrder = Omit<Order, 'receiver'> & { receiver: string }\n\nexport interface SignOrderParams {\n chainId: ChainId\n signer: Signer\n order: UnsignedOrder\n signingScheme: SigningScheme\n}\n\n// posted to /api/v1/orders on Order creation\n// serializable, so no BigNumbers\n// See https://protocol-rinkeby.dev.gnosisdev.com/api/\nexport interface OrderCreation extends UnsignedOrder {\n signingScheme: SigningScheme // signed method\n\n // Signature is used for:\n // - Signature: EIP-712,ETHSIGN\n // - Owner address: for PRESIGN\n signature: string // 65 bytes encoded as hex without `0x` prefix. r + s + v from the spec\n}\n\nexport interface SingOrderCancellationParams {\n chainId: ChainId\n signer: Signer\n orderId: string\n signingScheme: SigningScheme\n}\n\nexport interface OrderCancellation extends OrderCancellationGp {\n signature: string\n signingScheme: SigningScheme\n}\n\nexport type SigningSchemeValue = 'eip712' | 'ethsign' | 'eip1271' | 'presign'\n\ninterface SchemaInfo {\n libraryValue: number\n apiValue: SigningSchemeValue\n}\nconst mapSigningSchema: Map<SigningScheme, SchemaInfo> = new Map([\n [SigningScheme.EIP712, { libraryValue: 0, apiValue: 'eip712' }],\n [SigningScheme.ETHSIGN, { libraryValue: 1, apiValue: 'ethsign' }],\n [SigningScheme.EIP1271, { libraryValue: 2, apiValue: 'eip1271' }],\n [SigningScheme.PRESIGN, { libraryValue: 3, apiValue: 'presign' }],\n])\n\nfunction _getSigningSchemeInfo(ecdaSigningScheme: SigningScheme): SchemaInfo {\n const value = mapSigningSchema.get(ecdaSigningScheme)\n if (value === undefined) {\n throw new CowError('Unknown schema ' + ecdaSigningScheme)\n }\n\n return value\n}\n\ninterface ProviderRpcError extends Error {\n message: string\n code: number\n data?: unknown\n}\n\nfunction isProviderRpcError(error: unknown): error is ProviderRpcError {\n return (error as ProviderRpcError).code !== undefined || (error as ProviderRpcError).message !== undefined\n}\n\nexport function getSigningSchemeApiValue(ecdaSigningScheme: SigningScheme): string {\n return _getSigningSchemeInfo(ecdaSigningScheme).apiValue\n}\n\nexport function getSigningSchemeLibValue(ecdaSigningScheme: SigningScheme): number {\n return _getSigningSchemeInfo(ecdaSigningScheme).libraryValue\n}\n\nfunction _getDomain(chainId: ChainId): TypedDataDomain {\n // Get settlement contract address\n const settlementContract = GP_SETTLEMENT_CONTRACT_ADDRESS[chainId]\n\n if (!settlementContract) {\n throw new CowError('Unsupported network. Settlement contract is not deployed')\n }\n\n return domainGp(chainId, settlementContract)\n}\n\nasync function _signOrder(params: SignOrderParams): Promise<Signature> {\n const { chainId, signer, order, signingScheme } = params\n\n const domain = _getDomain(chainId)\n\n return signOrderGp(domain, order, signer, getSigningSchemeLibValue(signingScheme))\n}\n\nasync function _signOrderCancellation(params: SingOrderCancellationParams): Promise<Signature> {\n const { chainId, signer, signingScheme, orderId } = params\n\n const domain = _getDomain(chainId)\n\n return signOrderCancellationGp(domain, orderId, signer, getSigningSchemeLibValue(signingScheme))\n}\n\nexport type SigningResult = { signature: string; signingScheme: SigningScheme }\n\nasync function _signPayload(\n payload: any,\n signFn: typeof _signOrder | typeof _signOrderCancellation,\n signer: Signer,\n signingMethod: 'v4' | 'int_v4' | 'v3' | 'eth_sign' = 'v4'\n): Promise<SigningResult> {\n const signingScheme = signingMethod === 'eth_sign' ? SigningScheme.ETHSIGN : SigningScheme.EIP712\n let signature: Signature | null = null\n\n let _signer\n try {\n switch (signingMethod) {\n case 'v3':\n _signer = new TypedDataV3Signer(signer)\n break\n case 'int_v4':\n _signer = new IntChainIdTypedDataV4Signer(signer)\n break\n default:\n _signer = signer\n }\n } catch (e) {\n log.error('Wallet not supported:', e)\n throw new CowError('Wallet not supported')\n }\n\n try {\n signature = (await signFn({ ...payload, signer: _signer, signingScheme })) as EcdsaSignature // Only ECDSA signing supported for now\n } catch (e) {\n if (!isProviderRpcError(e)) {\n // Some other error signing. Let it bubble up.\n log.error(e)\n throw e\n }\n\n if (e.code === METHOD_NOT_FOUND_ERROR_CODE || RPC_REQUEST_FAILED_REGEX.test(e.message)) {\n // Maybe the wallet returns the proper error code? We can only hope 🤞\n // OR it failed with a generic message, there's no error code set, and we also hope it'll work\n // with other methods...\n switch (signingMethod) {\n case 'v4':\n return _signPayload(payload, signFn, signer, 'v3')\n case 'v3':\n return _signPayload(payload, signFn, signer, 'eth_sign')\n default:\n throw e\n }\n } else if (METAMASK_STRING_CHAINID_REGEX.test(e.message)) {\n // Metamask now enforces chainId to be an integer\n return _signPayload(payload, signFn, signer, 'int_v4')\n } else if (e.code === METAMASK_SIGNATURE_ERROR_CODE) {\n // We tried to sign order the nice way.\n // That works fine for regular MM addresses. Does not work for Hardware wallets, though.\n // See https://github.com/MetaMask/metamask-extension/issues/10240#issuecomment-810552020\n // So, when that specific error occurs, we know this is a problem with MM + HW.\n // Then, we fallback to ETHSIGN.\n return _signPayload(payload, signFn, signer, 'eth_sign')\n } else if (V4_ERROR_MSG_REGEX.test(e.message)) {\n // Failed with `v4`, and the wallet does not set the proper error code\n return _signPayload(payload, signFn, signer, 'v3')\n } else if (V3_ERROR_MSG_REGEX.test(e.message)) {\n // Failed with `v3`, and the wallet does not set the proper error code\n return _signPayload(payload, signFn, signer, 'eth_sign')\n }\n }\n return { signature: signature!.data.toString(), signingScheme }\n}\n/**\n * Returns the signature for the specified order with the signing scheme encoded\n * into the signature.\n * @export\n * @param {UnsignedOrder} order The order to sign.\n * @param {ChainId} chainId The chain Id\n * @param {Signer} signer The owner for the order used to sign.\n * @return {*} Encoded signature including signing scheme for the order.\n */\nexport async function signOrder(order: UnsignedOrder, chainId: ChainId, signer: Signer): Promise<SigningResult> {\n return _signPayload({ order, chainId }, _signOrder, signer)\n}\n\n/**\n * Returns the signature for the Order Cancellation with the signing scheme encoded\n * into the signature.\n *\n * @export\n * @param {string} orderId The unique identifier of the order being cancelled.\n * @param {ChainId} chainId The chain Id\n * @param {Signer} signer The owner for the order used to sign.\n * @return {*} Encoded signature including signing scheme for the order.\n */\nexport async function signOrderCancellation(orderId: string, chainId: ChainId, signer: Signer): Promise<SigningResult> {\n return _signPayload({ orderId, chainId }, _signOrderCancellation, signer)\n}\n","import log from 'loglevel'\nimport { CowError } from '/utils/common'\n\ntype ApiActionType = 'get' | 'create' | 'delete'\n\nexport interface ApiErrorObject {\n errorType: ApiErrorCodes\n description: string\n data?: any\n}\n\n// Conforms to backend API\n// https://github.com/gnosis/gp-v2-services/blob/d932e11c9a2125fdba239530be7684799f694909/crates/orderbook/openapi.yml#L801\n// and\n// https://github.com/gnosis/gp-v2-services/blob/d932e11c9a2125fdba239530be7684799f694909/crates/orderbook/openapi.yml#L740\nexport enum ApiErrorCodes {\n DuplicateOrder = 'DuplicateOrder',\n InvalidSignature = 'InvalidSignature',\n MissingOrderData = 'MissingOrderData',\n InsufficientValidTo = 'InsufficientValidTo',\n InsufficientAllowance = 'InsufficientAllowance',\n InsufficientBalance = 'InsufficientBalance',\n InsufficientFee = 'InsufficientFee',\n WrongOwner = 'WrongOwner',\n NotFound = 'NotFound',\n OrderNotFound = 'OrderNotFound',\n AlreadyCancelled = 'AlreadyCancelled',\n OrderFullyExecuted = 'OrderFullyExecuted',\n OrderExpired = 'OrderExpired',\n NoLiquidity = 'NoLiquidity',\n UnsupportedToken = 'UnsupportedToken',\n AmountIsZero = 'AmountIsZero',\n SellAmountDoesNotCoverFee = 'SellAmountDoesNotCoverFee',\n TransferEthToContract = 'TransferEthToContract',\n UNHANDLED_GET_ERROR = 'UNHANDLED_GET_ERROR',\n UNHANDLED_CREATE_ERROR = 'UNHANDLED_CREATE_ERROR',\n UNHANDLED_DELETE_ERROR = 'UNHANDLED_DELETE_ERROR',\n}\n\nexport enum ApiErrorCodeDetails {\n DuplicateOrder = 'There was another identical order already submitted. Please try again.',\n InsufficientFee = \"The signed fee is insufficient. It's possible that is higher now due to a change in the gas price, ether price, or the sell token price. Please try again to get an updated fee quote.\",\n InvalidSignature = 'The order signature is invalid. Check whether your Wallet app supports off-chain signing.',\n MissingOrderData = 'The order has missing information',\n InsufficientValidTo = 'The order you are signing is already expired. This can happen if you set a short expiration in the settings and waited too long before signing the transaction. Please try again.',\n InsufficientAllowance = \"The account doesn't have enough funds\",\n InsufficientBalance = 'The account needs to approve the selling token in order to trade',\n WrongOwner = \"The signature is invalid.\\n\\nIt's likely that the signing method provided by your wallet doesn't comply with the standards required by CowSwap.\\n\\nCheck whether your Wallet app supports off-chain signing (EIP-712 or ETHSIGN).\",\n NotFound = 'Token pair selected has insufficient liquidity',\n OrderNotFound = 'The order you are trying to cancel does not exist',\n AlreadyCancelled = 'Order is already cancelled',\n OrderFullyExecuted = 'Order is already filled',\n OrderExpired = 'Order is expired',\n NoLiquidity = 'Token pair selected has insufficient liquidity',\n UnsupportedToken = 'One of the tokens you are trading is unsupported. Please read the FAQ for more info.',\n AmountIsZero = 'Amount is zero',\n SellAmountDoesNotCoverFee = 'Sell amount does not sufficiently cover the current fee',\n TransferEthToContract = 'Sending the native currency to smart contract wallets is not currently supported',\n UNHANDLED_GET_ERROR = 'Order fetch failed. This may be due to a server or network connectivity issue. Please try again later.',\n UNHANDLED_CREATE_ERROR = 'The order was not accepted by the network',\n UNHANDLED_DELETE_ERROR = 'The order cancellation was not accepted by the network',\n}\n\nfunction _mapActionToErrorDetail(action?: ApiActionType) {\n switch (action) {\n case 'get':\n return ApiErrorCodeDetails.UNHANDLED_GET_ERROR\n case 'create':\n return ApiErrorCodeDetails.UNHANDLED_CREATE_ERROR\n case 'delete':\n return ApiErrorCodeDetails.UNHANDLED_DELETE_ERROR\n default:\n log.error(\n '[OperatorError::_mapActionToErrorDetails] Uncaught error mapping error action type to server error. Please try again later.'\n )\n return 'Something failed. Please try again later.'\n }\n}\n\nexport default class OperatorError extends CowError {\n name = 'OperatorError'\n description: ApiErrorObject['description']\n\n // Status 400 errors\n // https://github.com/gnosis/gp-v2-services/blob/9014ae55412a356e46343e051aefeb683cc69c41/orderbook/openapi.yml#L563\n static apiErrorDetails = ApiErrorCodeDetails\n\n public static async getErrorMessage(response: Response, action: ApiActionType) {\n try {\n const orderPostError: ApiErrorObject = await response.json()\n\n if (orderPostError.errorType) {\n const errorMessage = OperatorError.apiErrorDetails[orderPostError.errorType]\n // shouldn't fall through as this error constructor expects the error code to exist but just in case\n return errorMessage || orderPostError.errorType\n } else {\n log.error('Unknown reason for bad order submission', orderPostError)\n return orderPostError.description\n }\n } catch (error) {\n log.error('Error handling a 400 error. Likely a problem deserialising the JSON response')\n return _mapActionToErrorDetail(action)\n }\n }\n static async getErrorFromStatusCode(response: Response, action: 'create' | 'delete') {\n switch (response.status) {\n case 400:\n case 404:\n return this.getErrorMessage(response, action)\n\n case 403:\n return `The order cannot be ${action === 'create' ? 'accepted' : 'cancelled'}. Your account is deny-listed.`\n\n case 429:\n return `The order cannot be ${\n action === 'create' ? 'accepted. Too many order placements' : 'cancelled. Too many order cancellations'\n }. Please, retry in a minute`\n\n case 500:\n default:\n log.error(\n `[OperatorError::getErrorFromStatusCode] Error ${\n action === 'create' ? 'creating' : 'cancelling'\n } the order, status code:`,\n response.status || 'unknown'\n )\n return `Error ${action === 'create' ? 'creating' : 'cancelling'} the order`\n }\n }\n constructor(apiError: ApiErrorObject) {\n super(apiError.description, apiError.errorType)\n\n this.description = apiError.description\n this.message = ApiErrorCodeDetails[apiError.errorType]\n }\n}\n\nexport function isValidOperatorError(error: any): error is OperatorError {\n return error instanceof OperatorError\n}\n","import log from 'loglevel'\nimport { CowError } from '/utils/common'\nimport { ApiErrorCodes, ApiErrorObject } from './OperatorError'\n\nexport interface GpQuoteErrorObject {\n errorType: GpQuoteErrorCodes\n description: string\n data?: any\n}\n\n// Conforms to backend API\n// https://github.com/gnosis/gp-v2-services/blob/0bd5f7743bebaa5acd3be13e35ede2326a096f14/orderbook/openapi.yml#L562\nexport enum GpQuoteErrorCodes {\n UnsupportedToken = 'UnsupportedToken',\n InsufficientLiquidity = 'InsufficientLiquidity',\n FeeExceedsFrom = 'FeeExceedsFrom',\n ZeroPrice = 'ZeroPrice',\n UNHANDLED_ERROR = 'UNHANDLED_ERROR',\n}\n\nexport enum GpQuoteErrorDetails {\n UnsupportedToken = 'One of the tokens you are trading is unsupported. Please read the FAQ for more info.',\n InsufficientLiquidity = 'Token pair selected has insufficient liquidity',\n FeeExceedsFrom = 'Current fee exceeds entered \"from\" amount',\n ZeroPrice = 'Quoted price is zero. This is likely due to a significant price difference between the two tokens. Please try increasing amounts.',\n UNHANDLED_ERROR = 'Quote fetch failed. This may be due to a server or network connectivity issue. Please try again later.',\n}\n\nexport function mapOperatorErrorToQuoteError(error?: ApiErrorObject): GpQuoteErrorObject {\n switch (error?.errorType) {\n case ApiErrorCodes.NotFound:\n case ApiErrorCodes.NoLiquidity:\n return {\n errorType: GpQuoteErrorCodes.InsufficientLiquidity,\n description: GpQuoteErrorDetails.InsufficientLiquidity,\n }\n\n case ApiErrorCodes.SellAmountDoesNotCoverFee:\n return {\n errorType: GpQuoteErrorCodes.FeeExceedsFrom,\n description: GpQuoteErrorDetails.FeeExceedsFrom,\n data: error?.data,\n }\n\n case ApiErrorCodes.UnsupportedToken:\n return {\n errorType: GpQuoteErrorCodes.UnsupportedToken,\n description: error.description,\n }\n case ApiErrorCodes.SellAmountDoesNotCoverFee:\n return {\n errorType: GpQuoteErrorCodes.FeeExceedsFrom,\n description: error.description,\n }\n default:\n return { errorType: GpQuoteErrorCodes.UNHANDLED_ERROR, description: GpQuoteErrorDetails.UNHANDLED_ERROR }\n }\n}\n\nexport default class GpQuoteError extends CowError {\n name = 'QuoteErrorObject'\n description: string\n // any data attached\n data?: any\n\n // Status 400 errors\n // https://github.com/gnosis/gp-v2-services/blob/9014ae55412a356e46343e051aefeb683cc69c41/orderbook/openapi.yml#L563\n static quoteErrorDetails = GpQuoteErrorDetails\n\n public static async getErrorMessage(response: Response) {\n try {\n const orderPostError: GpQuoteErrorObject = await response.json()\n\n if (orderPostError.errorType) {\n const errorMessage = GpQuoteError.quoteErrorDetails[orderPostError.errorType]\n // shouldn't fall through as this error constructor expects the error code to exist but just in case\n return errorMessage || orderPostError.errorType\n } else {\n log.error('Unknown reason for bad quote fetch', orderPostError)\n return orderPostError.description\n }\n } catch (error) {\n log.error('Error handling 400/404 error. Likely a problem deserialising the JSON response')\n return GpQuoteError.quoteErrorDetails.UNHANDLED_ERROR\n }\n }\n\n static async getErrorFromStatusCode(response: Response) {\n switch (response.status) {\n case 400:\n case 404:\n return this.getErrorMessage(response)\n\n case 500:\n default:\n log.error(\n '[QuoteError::getErrorFromStatusCode] Error fetching quote, status code:',\n response.status || 'unknown'\n )\n return 'Error fetching quote'\n }\n }\n constructor(quoteError: GpQuoteErrorObject) {\n super(quoteError.description, quoteError.errorType)\n\n this.description = quoteError.description\n this.message = GpQuoteError.quoteErrorDetails[quoteError.errorType]\n this.data = quoteError?.data\n }\n}\n\nexport function isValidQuoteError(error: any): error is GpQuoteError {\n return error instanceof GpQuoteError\n}\n","import { SupportedChainId as ChainId } from '/constants/chains'\nimport { Token } from '/types'\n\nexport const XDAI_SYMBOL = 'XDAI'\n\nexport const WRAPPED_NATIVE_TOKEN: Record<ChainId, Token> = {\n [ChainId.MAINNET]: new Token('WETH', '0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2'),\n [ChainId.RINKEBY]: new Token('WETH', '0xc778417E063141139Fce010982780140Aa0cD5Ab'),\n [ChainId.GNOSIS_CHAIN]: new Token('WXDAI', '0xe91D153E0b41518A2Ce8Dd3D7944Fa863463a97d'),\n}\n\nexport const NATIVE: Record<ChainId, string> = {\n [ChainId.MAINNET]: 'ETH',\n [ChainId.RINKEBY]: 'ETH',\n [ChainId.GNOSIS_CHAIN]: XDAI_SYMBOL,\n}\n","import { SupportedChainId as ChainId } from '/constants/chains'\nimport { NATIVE, WRAPPED_NATIVE_TOKEN } from '/constants/tokens'\n\nexport function toErc20Address(tokenAddress: string, chainId: ChainId): string {\n let checkedAddress = tokenAddress\n\n if (tokenAddress === NATIVE[chainId]) {\n checkedAddress = WRAPPED_NATIVE_TOKEN[chainId].address\n }\n\n return checkedAddress\n}\n","import log from 'loglevel'\nimport fetch from 'cross-fetch'\nimport { OrderKind, QuoteQuery } from '@gnosis.pm/gp-v2-contracts'\nimport { SupportedChainId as ChainId } from '/constants/chains'\nimport { getSigningSchemeApiValue, OrderCreation } from '/utils/sign'\nimport OperatorError, { ApiErrorCodeDetails, ApiErrorCodes, ApiErrorObject } from './errors/OperatorError'\nimport QuoteError, {\n GpQuoteErrorCodes,\n GpQuoteErrorObject,\n mapOperatorErrorToQuoteError,\n GpQuoteErrorDetails,\n} from './errors/QuoteError'\nimport { toErc20Address } from '/utils/tokens'\nimport { FeeQuoteParams, PriceInformation, PriceQuoteParams, SimpleGetQuoteResponse } from '/utils/price'\n\nimport { ZERO_ADDRESS } from '/constants'\nimport {\n GetOrdersParams,\n GetTradesParams,\n OrderCancellationParams,\n OrderID,\n OrderMetaData,\n ProfileData,\n TradeMetaData,\n} from '/api/cow/types'\nimport { CowError, objectToQueryString } from '/utils/common'\nimport { Context } from '/utils/context'\n\nfunction getGnosisProtocolUrl(isDev: boolean): Partial<Record<ChainId, string>> {\n if (isDev) {\n return {\n [ChainId.MAINNET]: 'https://barn.api.cow.fi/mainnet/api',\n [ChainId.RINKEBY]: 'https://barn.api.cow.fi/rinkeby/api',\n [ChainId.GNOSIS_CHAIN]: 'https://barn.api.cow.fi/xdai/api',\n }\n }\n\n return {\n [ChainId.MAINNET]: 'https://api.cow.fi/mainnet/api',\n [ChainId.RINKEBY]: 'https://api.cow.fi/rinkeby/api',\n [ChainId.GNOSIS_CHAIN]: 'https://api.cow.fi/xdai/api',\n }\n}\n\nfunction getProfileUrl(isDev: boolean): Partial<Record<ChainId, string>> {\n if (isDev) {\n return {\n [ChainId.MAINNET]: 'https://barn.api.cow.fi/affiliate/api',\n }\n }\n\n return {\n [ChainId.MAINNET]: 'https://api.cow.fi/affiliate/api',\n }\n}\n\nconst UNHANDLED_QUOTE_ERROR: GpQuoteErrorObject = {\n errorType: GpQuoteErrorCodes.UNHANDLED_ERROR,\n description: GpQuoteErrorDetails.UNHANDLED_ERROR,\n}\n\nconst UNHANDLED_ORDER_ERROR: ApiErrorObject = {\n errorType: ApiErrorCodes.UNHANDLED_CREATE_ERROR,\n description: ApiErrorCodeDetails.UNHANDLED_CREATE_ERROR,\n}\n\nasync function _handleQuoteResponse<T = any, P extends QuoteQuery = QuoteQuery>(\n response: Response,\n params?: P\n): Promise<T> {\n if (!response.ok) {\n const errorObj: ApiErrorObject = await response.json()\n\n // we need to map the backend error codes to match our own for quotes\n const mappedError = mapOperatorErrorToQuoteError(errorObj)\n const quoteError = new QuoteError(mappedError)\n\n if (params) {\n const { sellToken, buyToken } = params\n log.error(`Error querying fee from API - sellToken: ${sellToken}, buyToken: ${buyToken}`)\n }\n\n throw quoteError\n } else {\n return response.json()\n }\n}\n\nexport class CowApi<T extends ChainId> {\n chainId: T\n context: Context\n\n API_NAME = 'CoW Protocol'\n\n constructor(chainId: T, context: Context) {\n this.chainId = chainId\n this.context = context\n }\n\n get DEFAULT_HEADERS() {\n return { 'Content-Type': 'application/json', 'X-AppId': this.context.appDataHash }\n }\n\n get API_BASE_URL() {\n return getGnosisProtocolUrl(this.context.isDevEnvironment)\n }\n\n get PROFILE_API_BASE_URL(): Partial<Record<ChainId, string>> {\n return getProfileUrl(this.context.isDevEnvironment)\n }\n\n async getProfileData(address: string): Promise<ProfileData | null> {\n log.debug(`[api:${this.API_NAME}] Get profile data for`, this.chainId, address)\n if (this.chainId !== ChainId.MAINNET) {\n log.info('Profile data is only available for mainnet')\n return null\n }\n\n const response = await this.getProfile(`/profile/${address}`)\n\n if (!response.ok) {\n const errorResponse = await response.json()\n log.error(errorResponse)\n throw new CowError(errorResponse?.description)\n } else {\n return response.json()\n }\n }\n\n async getTrades(params: GetTradesParams): Promise<TradeMetaData[]> {\n const { owner, limit, offset } = params\n const qsParams = objectToQueryString({ owner, limit, offset })\n log.debug('[util:operator] Get trades for', this.chainId, owner, { limit, offset })\n try {\n const response = await this.get(`/trades${qsParams}`)\n\n if (!response.ok) {\n const errorResponse = await response.json()\n throw new CowError(errorResponse)\n } else {\n return response.json()\n }\n } catch (error) {\n log.error('Error getting trades:', error)\n throw new CowError('Error getting trades: ' + error)\n }\n }\n\n async getOrders(params: GetOrdersParams): Promise<OrderMetaData[]> {\n const { owner, limit = 1000, offset = 0 } = params\n const queryString = objectToQueryString({ limit, offset })\n log.debug(`[api:${this.API_NAME}] Get orders for `, this.chainId, owner, limit, offset)\n\n try {\n const response = await this.get(`/account/${owner}/orders/${queryString}`)\n\n if (!response.ok) {\n const errorResponse: ApiErrorObject = await response.json()\n throw new OperatorError(errorResponse)\n } else {\n return response.json()\n }\n } catch (error) {\n log.error('Error getting orders information:', error)\n throw new OperatorError(UNHANDLED_ORDER_ERROR)\n }\n }\n\n async getOrder(orderId: string): Promise<OrderMetaData | null> {\n log.debug(`[api:${this.API_NAME}] Get order for `, this.chainId, orderId)\n try {\n const response = await this.get(`/orders/${orderId}`)\n\n if (!response.ok) {\n const errorResponse: ApiErrorObject = await response.json()\n throw new OperatorError(errorResponse)\n } else {\n return response.json()\n }\n } catch (error) {\n log.error('Error getting order information:', error)\n throw new OperatorError(UNHANDLED_ORDER_ERROR)\n }\n }\n\n async getPriceQuoteLegacy(params: PriceQuoteParams): Promise<PriceInformation | null> {\n const { baseToken, quoteToken, amount, kind } = params\n log.debug(`[api:${this.API_NAME}] Get price from API`, params)\n\n const response = await this.get(\n `/markets/${toErc20Address(baseToken, this.chainId)}-${toErc20Address(\n quoteToken,\n this.chainId\n )}/${kind}/${amount}`\n ).catch((error) => {\n log.error('Error getting price quote:', error)\n throw new QuoteError(UNHANDLED_QUOTE_ERROR)\n })\n\n return _handleQuoteResponse<PriceInformation | null>(response)\n }\n\n async getQuote(params: FeeQuoteParams): Promise<SimpleGetQuoteResponse> {\n const quoteParams = this.mapNewToLegacyParams(params, this.chainId)\n const response = await this.post('/quote', quoteParams)\n\n return _handleQuoteResponse<SimpleGetQuoteResponse>(response)\n }\n\n async sendSignedOrderCancellation(params: OrderCancellationParams): Promise<void> {\n const { cancellation, owner: from } = params\n\n log.debug(`[api:${this.API_NAME}] Delete signed order for network`, this.chainId, cancellation)\n\n const response = await this.delete(`/orders/${cancellation.orderUid}`, {\n signature: cancellation.signature,\n signingScheme: getSigningSchemeApiValue(cancellation.signingScheme),\n from,\n })\n\n if (!response.ok) {\n // Raise an exception\n const errorMessage = await OperatorError.getErrorFromStatusCode(response, 'delete')\n throw new CowError(errorMessage)\n }\n\n log.debug(`[api:${this.API_NAME}] Cancelled order`, cancellation.orderUid, this.chainId)\n }\n\n async sendOrder(params: { order: Omit<OrderCreation, 'appData'>; owner: string }): Promise<OrderID> {\n const fullOrder: OrderCreation = { ...params.order, appData: this.context.appDataHash }\n const { owner } = params\n log.debug(`[api:${this.API_NAME}] Post signed order for network`, this.chainId, fullOrder)\n\n // Call API\n const response = await this.post(`/orders`, {\n ...fullOrder,\n signingScheme: getSigningSchemeApiValue(fullOrder.signingScheme),\n from: owner,\n })\n\n // Handle response\n if (!response.ok) {\n // Raise an exception\n const errorMessage = await OperatorError.getErrorFromStatusCode(response, 'create')\n throw new CowError(errorMessage)\n }\n\n const uid = (await response.json()) as string\n log.debug(`[api:${this.API_NAME}] Success posting the signed order`, uid)\n return uid\n }\n\n getOrderLink(orderId: OrderID): string {\n const baseUrl = this.getApiBaseUrl()\n\n return baseUrl + `/orders/${orderId}`\n }\n\n private mapNewToLegacyParams(params: FeeQuoteParams, chainId: ChainId): QuoteQuery {\n const { amount, kind, userAddress, receiver, validTo, sellToken, buyToken } = params\n const fallbackAddress = userAddress || ZERO_ADDRESS\n\n const baseParams = {\n sellToken: toErc20Address(sellToken, chainId),\n buyToken: toErc20Address(buyToken, chainId),\n from: fallbackAddress,\n receiver: receiver || fallbackAddress,\n appData: this.context.appDataHash,\n validTo,\n partiallyFillable: false,\n }\n\n const finalParams: QuoteQuery =\n kind === OrderKind.SELL\n ? {\n kind: OrderKind.SELL,\n sellAmountBeforeFee: amount,\n ...baseParams,\n }\n : {\n kind: OrderKind.BUY,\n buyAmountAfterFee: amount,\n ...baseParams,\n }\n\n return finalParams\n }\n\n private getApiBaseUrl(): string {\n const baseUrl = this.API_BASE_URL[this.chainId]\n\n if (!baseUrl) {\n throw new CowError(`Unsupported Network. The ${this.API_NAME} API is not deployed in the Network ` + this.chainId)\n } else {\n return baseUrl + '/v1'\n }\n }\n\n private getProfileApiBaseUrl(): string {\n const baseUrl = this.PROFILE_API_BASE_URL[this.chainId]\n\n if (!baseUrl) {\n throw new CowError(`Unsupported Network. The ${this.API_NAME} API is not deployed in the Network ` + this.chainId)\n } else {\n return baseUrl + '/v1'\n }\n }\n\n private fetch(url: string, method: 'GET' | 'POST' | 'DELETE', data?: any): Promise<Response> {\n const baseUrl = this.getApiBaseUrl()\n return fetch(baseUrl + url, {\n headers: this.DEFAULT_HEADERS,\n method,\n body: data !== undefined ? JSON.stringify(data) : data,\n })\n }\n\n private fetchProfile(url: string, method: 'GET' | 'POST' | 'DELETE', data?: any): Promise<Response> {\n const baseUrl = this.getProfileApiBaseUrl()\n return fetch(baseUrl + url, {\n headers: this.DEFAULT_HEADERS,\n method,\n body: data !== undefined ? JSON.stringify(data) : data,\n })\n }\n\n private post(url: string, data: any): Promise<Response> {\n return this.fetch(url, 'POST', data)\n }\n\n private get(url: string): Promise<Response> {\n return this.fetch(url, 'GET')\n }\n\n private getProfile(url: string): Promise<Response> {\n return this.fetchProfile(url, 'GET')\n }\n\n private delete(url: string, data: any): Promise<Response> {\n return this.fetch(url, 'DELETE', data)\n }\n}\n","import Ajv, { ErrorObject, ValidateFunction } from 'ajv'\n\nlet validate: ValidateFunction | undefined\nlet ajv: Ajv\n\ninterface ValidationResult {\n result: boolean\n errors?: ErrorObject[]\n}\n\nasync function getValidator(): Promise<{ ajv: Ajv; validate: ValidateFunction }> {\n if (!ajv) {\n ajv = new Ajv()\n }\n\n if (!validate) {\n const appDataSchema = await import('../schemas/appData.schema.json')\n validate = ajv.compile(appDataSchema)\n }\n\n return { ajv, validate }\n}\n\nexport async function validateAppDataDocument(appDataDocument: any): Promise<ValidationResult> {\n const { ajv, validate } = await getValidator()\n const result = !!(await validate(appDataDocument))\n\n return {\n result,\n errors: ajv.errors ?? undefined,\n }\n}\n","import { Signer } from 'ethers'\nimport { CowError } from './common'\nimport { DEFAULT_APP_DATA_HASH } from '/constants'\n\nexport interface CowContext {\n appDataHash?: string\n isDevEnvironment?: boolean\n signer?: Signer\n}\n\nexport const DefaultCowContext = { appDataHash: DEFAULT_APP_DATA_HASH, isDevEnvironment: false }\n\n/**\n *\n *\n * @export\n * @class Context\n * @implements {Required<CowContext>}\n */\nexport class Context implements Required<CowContext> {\n private context: CowContext\n\n constructor(context: CowContext) {\n this.context = { ...DefaultCowContext, ...context }\n }\n\n get appDataHash(): string {\n return this.context.appDataHash ?? DefaultCowContext.appDataHash\n }\n\n get isDevEnvironment(): boolean {\n return this.context.isDevEnvironment ?? DefaultCowContext.isDevEnvironment\n }\n\n get signer(): Signer {\n if (this.context.signer) {\n return this.context.signer\n }\n\n throw new CowError('No signer was provided')\n }\n}\n","import { version as SDK_VERSION } from '../package.json'\nimport { CowApi } from './api'\nimport { SupportedChainId as ChainId } from '/constants/chains'\nimport { validateAppDataDocument } from '/utils/appData'\nimport { Context, CowContext } from '/utils/context'\nimport { signOrder, signOrderCancellation, UnsignedOrder } from '/utils/sign'\n\nexport class CowSdk<T extends ChainId> {\n static version = SDK_VERSION\n chainId: T\n context: Context\n cowApi: CowApi<T>\n\n constructor(chainId: T, cowContext: CowContext = {}) {\n this.chainId = chainId\n this.context = new Context(cowContext)\n this.cowApi = new CowApi(chainId, this.context)\n }\n\n validateAppDataDocument = validateAppDataDocument\n\n signOrder(order: Omit<UnsignedOrder, 'appData'>) {\n return signOrder({ ...order, appData: this.context.appDataHash }, this.chainId, this.context.signer)\n }\n\n signOrderCancellation(orderId: string) {\n return signOrderCancellation(orderId, this.chainId, this.context.signer)\n }\n}\n\nexport default CowSdk\n"],"names":["CowError","Error","constructor","message","error_code","super","this","objectToQueryString","o","qs","URLSearchParams","key","Object","keys","value","append","qsResult","toString","SupportedChainId","ALL_SUPPORTED_CHAIN_IDS","MAINNET","RINKEBY","GNOSIS_CHAIN","Token","symbol","address","GPv2Settlement","contractNetworks","GP_SETTLEMENT_CONTRACT_ADDRESS","ChainId","_signPayload","payload","signFn","signer","signingMethod","signature","data","signingScheme","SigningScheme","ETHSIGN","EIP712","_signer","TypedDataV3Signer","IntChainIdTypedDataV4Signer","e","log","error","undefined","code","METHOD_NOT_FOUND_ERROR_CODE","RPC_REQUEST_FAILED_REGEX","test","METAMASK_STRING_CHAINID_REGEX","METAMASK_SIGNATURE_ERROR_CODE","V4_ERROR_MSG_REGEX","V3_ERROR_MSG_REGEX","_signOrderCancellation","params","chainId","orderId","domain","_getDomain","signOrderCancellationGp","getSigningSchemeLibValue","_signOrder","order","signOrderGp","mapSigningSchema","Map","libraryValue","apiValue","EIP1271","PRESIGN","_getSigningSchemeInfo","ecdaSigningScheme","get","getSigningSchemeApiValue","settlementContract","domainGp","ApiErrorCodes","ApiErrorCodeDetails","GpQuoteErrorCodes","GpQuoteErrorDetails","OperatorError","static","response","action","json","orderPostError","errorType","apiErrorDetails","description","UNHANDLED_GET_ERROR","UNHANDLED_CREATE_ERROR","UNHANDLED_DELETE_ERROR","_mapActionToErrorDetail","status","_this","getErrorMessage","apiError","name","GpQuoteError","quoteErrorDetails","UNHANDLED_ERROR","quoteError","WRAPPED_NATIVE_TOKEN","NATIVE","toErc20Address","tokenAddress","checkedAddress","_handleQuoteResponse","ok","errorObj","mappedError","NotFound","NoLiquidity","InsufficientLiquidity","SellAmountDoesNotCoverFee","FeeExceedsFrom","UnsupportedToken","mapOperatorErrorToQuoteError","QuoteError","sellToken","buyToken","UNHANDLED_QUOTE_ERROR","UNHANDLED_ORDER_ERROR","CowApi","context","API_NAME","DEFAULT_HEADERS","appDataHash","API_BASE_URL","isDevEnvironment","PROFILE_API_BASE_URL","getProfileData","debug","info","getProfile","errorResponse","getTrades","owner","limit","offset","qsParams","_this2","getOrders","queryString","_this3","getOrder","_this4","getPriceQuoteLegacy","baseToken","quoteToken","amount","kind","_this5","catch","getQuote","quoteParams","_this6","mapNewToLegacyParams","post","sendSignedOrderCancellation","cancellation","from","_this7","delete","orderUid","getErrorFromStatusCode","errorMessage","sendOrder","fullOrder","appData","_this8","uid","getOrderLink","getApiBaseUrl","userAddress","receiver","validTo","fallbackAddress","baseParams","partiallyFillable","OrderKind","SELL","sellAmountBeforeFee","BUY","buyAmountAfterFee","baseUrl","getProfileApiBaseUrl","fetch","url","method","headers","body","JSON","stringify","fetchProfile","validateAppDataDocument","appDataDocument","getValidator","ajv","validate","result","errors","Ajv","import","appDataSchema","compile","DefaultCowContext","Context","CowSdk","cowContext","cowApi","signOrder","signOrderCancellation","version"],"mappings":"8WAAaA,UAAiBC,MAG5BC,YAAYC,EAAiBC,GAC3BC,MAAMF,QAHRC,kBAIEE,KAAKF,WAAaA,YAING,EAAoBC,GAClC,IAAKA,EACH,MAAO,GAGT,MAAMC,EAAK,IAAIC,gBAEf,IAAK,MAAMC,KAAOC,OAAOC,KAAKL,GAAI,CAChC,MAAMM,EAAQN,EAAEG,GACZG,GACFL,EAAGM,OAAOJ,EAAKG,GAInB,MAAME,EAAWP,EAAGQ,WAEpB,OAAOD,MAAeA,IAAa,OCzBzBE,GAAZ,SAAYA,GACVA,yBACAA,yBACAA,qCAHF,CAAYA,IAAAA,OAMCC,MAAAA,EAA8C,CACzDD,EAAiBE,QACjBF,EAAiBG,QACjBH,EAAiBI,oBCPNC,EACXrB,YAAmBsB,EAAuBC,QAAvBD,mBAAuBC,eAAvBnB,YAAAkB,EAAuBlB,aAAAmB,GCA5C,MAAMC,eAAEA,GAAmBC,EAEdC,EAAkE,CAC7E,CAACC,EAAQT,SAAUM,EAAeG,EAAQT,SAASK,QACnD,CAACI,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