@cowprotocol/cow-sdk 0.0.14 → 0.0.15
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 +13 -3
- package/dist/CowSdk.d.ts +2 -1
- package/dist/api/cow/index.d.ts +12 -13
- package/dist/api/cow/types.d.ts +6 -0
- package/dist/api/cow-subgraph/graphql.d.ts +25 -0
- package/dist/api/metadata/types.d.ts +7 -9
- package/dist/appData.schema-42d10730.js +2 -0
- package/dist/appData.schema-42d10730.js.map +1 -0
- package/dist/{appData.schema-adfc1c6f.js → appData.schema-b8f018d7.js} +2 -2
- package/dist/appData.schema-b8f018d7.js.map +1 -0
- package/dist/constants/chains.d.ts +1 -0
- package/dist/index.js +4 -4
- package/dist/index.js.map +1 -1
- package/dist/index.modern.js +4 -4
- package/dist/index.modern.js.map +1 -1
- package/dist/index.module.js +4 -4
- package/dist/index.module.js.map +1 -1
- package/dist/utils/context.d.ts +2 -0
- package/dist/utils/sign.d.ts +1 -0
- package/package.json +1 -1
- package/dist/appData.schema-4c010c50.js +0 -2
- package/dist/appData.schema-4c010c50.js.map +0 -1
- package/dist/appData.schema-adfc1c6f.js.map +0 -1
package/README.md
CHANGED
|
@@ -59,7 +59,7 @@ import { CowSdk, OrderKind } from 'cow-sdk'
|
|
|
59
59
|
// 1. Instantiate wallet and SDK
|
|
60
60
|
const mnemonic = 'fall dirt bread cactus...'
|
|
61
61
|
const wallet = Wallet.fromMnemonic(mnemonic)
|
|
62
|
-
const cowSdk = new CowSdk(4, { signer: wallet })
|
|
62
|
+
const cowSdk = new CowSdk(4, { signer: wallet }) // Leaving chainId empty will default to MAINNET
|
|
63
63
|
|
|
64
64
|
// 2. Get a price/fee quote from the API
|
|
65
65
|
// It will return the price and fee to "Sell 1 ETH for USDC"
|
|
@@ -96,6 +96,15 @@ const orderId = await cowSdk.cowApi.sendOrder({
|
|
|
96
96
|
|
|
97
97
|
// We can inspect the Order details in the CoW Protocol Explorer
|
|
98
98
|
console.log(`https://explorer.cow.fi/rinkeby/orders/${orderId}`)
|
|
99
|
+
|
|
100
|
+
// You can also override defaults params when using CowApi methods
|
|
101
|
+
const orderId = await cowSdk.cowApi.sendOrder(
|
|
102
|
+
{
|
|
103
|
+
order: { ...order, ...signedOrder },
|
|
104
|
+
owner: '0x1811be0994930fe9480eaede25165608b093ad7a',
|
|
105
|
+
},
|
|
106
|
+
{ chainId: 1, isDevEnvironment: false }
|
|
107
|
+
)
|
|
99
108
|
```
|
|
100
109
|
|
|
101
110
|
SDK also includes a Metadata API to interact with AppData documents and IPFS CIDs
|
|
@@ -188,10 +197,11 @@ const chainId = 1 // Mainnet
|
|
|
188
197
|
const cowSdk = new CowSdk(chainId)
|
|
189
198
|
|
|
190
199
|
// Get Cow Protocol totals
|
|
191
|
-
const { tokens, orders, traders, settlements, volumeUsd, volumeEth, feesUsd, feesEth } =
|
|
200
|
+
const { tokens, orders, traders, settlements, volumeUsd, volumeEth, feesUsd, feesEth } =
|
|
201
|
+
await cowSdk.cowSubgraphApi.getTotals()
|
|
192
202
|
console.log({ tokens, orders, traders, settlements, volumeUsd, volumeEth, feesUsd, feesEth })
|
|
193
203
|
|
|
194
|
-
// Get last 24 hours volume in usd
|
|
204
|
+
// Get last 24 hours volume in usd
|
|
195
205
|
const { hourlyTotals } = await cowSdk.cowSubgraphApi.getLastHoursVolume(24)
|
|
196
206
|
console.log(hourlyTotals)
|
|
197
207
|
|
package/dist/CowSdk.d.ts
CHANGED
|
@@ -13,8 +13,9 @@ export declare class CowSdk<T extends ChainId> {
|
|
|
13
13
|
cowApi: CowApi;
|
|
14
14
|
metadataApi: MetadataApi;
|
|
15
15
|
cowSubgraphApi: CowSubgraphApi;
|
|
16
|
-
constructor(chainId
|
|
16
|
+
constructor(chainId?: T, cowContext?: CowContext, options?: Options);
|
|
17
17
|
updateChainId: (chainId: ChainId) => void;
|
|
18
|
+
updateContext: (cowContext: CowContext, chainId?: ChainId | undefined) => Promise<void>;
|
|
18
19
|
validateAppDataDocument: typeof validateAppDataDocument;
|
|
19
20
|
signOrder(order: Omit<UnsignedOrder, 'appData'>): Promise<import("./utils/sign").SigningResult>;
|
|
20
21
|
signOrderCancellation(orderId: string): Promise<import("./utils/sign").SigningResult>;
|
package/dist/api/cow/index.d.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { SupportedChainId as ChainId } from '../../constants/chains';
|
|
2
2
|
import { OrderCreation } from '../../utils/sign';
|
|
3
3
|
import { FeeQuoteParams, PriceInformation, PriceQuoteParams, SimpleGetQuoteResponse } from './types';
|
|
4
|
-
import { GetOrdersParams, GetTradesParams, OrderCancellationParams, OrderID, OrderMetaData, ProfileData, TradeMetaData } from './types';
|
|
4
|
+
import { GetOrdersParams, GetTradesParams, OrderCancellationParams, OrderID, OrderMetaData, ProfileData, TradeMetaData, Options } from './types';
|
|
5
5
|
import { Context } from '../../utils/context';
|
|
6
6
|
export declare class CowApi {
|
|
7
7
|
context: Context;
|
|
@@ -12,27 +12,26 @@ export declare class CowApi {
|
|
|
12
12
|
'X-AppId': string;
|
|
13
13
|
};
|
|
14
14
|
get API_BASE_URL(): Partial<Record<ChainId, string>>;
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
sendSignedOrderCancellation(params: OrderCancellationParams): Promise<void>;
|
|
15
|
+
getProfileData(address: string, options?: Options): Promise<ProfileData | null>;
|
|
16
|
+
getTrades(params: GetTradesParams, options?: Options): Promise<TradeMetaData[]>;
|
|
17
|
+
getOrders(params: GetOrdersParams, options?: Options): Promise<OrderMetaData[]>;
|
|
18
|
+
getTxOrders(txHash: string, options?: Options): Promise<OrderMetaData[]>;
|
|
19
|
+
getOrder(orderId: string, options?: Options): Promise<OrderMetaData | null>;
|
|
20
|
+
getPriceQuoteLegacy(params: PriceQuoteParams, options?: Options): Promise<PriceInformation | null>;
|
|
21
|
+
getQuote(params: FeeQuoteParams, options?: Options): Promise<SimpleGetQuoteResponse>;
|
|
22
|
+
sendSignedOrderCancellation(params: OrderCancellationParams, options?: Options): Promise<void>;
|
|
24
23
|
sendOrder(params: {
|
|
25
24
|
order: Omit<OrderCreation, 'appData'>;
|
|
26
25
|
owner: string;
|
|
27
|
-
}): Promise<OrderID>;
|
|
28
|
-
getOrderLink(orderId: OrderID): string
|
|
26
|
+
}, options?: Options): Promise<OrderID>;
|
|
27
|
+
getOrderLink(orderId: OrderID): Promise<string>;
|
|
29
28
|
private mapNewToLegacyParams;
|
|
30
29
|
private getApiBaseUrl;
|
|
31
|
-
private getProfileApiBaseUrl;
|
|
32
30
|
private fetch;
|
|
33
31
|
private fetchProfile;
|
|
34
32
|
private post;
|
|
35
33
|
private get;
|
|
36
34
|
private getProfile;
|
|
37
35
|
private delete;
|
|
36
|
+
private handleMethod;
|
|
38
37
|
}
|
package/dist/api/cow/types.d.ts
CHANGED
|
@@ -89,6 +89,7 @@ export interface FeeInformation {
|
|
|
89
89
|
export interface PriceInformation {
|
|
90
90
|
token: string;
|
|
91
91
|
amount: string | null;
|
|
92
|
+
quoteId?: number;
|
|
92
93
|
}
|
|
93
94
|
export declare type SimpleGetQuoteResponse = Pick<GetQuoteResponse, 'from'> & {
|
|
94
95
|
quote: Omit<GetQuoteResponse['quote'], 'sellAmount' | 'buyAmount' | 'feeAmount' | 'validTo'> & {
|
|
@@ -98,6 +99,7 @@ export declare type SimpleGetQuoteResponse = Pick<GetQuoteResponse, 'from'> & {
|
|
|
98
99
|
feeAmount: string;
|
|
99
100
|
};
|
|
100
101
|
expiration: string;
|
|
102
|
+
id: number | null;
|
|
101
103
|
};
|
|
102
104
|
export declare type FeeQuoteParams = Pick<OrderMetaData, 'sellToken' | 'buyToken' | 'kind'> & {
|
|
103
105
|
amount: string;
|
|
@@ -109,4 +111,8 @@ export declare type PriceQuoteParams = Omit<FeeQuoteParams, 'sellToken' | 'buyTo
|
|
|
109
111
|
baseToken: string;
|
|
110
112
|
quoteToken: string;
|
|
111
113
|
};
|
|
114
|
+
export declare type Options = {
|
|
115
|
+
chainId?: ChainId;
|
|
116
|
+
isDevEnvironment?: boolean;
|
|
117
|
+
};
|
|
112
118
|
export {};
|
|
@@ -153,6 +153,7 @@ export declare type DailyTotal_Filter = {
|
|
|
153
153
|
timestamp_not?: InputMaybe<Scalars['Int']>;
|
|
154
154
|
timestamp_not_in?: InputMaybe<Array<Scalars['Int']>>;
|
|
155
155
|
tokens?: InputMaybe<Array<Scalars['String']>>;
|
|
156
|
+
tokens_?: InputMaybe<Token_Filter>;
|
|
156
157
|
tokens_contains?: InputMaybe<Array<Scalars['String']>>;
|
|
157
158
|
tokens_contains_nocase?: InputMaybe<Array<Scalars['String']>>;
|
|
158
159
|
tokens_not?: InputMaybe<Array<Scalars['String']>>;
|
|
@@ -288,6 +289,7 @@ export declare type HourlyTotal_Filter = {
|
|
|
288
289
|
timestamp_not?: InputMaybe<Scalars['Int']>;
|
|
289
290
|
timestamp_not_in?: InputMaybe<Array<Scalars['Int']>>;
|
|
290
291
|
tokens?: InputMaybe<Array<Scalars['String']>>;
|
|
292
|
+
tokens_?: InputMaybe<Token_Filter>;
|
|
291
293
|
tokens_contains?: InputMaybe<Array<Scalars['String']>>;
|
|
292
294
|
tokens_contains_nocase?: InputMaybe<Array<Scalars['String']>>;
|
|
293
295
|
tokens_not?: InputMaybe<Array<Scalars['String']>>;
|
|
@@ -390,6 +392,7 @@ export declare type Order_Filter = {
|
|
|
390
392
|
isValid_not?: InputMaybe<Scalars['Boolean']>;
|
|
391
393
|
isValid_not_in?: InputMaybe<Array<Scalars['Boolean']>>;
|
|
392
394
|
owner?: InputMaybe<Scalars['String']>;
|
|
395
|
+
owner_?: InputMaybe<User_Filter>;
|
|
393
396
|
owner_contains?: InputMaybe<Scalars['String']>;
|
|
394
397
|
owner_contains_nocase?: InputMaybe<Scalars['String']>;
|
|
395
398
|
owner_ends_with?: InputMaybe<Scalars['String']>;
|
|
@@ -425,6 +428,7 @@ export declare type Order_Filter = {
|
|
|
425
428
|
tradesTimestamp_lte?: InputMaybe<Scalars['Int']>;
|
|
426
429
|
tradesTimestamp_not?: InputMaybe<Scalars['Int']>;
|
|
427
430
|
tradesTimestamp_not_in?: InputMaybe<Array<Scalars['Int']>>;
|
|
431
|
+
trades_?: InputMaybe<Trade_Filter>;
|
|
428
432
|
};
|
|
429
433
|
export declare enum Order_OrderBy {
|
|
430
434
|
Id = "id",
|
|
@@ -516,6 +520,7 @@ export declare type PairDaily_Filter = {
|
|
|
516
520
|
token0Price_lte?: InputMaybe<Scalars['BigDecimal']>;
|
|
517
521
|
token0Price_not?: InputMaybe<Scalars['BigDecimal']>;
|
|
518
522
|
token0Price_not_in?: InputMaybe<Array<Scalars['BigDecimal']>>;
|
|
523
|
+
token0_?: InputMaybe<Token_Filter>;
|
|
519
524
|
token0_contains?: InputMaybe<Scalars['String']>;
|
|
520
525
|
token0_contains_nocase?: InputMaybe<Scalars['String']>;
|
|
521
526
|
token0_ends_with?: InputMaybe<Scalars['String']>;
|
|
@@ -552,6 +557,7 @@ export declare type PairDaily_Filter = {
|
|
|
552
557
|
token1Price_lte?: InputMaybe<Scalars['BigDecimal']>;
|
|
553
558
|
token1Price_not?: InputMaybe<Scalars['BigDecimal']>;
|
|
554
559
|
token1Price_not_in?: InputMaybe<Array<Scalars['BigDecimal']>>;
|
|
560
|
+
token1_?: InputMaybe<Token_Filter>;
|
|
555
561
|
token1_contains?: InputMaybe<Scalars['String']>;
|
|
556
562
|
token1_contains_nocase?: InputMaybe<Scalars['String']>;
|
|
557
563
|
token1_ends_with?: InputMaybe<Scalars['String']>;
|
|
@@ -681,6 +687,7 @@ export declare type PairHourly_Filter = {
|
|
|
681
687
|
token0Price_lte?: InputMaybe<Scalars['BigDecimal']>;
|
|
682
688
|
token0Price_not?: InputMaybe<Scalars['BigDecimal']>;
|
|
683
689
|
token0Price_not_in?: InputMaybe<Array<Scalars['BigDecimal']>>;
|
|
690
|
+
token0_?: InputMaybe<Token_Filter>;
|
|
684
691
|
token0_contains?: InputMaybe<Scalars['String']>;
|
|
685
692
|
token0_contains_nocase?: InputMaybe<Scalars['String']>;
|
|
686
693
|
token0_ends_with?: InputMaybe<Scalars['String']>;
|
|
@@ -717,6 +724,7 @@ export declare type PairHourly_Filter = {
|
|
|
717
724
|
token1Price_lte?: InputMaybe<Scalars['BigDecimal']>;
|
|
718
725
|
token1Price_not?: InputMaybe<Scalars['BigDecimal']>;
|
|
719
726
|
token1Price_not_in?: InputMaybe<Array<Scalars['BigDecimal']>>;
|
|
727
|
+
token1_?: InputMaybe<Token_Filter>;
|
|
720
728
|
token1_contains?: InputMaybe<Scalars['String']>;
|
|
721
729
|
token1_contains_nocase?: InputMaybe<Scalars['String']>;
|
|
722
730
|
token1_ends_with?: InputMaybe<Scalars['String']>;
|
|
@@ -811,6 +819,7 @@ export declare type Pair_Filter = {
|
|
|
811
819
|
token0Price_lte?: InputMaybe<Scalars['BigDecimal']>;
|
|
812
820
|
token0Price_not?: InputMaybe<Scalars['BigDecimal']>;
|
|
813
821
|
token0Price_not_in?: InputMaybe<Array<Scalars['BigDecimal']>>;
|
|
822
|
+
token0_?: InputMaybe<Token_Filter>;
|
|
814
823
|
token0_contains?: InputMaybe<Scalars['String']>;
|
|
815
824
|
token0_contains_nocase?: InputMaybe<Scalars['String']>;
|
|
816
825
|
token0_ends_with?: InputMaybe<Scalars['String']>;
|
|
@@ -847,6 +856,7 @@ export declare type Pair_Filter = {
|
|
|
847
856
|
token1Price_lte?: InputMaybe<Scalars['BigDecimal']>;
|
|
848
857
|
token1Price_not?: InputMaybe<Scalars['BigDecimal']>;
|
|
849
858
|
token1Price_not_in?: InputMaybe<Array<Scalars['BigDecimal']>>;
|
|
859
|
+
token1_?: InputMaybe<Token_Filter>;
|
|
850
860
|
token1_contains?: InputMaybe<Scalars['String']>;
|
|
851
861
|
token1_contains_nocase?: InputMaybe<Scalars['String']>;
|
|
852
862
|
token1_ends_with?: InputMaybe<Scalars['String']>;
|
|
@@ -1240,6 +1250,7 @@ export declare type Settlement_Filter = {
|
|
|
1240
1250
|
id_not?: InputMaybe<Scalars['ID']>;
|
|
1241
1251
|
id_not_in?: InputMaybe<Array<Scalars['ID']>>;
|
|
1242
1252
|
solver?: InputMaybe<Scalars['String']>;
|
|
1253
|
+
solver_?: InputMaybe<User_Filter>;
|
|
1243
1254
|
solver_contains?: InputMaybe<Scalars['String']>;
|
|
1244
1255
|
solver_contains_nocase?: InputMaybe<Scalars['String']>;
|
|
1245
1256
|
solver_ends_with?: InputMaybe<Scalars['String']>;
|
|
@@ -1259,6 +1270,7 @@ export declare type Settlement_Filter = {
|
|
|
1259
1270
|
solver_not_starts_with_nocase?: InputMaybe<Scalars['String']>;
|
|
1260
1271
|
solver_starts_with?: InputMaybe<Scalars['String']>;
|
|
1261
1272
|
solver_starts_with_nocase?: InputMaybe<Scalars['String']>;
|
|
1273
|
+
trades_?: InputMaybe<Trade_Filter>;
|
|
1262
1274
|
txHash?: InputMaybe<Scalars['Bytes']>;
|
|
1263
1275
|
txHash_contains?: InputMaybe<Scalars['Bytes']>;
|
|
1264
1276
|
txHash_in?: InputMaybe<Array<Scalars['Bytes']>>;
|
|
@@ -1676,6 +1688,7 @@ export declare type TokenDailyTotal_Filter = {
|
|
|
1676
1688
|
timestamp_not?: InputMaybe<Scalars['Int']>;
|
|
1677
1689
|
timestamp_not_in?: InputMaybe<Array<Scalars['Int']>>;
|
|
1678
1690
|
token?: InputMaybe<Scalars['String']>;
|
|
1691
|
+
token_?: InputMaybe<Token_Filter>;
|
|
1679
1692
|
token_contains?: InputMaybe<Scalars['String']>;
|
|
1680
1693
|
token_contains_nocase?: InputMaybe<Scalars['String']>;
|
|
1681
1694
|
token_ends_with?: InputMaybe<Scalars['String']>;
|
|
@@ -1829,6 +1842,7 @@ export declare type TokenHourlyTotal_Filter = {
|
|
|
1829
1842
|
timestamp_not?: InputMaybe<Scalars['Int']>;
|
|
1830
1843
|
timestamp_not_in?: InputMaybe<Array<Scalars['Int']>>;
|
|
1831
1844
|
token?: InputMaybe<Scalars['String']>;
|
|
1845
|
+
token_?: InputMaybe<Token_Filter>;
|
|
1832
1846
|
token_contains?: InputMaybe<Scalars['String']>;
|
|
1833
1847
|
token_contains_nocase?: InputMaybe<Scalars['String']>;
|
|
1834
1848
|
token_ends_with?: InputMaybe<Scalars['String']>;
|
|
@@ -1946,6 +1960,7 @@ export declare type TokenTradingEvent_Filter = {
|
|
|
1946
1960
|
timestamp_not?: InputMaybe<Scalars['Int']>;
|
|
1947
1961
|
timestamp_not_in?: InputMaybe<Array<Scalars['Int']>>;
|
|
1948
1962
|
token?: InputMaybe<Scalars['String']>;
|
|
1963
|
+
token_?: InputMaybe<Token_Filter>;
|
|
1949
1964
|
token_contains?: InputMaybe<Scalars['String']>;
|
|
1950
1965
|
token_contains_nocase?: InputMaybe<Scalars['String']>;
|
|
1951
1966
|
token_ends_with?: InputMaybe<Scalars['String']>;
|
|
@@ -1966,6 +1981,7 @@ export declare type TokenTradingEvent_Filter = {
|
|
|
1966
1981
|
token_starts_with?: InputMaybe<Scalars['String']>;
|
|
1967
1982
|
token_starts_with_nocase?: InputMaybe<Scalars['String']>;
|
|
1968
1983
|
trade?: InputMaybe<Scalars['String']>;
|
|
1984
|
+
trade_?: InputMaybe<Trade_Filter>;
|
|
1969
1985
|
trade_contains?: InputMaybe<Scalars['String']>;
|
|
1970
1986
|
trade_contains_nocase?: InputMaybe<Scalars['String']>;
|
|
1971
1987
|
trade_ends_with?: InputMaybe<Scalars['String']>;
|
|
@@ -2019,6 +2035,7 @@ export declare type Token_Filter = {
|
|
|
2019
2035
|
firstTradeTimestamp_lte?: InputMaybe<Scalars['Int']>;
|
|
2020
2036
|
firstTradeTimestamp_not?: InputMaybe<Scalars['Int']>;
|
|
2021
2037
|
firstTradeTimestamp_not_in?: InputMaybe<Array<Scalars['Int']>>;
|
|
2038
|
+
history_?: InputMaybe<TokenTradingEvent_Filter>;
|
|
2022
2039
|
id?: InputMaybe<Scalars['ID']>;
|
|
2023
2040
|
id_gt?: InputMaybe<Scalars['ID']>;
|
|
2024
2041
|
id_gte?: InputMaybe<Scalars['ID']>;
|
|
@@ -2311,6 +2328,7 @@ export declare type Trade_Filter = {
|
|
|
2311
2328
|
buyAmount_not?: InputMaybe<Scalars['BigInt']>;
|
|
2312
2329
|
buyAmount_not_in?: InputMaybe<Array<Scalars['BigInt']>>;
|
|
2313
2330
|
buyToken?: InputMaybe<Scalars['String']>;
|
|
2331
|
+
buyToken_?: InputMaybe<Token_Filter>;
|
|
2314
2332
|
buyToken_contains?: InputMaybe<Scalars['String']>;
|
|
2315
2333
|
buyToken_contains_nocase?: InputMaybe<Scalars['String']>;
|
|
2316
2334
|
buyToken_ends_with?: InputMaybe<Scalars['String']>;
|
|
@@ -2355,6 +2373,7 @@ export declare type Trade_Filter = {
|
|
|
2355
2373
|
id_not?: InputMaybe<Scalars['ID']>;
|
|
2356
2374
|
id_not_in?: InputMaybe<Array<Scalars['ID']>>;
|
|
2357
2375
|
order?: InputMaybe<Scalars['String']>;
|
|
2376
|
+
order_?: InputMaybe<Order_Filter>;
|
|
2358
2377
|
order_contains?: InputMaybe<Scalars['String']>;
|
|
2359
2378
|
order_contains_nocase?: InputMaybe<Scalars['String']>;
|
|
2360
2379
|
order_ends_with?: InputMaybe<Scalars['String']>;
|
|
@@ -2399,6 +2418,7 @@ export declare type Trade_Filter = {
|
|
|
2399
2418
|
sellAmount_not?: InputMaybe<Scalars['BigInt']>;
|
|
2400
2419
|
sellAmount_not_in?: InputMaybe<Array<Scalars['BigInt']>>;
|
|
2401
2420
|
sellToken?: InputMaybe<Scalars['String']>;
|
|
2421
|
+
sellToken_?: InputMaybe<Token_Filter>;
|
|
2402
2422
|
sellToken_contains?: InputMaybe<Scalars['String']>;
|
|
2403
2423
|
sellToken_contains_nocase?: InputMaybe<Scalars['String']>;
|
|
2404
2424
|
sellToken_ends_with?: InputMaybe<Scalars['String']>;
|
|
@@ -2419,6 +2439,7 @@ export declare type Trade_Filter = {
|
|
|
2419
2439
|
sellToken_starts_with?: InputMaybe<Scalars['String']>;
|
|
2420
2440
|
sellToken_starts_with_nocase?: InputMaybe<Scalars['String']>;
|
|
2421
2441
|
settlement?: InputMaybe<Scalars['String']>;
|
|
2442
|
+
settlement_?: InputMaybe<Settlement_Filter>;
|
|
2422
2443
|
settlement_contains?: InputMaybe<Scalars['String']>;
|
|
2423
2444
|
settlement_contains_nocase?: InputMaybe<Scalars['String']>;
|
|
2424
2445
|
settlement_ends_with?: InputMaybe<Scalars['String']>;
|
|
@@ -2527,6 +2548,7 @@ export declare type UniswapPool_Filter = {
|
|
|
2527
2548
|
token0Price_lte?: InputMaybe<Scalars['BigDecimal']>;
|
|
2528
2549
|
token0Price_not?: InputMaybe<Scalars['BigDecimal']>;
|
|
2529
2550
|
token0Price_not_in?: InputMaybe<Array<Scalars['BigDecimal']>>;
|
|
2551
|
+
token0_?: InputMaybe<UniswapToken_Filter>;
|
|
2530
2552
|
token0_contains?: InputMaybe<Scalars['String']>;
|
|
2531
2553
|
token0_contains_nocase?: InputMaybe<Scalars['String']>;
|
|
2532
2554
|
token0_ends_with?: InputMaybe<Scalars['String']>;
|
|
@@ -2555,6 +2577,7 @@ export declare type UniswapPool_Filter = {
|
|
|
2555
2577
|
token1Price_lte?: InputMaybe<Scalars['BigDecimal']>;
|
|
2556
2578
|
token1Price_not?: InputMaybe<Scalars['BigDecimal']>;
|
|
2557
2579
|
token1Price_not_in?: InputMaybe<Array<Scalars['BigDecimal']>>;
|
|
2580
|
+
token1_?: InputMaybe<UniswapToken_Filter>;
|
|
2558
2581
|
token1_contains?: InputMaybe<Scalars['String']>;
|
|
2559
2582
|
token1_contains_nocase?: InputMaybe<Scalars['String']>;
|
|
2560
2583
|
token1_ends_with?: InputMaybe<Scalars['String']>;
|
|
@@ -2638,6 +2661,7 @@ export declare type UniswapToken_Filter = {
|
|
|
2638
2661
|
address_not_contains?: InputMaybe<Scalars['Bytes']>;
|
|
2639
2662
|
address_not_in?: InputMaybe<Array<Scalars['Bytes']>>;
|
|
2640
2663
|
allowedPools?: InputMaybe<Array<Scalars['String']>>;
|
|
2664
|
+
allowedPools_?: InputMaybe<UniswapToken_Filter>;
|
|
2641
2665
|
allowedPools_contains?: InputMaybe<Array<Scalars['String']>>;
|
|
2642
2666
|
allowedPools_contains_nocase?: InputMaybe<Array<Scalars['String']>>;
|
|
2643
2667
|
allowedPools_not?: InputMaybe<Array<Scalars['String']>>;
|
|
@@ -2793,6 +2817,7 @@ export declare type User_Filter = {
|
|
|
2793
2817
|
numberOfTrades_lte?: InputMaybe<Scalars['Int']>;
|
|
2794
2818
|
numberOfTrades_not?: InputMaybe<Scalars['Int']>;
|
|
2795
2819
|
numberOfTrades_not_in?: InputMaybe<Array<Scalars['Int']>>;
|
|
2820
|
+
ordersPlaced_?: InputMaybe<Order_Filter>;
|
|
2796
2821
|
solvedAmountEth?: InputMaybe<Scalars['BigDecimal']>;
|
|
2797
2822
|
solvedAmountEth_gt?: InputMaybe<Scalars['BigDecimal']>;
|
|
2798
2823
|
solvedAmountEth_gte?: InputMaybe<Scalars['BigDecimal']>;
|
|
@@ -1,14 +1,12 @@
|
|
|
1
|
-
|
|
1
|
+
declare type Metadata = {
|
|
2
2
|
version: string;
|
|
3
|
-
}
|
|
4
|
-
export
|
|
3
|
+
};
|
|
4
|
+
export declare type ReferralMetadata = Metadata & {
|
|
5
5
|
address: string;
|
|
6
|
-
}
|
|
7
|
-
export
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
buyAmount: string;
|
|
11
|
-
}
|
|
6
|
+
};
|
|
7
|
+
export declare type QuoteMetadata = Metadata & {
|
|
8
|
+
slippageBips: string;
|
|
9
|
+
};
|
|
12
10
|
export declare type MetadataDoc = {
|
|
13
11
|
referrer?: ReferralMetadata;
|
|
14
12
|
quote?: QuoteMetadata;
|
|
@@ -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",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"},environment:{$id:"#/properties/environment",description:"Environment from which the order came from",title:"Environment",type:"string",examples:["production","development","staging","ens"]},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"},quote:{$ref:"#/definitions/kindMetadata/quote"}}}},n={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"},bigNumber:{$id:"#/definitions/bigNumber",pattern:"^\\d+$",title:"BigNumber",examples:["90741097240912730913, 0, 75891372"],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"}}},quote:{$id:"#/definitions/quote",required:["version","slippageBips"],title:"Quote",type:"object",properties:{version:{$ref:"#/definitions/version"},slippageBips:{$id:"#/definitions/quote/slippageBips",title:"Slippage tolerance that was applied to the order to get the limit price. Expressed in Basis Points (BIPS)",examples:["5","10","20","100"],pattern:"^\\d+(\\.\\d+)?$",type:"string"}}}}},d={$id:e,$schema:t,description:i,required:r,title:s,type:"object",properties:o,definitions:n};exports.$id=e,exports.$schema=t,exports.default=d,exports.definitions=n,exports.description=i,exports.properties=o,exports.required=r,exports.title=s,exports.type="object";
|
|
2
|
+
//# sourceMappingURL=appData.schema-42d10730.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"appData.schema-42d10730.js","sources":[],"sourcesContent":[],"names":[],"mappings":""}
|
|
@@ -1,2 +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"],n="AppData Root Schema",
|
|
2
|
-
//# sourceMappingURL=appData.schema-
|
|
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"],n="AppData Root Schema",s="object",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"},environment:{$id:"#/properties/environment",description:"Environment from which the order came from",title:"Environment",type:"string",examples:["production","development","staging","ens"]},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"},quote:{$ref:"#/definitions/kindMetadata/quote"}}}},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"},bigNumber:{$id:"#/definitions/bigNumber",pattern:"^\\d+$",title:"BigNumber",examples:["90741097240912730913, 0, 75891372"],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"}}},quote:{$id:"#/definitions/quote",required:["version","slippageBips"],title:"Quote",type:"object",properties:{version:{$ref:"#/definitions/version"},slippageBips:{$id:"#/definitions/quote/slippageBips",title:"Slippage tolerance that was applied to the order to get the limit price. Expressed in Basis Points (BIPS)",examples:["5","10","20","100"],pattern:"^\\d+(\\.\\d+)?$",type:"string"}}}}},a={$id:e,$schema:t,description:i,required:r,title:n,type:"object",properties:o,definitions:d};export{e as $id,t as $schema,a as default,d as definitions,i as description,o as properties,r as required,n as title,s as type};
|
|
2
|
+
//# sourceMappingURL=appData.schema-b8f018d7.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"appData.schema-b8f018d7.js","sources":[],"sourcesContent":[],"names":[],"mappings":""}
|
package/dist/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
var e=require("loglevel"),r=require("cross-fetch"),t=require("@cowprotocol/contracts"),n=require("@cowprotocol/contracts/networks.json"),o=require("graphql-request"),i=require("ajv");function s(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}function a(e){if(e&&e.__esModule)return e;var r=Object.create(null);return e&&Object.keys(e).forEach(function(t){if("default"!==t){var n=Object.getOwnPropertyDescriptor(e,t);Object.defineProperty(r,t,n.get?n:{enumerable:!0,get:function(){return e[t]}})}}),r.default=e,r}var u=/*#__PURE__*/s(e),c=/*#__PURE__*/s(r),d=/*#__PURE__*/s(n),l=/*#__PURE__*/s(i);class h extends Error{constructor(e,r){super(e),this.error_code=void 0,this.error_code=r}}function p(e){if(!e)return"";const r=new URLSearchParams;for(const t of Object.keys(e)){const n=e[t];n&&r.append(t,n.toString())}const t=r.toString();return t?`?${t}`:""}const m="cow-sdk:";var f;exports.SupportedChainId=void 0,(f=exports.SupportedChainId||(exports.SupportedChainId={}))[f.MAINNET=1]="MAINNET",f[f.RINKEBY=4]="RINKEBY",f[f.GNOSIS_CHAIN=100]="GNOSIS_CHAIN";const g=[exports.SupportedChainId.MAINNET,exports.SupportedChainId.RINKEBY,exports.SupportedChainId.GNOSIS_CHAIN],{GPv2Settlement:T}=d.default,v={[exports.SupportedChainId.MAINNET]:T[exports.SupportedChainId.MAINNET].address,[exports.SupportedChainId.RINKEBY]:T[exports.SupportedChainId.RINKEBY].address,[exports.SupportedChainId.GNOSIS_CHAIN]:T[exports.SupportedChainId.GNOSIS_CHAIN].address},P=function(e,r,n,o="v4"){try{let s;function i(e){var r;return s?e:{signature:null==(r=d)?void 0:r.data.toString(),signingScheme:a}}const a="eth_sign"===o?t.SigningScheme.ETHSIGN:t.SigningScheme.EIP712;let c,d=null;try{switch(o){case"v3":c=new t.TypedDataV3Signer(n);break;case"int_v4":c=new t.IntChainIdTypedDataV4Signer(n);break;default:c=n}}catch(p){throw u.default.error(m,"Wallet not supported:",p),new h("Wallet not supported")}const l=function(t,n){try{var o=Promise.resolve(r({...e,signer:c,signingScheme:a})).then(function(e){d=e})}catch(e){return n(e)}return o&&o.then?o.then(void 0,n):o}(0,function(t){if(void 0===(i=t).code&&void 0===i.message)throw u.default.error(m,t),t;var i;if(t.code===A||N.test(t.message))switch(o){case"v4":const o=P(e,r,n,"v3");return s=1,o;case"v3":const i=P(e,r,n,"eth_sign");return s=1,i;default:throw t}else{if(S.test(t.message)){const t=P(e,r,n,"int_v4");return s=1,t}if(t.code===I){const t=P(e,r,n,"eth_sign");return s=1,t}if(w.test(t.message)){const t=P(e,r,n,"v3");return s=1,t}if(k.test(t.message)){const t=P(e,r,n,"eth_sign");return s=1,t}}});return Promise.resolve(l&&l.then?l.then(i):i(l))}catch(f){return Promise.reject(f)}},E=function(e){try{const{chainId:r,signer:n,signingScheme:o,orderId:i}=e,s=C(r);return Promise.resolve(t.signOrderCancellation(s,i,n,x(o)))}catch(e){return Promise.reject(e)}},y=function(e){try{const{chainId:r,signer:n,order:o,signingScheme:i}=e,s=C(r);return Promise.resolve(t.signOrder(s,o,n,x(i)))}catch(e){return Promise.reject(e)}},I=-32603,A=-32601,w=/eth_signTypedData_v4 does not exist/i,k=/eth_signTypedData_v3 does not exist/i,N=/RPC request failed/i,S=/provided chainid .* must match the active chainid/i,D=new Map([[t.SigningScheme.EIP712,{libraryValue:0,apiValue:"eip712"}],[t.SigningScheme.ETHSIGN,{libraryValue:1,apiValue:"ethsign"}],[t.SigningScheme.EIP1271,{libraryValue:2,apiValue:"eip1271"}],[t.SigningScheme.PRESIGN,{libraryValue:3,apiValue:"presign"}]]);function O(e){const r=D.get(e);if(void 0===r)throw new h("Unknown schema "+e);return r}function _(e){return O(e).apiValue}function x(e){return O(e).libraryValue}function C(e){const r=v[e];if(!r)throw new h("Unsupported network. Settlement contract is not deployed");return t.domain(e,r)}var U,b,R,j;!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"}(U||(U={})),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"}(b||(b={}));class H 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?H.apiErrorDetails[e.errorType]||e.errorType:(u.default.error(m,"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 u.default.error(m,"Error handling a 400 error. Likely a problem deserialising the JSON response"),function(e){switch(e){case"get":return b.UNHANDLED_GET_ERROR;case"create":return b.UNHANDLED_CREATE_ERROR;case"delete":return b.UNHANDLED_DELETE_ERROR;default:return u.default.error(m,"[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 u.default.error(m,`[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=b[e.errorType]}}H.apiErrorDetails=b,function(e){e.UnsupportedToken="UnsupportedToken",e.InsufficientLiquidity="InsufficientLiquidity",e.FeeExceedsFrom="FeeExceedsFrom",e.ZeroPrice="ZeroPrice",e.UNHANDLED_ERROR="UNHANDLED_ERROR"}(R||(R={})),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."}(j||(j={}));class L 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?L.quoteErrorDetails[e.errorType]||e.errorType:(u.default.error(m,"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 u.default.error(m,"Error handling 400/404 error. Likely a problem deserialising the JSON response"),L.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 u.default.error(m,"[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=L.quoteErrorDetails[e.errorType],this.data=null==e?void 0:e.data}}L.quoteErrorDetails=j;class V{constructor(e,r){this.symbol=void 0,this.address=void 0,this.symbol=e,this.address=r}}const F={[exports.SupportedChainId.MAINNET]:new V("WETH","0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2"),[exports.SupportedChainId.RINKEBY]:new V("WETH","0xc778417E063141139Fce010982780140Aa0cD5Ab"),[exports.SupportedChainId.GNOSIS_CHAIN]:new V("WXDAI","0xe91D153E0b41518A2Ce8Dd3D7944Fa863463a97d")},B={[exports.SupportedChainId.MAINNET]:"ETH",[exports.SupportedChainId.RINKEBY]:"ETH",[exports.SupportedChainId.GNOSIS_CHAIN]:"XDAI"};function $(e,r){let t=e;return e===B[r]&&(t=F[r].address),t}function q(e,r){try{var t=e()}catch(e){return r(e)}return t&&t.then?t.then(void 0,r):t}const M=function(e,r){try{return e.ok?Promise.resolve(e.json()):Promise.resolve(e.json()).then(function(e){const t=function(e){switch(null==e?void 0:e.errorType){case U.NotFound:case U.NoLiquidity:return{errorType:R.InsufficientLiquidity,description:j.InsufficientLiquidity};case U.SellAmountDoesNotCoverFee:return{errorType:R.FeeExceedsFrom,description:j.FeeExceedsFrom,data:null==e?void 0:e.data};case U.UnsupportedToken:return{errorType:R.UnsupportedToken,description:e.description};case U.SellAmountDoesNotCoverFee:return{errorType:R.FeeExceedsFrom,description:e.description};default:return{errorType:R.UNHANDLED_ERROR,description:j.UNHANDLED_ERROR}}}(e),n=new L(t);if(r){const{sellToken:e,buyToken:t}=r;u.default.error(m,`Error querying fee from API - sellToken: ${e}, buyToken: ${t}`)}throw n})}catch(e){return Promise.reject(e)}},G={errorType:R.UNHANDLED_ERROR,description:j.UNHANDLED_ERROR},K={errorType:U.UNHANDLED_CREATE_ERROR,description:b.UNHANDLED_CREATE_ERROR};class Q{constructor(e){this.context=void 0,this.API_NAME="CoW Protocol",this.context=e}get DEFAULT_HEADERS(){return{"Content-Type":"application/json","X-AppId":this.context.appDataHash}}get API_BASE_URL(){return this.context.isDevEnvironment?{[exports.SupportedChainId.MAINNET]:"https://barn.api.cow.fi/mainnet/api",[exports.SupportedChainId.RINKEBY]:"https://barn.api.cow.fi/rinkeby/api",[exports.SupportedChainId.GNOSIS_CHAIN]:"https://barn.api.cow.fi/xdai/api"}:{[exports.SupportedChainId.MAINNET]:"https://api.cow.fi/mainnet/api",[exports.SupportedChainId.RINKEBY]:"https://api.cow.fi/rinkeby/api",[exports.SupportedChainId.GNOSIS_CHAIN]:"https://api.cow.fi/xdai/api"}}get PROFILE_API_BASE_URL(){return this.context.isDevEnvironment?{[exports.SupportedChainId.MAINNET]:"https://barn.api.cow.fi/affiliate/api"}:{[exports.SupportedChainId.MAINNET]:"https://api.cow.fi/affiliate/api"}}getProfileData(e){try{const r=this;return Promise.resolve(r.context.chainId).then(function(t){return u.default.debug(m,`[api:${r.API_NAME}] Get profile data for`,t,e),t!==exports.SupportedChainId.MAINNET?(u.default.info(m,"Profile data is only available for mainnet"),null):Promise.resolve(r.getProfile(`/profile/${e}`)).then(function(e){return e.ok?e.json():Promise.resolve(e.json()).then(function(e){throw u.default.error(m,e),new h(null==e?void 0:e.description)})})})}catch(e){return Promise.reject(e)}}getTrades(e){try{const r=this,{owner:t,orderId:n,limit:o,offset:i}=e;if(t&&n)throw new h("Cannot specify both owner and orderId");const s=p({owner:t,orderUid:n,limit:o,offset:i});return Promise.resolve(r.context.chainId).then(function(e){return u.default.debug(m,"[util:operator] Get trades for",e,{owner:t,orderId:n,limit:o,offset:i}),q(function(){return Promise.resolve(r.get(`/trades${s}`)).then(function(e){return e.ok?e.json():Promise.resolve(e.json()).then(function(e){throw new H(e)})})},function(e){if(u.default.error(m,"Error getting trades:",e),e instanceof H)throw e;throw 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=p({limit:n,offset:o});return Promise.resolve(r.context.chainId).then(function(e){return u.default.debug(m,`[api:${r.API_NAME}] Get orders for `,e,t,n,o),q(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 H(e)})})},function(e){if(u.default.error(m,"Error getting orders information:",e),e instanceof H)throw e;throw new H(K)})})}catch(e){return Promise.reject(e)}}getTxOrders(e){try{const r=this;return Promise.resolve(r.context.chainId).then(function(t){return u.default.debug(`[api:${r.API_NAME}] Get tx orders for `,t,e),q(function(){return Promise.resolve(r.get(`/transactions/${e}/orders`)).then(function(e){return e.ok?e.json():Promise.resolve(e.json()).then(function(e){throw new H(e)})})},function(e){if(u.default.error("Error getting transaction orders information:",e),e instanceof H)throw e;throw new H(K)})})}catch(e){return Promise.reject(e)}}getOrder(e){try{const r=this;return Promise.resolve(r.context.chainId).then(function(t){return u.default.debug(m,`[api:${r.API_NAME}] Get order for `,t,e),q(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 H(e)})})},function(e){if(u.default.error(m,"Error getting order information:",e),e instanceof H)throw e;throw new H(K)})})}catch(e){return Promise.reject(e)}}getPriceQuoteLegacy(e){try{const r=this,{baseToken:t,quoteToken:n,amount:o,kind:i}=e;return Promise.resolve(r.context.chainId).then(function(s){return u.default.debug(m,`[api:${r.API_NAME}] Get price from API`,e,"for",s),Promise.resolve(r.get(`/markets/${$(t,s)}-${$(n,s)}/${i}/${o}`).catch(e=>{throw u.default.error(m,"Error getting price quote:",e),new L(G)})).then(M)})}catch(e){return Promise.reject(e)}}getQuote(e){try{const r=this;return Promise.resolve(r.context.chainId).then(function(t){const n=r.mapNewToLegacyParams(e,t);return Promise.resolve(r.post("/quote",n)).then(M)})}catch(e){return Promise.reject(e)}}sendSignedOrderCancellation(e){try{const r=this,{cancellation:t,owner:n}=e;return Promise.resolve(r.context.chainId).then(function(e){return u.default.debug(m,`[api:${r.API_NAME}] Delete signed order for network`,e,t),Promise.resolve(r.delete(`/orders/${t.orderUid}`,{signature:t.signature,signingScheme:_(t.signingScheme),from:n})).then(function(n){function o(n){u.default.debug(m,`[api:${r.API_NAME}] Cancelled order`,t.orderUid,e)}const i=function(){if(!n.ok)return Promise.resolve(H.getErrorFromStatusCode(n,"delete")).then(function(e){throw new h(e)})}();return i&&i.then?i.then(o):o()})})}catch(e){return Promise.reject(e)}}sendOrder(e){try{const r=this,t={...e.order,appData:r.context.appDataHash};return Promise.resolve(r.context.chainId).then(function(n){const{owner:o}=e;return u.default.debug(m,`[api:${r.API_NAME}] Post signed order for network`,n,t),Promise.resolve(r.post("/orders",{...t,signingScheme:_(t.signingScheme),from:o})).then(function(e){function t(t){return Promise.resolve(e.json()).then(function(e){return u.default.debug(m,`[api:${r.API_NAME}] Success posting the signed order`,e),e})}const n=function(){if(!e.ok)return Promise.resolve(H.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:n,kind:o,userAddress:i,receiver:s,validTo:a,sellToken:u,buyToken:c}=e,d=i||"0x0000000000000000000000000000000000000000",l={sellToken:$(u,r),buyToken:$(c,r),from:d,receiver:s||d,appData:this.context.appDataHash,validTo:a,partiallyFillable:!1};return o===t.OrderKind.SELL?{kind:t.OrderKind.SELL,sellAmountBeforeFee:n,...l}:{kind:t.OrderKind.BUY,buyAmountAfterFee:n,...l}}getApiBaseUrl(){try{const e=this;return Promise.resolve(e.context.chainId).then(function(r){const t=e.API_BASE_URL[r];if(t)return t+"/v1";throw new h(`Unsupported Network. The ${e.API_NAME} API is not deployed in the Network `+r)})}catch(e){return Promise.reject(e)}}getProfileApiBaseUrl(){try{const e=this;return Promise.resolve(e.context.chainId).then(function(r){const t=e.PROFILE_API_BASE_URL[r];if(t)return t+"/v1";throw new h(`Unsupported Network. The ${e.API_NAME} API is not deployed in the Network `+r)})}catch(e){return Promise.reject(e)}}fetch(e,r,t){try{const n=this;return Promise.resolve(n.getApiBaseUrl()).then(function(o){return c.default(o+e,{headers:n.DEFAULT_HEADERS,method:r,body:void 0!==t?JSON.stringify(t):t})})}catch(e){return Promise.reject(e)}}fetchProfile(e,r,t){try{const n=this;return Promise.resolve(n.getProfileApiBaseUrl()).then(function(o){return c.default(o+e,{headers:n.DEFAULT_HEADERS,method:r,body:void 0!==t?JSON.stringify(t):t})})}catch(e){return Promise.reject(e)}}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 Y=o.gql`
|
|
1
|
+
var e=require("loglevel"),t=require("cross-fetch"),r=require("@cowprotocol/contracts"),n=require("@cowprotocol/contracts/networks.json"),o=require("graphql-request"),i=require("ajv");function s(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}function a(e){if(e&&e.__esModule)return e;var t=Object.create(null);return e&&Object.keys(e).forEach(function(r){if("default"!==r){var n=Object.getOwnPropertyDescriptor(e,r);Object.defineProperty(t,r,n.get?n:{enumerable:!0,get:function(){return e[r]}})}}),t.default=e,t}var c=/*#__PURE__*/s(e),u=/*#__PURE__*/s(t),d=/*#__PURE__*/s(n),l=/*#__PURE__*/s(i);class h extends Error{constructor(e,t){super(e),this.error_code=void 0,this.error_code=t}}function p(e){if(!e)return"";const t=new URLSearchParams;for(const r of Object.keys(e)){const n=e[r];n&&t.append(r,n.toString())}const r=t.toString();return r?`?${r}`:""}const m="cow-sdk:";var f;exports.SupportedChainId=void 0,(f=exports.SupportedChainId||(exports.SupportedChainId={}))[f.MAINNET=1]="MAINNET",f[f.RINKEBY=4]="RINKEBY",f[f.GOERLI=5]="GOERLI",f[f.GNOSIS_CHAIN=100]="GNOSIS_CHAIN";const v=[exports.SupportedChainId.MAINNET,exports.SupportedChainId.RINKEBY,exports.SupportedChainId.GOERLI,exports.SupportedChainId.GNOSIS_CHAIN],{GPv2Settlement:g}=d.default,E={[exports.SupportedChainId.MAINNET]:g[exports.SupportedChainId.MAINNET].address,[exports.SupportedChainId.RINKEBY]:g[exports.SupportedChainId.RINKEBY].address,[exports.SupportedChainId.GOERLI]:g[exports.SupportedChainId.GOERLI].address,[exports.SupportedChainId.GNOSIS_CHAIN]:g[exports.SupportedChainId.GNOSIS_CHAIN].address},T=function(e,t,n,o="v4"){try{let s;function i(e){var t;return s?e:{signature:null==(t=d)?void 0:t.data.toString(),signingScheme:a}}const a="eth_sign"===o?r.SigningScheme.ETHSIGN:r.SigningScheme.EIP712;let u,d=null;try{switch(o){case"v3":u=new r.TypedDataV3Signer(n);break;case"int_v4":u=new r.IntChainIdTypedDataV4Signer(n);break;default:u=n}}catch(p){throw c.default.error(m,"Wallet not supported:",p),new h("Wallet not supported")}const l=function(r,n){try{var o=Promise.resolve(t({...e,signer:u,signingScheme:a})).then(function(e){d=e})}catch(e){return n(e)}return o&&o.then?o.then(void 0,n):o}(0,function(r){if(void 0===(i=r).code&&void 0===i.message)throw c.default.error(m,r),r;var i;if(r.code===A||N.test(r.message))switch(o){case"v4":const o=T(e,t,n,"v3");return s=1,o;case"v3":const i=T(e,t,n,"eth_sign");return s=1,i;default:throw r}else{if(k.test(r.message)){const r=T(e,t,n,"int_v4");return s=1,r}if(r.code===y){const r=T(e,t,n,"eth_sign");return s=1,r}if(w.test(r.message)){const r=T(e,t,n,"v3");return s=1,r}if(S.test(r.message)){const r=T(e,t,n,"eth_sign");return s=1,r}}});return Promise.resolve(l&&l.then?l.then(i):i(l))}catch(f){return Promise.reject(f)}},P=function(e){try{const{chainId:t,signer:n,signingScheme:o,orderId:i}=e,s=_(t);return Promise.resolve(r.signOrderCancellation(s,i,n,C(o)))}catch(e){return Promise.reject(e)}},I=function(e){try{const{chainId:t,signer:n,order:o,signingScheme:i}=e,s=_(t);return Promise.resolve(r.signOrder(s,o,n,C(i)))}catch(e){return Promise.reject(e)}},y=-32603,A=-32601,w=/eth_signTypedData_v4 does not exist/i,S=/eth_signTypedData_v3 does not exist/i,N=/RPC request failed/i,k=/provided chainid .* must match the active chainid/i,D=new Map([[r.SigningScheme.EIP712,{libraryValue:0,apiValue:"eip712"}],[r.SigningScheme.ETHSIGN,{libraryValue:1,apiValue:"ethsign"}],[r.SigningScheme.EIP1271,{libraryValue:2,apiValue:"eip1271"}],[r.SigningScheme.PRESIGN,{libraryValue:3,apiValue:"presign"}]]);function O(e){const t=D.get(e);if(void 0===t)throw new h("Unknown schema "+e);return t}function x(e){return O(e).apiValue}function C(e){return O(e).libraryValue}function _(e){const t=E[e];if(!t)throw new h("Unsupported network. Settlement contract is not deployed");return r.domain(e,t)}var b,R,U,L;!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"}(R||(R={}));class j extends h{static getErrorMessage(e,t){try{return Promise.resolve(function(t,r){try{var n=Promise.resolve(e.json()).then(function(e){return e.errorType?j.apiErrorDetails[e.errorType]||e.errorType:(c.default.error(m,"Unknown reason for bad order submission",e),e.description)})}catch(e){return r()}return n&&n.then?n.then(void 0,r):n}(0,function(){return c.default.error(m,"Error handling a 400 error. Likely a problem deserialising the JSON response"),function(e){switch(e){case"get":return R.UNHANDLED_GET_ERROR;case"create":return R.UNHANDLED_CREATE_ERROR;case"delete":return R.UNHANDLED_DELETE_ERROR;default:return c.default.error(m,"[OperatorError::_mapActionToErrorDetails] Uncaught error mapping error action type to server error. Please try again later."),"Something failed. Please try again later."}}(t)}))}catch(e){return Promise.reject(e)}}static getErrorFromStatusCode(e,t){try{const r=this;switch(e.status){case 400:case 404:return Promise.resolve(r.getErrorMessage(e,t));case 403:return Promise.resolve(`The order cannot be ${"create"===t?"accepted":"cancelled"}. Your account is deny-listed.`);case 429:return Promise.resolve(`The order cannot be ${"create"===t?"accepted. Too many order placements":"cancelled. Too many order cancellations"}. Please, retry in a minute`);default:return c.default.error(m,`[OperatorError::getErrorFromStatusCode] Error ${"create"===t?"creating":"cancelling"} the order, status code:`,e.status||"unknown"),Promise.resolve(`Error ${"create"===t?"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=R[e.errorType]}}j.apiErrorDetails=R,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."}(L||(L={}));class H extends h{static getErrorMessage(e){try{return Promise.resolve(function(t,r){try{var n=Promise.resolve(e.json()).then(function(e){return e.errorType?H.quoteErrorDetails[e.errorType]||e.errorType:(c.default.error(m,"Unknown reason for bad quote fetch",e),e.description)})}catch(e){return r()}return n&&n.then?n.then(void 0,r):n}(0,function(){return c.default.error(m,"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 t=this;switch(e.status){case 400:case 404:return Promise.resolve(t.getErrorMessage(e));default:return c.default.error(m,"[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=null==e?void 0:e.data}}H.quoteErrorDetails=L;class V{constructor(e,t){this.symbol=void 0,this.address=void 0,this.symbol=e,this.address=t}}const F={[exports.SupportedChainId.MAINNET]:new V("WETH","0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2"),[exports.SupportedChainId.RINKEBY]:new V("WETH","0xc778417E063141139Fce010982780140Aa0cD5Ab"),[exports.SupportedChainId.GOERLI]:new V("WETH","0xb4fbf271143f4fbf7b91a5ded31805e42b2208d6"),[exports.SupportedChainId.GNOSIS_CHAIN]:new V("WXDAI","0xe91D153E0b41518A2Ce8Dd3D7944Fa863463a97d")},$={[exports.SupportedChainId.MAINNET]:"ETH",[exports.SupportedChainId.RINKEBY]:"ETH",[exports.SupportedChainId.GOERLI]:"ETH",[exports.SupportedChainId.GNOSIS_CHAIN]:"XDAI"};function G(e,t){let r=e;return e===$[t]&&(r=F[t].address),r}function q(e,t){try{var r=e()}catch(e){return t(e)}return r&&r.then?r.then(void 0,t):r}function B(e){return e?{[exports.SupportedChainId.MAINNET]:"https://barn.api.cow.fi/mainnet/api",[exports.SupportedChainId.RINKEBY]:"https://barn.api.cow.fi/rinkeby/api",[exports.SupportedChainId.GOERLI]:"https://barn.api.cow.fi/goerli/api",[exports.SupportedChainId.GNOSIS_CHAIN]:"https://barn.api.cow.fi/xdai/api"}:{[exports.SupportedChainId.MAINNET]:"https://api.cow.fi/mainnet/api",[exports.SupportedChainId.RINKEBY]:"https://api.cow.fi/rinkeby/api",[exports.SupportedChainId.GOERLI]:"https://api.cow.fi/goerli/api",[exports.SupportedChainId.GNOSIS_CHAIN]:"https://api.cow.fi/xdai/api"}}function M(e){return e?{[exports.SupportedChainId.MAINNET]:"https://barn.api.cow.fi/affiliate/api"}:{[exports.SupportedChainId.MAINNET]:"https://api.cow.fi/affiliate/api"}}const K=function(e,t){try{return e.ok?Promise.resolve(e.json()):Promise.resolve(e.json()).then(function(e){const r=function(e){switch(null==e?void 0:e.errorType){case b.NotFound:case b.NoLiquidity:return{errorType:U.InsufficientLiquidity,description:L.InsufficientLiquidity};case b.SellAmountDoesNotCoverFee:return{errorType:U.FeeExceedsFrom,description:L.FeeExceedsFrom,data:null==e?void 0: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:L.UNHANDLED_ERROR}}}(e),n=new H(r);if(t){const{sellToken:e,buyToken:r}=t;c.default.error(m,`Error querying fee from API - sellToken: ${e}, buyToken: ${r}`)}throw n})}catch(e){return Promise.reject(e)}},Q={errorType:U.UNHANDLED_ERROR,description:L.UNHANDLED_ERROR},Y={errorType:b.UNHANDLED_CREATE_ERROR,description:R.UNHANDLED_CREATE_ERROR};class W{constructor(e){this.context=void 0,this.API_NAME="CoW Protocol",this.context=e}get DEFAULT_HEADERS(){return{"Content-Type":"application/json","X-AppId":this.context.appDataHash}}get API_BASE_URL(){return B(this.context.isDevEnvironment)}getProfileData(e,t={}){try{const r=this;function n(t){return c.default.debug(m,`[api:${r.API_NAME}] Get profile data for`,t,e),t!==exports.SupportedChainId.MAINNET?(c.default.info(m,"Profile data is only available for mainnet"),null):Promise.resolve(r.getProfile(`/profile/${e}`,{chainId:t,isDevEnvironment:i})).then(function(e){return e.ok?e.json():Promise.resolve(e.json()).then(function(e){throw c.default.error(m,e),new h(null==e?void 0:e.description)})})}const{chainId:o,isDevEnvironment:i}=t;return Promise.resolve(o?n(o):Promise.resolve(r.context.chainId).then(n))}catch(s){return Promise.reject(s)}}getTrades(e,t={}){try{const r=this;function n(e){return c.default.debug(m,"[util:operator] Get trades for",e,{owner:s,orderId:a,limit:u,offset:d}),q(function(){return Promise.resolve(r.get(`/trades${l}`,{chainId:e,isDevEnvironment:i})).then(function(e){return e.ok?e.json():Promise.resolve(e.json()).then(function(e){throw new j(e)})})},function(e){if(c.default.error(m,"Error getting trades:",e),e instanceof j)throw e;throw new h("Error getting trades: "+e)})}const{chainId:o,isDevEnvironment:i=r.context.isDevEnvironment}=t,{owner:s,orderId:a,limit:u,offset:d}=e;if(s&&a)throw new h("Cannot specify both owner and orderId");const l=p({owner:s,orderUid:a,limit:u,offset:d});return Promise.resolve(o?n(o):Promise.resolve(r.context.chainId).then(n))}catch(f){return Promise.reject(f)}}getOrders(e,t={}){try{const r=this;function n(e){return c.default.debug(m,`[api:${r.API_NAME}] Get orders for `,e,s,a,u),q(function(){return Promise.resolve(r.get(`/account/${s}/orders/${d}`,{chainId:e,isDevEnvironment:i})).then(function(e){return e.ok?e.json():Promise.resolve(e.json()).then(function(e){throw new j(e)})})},function(e){if(c.default.error(m,"Error getting orders information:",e),e instanceof j)throw e;throw new j(Y)})}const{chainId:o,isDevEnvironment:i=r.context.isDevEnvironment}=t,{owner:s,limit:a=1e3,offset:u=0}=e,d=p({limit:a,offset:u});return Promise.resolve(o?n(o):Promise.resolve(r.context.chainId).then(n))}catch(l){return Promise.reject(l)}}getTxOrders(e,t={}){try{const r=this;function n(t){return c.default.debug(`[api:${r.API_NAME}] Get tx orders for `,t,e),q(function(){return Promise.resolve(r.get(`/transactions/${e}/orders`,{chainId:t,isDevEnvironment:i})).then(function(e){return e.ok?e.json():Promise.resolve(e.json()).then(function(e){throw new j(e)})})},function(e){if(c.default.error("Error getting transaction orders information:",e),e instanceof j)throw e;throw new j(Y)})}const{chainId:o,isDevEnvironment:i}=t;return Promise.resolve(o?n(o):Promise.resolve(r.context.chainId).then(n))}catch(s){return Promise.reject(s)}}getOrder(e,t={}){try{const r=this;function n(t){return c.default.debug(m,`[api:${r.API_NAME}] Get order for `,t,e),q(function(){return Promise.resolve(r.get(`/orders/${e}`,{chainId:t,isDevEnvironment:i})).then(function(e){return e.ok?e.json():Promise.resolve(e.json()).then(function(e){throw new j(e)})})},function(e){if(c.default.error(m,"Error getting order information:",e),e instanceof j)throw e;throw new j(Y)})}const{chainId:o,isDevEnvironment:i}=t;return Promise.resolve(o?n(o):Promise.resolve(r.context.chainId).then(n))}catch(s){return Promise.reject(s)}}getPriceQuoteLegacy(e,t={}){try{const r=this;function n(t){return c.default.debug(m,`[api:${r.API_NAME}] Get price from API`,e,"for",t),Promise.resolve(r.get(`/markets/${G(s,t)}-${G(a,t)}/${d}/${u}`,{chainId:t,isDevEnvironment:i}).catch(e=>{throw c.default.error(m,"Error getting price quote:",e),new H(Q)})).then(K)}const{chainId:o,isDevEnvironment:i}=t,{baseToken:s,quoteToken:a,amount:u,kind:d}=e;return Promise.resolve(o?n(o):Promise.resolve(r.context.chainId).then(n))}catch(l){return Promise.reject(l)}}getQuote(e,t={}){try{const r=this;function n(t){const n=r.mapNewToLegacyParams(e,t);return Promise.resolve(r.post("/quote",n,{chainId:t,isDevEnvironment:i})).then(K)}const{chainId:o,isDevEnvironment:i}=t;return Promise.resolve(o?n(o):Promise.resolve(r.context.chainId).then(n))}catch(s){return Promise.reject(s)}}sendSignedOrderCancellation(e,t={}){try{const r=this;function n(e){return c.default.debug(m,`[api:${r.API_NAME}] Delete signed order for network`,e,s),Promise.resolve(r.delete(`/orders/${s.orderUid}`,{signature:s.signature,signingScheme:x(s.signingScheme),from:a},{chainId:e,isDevEnvironment:i})).then(function(t){function n(t){c.default.debug(m,`[api:${r.API_NAME}] Cancelled order`,s.orderUid,e)}const o=function(){if(!t.ok)return Promise.resolve(j.getErrorFromStatusCode(t,"delete")).then(function(e){throw new h(e)})}();return o&&o.then?o.then(n):n()})}const{chainId:o,isDevEnvironment:i}=t,{cancellation:s,owner:a}=e;return Promise.resolve(o?n(o):Promise.resolve(r.context.chainId).then(n))}catch(u){return Promise.reject(u)}}sendOrder(e,t={}){try{const r=this;function n(t){const{owner:n}=e;return c.default.debug(m,`[api:${r.API_NAME}] Post signed order for network`,t,o),Promise.resolve(r.post("/orders",{...o,signingScheme:x(o.signingScheme),from:n},{chainId:t,isDevEnvironment:s})).then(function(e){function t(t){return Promise.resolve(e.json()).then(function(e){return c.default.debug(m,`[api:${r.API_NAME}] Success posting the signed order`,e),e})}const n=function(){if(!e.ok)return Promise.resolve(j.getErrorFromStatusCode(e,"create")).then(function(e){throw new h(e)})}();return n&&n.then?n.then(t):t()})}const o={...e.order,appData:r.context.appDataHash},{chainId:i,isDevEnvironment:s}=t;return Promise.resolve(i?n(i):Promise.resolve(r.context.chainId).then(n))}catch(a){return Promise.reject(a)}}getOrderLink(e){try{return Promise.resolve(this.getApiBaseUrl()).then(function(t){return t+`/orders/${e}`})}catch(e){return Promise.reject(e)}}mapNewToLegacyParams(e,t){const{amount:n,kind:o,userAddress:i,receiver:s,validTo:a,sellToken:c,buyToken:u}=e,d=i||"0x0000000000000000000000000000000000000000",l={sellToken:G(c,t),buyToken:G(u,t),from:d,receiver:s||d,appData:this.context.appDataHash,validTo:a,partiallyFillable:!1};return o===r.OrderKind.SELL?{kind:r.OrderKind.SELL,sellAmountBeforeFee:n,...l}:{kind:r.OrderKind.BUY,buyAmountAfterFee:n,...l}}getApiBaseUrl(){try{const e=this;return Promise.resolve(e.context.chainId).then(function(t){const r=e.API_BASE_URL[t];if(r)return r+"/v1";throw new h(`Unsupported Network. The ${e.API_NAME} API is not deployed in the Network `+t)})}catch(e){return Promise.reject(e)}}fetch(e,t,r,n){try{return Promise.resolve(u.default(r+e,{headers:this.DEFAULT_HEADERS,method:t,body:void 0!==n?JSON.stringify(n):n}))}catch(e){return Promise.reject(e)}}fetchProfile(e,t,r,n){try{return Promise.resolve(u.default(r+e,{headers:this.DEFAULT_HEADERS,method:t,body:void 0!==n?JSON.stringify(n):n}))}catch(e){return Promise.reject(e)}}post(e,t,r={}){return this.handleMethod(e,"POST",this.fetch.bind(this),B,r,t)}get(e,t={}){return this.handleMethod(e,"GET",this.fetch.bind(this),B,t)}getProfile(e,t={}){return this.handleMethod(e,"GET",this.fetchProfile.bind(this),M,t)}delete(e,t,r={}){return this.handleMethod(e,"DELETE",this.fetch.bind(this),B,r,t)}handleMethod(e,t,r,n,o={},i){try{const s=this;function a(n){let o;const s=function(){if(void 0!==u)return Promise.resolve(r(e,t,`${(u?l:d)[n]}/v1`,i)).then(function(e){o=e});{const s=q(function(){return Promise.resolve(r(e,t,`${d[n]}/v1`,i)).then(function(e){o=e})},function(){return Promise.resolve(r(e,t,`${l[n]}/v1`,i)).then(function(e){o=e})});if(s&&s.then)return s.then(function(){})}}();return s&&s.then?s.then(function(){return o}):o}const{chainId:c,isDevEnvironment:u}=o,d=n(!1),l=n(!0);return Promise.resolve(c?a(c):Promise.resolve(s.context.chainId).then(a))}catch(h){return Promise.reject(h)}}}const J=o.gql`
|
|
2
2
|
query Totals {
|
|
3
3
|
totals {
|
|
4
4
|
tokens
|
|
@@ -11,19 +11,19 @@ var e=require("loglevel"),r=require("cross-fetch"),t=require("@cowprotocol/contr
|
|
|
11
11
|
feesEth
|
|
12
12
|
}
|
|
13
13
|
}
|
|
14
|
-
`,
|
|
14
|
+
`,Z=o.gql`
|
|
15
15
|
query LastDaysVolume($days: Int!) {
|
|
16
16
|
dailyTotals(orderBy: timestamp, orderDirection: desc, first: $days) {
|
|
17
17
|
timestamp
|
|
18
18
|
volumeUsd
|
|
19
19
|
}
|
|
20
20
|
}
|
|
21
|
-
`,
|
|
21
|
+
`,z=o.gql`
|
|
22
22
|
query LastHoursVolume($hours: Int!) {
|
|
23
23
|
hourlyTotals(orderBy: timestamp, orderDirection: desc, first: $hours) {
|
|
24
24
|
timestamp
|
|
25
25
|
volumeUsd
|
|
26
26
|
}
|
|
27
27
|
}
|
|
28
|
-
`,Z={[exports.SupportedChainId.MAINNET]:"https://api.thegraph.com/subgraphs/name/cowprotocol/cow",[exports.SupportedChainId.RINKEBY]:"https://api.thegraph.com/subgraphs/name/cowprotocol/cow-rinkeby",[exports.SupportedChainId.GNOSIS_CHAIN]:"https://api.thegraph.com/subgraphs/name/cowprotocol/cow-gc"};class z{constructor(e){this.context=void 0,this.clients=void 0,this.API_NAME="CoW Protocol Subgraph",this.context=e,this.clients=this.createClients()}createClients(){return{[exports.SupportedChainId.MAINNET]:new o.GraphQLClient(Z[exports.SupportedChainId.MAINNET],{fetch:c.default}),[exports.SupportedChainId.RINKEBY]:new o.GraphQLClient(Z[exports.SupportedChainId.RINKEBY],{fetch:c.default}),[exports.SupportedChainId.GNOSIS_CHAIN]:new o.GraphQLClient(Z[exports.SupportedChainId.GNOSIS_CHAIN],{fetch:c.default})}}getBaseUrl(){try{return Promise.resolve(this.context.chainId).then(function(e){return Z[e]})}catch(e){return Promise.reject(e)}}getTotals(){try{const e=this;return Promise.resolve(e.context.chainId).then(function(r){return u.default.debug(`[subgraph:${e.API_NAME}] Get totals for:`,r),Promise.resolve(e.runQuery(Y)).then(function(e){return e.totals[0]})})}catch(e){return Promise.reject(e)}}getLastDaysVolume(e){try{const r=this;return Promise.resolve(r.context.chainId).then(function(t){return u.default.debug(`[subgraph:${r.API_NAME}] Get last ${e} days volume for:`,t),r.runQuery(W,{days:e})})}catch(e){return Promise.reject(e)}}getLastHoursVolume(e){try{const r=this;return Promise.resolve(r.context.chainId).then(function(t){return u.default.debug(`[subgraph:${r.API_NAME}] Get last ${e} hours volume for:`,t),r.runQuery(J,{hours:e})})}catch(e){return Promise.reject(e)}}runQuery(e,r){try{const t=this;return Promise.resolve(function(n,o){try{var i=Promise.resolve(t.context.chainId).then(function(n){return Promise.resolve(t.clients[n].request(e,r))})}catch(e){return o(e)}return i&&i.then?i.then(void 0,o):i}(0,function(n){return u.default.error(n),Promise.resolve(t.getBaseUrl()).then(function(t){throw new h(`Error running query: ${e}. Variables: ${JSON.stringify(r)}. API: ${t}. Inner Error: ${n}`)})}))}catch(e){return Promise.reject(e)}}}const X=function(e){return Promise.resolve(re()).then(function({ajv:r,validate:t}){return{result:!!t(e),errors:r.errors?r.errorsText(r.errors):void 0}})},ee=function(e){try{const r=1,t=112,n=18,o=32,i=function(e){const r=e.match(/.{1,2}/g);if(r)return new Uint8Array(r.map(e=>parseInt(e,16)))}(e.replace(/(^0x)/,""));if(!i)return Promise.resolve();const s=Uint8Array.from([r,t,n,o,...i]);return Promise.resolve(Promise.resolve().then(function(){/*#__PURE__*/return a(require("multiformats/cid"))})).then(function({CID:e}){return e.decode(s).toV0().toString()})}catch(e){return Promise.reject(e)}},re=function(){try{function e(){return{ajv:ne,validate:te}}ne||(ne=new l.default);const r=function(){if(!te)return Promise.resolve(Promise.resolve().then(function(){return require("./appData.schema-4c010c50.js")})).then(function(e){te=ne.compile(e)})}();return Promise.resolve(r&&r.then?r.then(e):e())}catch(t){return Promise.reject(t)}};let te,ne;function oe(e,r){try{var t=e()}catch(e){return r(e)}return t&&t.then?t.then(void 0,r):t}const ie="CowSwap";class se{constructor(e){this.context=void 0,this.context=e}generateAppDataDoc(e={},r){const{appCode:t=ie,environment:n}=r||{};return{version:"0.3.0",appCode:t,environment:n,metadata:{...e}}}decodeAppData(e){try{return Promise.resolve(oe(function(){return Promise.resolve(ee(e)).then(function(e){if(!e)throw new h("Error getting serialized CID");return function(e,r="https://gnosis.mypinata.cloud/ipfs"){try{return Promise.resolve(Promise.resolve().then(function(){/*#__PURE__*/return a(require("cross-fetch"))})).then(function({default:t}){return Promise.resolve(t(`${r}/${e}`)).then(function(e){return Promise.resolve(e.json())})})}catch(e){return Promise.reject(e)}}(e)})},function(e){const r=e;throw u.default.error("Error decoding AppData:",r),new h("Error decoding AppData: "+r.message)}))}catch(e){return Promise.reject(e)}}cidToAppDataHex(e){try{return Promise.resolve(Promise.resolve().then(function(){/*#__PURE__*/return a(require("multiformats/cid"))})).then(function({CID:r}){const{digest:t}=r.parse(e).multihash;return`0x${Buffer.from(t).toString("hex")}`})}catch(e){return Promise.reject(e)}}appDataHexToCid(e){try{return Promise.resolve(ee(e)).then(function(e){if(!e)throw new h("Error getting serialized CID");return e})}catch(e){return Promise.reject(e)}}calculateAppDataHash(e){try{const r=this;return Promise.resolve(X(e)).then(function(t){if(null==t||!t.result)throw new h("Invalid appData provided",null==t?void 0:t.errors);return oe(function(){return Promise.resolve(function(e){try{const r=JSON.stringify(e);return Promise.resolve(Promise.resolve().then(function(){/*#__PURE__*/return a(require("ipfs-only-hash"))})).then(function({of:e}){return e(r,{cidVersion:0})})}catch(e){return Promise.reject(e)}}(e)).then(function(e){return Promise.resolve(r.cidToAppDataHex(e)).then(function(r){if(!r)throw new h(`Could not extract appDataHash from calculated cidV0 ${e}`);return{cidV0:e,appDataHash:r}})})},function(e){throw new h("Failed to calculate appDataHash",e.message)})})}catch(e){return Promise.reject(e)}}uploadMetadataDocToIpfs(e){try{const r=this;return Promise.resolve(function(e,{writeUri:r="https://api.pinata.cloud",pinataApiKey:t="",pinataApiSecret:n=""}){try{return Promise.resolve(Promise.resolve().then(function(){/*#__PURE__*/return a(require("cross-fetch"))})).then(function({default:o}){if(!t||!n)throw new h("You need to pass IPFS api credentials.");const i=JSON.stringify({pinataContent:e,pinataMetadata:{name:"appData"}});return Promise.resolve(o(`${r}/pinning/pinJSONToIPFS`,{method:"POST",body:i,headers:{"Content-Type":"application/json",pinata_api_key:t,pinata_secret_api_key:n}})).then(function(e){return Promise.resolve(e.json()).then(function(r){if(200!==e.status)throw new Error(r.error.details||r.error);return r})})})}catch(e){return Promise.reject(e)}}(e,r.context.ipfs)).then(function({IpfsHash:e}){return r.cidToAppDataHex(e)})}catch(e){return Promise.reject(e)}}}var ae=0;function ue(e){return"__private_"+ae+++"_"+e}function ce(e,r){if(!Object.prototype.hasOwnProperty.call(e,r))throw new TypeError("attempted to use private field on non-instance");return e}const de={appDataHash:"0x0000000000000000000000000000000000000000000000000000000000000000",isDevEnvironment:!1,ipfs:{readUri:"https://gnosis.mypinata.cloud/ipfs",writeUri:"https://api.pinata.cloud",apiKey:void 0,apiSecret:void 0}};var le,he,pe,me,fe,ge,Te,ve,Pe,Ee,ye,Ie,Ae,we,ke,Ne,Se,De,Oe,_e=/*#__PURE__*/ue("context"),xe=/*#__PURE__*/ue("chainId");class Ce{constructor(e,r){Object.defineProperty(this,_e,{writable:!0,value:void 0}),Object.defineProperty(this,xe,{writable:!0,value:void 0}),ce(this,xe)[xe]=this.updateChainId(e),ce(this,_e)[_e]={...de,...r,ipfs:{...de.ipfs,...r.ipfs}}}updateChainId(e){if(!exports.SupportedChainId[e])throw new h(`Invalid chainId: ${e}`);return u.default.debug(m,`Updating chainId to: ${e}`),ce(this,xe)[xe]=e,e}get chainId(){const e=this;var r;const t=null==(r=ce(this,_e)[_e].signer)?void 0:r.provider;return t?(u.default.debug(m,"Getting chainId from provider"),function(){try{return Promise.resolve(t.getNetwork()).then(function(r){const t=r.chainId;return t!==ce(e,xe)[xe]&&(u.default.debug(m,`ChainId mismatch: Provider's chainId: ${t} vs Context's chainId: ${ce(e,xe)[xe]}. Updating Context's chainId`),e.updateChainId(t)),t})}catch(e){return Promise.reject(e)}}()):Promise.resolve(ce(this,xe)[xe])}get appDataHash(){var e;return null!==(e=ce(this,_e)[_e].appDataHash)&&void 0!==e?e:de.appDataHash}get isDevEnvironment(){var e;return null!==(e=ce(this,_e)[_e].isDevEnvironment)&&void 0!==e?e:de.isDevEnvironment}get signer(){return ce(this,_e)[_e].signer}get ipfs(){var e;return null!==(e=ce(this,_e)[_e].ipfs)&&void 0!==e?e:de.ipfs}}!function(e){e.EthPriceUsd="ethPriceUSD",e.Id="id"}(le||(le={})),function(e){e.FeesEth="feesEth",e.FeesUsd="feesUsd",e.Id="id",e.NumberOfTrades="numberOfTrades",e.Orders="orders",e.Settlements="settlements",e.Timestamp="timestamp",e.Tokens="tokens",e.TotalTokens="totalTokens",e.VolumeEth="volumeEth",e.VolumeUsd="volumeUsd"}(he||(he={})),function(e){e.FeesEth="feesEth",e.FeesUsd="feesUsd",e.Id="id",e.NumberOfTrades="numberOfTrades",e.Orders="orders",e.Settlements="settlements",e.Timestamp="timestamp",e.Tokens="tokens",e.TotalTokens="totalTokens",e.VolumeEth="volumeEth",e.VolumeUsd="volumeUsd"}(pe||(pe={})),function(e){e.Asc="asc",e.Desc="desc"}(me||(me={})),function(e){e.Id="id",e.InvalidateTimestamp="invalidateTimestamp",e.IsSigned="isSigned",e.IsValid="isValid",e.Owner="owner",e.PresignTimestamp="presignTimestamp",e.Trades="trades",e.TradesTimestamp="tradesTimestamp"}(fe||(fe={})),function(e){e.Id="id",e.Timestamp="timestamp",e.Token0="token0",e.Token0Price="token0Price",e.Token0relativePrice="token0relativePrice",e.Token1="token1",e.Token1Price="token1Price",e.Token1relativePrice="token1relativePrice",e.VolumeToken0="volumeToken0",e.VolumeToken1="volumeToken1",e.VolumeTradedEth="volumeTradedEth",e.VolumeTradedUsd="volumeTradedUsd"}(ge||(ge={})),function(e){e.Id="id",e.Timestamp="timestamp",e.Token0="token0",e.Token0Price="token0Price",e.Token0relativePrice="token0relativePrice",e.Token1="token1",e.Token1Price="token1Price",e.Token1relativePrice="token1relativePrice",e.VolumeToken0="volumeToken0",e.VolumeToken1="volumeToken1",e.VolumeTradedEth="volumeTradedEth",e.VolumeTradedUsd="volumeTradedUsd"}(Te||(Te={})),function(e){e.Id="id",e.Token0="token0",e.Token0Price="token0Price",e.Token0relativePrice="token0relativePrice",e.Token1="token1",e.Token1Price="token1Price",e.Token1relativePrice="token1relativePrice",e.VolumeToken0="volumeToken0",e.VolumeToken1="volumeToken1",e.VolumeTradedEth="volumeTradedEth",e.VolumeTradedUsd="volumeTradedUsd"}(ve||(ve={})),function(e){e.FirstTradeTimestamp="firstTradeTimestamp",e.Id="id",e.Solver="solver",e.Trades="trades",e.TxHash="txHash"}(Pe||(Pe={})),function(e){e.AveragePrice="averagePrice",e.ClosePrice="closePrice",e.HigherPrice="higherPrice",e.Id="id",e.LowerPrice="lowerPrice",e.OpenPrice="openPrice",e.Timestamp="timestamp",e.Token="token",e.TotalTrades="totalTrades",e.TotalVolume="totalVolume",e.TotalVolumeEth="totalVolumeEth",e.TotalVolumeUsd="totalVolumeUsd"}(Ee||(Ee={})),function(e){e.AveragePrice="averagePrice",e.ClosePrice="closePrice",e.HigherPrice="higherPrice",e.Id="id",e.LowerPrice="lowerPrice",e.OpenPrice="openPrice",e.Timestamp="timestamp",e.Token="token",e.TotalTrades="totalTrades",e.TotalVolume="totalVolume",e.TotalVolumeEth="totalVolumeEth",e.TotalVolumeUsd="totalVolumeUsd"}(ye||(ye={})),function(e){e.AmountEth="amountEth",e.AmountUsd="amountUsd",e.Id="id",e.Timestamp="timestamp",e.Token="token",e.Trade="trade"}(Ie||(Ie={})),function(e){e.Address="address",e.Decimals="decimals",e.FirstTradeTimestamp="firstTradeTimestamp",e.History="history",e.Id="id",e.Name="name",e.NumberOfTrades="numberOfTrades",e.PriceEth="priceEth",e.PriceUsd="priceUsd",e.Symbol="symbol",e.TotalVolume="totalVolume",e.TotalVolumeEth="totalVolumeEth",e.TotalVolumeUsd="totalVolumeUsd"}(Ae||(Ae={})),function(e){e.FeesEth="feesEth",e.FeesUsd="feesUsd",e.Id="id",e.NumberOfTrades="numberOfTrades",e.Orders="orders",e.Settlements="settlements",e.Tokens="tokens",e.Traders="traders",e.VolumeEth="volumeEth",e.VolumeUsd="volumeUsd"}(we||(we={})),function(e){e.BuyAmount="buyAmount",e.BuyAmountEth="buyAmountEth",e.BuyAmountUsd="buyAmountUsd",e.BuyToken="buyToken",e.FeeAmount="feeAmount",e.GasPrice="gasPrice",e.Id="id",e.Order="order",e.SellAmount="sellAmount",e.SellAmountEth="sellAmountEth",e.SellAmountUsd="sellAmountUsd",e.SellToken="sellToken",e.Settlement="settlement",e.Timestamp="timestamp",e.TxHash="txHash"}(ke||(ke={})),function(e){e.Id="id",e.Liquidity="liquidity",e.Tick="tick",e.Token0="token0",e.Token0Price="token0Price",e.Token1="token1",e.Token1Price="token1Price",e.TotalValueLockedToken0="totalValueLockedToken0",e.TotalValueLockedToken1="totalValueLockedToken1"}(Ne||(Ne={})),function(e){e.Address="address",e.AllowedPools="allowedPools",e.Decimals="decimals",e.Id="id",e.Name="name",e.PriceEth="priceEth",e.PriceUsd="priceUsd",e.Symbol="symbol"}(Se||(Se={})),function(e){e.Address="address",e.FirstTradeTimestamp="firstTradeTimestamp",e.Id="id",e.IsSolver="isSolver",e.NumberOfTrades="numberOfTrades",e.OrdersPlaced="ordersPlaced",e.SolvedAmountEth="solvedAmountEth",e.SolvedAmountUsd="solvedAmountUsd",e.TradedAmountEth="tradedAmountEth",e.TradedAmountUsd="tradedAmountUsd"}(De||(De={})),function(e){e.Allow="allow",e.Deny="deny"}(Oe||(Oe={}));var Ue={__proto__:null,get Bundle_OrderBy(){return le},get DailyTotal_OrderBy(){return he},get HourlyTotal_OrderBy(){return pe},get OrderDirection(){return me},get Order_OrderBy(){return fe},get PairDaily_OrderBy(){return ge},get PairHourly_OrderBy(){return Te},get Pair_OrderBy(){return ve},get Settlement_OrderBy(){return Pe},get TokenDailyTotal_OrderBy(){return Ee},get TokenHourlyTotal_OrderBy(){return ye},get TokenTradingEvent_OrderBy(){return Ie},get Token_OrderBy(){return Ae},get Total_OrderBy(){return we},get Trade_OrderBy(){return ke},get UniswapPool_OrderBy(){return Ne},get UniswapToken_OrderBy(){return Se},get User_OrderBy(){return De},get _SubgraphErrorPolicy_(){return Oe}};Object.defineProperty(exports,"OrderKind",{enumerable:!0,get:function(){return t.OrderKind}}),exports.ALL_SUPPORTED_CHAIN_IDS=g,exports.CowError=h,exports.CowSdk=class{constructor(e,r={},t={}){this.context=void 0,this.cowApi=void 0,this.metadataApi=void 0,this.cowSubgraphApi=void 0,this.updateChainId=e=>{this.context.updateChainId(e)},this.validateAppDataDocument=X,this.context=new Ce(e,{...r}),this.cowApi=new Q(this.context),this.cowSubgraphApi=new z(this.context),this.metadataApi=new se(this.context),u.default.setLevel(t.loglevel||"error")}signOrder(e){try{const r=this,t=r._checkSigner();return Promise.resolve(r.context.chainId).then(function(n){return function(e,r,t){return P({order:e,chainId:r},y,t)}({...e,appData:r.context.appDataHash},n,t)})}catch(e){return Promise.reject(e)}}signOrderCancellation(e){try{const r=this,t=r._checkSigner();return Promise.resolve(r.context.chainId).then(function(r){return function(e,r,t){return P({orderId:e,chainId:r},E,t)}(e,r,t)})}catch(e){return Promise.reject(e)}}_checkSigner(e=this.context.signer){if(!e)throw new h("No signer available");return e}},exports.GraphQL=Ue,exports.Token=V;
|
|
28
|
+
`,X={[exports.SupportedChainId.MAINNET]:"https://api.thegraph.com/subgraphs/name/cowprotocol/cow",[exports.SupportedChainId.RINKEBY]:"https://api.thegraph.com/subgraphs/name/cowprotocol/cow-rinkeby",[exports.SupportedChainId.GOERLI]:"https://api.thegraph.com/subgraphs/name/cowprotocol/cow-goerli",[exports.SupportedChainId.GNOSIS_CHAIN]:"https://api.thegraph.com/subgraphs/name/cowprotocol/cow-gc"};class ee{constructor(e){this.context=void 0,this.clients=void 0,this.API_NAME="CoW Protocol Subgraph",this.context=e,this.clients=this.createClients()}createClients(){return{[exports.SupportedChainId.MAINNET]:new o.GraphQLClient(X[exports.SupportedChainId.MAINNET],{fetch:u.default}),[exports.SupportedChainId.RINKEBY]:new o.GraphQLClient(X[exports.SupportedChainId.RINKEBY],{fetch:u.default}),[exports.SupportedChainId.GOERLI]:new o.GraphQLClient(X[exports.SupportedChainId.GOERLI],{fetch:u.default}),[exports.SupportedChainId.GNOSIS_CHAIN]:new o.GraphQLClient(X[exports.SupportedChainId.GNOSIS_CHAIN],{fetch:u.default})}}getBaseUrl(){try{return Promise.resolve(this.context.chainId).then(function(e){return X[e]})}catch(e){return Promise.reject(e)}}getTotals(){try{const e=this;return Promise.resolve(e.context.chainId).then(function(t){return c.default.debug(`[subgraph:${e.API_NAME}] Get totals for:`,t),Promise.resolve(e.runQuery(J)).then(function(e){return e.totals[0]})})}catch(e){return Promise.reject(e)}}getLastDaysVolume(e){try{const t=this;return Promise.resolve(t.context.chainId).then(function(r){return c.default.debug(`[subgraph:${t.API_NAME}] Get last ${e} days volume for:`,r),t.runQuery(Z,{days:e})})}catch(e){return Promise.reject(e)}}getLastHoursVolume(e){try{const t=this;return Promise.resolve(t.context.chainId).then(function(r){return c.default.debug(`[subgraph:${t.API_NAME}] Get last ${e} hours volume for:`,r),t.runQuery(z,{hours:e})})}catch(e){return Promise.reject(e)}}runQuery(e,t){try{const r=this;return Promise.resolve(function(n,o){try{var i=Promise.resolve(r.context.chainId).then(function(n){return Promise.resolve(r.clients[n].request(e,t))})}catch(e){return o(e)}return i&&i.then?i.then(void 0,o):i}(0,function(n){return c.default.error(n),Promise.resolve(r.getBaseUrl()).then(function(r){throw new h(`Error running query: ${e}. Variables: ${JSON.stringify(t)}. API: ${r}. Inner Error: ${n}`)})}))}catch(e){return Promise.reject(e)}}}const te=function(e){return Promise.resolve(ne()).then(function({ajv:t,validate:r}){return{result:!!r(e),errors:t.errors?t.errorsText(t.errors):void 0}})},re=function(e){try{const t=1,r=112,n=18,o=32,i=function(e){const t=e.match(/.{1,2}/g);if(t)return new Uint8Array(t.map(e=>parseInt(e,16)))}(e.replace(/(^0x)/,""));if(!i)return Promise.resolve();const s=Uint8Array.from([t,r,n,o,...i]);return Promise.resolve(Promise.resolve().then(function(){/*#__PURE__*/return a(require("multiformats/cid"))})).then(function({CID:e}){return e.decode(s).toV0().toString()})}catch(e){return Promise.reject(e)}},ne=function(){try{function e(){return{ajv:ie,validate:oe}}ie||(ie=new l.default);const t=function(){if(!oe)return Promise.resolve(Promise.resolve().then(function(){return require("./appData.schema-42d10730.js")})).then(function(e){oe=ie.compile(e)})}();return Promise.resolve(t&&t.then?t.then(e):e())}catch(r){return Promise.reject(r)}};let oe,ie;function se(e,t){try{var r=e()}catch(e){return t(e)}return r&&r.then?r.then(void 0,t):r}const ae="CowSwap";class ce{constructor(e){this.context=void 0,this.context=e}generateAppDataDoc(e={},t){const{appCode:r=ae,environment:n}=t||{};return{version:"0.4.0",appCode:r,environment:n,metadata:{...e}}}decodeAppData(e){try{return Promise.resolve(se(function(){return Promise.resolve(re(e)).then(function(e){if(!e)throw new h("Error getting serialized CID");return function(e,t="https://gnosis.mypinata.cloud/ipfs"){try{return Promise.resolve(Promise.resolve().then(function(){/*#__PURE__*/return a(require("cross-fetch"))})).then(function({default:r}){return Promise.resolve(r(`${t}/${e}`)).then(function(e){return Promise.resolve(e.json())})})}catch(e){return Promise.reject(e)}}(e)})},function(e){const t=e;throw c.default.error("Error decoding AppData:",t),new h("Error decoding AppData: "+t.message)}))}catch(e){return Promise.reject(e)}}cidToAppDataHex(e){try{return Promise.resolve(Promise.resolve().then(function(){/*#__PURE__*/return a(require("multiformats/cid"))})).then(function({CID:t}){const{digest:r}=t.parse(e).multihash;return`0x${Buffer.from(r).toString("hex")}`})}catch(e){return Promise.reject(e)}}appDataHexToCid(e){try{return Promise.resolve(re(e)).then(function(e){if(!e)throw new h("Error getting serialized CID");return e})}catch(e){return Promise.reject(e)}}calculateAppDataHash(e){try{const t=this;return Promise.resolve(te(e)).then(function(r){if(null==r||!r.result)throw new h("Invalid appData provided",null==r?void 0:r.errors);return se(function(){return Promise.resolve(function(e){try{const t=JSON.stringify(e);return Promise.resolve(Promise.resolve().then(function(){/*#__PURE__*/return a(require("ipfs-only-hash"))})).then(function({of:e}){return e(t,{cidVersion:0})})}catch(e){return Promise.reject(e)}}(e)).then(function(e){return Promise.resolve(t.cidToAppDataHex(e)).then(function(t){if(!t)throw new h(`Could not extract appDataHash from calculated cidV0 ${e}`);return{cidV0:e,appDataHash:t}})})},function(e){throw new h("Failed to calculate appDataHash",e.message)})})}catch(e){return Promise.reject(e)}}uploadMetadataDocToIpfs(e){try{const t=this;return Promise.resolve(function(e,{writeUri:t="https://api.pinata.cloud",pinataApiKey:r="",pinataApiSecret:n=""}){try{return Promise.resolve(Promise.resolve().then(function(){/*#__PURE__*/return a(require("cross-fetch"))})).then(function({default:o}){if(!r||!n)throw new h("You need to pass IPFS api credentials.");const i=JSON.stringify({pinataContent:e,pinataMetadata:{name:"appData"}});return Promise.resolve(o(`${t}/pinning/pinJSONToIPFS`,{method:"POST",body:i,headers:{"Content-Type":"application/json",pinata_api_key:r,pinata_secret_api_key:n}})).then(function(e){return Promise.resolve(e.json()).then(function(t){if(200!==e.status)throw new Error(t.error.details||t.error);return t})})})}catch(e){return Promise.reject(e)}}(e,t.context.ipfs)).then(function({IpfsHash:e}){return t.cidToAppDataHex(e)})}catch(e){return Promise.reject(e)}}}var ue=0;function de(e){return"__private_"+ue+++"_"+e}function le(e,t){if(!Object.prototype.hasOwnProperty.call(e,t))throw new TypeError("attempted to use private field on non-instance");return e}const he={appDataHash:"0x0000000000000000000000000000000000000000000000000000000000000000",isDevEnvironment:!1,ipfs:{readUri:"https://gnosis.mypinata.cloud/ipfs",writeUri:"https://api.pinata.cloud",apiKey:void 0,apiSecret:void 0}};var pe,me,fe,ve,ge,Ee,Te,Pe,Ie,ye,Ae,we,Se,Ne,ke,De,Oe,xe,Ce,_e=/*#__PURE__*/de("context"),be=/*#__PURE__*/de("chainId");class Re{updateContext(e,t){this.setParams(t,e)}constructor(e,t){Object.defineProperty(this,_e,{writable:!0,value:{}}),Object.defineProperty(this,be,{writable:!0,value:exports.SupportedChainId.MAINNET}),this.setParams(e,t)}setParams(e,t){le(this,be)[be]=this.updateChainId(e),le(this,_e)[_e]={...he,...t,ipfs:{...he.ipfs,...t.ipfs}}}updateChainId(e){if(!exports.SupportedChainId[e])throw new h(`Invalid chainId: ${e}`);return c.default.debug(m,`Updating chainId to: ${e}`),le(this,be)[be]=e,e}get chainId(){const e=this;var t;const r=null==(t=le(this,_e)[_e].signer)?void 0:t.provider;return r?(c.default.debug(m,"Getting chainId from provider"),function(){try{return Promise.resolve(r.getNetwork()).then(function(t){const r=t.chainId;return r!==le(e,be)[be]&&(c.default.debug(m,`ChainId mismatch: Provider's chainId: ${r} vs Context's chainId: ${le(e,be)[be]}. Updating Context's chainId`),e.updateChainId(r)),r})}catch(e){return Promise.reject(e)}}()):Promise.resolve(le(this,be)[be])}get appDataHash(){var e;return null!==(e=le(this,_e)[_e].appDataHash)&&void 0!==e?e:he.appDataHash}get isDevEnvironment(){var e;return null!==(e=le(this,_e)[_e].isDevEnvironment)&&void 0!==e?e:he.isDevEnvironment}get signer(){return le(this,_e)[_e].signer}get ipfs(){var e;return null!==(e=le(this,_e)[_e].ipfs)&&void 0!==e?e:he.ipfs}}!function(e){e.EthPriceUsd="ethPriceUSD",e.Id="id"}(pe||(pe={})),function(e){e.FeesEth="feesEth",e.FeesUsd="feesUsd",e.Id="id",e.NumberOfTrades="numberOfTrades",e.Orders="orders",e.Settlements="settlements",e.Timestamp="timestamp",e.Tokens="tokens",e.TotalTokens="totalTokens",e.VolumeEth="volumeEth",e.VolumeUsd="volumeUsd"}(me||(me={})),function(e){e.FeesEth="feesEth",e.FeesUsd="feesUsd",e.Id="id",e.NumberOfTrades="numberOfTrades",e.Orders="orders",e.Settlements="settlements",e.Timestamp="timestamp",e.Tokens="tokens",e.TotalTokens="totalTokens",e.VolumeEth="volumeEth",e.VolumeUsd="volumeUsd"}(fe||(fe={})),function(e){e.Asc="asc",e.Desc="desc"}(ve||(ve={})),function(e){e.Id="id",e.InvalidateTimestamp="invalidateTimestamp",e.IsSigned="isSigned",e.IsValid="isValid",e.Owner="owner",e.PresignTimestamp="presignTimestamp",e.Trades="trades",e.TradesTimestamp="tradesTimestamp"}(ge||(ge={})),function(e){e.Id="id",e.Timestamp="timestamp",e.Token0="token0",e.Token0Price="token0Price",e.Token0relativePrice="token0relativePrice",e.Token1="token1",e.Token1Price="token1Price",e.Token1relativePrice="token1relativePrice",e.VolumeToken0="volumeToken0",e.VolumeToken1="volumeToken1",e.VolumeTradedEth="volumeTradedEth",e.VolumeTradedUsd="volumeTradedUsd"}(Ee||(Ee={})),function(e){e.Id="id",e.Timestamp="timestamp",e.Token0="token0",e.Token0Price="token0Price",e.Token0relativePrice="token0relativePrice",e.Token1="token1",e.Token1Price="token1Price",e.Token1relativePrice="token1relativePrice",e.VolumeToken0="volumeToken0",e.VolumeToken1="volumeToken1",e.VolumeTradedEth="volumeTradedEth",e.VolumeTradedUsd="volumeTradedUsd"}(Te||(Te={})),function(e){e.Id="id",e.Token0="token0",e.Token0Price="token0Price",e.Token0relativePrice="token0relativePrice",e.Token1="token1",e.Token1Price="token1Price",e.Token1relativePrice="token1relativePrice",e.VolumeToken0="volumeToken0",e.VolumeToken1="volumeToken1",e.VolumeTradedEth="volumeTradedEth",e.VolumeTradedUsd="volumeTradedUsd"}(Pe||(Pe={})),function(e){e.FirstTradeTimestamp="firstTradeTimestamp",e.Id="id",e.Solver="solver",e.Trades="trades",e.TxHash="txHash"}(Ie||(Ie={})),function(e){e.AveragePrice="averagePrice",e.ClosePrice="closePrice",e.HigherPrice="higherPrice",e.Id="id",e.LowerPrice="lowerPrice",e.OpenPrice="openPrice",e.Timestamp="timestamp",e.Token="token",e.TotalTrades="totalTrades",e.TotalVolume="totalVolume",e.TotalVolumeEth="totalVolumeEth",e.TotalVolumeUsd="totalVolumeUsd"}(ye||(ye={})),function(e){e.AveragePrice="averagePrice",e.ClosePrice="closePrice",e.HigherPrice="higherPrice",e.Id="id",e.LowerPrice="lowerPrice",e.OpenPrice="openPrice",e.Timestamp="timestamp",e.Token="token",e.TotalTrades="totalTrades",e.TotalVolume="totalVolume",e.TotalVolumeEth="totalVolumeEth",e.TotalVolumeUsd="totalVolumeUsd"}(Ae||(Ae={})),function(e){e.AmountEth="amountEth",e.AmountUsd="amountUsd",e.Id="id",e.Timestamp="timestamp",e.Token="token",e.Trade="trade"}(we||(we={})),function(e){e.Address="address",e.Decimals="decimals",e.FirstTradeTimestamp="firstTradeTimestamp",e.History="history",e.Id="id",e.Name="name",e.NumberOfTrades="numberOfTrades",e.PriceEth="priceEth",e.PriceUsd="priceUsd",e.Symbol="symbol",e.TotalVolume="totalVolume",e.TotalVolumeEth="totalVolumeEth",e.TotalVolumeUsd="totalVolumeUsd"}(Se||(Se={})),function(e){e.FeesEth="feesEth",e.FeesUsd="feesUsd",e.Id="id",e.NumberOfTrades="numberOfTrades",e.Orders="orders",e.Settlements="settlements",e.Tokens="tokens",e.Traders="traders",e.VolumeEth="volumeEth",e.VolumeUsd="volumeUsd"}(Ne||(Ne={})),function(e){e.BuyAmount="buyAmount",e.BuyAmountEth="buyAmountEth",e.BuyAmountUsd="buyAmountUsd",e.BuyToken="buyToken",e.FeeAmount="feeAmount",e.GasPrice="gasPrice",e.Id="id",e.Order="order",e.SellAmount="sellAmount",e.SellAmountEth="sellAmountEth",e.SellAmountUsd="sellAmountUsd",e.SellToken="sellToken",e.Settlement="settlement",e.Timestamp="timestamp",e.TxHash="txHash"}(ke||(ke={})),function(e){e.Id="id",e.Liquidity="liquidity",e.Tick="tick",e.Token0="token0",e.Token0Price="token0Price",e.Token1="token1",e.Token1Price="token1Price",e.TotalValueLockedToken0="totalValueLockedToken0",e.TotalValueLockedToken1="totalValueLockedToken1"}(De||(De={})),function(e){e.Address="address",e.AllowedPools="allowedPools",e.Decimals="decimals",e.Id="id",e.Name="name",e.PriceEth="priceEth",e.PriceUsd="priceUsd",e.Symbol="symbol"}(Oe||(Oe={})),function(e){e.Address="address",e.FirstTradeTimestamp="firstTradeTimestamp",e.Id="id",e.IsSolver="isSolver",e.NumberOfTrades="numberOfTrades",e.OrdersPlaced="ordersPlaced",e.SolvedAmountEth="solvedAmountEth",e.SolvedAmountUsd="solvedAmountUsd",e.TradedAmountEth="tradedAmountEth",e.TradedAmountUsd="tradedAmountUsd"}(xe||(xe={})),function(e){e.Allow="allow",e.Deny="deny"}(Ce||(Ce={}));var Ue={__proto__:null,get Bundle_OrderBy(){return pe},get DailyTotal_OrderBy(){return me},get HourlyTotal_OrderBy(){return fe},get OrderDirection(){return ve},get Order_OrderBy(){return ge},get PairDaily_OrderBy(){return Ee},get PairHourly_OrderBy(){return Te},get Pair_OrderBy(){return Pe},get Settlement_OrderBy(){return Ie},get TokenDailyTotal_OrderBy(){return ye},get TokenHourlyTotal_OrderBy(){return Ae},get TokenTradingEvent_OrderBy(){return we},get Token_OrderBy(){return Se},get Total_OrderBy(){return Ne},get Trade_OrderBy(){return ke},get UniswapPool_OrderBy(){return De},get UniswapToken_OrderBy(){return Oe},get User_OrderBy(){return xe},get _SubgraphErrorPolicy_(){return Ce}};Object.defineProperty(exports,"OrderKind",{enumerable:!0,get:function(){return r.OrderKind}}),exports.ALL_SUPPORTED_CHAIN_IDS=v,exports.CowError=h,exports.CowSdk=class{constructor(e=exports.SupportedChainId.MAINNET,t={},r={}){const n=this;this.context=void 0,this.cowApi=void 0,this.metadataApi=void 0,this.cowSubgraphApi=void 0,this.updateChainId=e=>{this.context.updateChainId(e)},this.updateContext=function(e,t){try{return Promise.resolve(n.context.chainId).then(function(r){n.context.updateContext(e,t||r)})}catch(e){return Promise.reject(e)}},this.validateAppDataDocument=te,this.context=new Re(e,{...t}),this.cowApi=new W(this.context),this.cowSubgraphApi=new ee(this.context),this.metadataApi=new ce(this.context),c.default.setLevel(r.loglevel||"error")}signOrder(e){try{const t=this,r=t._checkSigner();return Promise.resolve(t.context.chainId).then(function(n){return function(e,t,r){return T({order:e,chainId:t},I,r)}({...e,appData:t.context.appDataHash},n,r)})}catch(e){return Promise.reject(e)}}signOrderCancellation(e){try{const t=this,r=t._checkSigner();return Promise.resolve(t.context.chainId).then(function(t){return function(e,t,r){return T({orderId:e,chainId:t},P,r)}(e,t,r)})}catch(e){return Promise.reject(e)}}_checkSigner(e=this.context.signer){if(!e)throw new h("No signer available");return e}},exports.GraphQL=Ue,exports.Token=V;
|
|
29
29
|
//# sourceMappingURL=index.js.map
|