@cowprotocol/cow-sdk 0.0.15 → 0.0.16-RC.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/api/0x/error/index.d.ts +21 -0
- package/dist/api/0x/index.d.ts +11 -0
- package/dist/api/0x/utils.d.ts +17 -0
- package/dist/api/base/index.d.ts +25 -0
- package/dist/api/cow/index.d.ts +5 -3
- package/dist/api/cow/types.d.ts +1 -1
- package/dist/api/cow-subgraph/graphql.d.ts +24 -2
- package/dist/appData.schema-0c8db23b.js +2 -0
- package/dist/appData.schema-0c8db23b.js.map +1 -0
- package/dist/appData.schema-412cbfbf.js +2 -0
- package/dist/appData.schema-412cbfbf.js.map +1 -0
- package/dist/appData.schema-4c010c50.js +2 -0
- package/dist/appData.schema-4c010c50.js.map +1 -0
- package/dist/appData.schema-adfc1c6f.js +2 -0
- package/dist/appData.schema-adfc1c6f.js.map +1 -0
- package/dist/index.js +2 -2
- package/dist/index.js.map +1 -1
- package/dist/index.modern.js +2 -2
- package/dist/index.modern.js.map +1 -1
- package/dist/index.modern.mjs +29 -0
- package/dist/index.modern.mjs.map +1 -0
- package/dist/index.module.js +2 -2
- package/dist/index.module.js.map +1 -1
- package/dist/src/appData.schema-d44994e0.js +2 -0
- package/dist/src/appData.schema-d44994e0.js.map +1 -0
- package/dist/src/appData.schema-fb2df827.js +2 -0
- package/dist/src/appData.schema-fb2df827.js.map +1 -0
- package/dist/src/cow-sdk.esm.js +2 -0
- package/dist/src/cow-sdk.esm.js.map +1 -0
- package/dist/src/cow-sdk.js +2 -0
- package/dist/src/cow-sdk.js.map +1 -0
- package/dist/src/cow-sdk.modern.js +2 -0
- package/dist/src/cow-sdk.modern.js.map +1 -0
- package/dist/src/src/CowSdk.d.ts +16 -0
- package/dist/src/src/api/cow/errors/OperatorError.d.ts +63 -0
- package/dist/src/src/api/cow/errors/QuoteError.d.ts +32 -0
- package/dist/src/src/api/cow/index.d.ts +38 -0
- package/dist/src/src/api/cow/types.d.ts +73 -0
- package/dist/src/src/api/index.d.ts +1 -0
- package/dist/src/src/constants/chains.d.ts +6 -0
- package/dist/src/src/constants/index.d.ts +3 -0
- package/dist/src/src/constants/tokens.d.ts +5 -0
- package/dist/src/src/index.d.ts +4 -0
- package/dist/src/src/types/index.d.ts +7 -0
- package/dist/src/src/utils/appData.d.ts +7 -0
- package/dist/src/src/utils/common.d.ts +5 -0
- package/dist/src/src/utils/context.d.ts +24 -0
- package/dist/src/src/utils/sign.d.ts +54 -0
- package/dist/src/src/utils/tokens.d.ts +2 -0
- package/dist/utils/market.d.ts +16 -0
- package/package.json +1 -1
- package/LICENSE-APACHE +0 -201
- package/LICENSE-MIT +0 -21
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import { CowError } from '../../../utils/common';
|
|
2
|
+
interface ValidationError {
|
|
3
|
+
field: string;
|
|
4
|
+
code: number;
|
|
5
|
+
reason: string;
|
|
6
|
+
}
|
|
7
|
+
export interface ZeroXErrorResponse {
|
|
8
|
+
code: number;
|
|
9
|
+
reason: string;
|
|
10
|
+
validationErrors?: ValidationError[];
|
|
11
|
+
}
|
|
12
|
+
export declare const logPrefix = "0x-sdk:";
|
|
13
|
+
export default class ZeroXError extends CowError {
|
|
14
|
+
name: string;
|
|
15
|
+
description: string;
|
|
16
|
+
message: string;
|
|
17
|
+
static getErrorMessage(response: Response): Promise<string>;
|
|
18
|
+
static getErrorFromStatusCode(response: Response): Promise<string>;
|
|
19
|
+
constructor(apiError: ZeroXErrorResponse);
|
|
20
|
+
}
|
|
21
|
+
export {};
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import { SupportedChainId } from '../../constants/chains';
|
|
2
|
+
import BaseApi from '../base';
|
|
3
|
+
import { Options, PriceQuoteParams } from '../cow/types';
|
|
4
|
+
import { MatchaOptions, MatchaPriceQuote } from './types';
|
|
5
|
+
export declare class ZeroXApi extends BaseApi {
|
|
6
|
+
MATCHA_OPTIONS: MatchaOptions;
|
|
7
|
+
MATCHA_OPTIONS_URL: string;
|
|
8
|
+
constructor(chainId: SupportedChainId, { affiliateAddressMap, excludedSources }?: MatchaOptions);
|
|
9
|
+
getQuote(params: PriceQuoteParams, options?: Options): Promise<MatchaPriceQuote | null>;
|
|
10
|
+
updateOptions({ affiliateAddressMap, excludedSources }: Partial<MatchaOptions>): Promise<void>;
|
|
11
|
+
}
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import { OrderKind } from '@cowprotocol/contracts';
|
|
2
|
+
import { SupportedChainId } from '../../constants/chains';
|
|
3
|
+
import { PriceInformation, PriceQuoteParams } from '../cow/types';
|
|
4
|
+
import { MatchaOptions, MatchaPriceQuote } from './types';
|
|
5
|
+
export declare function get0xUrls(): Partial<Record<SupportedChainId, string>>;
|
|
6
|
+
export declare function normaliseQuoteResponse(priceRaw: MatchaPriceQuote | null, kind: OrderKind): PriceInformation | null;
|
|
7
|
+
export declare function getMatchaChainId(chainId: SupportedChainId): SupportedChainId | null;
|
|
8
|
+
export declare function optionsToMatchaParamsUrl({ excludedSources, affiliateAddress, }: {
|
|
9
|
+
excludedSources: MatchaOptions['excludedSources'];
|
|
10
|
+
affiliateAddress: string;
|
|
11
|
+
}): string;
|
|
12
|
+
export declare function handleQuoteResponse<T = unknown, P extends PriceQuoteParams = PriceQuoteParams>(response: Response, params?: P): Promise<T>;
|
|
13
|
+
export declare function throwOrReturnAffiliateAddress({ affiliateAddressMap, chainId, }: {
|
|
14
|
+
affiliateAddressMap: MatchaOptions['affiliateAddressMap'];
|
|
15
|
+
chainId: SupportedChainId;
|
|
16
|
+
}): string;
|
|
17
|
+
export declare function extractExcludedSources({ excludedSources }: Pick<MatchaOptions, 'excludedSources'>): string;
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import { SupportedChainId } from '../../constants/chains';
|
|
2
|
+
import { Context } from '../../utils/context';
|
|
3
|
+
import { Options } from '../cow/types';
|
|
4
|
+
interface ConstructorParams {
|
|
5
|
+
context: Context;
|
|
6
|
+
name: string;
|
|
7
|
+
apiVersion?: string;
|
|
8
|
+
getApiUrl: (...params: any[]) => Partial<Record<SupportedChainId, string>>;
|
|
9
|
+
defaultHeaders?: HeadersInit;
|
|
10
|
+
}
|
|
11
|
+
export default class BaseApi {
|
|
12
|
+
context: Context;
|
|
13
|
+
API_NAME: string;
|
|
14
|
+
API_VERSION: string;
|
|
15
|
+
API_URL_GETTER: (...params: any[]) => Partial<Record<SupportedChainId, string>>;
|
|
16
|
+
DEFAULT_HEADERS: HeadersInit;
|
|
17
|
+
constructor({ context, name, getApiUrl, defaultHeaders, apiVersion, }: ConstructorParams);
|
|
18
|
+
protected getApiBaseUrl(...params: unknown[]): Promise<string>;
|
|
19
|
+
protected post(url: string, data: unknown, options?: Options): Promise<Response>;
|
|
20
|
+
protected get(url: string, options?: Options): Promise<Response>;
|
|
21
|
+
protected delete(url: string, data: unknown, options?: Options): Promise<Response>;
|
|
22
|
+
protected handleMethod(url: string, method: 'GET' | 'POST' | 'DELETE', fetchFn: BaseApi['fetch'], getApiUrl: BaseApi['API_URL_GETTER'], options?: Options, data?: unknown): Promise<Response>;
|
|
23
|
+
protected fetch(url: string, method: 'GET' | 'POST' | 'DELETE', baseUrl: string, data?: unknown, requestOptions?: RequestInit): Promise<Response>;
|
|
24
|
+
}
|
|
25
|
+
export {};
|
package/dist/api/cow/index.d.ts
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
|
+
import { QuoteQuery } from '@cowprotocol/contracts';
|
|
1
2
|
import { SupportedChainId as ChainId } from '../../constants/chains';
|
|
2
3
|
import { OrderCreation } from '../../utils/sign';
|
|
3
|
-
import { FeeQuoteParams, PriceInformation,
|
|
4
|
+
import { FeeQuoteParams, PriceInformation, PriceQuoteLegacyParams, SimpleGetQuoteResponse } from './types';
|
|
4
5
|
import { GetOrdersParams, GetTradesParams, OrderCancellationParams, OrderID, OrderMetaData, ProfileData, TradeMetaData, Options } from './types';
|
|
5
6
|
import { Context } from '../../utils/context';
|
|
6
7
|
export declare class CowApi {
|
|
@@ -17,8 +18,9 @@ export declare class CowApi {
|
|
|
17
18
|
getOrders(params: GetOrdersParams, options?: Options): Promise<OrderMetaData[]>;
|
|
18
19
|
getTxOrders(txHash: string, options?: Options): Promise<OrderMetaData[]>;
|
|
19
20
|
getOrder(orderId: string, options?: Options): Promise<OrderMetaData | null>;
|
|
20
|
-
getPriceQuoteLegacy(params:
|
|
21
|
-
|
|
21
|
+
getPriceQuoteLegacy(params: PriceQuoteLegacyParams, options?: Options): Promise<PriceInformation | null>;
|
|
22
|
+
getQuoteLegacyParams(params: FeeQuoteParams, options?: Options): Promise<SimpleGetQuoteResponse>;
|
|
23
|
+
getQuote(params: QuoteQuery, options?: Options): Promise<SimpleGetQuoteResponse>;
|
|
22
24
|
sendSignedOrderCancellation(params: OrderCancellationParams, options?: Options): Promise<void>;
|
|
23
25
|
sendOrder(params: {
|
|
24
26
|
order: Omit<OrderCreation, 'appData'>;
|
package/dist/api/cow/types.d.ts
CHANGED
|
@@ -107,7 +107,7 @@ export declare type FeeQuoteParams = Pick<OrderMetaData, 'sellToken' | 'buyToken
|
|
|
107
107
|
receiver?: string | null;
|
|
108
108
|
validTo: number;
|
|
109
109
|
};
|
|
110
|
-
export declare type
|
|
110
|
+
export declare type PriceQuoteLegacyParams = Omit<FeeQuoteParams, 'sellToken' | 'buyToken'> & {
|
|
111
111
|
baseToken: string;
|
|
112
112
|
quoteToken: string;
|
|
113
113
|
};
|
|
@@ -1569,12 +1569,16 @@ export declare type Token = {
|
|
|
1569
1569
|
__typename?: 'Token';
|
|
1570
1570
|
/** Token address */
|
|
1571
1571
|
address: Scalars['Bytes'];
|
|
1572
|
+
/** Daily totals */
|
|
1573
|
+
dailyTotals: Array<TokenDailyTotal>;
|
|
1572
1574
|
/** Token decimals fetched by contract call */
|
|
1573
1575
|
decimals: Scalars['Int'];
|
|
1574
1576
|
/** First token trade block timestamp */
|
|
1575
|
-
firstTradeTimestamp
|
|
1577
|
+
firstTradeTimestamp: Scalars['Int'];
|
|
1576
1578
|
/** History of trading for this token */
|
|
1577
1579
|
history: Array<TokenTradingEvent>;
|
|
1580
|
+
/** Hourly totals */
|
|
1581
|
+
hourlyTotals: Array<TokenHourlyTotal>;
|
|
1578
1582
|
/** Token address to hexString */
|
|
1579
1583
|
id: Scalars['ID'];
|
|
1580
1584
|
/** Token name fetched by ERC20 contract call */
|
|
@@ -1594,6 +1598,13 @@ export declare type Token = {
|
|
|
1594
1598
|
/** Total volume in Usd */
|
|
1595
1599
|
totalVolumeUsd: Scalars['BigDecimal'];
|
|
1596
1600
|
};
|
|
1601
|
+
export declare type TokenDailyTotalsArgs = {
|
|
1602
|
+
first?: InputMaybe<Scalars['Int']>;
|
|
1603
|
+
orderBy?: InputMaybe<TokenDailyTotal_OrderBy>;
|
|
1604
|
+
orderDirection?: InputMaybe<OrderDirection>;
|
|
1605
|
+
skip?: InputMaybe<Scalars['Int']>;
|
|
1606
|
+
where?: InputMaybe<TokenDailyTotal_Filter>;
|
|
1607
|
+
};
|
|
1597
1608
|
export declare type TokenHistoryArgs = {
|
|
1598
1609
|
first?: InputMaybe<Scalars['Int']>;
|
|
1599
1610
|
orderBy?: InputMaybe<TokenTradingEvent_OrderBy>;
|
|
@@ -1601,6 +1612,13 @@ export declare type TokenHistoryArgs = {
|
|
|
1601
1612
|
skip?: InputMaybe<Scalars['Int']>;
|
|
1602
1613
|
where?: InputMaybe<TokenTradingEvent_Filter>;
|
|
1603
1614
|
};
|
|
1615
|
+
export declare type TokenHourlyTotalsArgs = {
|
|
1616
|
+
first?: InputMaybe<Scalars['Int']>;
|
|
1617
|
+
orderBy?: InputMaybe<TokenHourlyTotal_OrderBy>;
|
|
1618
|
+
orderDirection?: InputMaybe<OrderDirection>;
|
|
1619
|
+
skip?: InputMaybe<Scalars['Int']>;
|
|
1620
|
+
where?: InputMaybe<TokenHourlyTotal_Filter>;
|
|
1621
|
+
};
|
|
1604
1622
|
export declare type TokenDailyTotal = {
|
|
1605
1623
|
__typename?: 'TokenDailyTotal';
|
|
1606
1624
|
/** Average trade price */
|
|
@@ -2019,6 +2037,7 @@ export declare type Token_Filter = {
|
|
|
2019
2037
|
address_not?: InputMaybe<Scalars['Bytes']>;
|
|
2020
2038
|
address_not_contains?: InputMaybe<Scalars['Bytes']>;
|
|
2021
2039
|
address_not_in?: InputMaybe<Array<Scalars['Bytes']>>;
|
|
2040
|
+
dailyTotals_?: InputMaybe<TokenDailyTotal_Filter>;
|
|
2022
2041
|
decimals?: InputMaybe<Scalars['Int']>;
|
|
2023
2042
|
decimals_gt?: InputMaybe<Scalars['Int']>;
|
|
2024
2043
|
decimals_gte?: InputMaybe<Scalars['Int']>;
|
|
@@ -2036,6 +2055,7 @@ export declare type Token_Filter = {
|
|
|
2036
2055
|
firstTradeTimestamp_not?: InputMaybe<Scalars['Int']>;
|
|
2037
2056
|
firstTradeTimestamp_not_in?: InputMaybe<Array<Scalars['Int']>>;
|
|
2038
2057
|
history_?: InputMaybe<TokenTradingEvent_Filter>;
|
|
2058
|
+
hourlyTotals_?: InputMaybe<TokenHourlyTotal_Filter>;
|
|
2039
2059
|
id?: InputMaybe<Scalars['ID']>;
|
|
2040
2060
|
id_gt?: InputMaybe<Scalars['ID']>;
|
|
2041
2061
|
id_gte?: InputMaybe<Scalars['ID']>;
|
|
@@ -2135,9 +2155,11 @@ export declare type Token_Filter = {
|
|
|
2135
2155
|
};
|
|
2136
2156
|
export declare enum Token_OrderBy {
|
|
2137
2157
|
Address = "address",
|
|
2158
|
+
DailyTotals = "dailyTotals",
|
|
2138
2159
|
Decimals = "decimals",
|
|
2139
2160
|
FirstTradeTimestamp = "firstTradeTimestamp",
|
|
2140
2161
|
History = "history",
|
|
2162
|
+
HourlyTotals = "hourlyTotals",
|
|
2141
2163
|
Id = "id",
|
|
2142
2164
|
Name = "name",
|
|
2143
2165
|
NumberOfTrades = "numberOfTrades",
|
|
@@ -2755,7 +2777,7 @@ export declare type User = {
|
|
|
2755
2777
|
/** Owner's address */
|
|
2756
2778
|
address: Scalars['Bytes'];
|
|
2757
2779
|
/** First trade block timestamp */
|
|
2758
|
-
firstTradeTimestamp
|
|
2780
|
+
firstTradeTimestamp: Scalars['Int'];
|
|
2759
2781
|
/** Trade event order owner */
|
|
2760
2782
|
id: Scalars['ID'];
|
|
2761
2783
|
/** Determine if user has solved a settlement */
|
|
@@ -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"],o="AppData Root Schema",n="object",d={version:{$id:"#/properties/version",description:"Semantic versioning of document",examples:["1.0.0","1.2.3"],title:"Semantic Versioning",type:"string"},appCode:{$id:"#/properties/appCode",description:"The code identifying the CLI, UI, service generating the order.",examples:["CowSwap"],title:"App Code",type:"string"},metadata:{$id:"#/properties/metadata",default:{},description:"Each metadata will specify one aspect of the order.",required:[],title:"Metadata descriptors",type:"object",properties:{referrer:{$ref:"#/definitions/kindMetadata/referrer"},quote:{$ref:"#/definitions/kindMetadata/quote"}}}},s={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:["sellAmount","buyAmount"],title:"Quote",type:"object",properties:{id:{$id:"#/definitions/quote/id",title:"Quote id",examples:["XA23443543534FF"],type:"string"},sellAmount:{$ref:"#/definitions/bigNumber",title:"Quote sell amount"},buyAmount:{$ref:"#/definitions/bigNumber",title:"Quote buy amount"}}}}},a={$id:e,$schema:t,description:i,required:r,title:o,type:"object",properties:d,definitions:s};export{e as $id,t as $schema,a as default,s as definitions,i as description,d as properties,r as required,o as title,n as type};
|
|
2
|
+
//# sourceMappingURL=appData.schema-0c8db23b.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"appData.schema-0c8db23b.js","sources":[],"sourcesContent":[],"names":[],"mappings":""}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
var e="https://cowswap.exchange/appdata.schema.json",t="http://json-schema.org/draft-07/schema",i="Metadata JSON document for adding information to orders.",r=["version","metadata"],o="AppData Root Schema",s={version:{$id:"#/properties/version",description:"Semantic versioning of document",examples:["1.0.0","1.2.3"],title:"Semantic Versioning",type:"string"},appCode:{$id:"#/properties/appCode",description:"The code identifying the CLI, UI, service generating the order.",examples:["CowSwap"],title:"App Code",type:"string"},metadata:{$id:"#/properties/metadata",default:{},description:"Each metadata will specify one aspect of the order.",required:[],title:"Metadata descriptors",type:"object",properties:{referrer:{$ref:"#/definitions/kindMetadata/referrer"},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:["sellAmount","buyAmount"],title:"Quote",type:"object",properties:{id:{$id:"#/definitions/quote/id",title:"Quote id",examples:["XA23443543534FF"],type:"string"},sellAmount:{$ref:"#/definitions/bigNumber",title:"Quote sell amount"},buyAmount:{$ref:"#/definitions/bigNumber",title:"Quote buy amount"}}}}},n={$id:e,$schema:t,description:i,required:r,title:o,type:"object",properties:s,definitions:d};exports.$id=e,exports.$schema=t,exports.default=n,exports.definitions=d,exports.description=i,exports.properties=s,exports.required=r,exports.title=o,exports.type="object";
|
|
2
|
+
//# sourceMappingURL=appData.schema-412cbfbf.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"appData.schema-412cbfbf.js","sources":[],"sourcesContent":[],"names":[],"mappings":""}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
var e="https://cowswap.exchange/appdata.schema.json",t="http://json-schema.org/draft-07/schema",i="Metadata JSON document for adding information to orders.",r=["version","metadata"],o="AppData Root Schema",n={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"}}}},s={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:["sellAmount","buyAmount","version"],title:"Quote",type:"object",properties:{id:{$id:"#/definitions/quote/id",title:"Quote id",examples:["XA23443543534FF"],type:"string"},sellAmount:{$ref:"#/definitions/bigNumber",title:"Quote sell amount"},buyAmount:{$ref:"#/definitions/bigNumber",title:"Quote buy amount"},version:{$ref:"#/definitions/version"}}}}},d={$id:e,$schema:t,description:i,required:r,title:o,type:"object",properties:n,definitions:s};exports.$id=e,exports.$schema=t,exports.default=d,exports.definitions=s,exports.description=i,exports.properties=n,exports.required=r,exports.title=o,exports.type="object";
|
|
2
|
+
//# sourceMappingURL=appData.schema-4c010c50.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"appData.schema-4c010c50.js","sources":[],"sourcesContent":[],"names":[],"mappings":""}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
var e="https://cowswap.exchange/appdata.schema.json",t="http://json-schema.org/draft-07/schema",i="Metadata JSON document for adding information to orders.",r=["version","metadata"],n="AppData Root Schema",o="object",s={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:["sellAmount","buyAmount","version"],title:"Quote",type:"object",properties:{id:{$id:"#/definitions/quote/id",title:"Quote id",examples:["XA23443543534FF"],type:"string"},sellAmount:{$ref:"#/definitions/bigNumber",title:"Quote sell amount"},buyAmount:{$ref:"#/definitions/bigNumber",title:"Quote buy amount"},version:{$ref:"#/definitions/version"}}}}},a={$id:e,$schema:t,description:i,required:r,title:n,type:"object",properties:s,definitions:d};export{e as $id,t as $schema,a as default,d as definitions,i as description,s as properties,r as required,n as title,o as type};
|
|
2
|
+
//# sourceMappingURL=appData.schema-adfc1c6f.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"appData.schema-adfc1c6f.js","sources":[],"sourcesContent":[],"names":[],"mappings":""}
|
package/dist/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
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`
|
|
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:E}=d.default,g={[exports.SupportedChainId.MAINNET]:E[exports.SupportedChainId.MAINNET].address,[exports.SupportedChainId.RINKEBY]:E[exports.SupportedChainId.RINKEBY].address,[exports.SupportedChainId.GOERLI]:E[exports.SupportedChainId.GOERLI].address,[exports.SupportedChainId.GNOSIS_CHAIN]:E[exports.SupportedChainId.GNOSIS_CHAIN].address},T=function(e,t,n,o="v4"){try{let s;function i(e){return s?e:{signature:d?.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 x(e){const t=D.get(e);if(void 0===t)throw new h("Unknown schema "+e);return t}function O(e){return x(e).apiValue}function C(e){return x(e).libraryValue}function _(e){const t=g[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=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 q(e,t){let r=e;return e===$[t]&&(r=F[t].address),r}function G(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()):"application/json"===e.headers.get("Content-Type")?Promise.resolve(e.json()).then(function(e){const r=function(e){switch(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: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}):Promise.resolve(e.text()).then(function(e){throw new H({description:e,errorType:U.UNHANDLED_ERROR})})}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(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}),G(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),G(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),G(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),G(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/${q(s,t)}-${q(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)}}getQuoteLegacyParams(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)}}getQuote(e,t={}){try{const r=this;function n(t){return Promise.resolve(r.post("/quote",e,{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:O(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:O(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:q(c,t),buyToken:q(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=G(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
|
|
@@ -25,5 +25,5 @@ var e=require("loglevel"),t=require("cross-fetch"),r=require("@cowprotocol/contr
|
|
|
25
25
|
volumeUsd
|
|
26
26
|
}
|
|
27
27
|
}
|
|
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;
|
|
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(!r?.result)throw new h("Invalid appData provided",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,Ee,ge,Te,Pe,Ie,ye,Ae,we,Se,Ne,ke,De,xe,Oe,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,t=le(this,_e)[_e].signer?.provider;return t?(c.default.debug(m,"Getting chainId from provider"),function(){try{return Promise.resolve(t.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"}(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"}(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"}(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.DailyTotals="dailyTotals",e.Decimals="decimals",e.FirstTradeTimestamp="firstTradeTimestamp",e.History="history",e.HourlyTotals="hourlyTotals",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"}(xe||(xe={})),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"}(Oe||(Oe={})),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 Ee},get PairDaily_OrderBy(){return ge},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 xe},get User_OrderBy(){return Oe},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
|