@cowprotocol/cow-sdk 0.0.9 → 0.0.10
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +15 -8
- package/dist/api/cow/types.d.ts +1 -0
- package/dist/api/cow-subgraph/graphql.d.ts +30 -3
- package/dist/index.js +4 -4
- package/dist/index.js.map +1 -1
- package/dist/index.modern.js +1 -1
- package/dist/index.modern.js.map +1 -1
- package/dist/index.module.js +1 -1
- package/dist/index.module.js.map +1 -1
- package/package.json +6 -2
- package/LICENSE-APACHE +0 -201
- package/LICENSE-MIT +0 -21
package/README.md
CHANGED
|
@@ -184,22 +184,29 @@ const chainId = 1 // Mainnet
|
|
|
184
184
|
const cowSdk = new CowSdk(chainId)
|
|
185
185
|
|
|
186
186
|
// Get Cow Protocol totals
|
|
187
|
-
const {
|
|
188
|
-
const { tokens, orders, traders, settlements, volumeUsd, volumeEth, feesUsd, feesEth } = totals
|
|
187
|
+
const { tokens, orders, traders, settlements, volumeUsd, volumeEth, feesUsd, feesEth } = await cowSdk.cowSubgraphApi.getTotals()
|
|
189
188
|
console.log({ tokens, orders, traders, settlements, volumeUsd, volumeEth, feesUsd, feesEth })
|
|
190
189
|
|
|
190
|
+
// Get last 24 hours volume in usd
|
|
191
|
+
const { hourlyTotals } = await cowSdk.cowSubgraphApi.getLastHoursVolume(24)
|
|
192
|
+
console.log(hourlyTotals)
|
|
193
|
+
|
|
194
|
+
// Get last week volume in usd
|
|
195
|
+
const { dailyTotals } = await cowSdk.cowSubgraphApi.getLastDaysVolume(7)
|
|
196
|
+
console.log(dailyTotals)
|
|
197
|
+
|
|
191
198
|
// Get the last 5 batches
|
|
192
199
|
const query = `
|
|
193
|
-
query LastBatches($n: Int!) {
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
200
|
+
query LastBatches($n: Int!) {
|
|
201
|
+
settlements(orderBy: firstTradeTimestamp, orderDirection: desc, first: $n) {
|
|
202
|
+
txHash
|
|
203
|
+
firstTradeTimestamp
|
|
204
|
+
}
|
|
197
205
|
}
|
|
198
|
-
}
|
|
199
206
|
`
|
|
200
207
|
const variables = { n: 5 }
|
|
201
208
|
const response = await cowSdk.cowSubgraphApi.runQuery(query, variables)
|
|
202
|
-
console.log(response
|
|
209
|
+
console.log(response)
|
|
203
210
|
```
|
|
204
211
|
|
|
205
212
|
### Install Dependencies
|
package/dist/api/cow/types.d.ts
CHANGED
|
@@ -315,6 +315,8 @@ export declare type Order = {
|
|
|
315
315
|
id: Scalars['ID'];
|
|
316
316
|
/** block's timestamp on invalidate event */
|
|
317
317
|
invalidateTimestamp?: Maybe<Scalars['BigInt']>;
|
|
318
|
+
/** Boolean value to show if the order is signed */
|
|
319
|
+
isSigned: Scalars['Boolean'];
|
|
318
320
|
/** Boolean value true by default unless is invalidated by the event */
|
|
319
321
|
isValid: Scalars['Boolean'];
|
|
320
322
|
/** Trade's owner or presign User */
|
|
@@ -357,6 +359,10 @@ export declare type Order_Filter = {
|
|
|
357
359
|
invalidateTimestamp_lte?: InputMaybe<Scalars['BigInt']>;
|
|
358
360
|
invalidateTimestamp_not?: InputMaybe<Scalars['BigInt']>;
|
|
359
361
|
invalidateTimestamp_not_in?: InputMaybe<Array<Scalars['BigInt']>>;
|
|
362
|
+
isSigned?: InputMaybe<Scalars['Boolean']>;
|
|
363
|
+
isSigned_in?: InputMaybe<Array<Scalars['Boolean']>>;
|
|
364
|
+
isSigned_not?: InputMaybe<Scalars['Boolean']>;
|
|
365
|
+
isSigned_not_in?: InputMaybe<Array<Scalars['Boolean']>>;
|
|
360
366
|
isValid?: InputMaybe<Scalars['Boolean']>;
|
|
361
367
|
isValid_in?: InputMaybe<Array<Scalars['Boolean']>>;
|
|
362
368
|
isValid_not?: InputMaybe<Scalars['Boolean']>;
|
|
@@ -401,6 +407,7 @@ export declare type Order_Filter = {
|
|
|
401
407
|
export declare enum Order_OrderBy {
|
|
402
408
|
Id = "id",
|
|
403
409
|
InvalidateTimestamp = "invalidateTimestamp",
|
|
410
|
+
IsSigned = "isSigned",
|
|
404
411
|
IsValid = "isValid",
|
|
405
412
|
Owner = "owner",
|
|
406
413
|
PresignTimestamp = "presignTimestamp",
|
|
@@ -409,25 +416,38 @@ export declare enum Order_OrderBy {
|
|
|
409
416
|
}
|
|
410
417
|
export declare type Pair = {
|
|
411
418
|
__typename?: 'Pair';
|
|
412
|
-
/**
|
|
419
|
+
/** Token0-token1 sorted by token0 < token1 */
|
|
413
420
|
id: Scalars['ID'];
|
|
421
|
+
/** The token 0 address lower than token1 */
|
|
414
422
|
token0: Token;
|
|
423
|
+
/** The token 1 address greater than token0 */
|
|
415
424
|
token1: Token;
|
|
425
|
+
/** Total volume of token 0 traded */
|
|
416
426
|
volumeToken0?: Maybe<Scalars['BigInt']>;
|
|
427
|
+
/** Total volume of token 1 traded */
|
|
417
428
|
volumeToken1?: Maybe<Scalars['BigInt']>;
|
|
429
|
+
/** Total volume in Eth */
|
|
418
430
|
volumeTradedEth?: Maybe<Scalars['BigDecimal']>;
|
|
431
|
+
/** Total volume in Usd */
|
|
419
432
|
volumeTradedUsd?: Maybe<Scalars['BigDecimal']>;
|
|
420
433
|
};
|
|
421
434
|
export declare type PairDaily = {
|
|
422
435
|
__typename?: 'PairDaily';
|
|
423
436
|
/** token0-token1-timestamp sorted by token0 < token1 */
|
|
424
437
|
id: Scalars['ID'];
|
|
438
|
+
/** Start day timestamp */
|
|
425
439
|
timestamp?: Maybe<Scalars['BigInt']>;
|
|
440
|
+
/** The token 0 address lower than token1 */
|
|
426
441
|
token0: Token;
|
|
442
|
+
/** The token 1 address greater than token0 */
|
|
427
443
|
token1: Token;
|
|
444
|
+
/** Total volume of token 0 traded */
|
|
428
445
|
volumeToken0?: Maybe<Scalars['BigInt']>;
|
|
446
|
+
/** Total volume of token 1 traded */
|
|
429
447
|
volumeToken1?: Maybe<Scalars['BigInt']>;
|
|
448
|
+
/** Total volume in Eth */
|
|
430
449
|
volumeTradedEth?: Maybe<Scalars['BigDecimal']>;
|
|
450
|
+
/** Total volume in Usd */
|
|
431
451
|
volumeTradedUsd?: Maybe<Scalars['BigDecimal']>;
|
|
432
452
|
};
|
|
433
453
|
export declare type PairDaily_Filter = {
|
|
@@ -536,12 +556,19 @@ export declare type PairHourly = {
|
|
|
536
556
|
__typename?: 'PairHourly';
|
|
537
557
|
/** token0-token1-timestamp sorted by token0 < token1 */
|
|
538
558
|
id: Scalars['ID'];
|
|
559
|
+
/** Start hour timestamp */
|
|
539
560
|
timestamp?: Maybe<Scalars['BigInt']>;
|
|
561
|
+
/** The token 0 address lower than token1 */
|
|
540
562
|
token0: Token;
|
|
563
|
+
/** The token 1 address greater than token0 */
|
|
541
564
|
token1: Token;
|
|
565
|
+
/** Total volume of token 0 traded */
|
|
542
566
|
volumeToken0?: Maybe<Scalars['BigInt']>;
|
|
567
|
+
/** Total volume of token 1 traded */
|
|
543
568
|
volumeToken1?: Maybe<Scalars['BigInt']>;
|
|
569
|
+
/** Total volume in Eth */
|
|
544
570
|
volumeTradedEth?: Maybe<Scalars['BigDecimal']>;
|
|
571
|
+
/** Total volume in Usd */
|
|
545
572
|
volumeTradedUsd?: Maybe<Scalars['BigDecimal']>;
|
|
546
573
|
};
|
|
547
574
|
export declare type PairHourly_Filter = {
|
|
@@ -2402,8 +2429,8 @@ export declare type User = {
|
|
|
2402
2429
|
firstTradeTimestamp?: Maybe<Scalars['BigInt']>;
|
|
2403
2430
|
/** Trade event order owner */
|
|
2404
2431
|
id: Scalars['ID'];
|
|
2405
|
-
/**
|
|
2406
|
-
isSolver
|
|
2432
|
+
/** Determine if user has solved a settlement */
|
|
2433
|
+
isSolver: Scalars['Boolean'];
|
|
2407
2434
|
/** Solved trades */
|
|
2408
2435
|
numberOfTrades: Scalars['Int'];
|
|
2409
2436
|
/** List of orders placed by this user */
|
package/dist/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
var e=require("loglevel"),t=require("cross-fetch"),r=require("@gnosis.pm/gp-v2-contracts"),o=require("@gnosis.pm/gp-v2-contracts/networks.json"),n=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 o=Object.getOwnPropertyDescriptor(e,r);Object.defineProperty(t,r,o.get?o:{enumerable:!0,get:function(){return e[r]}})}}),t.default=e,t}var u=/*#__PURE__*/s(e),c=/*#__PURE__*/s(t),d=/*#__PURE__*/s(o),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 o=e[r];o&&t.append(r,o)}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.GNOSIS_CHAIN=100]="GNOSIS_CHAIN";const g=[exports.SupportedChainId.MAINNET,exports.SupportedChainId.RINKEBY,exports.SupportedChainId.GNOSIS_CHAIN],{GPv2Settlement:E}=d.default,T={[exports.SupportedChainId.MAINNET]:E[exports.SupportedChainId.MAINNET].address,[exports.SupportedChainId.RINKEBY]:E[exports.SupportedChainId.RINKEBY].address,[exports.SupportedChainId.GNOSIS_CHAIN]:E[exports.SupportedChainId.GNOSIS_CHAIN].address},v=function(e,t,o,n="v4"){try{let s;function i(e){return s?e:{signature:d.data.toString(),signingScheme:a}}const a="eth_sign"===n?r.SigningScheme.ETHSIGN:r.SigningScheme.EIP712;let c,d=null;try{switch(n){case"v3":c=new r.TypedDataV3Signer(o);break;case"int_v4":c=new r.IntChainIdTypedDataV4Signer(o);break;default:c=o}}catch(p){throw u.default.error(m,"Wallet not supported:",p),new h("Wallet not supported")}const l=function(r,o){try{var n=Promise.resolve(t({...e,signer:c,signingScheme:a})).then(function(e){d=e})}catch(e){return o(e)}return n&&n.then?n.then(void 0,o):n}(0,function(r){if(void 0===(i=r).code&&void 0===i.message)throw u.default.error(m,r),r;var i;if(r.code===A||S.test(r.message))switch(n){case"v4":const n=v(e,t,o,"v3");return s=1,n;case"v3":const i=v(e,t,o,"eth_sign");return s=1,i;default:throw r}else{if(k.test(r.message)){const r=v(e,t,o,"int_v4");return s=1,r}if(r.code===I){const r=v(e,t,o,"eth_sign");return s=1,r}if(w.test(r.message)){const r=v(e,t,o,"v3");return s=1,r}if(N.test(r.message)){const r=v(e,t,o,"eth_sign");return s=1,r}}});return Promise.resolve(l&&l.then?l.then(i):i(l))}catch(f){return Promise.reject(f)}},y=function(e){try{const{chainId:t,signer:o,signingScheme:n,orderId:i}=e,s=C(t);return Promise.resolve(r.signOrderCancellation(s,i,o,x(n)))}catch(e){return Promise.reject(e)}},P=function(e){try{const{chainId:t,signer:o,order:n,signingScheme:i}=e,s=C(t);return Promise.resolve(r.signOrder(s,n,o,x(i)))}catch(e){return Promise.reject(e)}},I=-32603,A=-32601,w=/eth_signTypedData_v4 does not exist/i,N=/eth_signTypedData_v3 does not exist/i,S=/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 _(e){return O(e).apiValue}function x(e){return O(e).libraryValue}function C(e){const t=T[e];if(!t)throw new h("Unsupported network. Settlement contract is not deployed");return r.domain(e,t)}var U,b,R,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"}(U||(U={})),function(e){e.DuplicateOrder="There was another identical order already submitted. Please try again.",e.InsufficientFee="The signed fee is insufficient. It's possible that is higher now due to a change in the gas price, ether price, or the sell token price. Please try again to get an updated fee quote.",e.InvalidSignature="The order signature is invalid. Check whether your Wallet app supports off-chain signing.",e.MissingOrderData="The order has missing information",e.InsufficientValidTo="The order you are signing is already expired. This can happen if you set a short expiration in the settings and waited too long before signing the transaction. Please try again.",e.InsufficientAllowance="The account doesn't have enough funds",e.InsufficientBalance="The account needs to approve the selling token in order to trade",e.WrongOwner="The signature is invalid.\n\nIt's likely that the signing method provided by your wallet doesn't comply with the standards required by CowSwap.\n\nCheck whether your Wallet app supports off-chain signing (EIP-712 or ETHSIGN).",e.NotFound="Token pair selected has insufficient liquidity",e.OrderNotFound="The order you are trying to cancel does not exist",e.AlreadyCancelled="Order is already cancelled",e.OrderFullyExecuted="Order is already filled",e.OrderExpired="Order is expired",e.NoLiquidity="Token pair selected has insufficient liquidity",e.UnsupportedToken="One of the tokens you are trading is unsupported. Please read the FAQ for more info.",e.AmountIsZero="Amount is zero",e.SellAmountDoesNotCoverFee="Sell amount does not sufficiently cover the current fee",e.TransferEthToContract="Sending the native currency to smart contract wallets is not currently supported",e.UNHANDLED_GET_ERROR="Order fetch failed. This may be due to a server or network connectivity issue. Please try again later.",e.UNHANDLED_CREATE_ERROR="The order was not accepted by the network",e.UNHANDLED_DELETE_ERROR="The order cancellation was not accepted by the network"}(b||(b={}));class j extends h{static getErrorMessage(e,t){try{return Promise.resolve(function(t,r){try{var o=Promise.resolve(e.json()).then(function(e){return e.errorType?j.apiErrorDetails[e.errorType]||e.errorType:(u.default.error(m,"Unknown reason for bad order submission",e),e.description)})}catch(e){return r()}return o&&o.then?o.then(void 0,r):o}(0,function(){return u.default.error(m,"Error handling a 400 error. Likely a problem deserialising the JSON response"),function(e){switch(e){case"get":return b.UNHANDLED_GET_ERROR;case"create":return b.UNHANDLED_CREATE_ERROR;case"delete":return b.UNHANDLED_DELETE_ERROR;default:return u.default.error(m,"[OperatorError::_mapActionToErrorDetails] Uncaught error mapping error action type to server error. Please try again later."),"Something failed. Please try again later."}}(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 u.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=b[e.errorType]}}j.apiErrorDetails=b,function(e){e.UnsupportedToken="UnsupportedToken",e.InsufficientLiquidity="InsufficientLiquidity",e.FeeExceedsFrom="FeeExceedsFrom",e.ZeroPrice="ZeroPrice",e.UNHANDLED_ERROR="UNHANDLED_ERROR"}(R||(R={})),function(e){e.UnsupportedToken="One of the tokens you are trading is unsupported. Please read the FAQ for more info.",e.InsufficientLiquidity="Token pair selected has insufficient liquidity",e.FeeExceedsFrom='Current fee exceeds entered "from" amount',e.ZeroPrice="Quoted price is zero. This is likely due to a significant price difference between the two tokens. Please try increasing amounts.",e.UNHANDLED_ERROR="Quote fetch failed. This may be due to a server or network connectivity issue. Please try again later."}(L||(L={}));class H extends h{static getErrorMessage(e){try{return Promise.resolve(function(t,r){try{var o=Promise.resolve(e.json()).then(function(e){return e.errorType?H.quoteErrorDetails[e.errorType]||e.errorType:(u.default.error(m,"Unknown reason for bad quote fetch",e),e.description)})}catch(e){return r()}return o&&o.then?o.then(void 0,r):o}(0,function(){return u.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 u.default.error(m,"[QuoteError::getErrorFromStatusCode] Error fetching quote, status code:",e.status||"unknown"),Promise.resolve("Error fetching quote")}return Promise.resolve()}catch(e){return Promise.reject(e)}}constructor(e){super(e.description,e.errorType),this.name="QuoteErrorObject",this.description=void 0,this.data=void 0,this.description=e.description,this.message=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.GNOSIS_CHAIN]:new V("WXDAI","0xe91D153E0b41518A2Ce8Dd3D7944Fa863463a97d")},B={[exports.SupportedChainId.MAINNET]:"ETH",[exports.SupportedChainId.RINKEBY]:"ETH",[exports.SupportedChainId.GNOSIS_CHAIN]:"XDAI"};function $(e,t){let r=e;return e===B[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}const M=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 U.NotFound:case U.NoLiquidity:return{errorType:R.InsufficientLiquidity,description:L.InsufficientLiquidity};case U.SellAmountDoesNotCoverFee:return{errorType:R.FeeExceedsFrom,description:L.FeeExceedsFrom,data:null==e?void 0:e.data};case U.UnsupportedToken:return{errorType:R.UnsupportedToken,description:e.description};case U.SellAmountDoesNotCoverFee:return{errorType:R.FeeExceedsFrom,description:e.description};default:return{errorType:R.UNHANDLED_ERROR,description:L.UNHANDLED_ERROR}}}(e),o=new H(r);if(t){const{sellToken:e,buyToken:r}=t;u.default.error(m,`Error querying fee from API - sellToken: ${e}, buyToken: ${r}`)}throw o})}catch(e){return Promise.reject(e)}},G={errorType:R.UNHANDLED_ERROR,description:L.UNHANDLED_ERROR},K={errorType:U.UNHANDLED_CREATE_ERROR,description:b.UNHANDLED_CREATE_ERROR};class Q{constructor(e){this.context=void 0,this.API_NAME="CoW Protocol",this.context=e}get DEFAULT_HEADERS(){return{"Content-Type":"application/json","X-AppId":this.context.appDataHash}}get API_BASE_URL(){return this.context.isDevEnvironment?{[exports.SupportedChainId.MAINNET]:"https://barn.api.cow.fi/mainnet/api",[exports.SupportedChainId.RINKEBY]:"https://barn.api.cow.fi/rinkeby/api",[exports.SupportedChainId.GNOSIS_CHAIN]:"https://barn.api.cow.fi/xdai/api"}:{[exports.SupportedChainId.MAINNET]:"https://api.cow.fi/mainnet/api",[exports.SupportedChainId.RINKEBY]:"https://api.cow.fi/rinkeby/api",[exports.SupportedChainId.GNOSIS_CHAIN]:"https://api.cow.fi/xdai/api"}}get PROFILE_API_BASE_URL(){return this.context.isDevEnvironment?{[exports.SupportedChainId.MAINNET]:"https://barn.api.cow.fi/affiliate/api"}:{[exports.SupportedChainId.MAINNET]:"https://api.cow.fi/affiliate/api"}}getProfileData(e){try{const t=this;return Promise.resolve(t.context.chainId).then(function(r){return u.default.debug(m,`[api:${t.API_NAME}] Get profile data for`,r,e),r!==exports.SupportedChainId.MAINNET?(u.default.info(m,"Profile data is only available for mainnet"),null):Promise.resolve(t.getProfile(`/profile/${e}`)).then(function(e){return e.ok?e.json():Promise.resolve(e.json()).then(function(e){throw u.default.error(m,e),new h(null==e?void 0:e.description)})})})}catch(e){return Promise.reject(e)}}getTrades(e){try{const t=this,{owner:r,limit:o,offset:n}=e,i=p({owner:r,limit:o,offset:n});return Promise.resolve(t.context.chainId).then(function(e){return u.default.debug(m,"[util:operator] Get trades for",e,r,{limit:o,offset:n}),q(function(){return Promise.resolve(t.get(`/trades${i}`)).then(function(e){return e.ok?e.json():Promise.resolve(e.json()).then(function(e){throw new j(e)})})},function(e){if(u.default.error(m,"Error getting trades:",e),e instanceof j)throw e;throw new h("Error getting trades: "+e)})})}catch(e){return Promise.reject(e)}}getOrders(e){try{const t=this,{owner:r,limit:o=1e3,offset:n=0}=e,i=p({limit:o,offset:n});return Promise.resolve(t.context.chainId).then(function(e){return u.default.debug(m,`[api:${t.API_NAME}] Get orders for `,e,r,o,n),q(function(){return Promise.resolve(t.get(`/account/${r}/orders/${i}`)).then(function(e){return e.ok?e.json():Promise.resolve(e.json()).then(function(e){throw new j(e)})})},function(e){if(u.default.error(m,"Error getting orders information:",e),e instanceof j)throw e;throw new j(K)})})}catch(e){return Promise.reject(e)}}getTxOrders(e){try{const t=this;return Promise.resolve(t.context.chainId).then(function(r){return u.default.debug(`[api:${t.API_NAME}] Get tx orders for `,r,e),q(function(){return Promise.resolve(t.get(`/transactions/${e}/orders`)).then(function(e){return e.ok?e.json():Promise.resolve(e.json()).then(function(e){throw new j(e)})})},function(e){if(u.default.error("Error getting transaction orders information:",e),e instanceof j)throw e;throw new j(K)})})}catch(e){return Promise.reject(e)}}getOrder(e){try{const t=this;return Promise.resolve(t.context.chainId).then(function(r){return u.default.debug(m,`[api:${t.API_NAME}] Get order for `,r,e),q(function(){return Promise.resolve(t.get(`/orders/${e}`)).then(function(e){return e.ok?e.json():Promise.resolve(e.json()).then(function(e){throw new j(e)})})},function(e){if(u.default.error(m,"Error getting order information:",e),e instanceof j)throw e;throw new j(K)})})}catch(e){return Promise.reject(e)}}getPriceQuoteLegacy(e){try{const t=this,{baseToken:r,quoteToken:o,amount:n,kind:i}=e;return Promise.resolve(t.context.chainId).then(function(s){return u.default.debug(m,`[api:${t.API_NAME}] Get price from API`,e,"for",s),Promise.resolve(t.get(`/markets/${$(r,s)}-${$(o,s)}/${i}/${n}`).catch(e=>{throw u.default.error(m,"Error getting price quote:",e),new H(G)})).then(M)})}catch(e){return Promise.reject(e)}}getQuote(e){try{const t=this;return Promise.resolve(t.context.chainId).then(function(r){const o=t.mapNewToLegacyParams(e,r);return Promise.resolve(t.post("/quote",o)).then(M)})}catch(e){return Promise.reject(e)}}sendSignedOrderCancellation(e){try{const t=this,{cancellation:r,owner:o}=e;return Promise.resolve(t.context.chainId).then(function(e){return u.default.debug(m,`[api:${t.API_NAME}] Delete signed order for network`,e,r),Promise.resolve(t.delete(`/orders/${r.orderUid}`,{signature:r.signature,signingScheme:_(r.signingScheme),from:o})).then(function(o){function n(o){u.default.debug(m,`[api:${t.API_NAME}] Cancelled order`,r.orderUid,e)}const i=function(){if(!o.ok)return Promise.resolve(j.getErrorFromStatusCode(o,"delete")).then(function(e){throw new h(e)})}();return i&&i.then?i.then(n):n()})})}catch(e){return Promise.reject(e)}}sendOrder(e){try{const t=this,r={...e.order,appData:t.context.appDataHash};return Promise.resolve(t.context.chainId).then(function(o){const{owner:n}=e;return u.default.debug(m,`[api:${t.API_NAME}] Post signed order for network`,o,r),Promise.resolve(t.post("/orders",{...r,signingScheme:_(r.signingScheme),from:n})).then(function(e){function r(r){return Promise.resolve(e.json()).then(function(e){return u.default.debug(m,`[api:${t.API_NAME}] Success posting the signed order`,e),e})}const o=function(){if(!e.ok)return Promise.resolve(j.getErrorFromStatusCode(e,"create")).then(function(e){throw new h(e)})}();return o&&o.then?o.then(r):r()})})}catch(e){return Promise.reject(e)}}getOrderLink(e){return this.getApiBaseUrl()+`/orders/${e}`}mapNewToLegacyParams(e,t){const{amount:o,kind:n,userAddress:i,receiver:s,validTo:a,sellToken:u,buyToken:c}=e,d=i||"0x0000000000000000000000000000000000000000",l={sellToken:$(u,t),buyToken:$(c,t),from:d,receiver:s||d,appData:this.context.appDataHash,validTo:a,partiallyFillable:!1};return n===r.OrderKind.SELL?{kind:r.OrderKind.SELL,sellAmountBeforeFee:o,...l}:{kind:r.OrderKind.BUY,buyAmountAfterFee:o,...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)}}getProfileApiBaseUrl(){try{const e=this;return Promise.resolve(e.context.chainId).then(function(t){const r=e.PROFILE_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){try{const o=this;return Promise.resolve(o.getApiBaseUrl()).then(function(n){return c.default(n+e,{headers:o.DEFAULT_HEADERS,method:t,body:void 0!==r?JSON.stringify(r):r})})}catch(e){return Promise.reject(e)}}fetchProfile(e,t,r){try{const o=this;return Promise.resolve(o.getProfileApiBaseUrl()).then(function(n){return c.default(n+e,{headers:o.DEFAULT_HEADERS,method:t,body:void 0!==r?JSON.stringify(r):r})})}catch(e){return Promise.reject(e)}}post(e,t){return this.fetch(e,"POST",t)}get(e){return this.fetch(e,"GET")}getProfile(e){return this.fetchProfile(e,"GET")}delete(e,t){return this.fetch(e,"DELETE",t)}}const Y=n.gql`
|
|
1
|
+
var e=require("loglevel"),t=require("cross-fetch"),r=require("@gnosis.pm/gp-v2-contracts"),n=require("@gnosis.pm/gp-v2-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 u=/*#__PURE__*/s(e),c=/*#__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)}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.GNOSIS_CHAIN=100]="GNOSIS_CHAIN";const g=[exports.SupportedChainId.MAINNET,exports.SupportedChainId.RINKEBY,exports.SupportedChainId.GNOSIS_CHAIN],{GPv2Settlement:E}=d.default,T={[exports.SupportedChainId.MAINNET]:E[exports.SupportedChainId.MAINNET].address,[exports.SupportedChainId.RINKEBY]:E[exports.SupportedChainId.RINKEBY].address,[exports.SupportedChainId.GNOSIS_CHAIN]:E[exports.SupportedChainId.GNOSIS_CHAIN].address},v=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 c,d=null;try{switch(o){case"v3":c=new r.TypedDataV3Signer(n);break;case"int_v4":c=new r.IntChainIdTypedDataV4Signer(n);break;default:c=n}}catch(p){throw u.default.error(m,"Wallet not supported:",p),new h("Wallet not supported")}const l=function(r,n){try{var o=Promise.resolve(t({...e,signer:c,signingScheme:a})).then(function(e){d=e})}catch(e){return n(e)}return o&&o.then?o.then(void 0,n):o}(0,function(r){if(void 0===(i=r).code&&void 0===i.message)throw u.default.error(m,r),r;var i;if(r.code===A||S.test(r.message))switch(o){case"v4":const o=v(e,t,n,"v3");return s=1,o;case"v3":const i=v(e,t,n,"eth_sign");return s=1,i;default:throw r}else{if(k.test(r.message)){const r=v(e,t,n,"int_v4");return s=1,r}if(r.code===I){const r=v(e,t,n,"eth_sign");return s=1,r}if(w.test(r.message)){const r=v(e,t,n,"v3");return s=1,r}if(N.test(r.message)){const r=v(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)}},y=function(e){try{const{chainId:t,signer:n,signingScheme:o,orderId:i}=e,s=C(t);return Promise.resolve(r.signOrderCancellation(s,i,n,x(o)))}catch(e){return Promise.reject(e)}},P=function(e){try{const{chainId:t,signer:n,order:o,signingScheme:i}=e,s=C(t);return Promise.resolve(r.signOrder(s,o,n,x(i)))}catch(e){return Promise.reject(e)}},I=-32603,A=-32601,w=/eth_signTypedData_v4 does not exist/i,N=/eth_signTypedData_v3 does not exist/i,S=/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 _(e){return O(e).apiValue}function x(e){return O(e).libraryValue}function C(e){const t=T[e];if(!t)throw new h("Unsupported network. Settlement contract is not deployed");return r.domain(e,t)}var U,b,R,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"}(U||(U={})),function(e){e.DuplicateOrder="There was another identical order already submitted. Please try again.",e.InsufficientFee="The signed fee is insufficient. It's possible that is higher now due to a change in the gas price, ether price, or the sell token price. Please try again to get an updated fee quote.",e.InvalidSignature="The order signature is invalid. Check whether your Wallet app supports off-chain signing.",e.MissingOrderData="The order has missing information",e.InsufficientValidTo="The order you are signing is already expired. This can happen if you set a short expiration in the settings and waited too long before signing the transaction. Please try again.",e.InsufficientAllowance="The account doesn't have enough funds",e.InsufficientBalance="The account needs to approve the selling token in order to trade",e.WrongOwner="The signature is invalid.\n\nIt's likely that the signing method provided by your wallet doesn't comply with the standards required by CowSwap.\n\nCheck whether your Wallet app supports off-chain signing (EIP-712 or ETHSIGN).",e.NotFound="Token pair selected has insufficient liquidity",e.OrderNotFound="The order you are trying to cancel does not exist",e.AlreadyCancelled="Order is already cancelled",e.OrderFullyExecuted="Order is already filled",e.OrderExpired="Order is expired",e.NoLiquidity="Token pair selected has insufficient liquidity",e.UnsupportedToken="One of the tokens you are trading is unsupported. Please read the FAQ for more info.",e.AmountIsZero="Amount is zero",e.SellAmountDoesNotCoverFee="Sell amount does not sufficiently cover the current fee",e.TransferEthToContract="Sending the native currency to smart contract wallets is not currently supported",e.UNHANDLED_GET_ERROR="Order fetch failed. This may be due to a server or network connectivity issue. Please try again later.",e.UNHANDLED_CREATE_ERROR="The order was not accepted by the network",e.UNHANDLED_DELETE_ERROR="The order cancellation was not accepted by the network"}(b||(b={}));class 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:(u.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 u.default.error(m,"Error handling a 400 error. Likely a problem deserialising the JSON response"),function(e){switch(e){case"get":return b.UNHANDLED_GET_ERROR;case"create":return b.UNHANDLED_CREATE_ERROR;case"delete":return b.UNHANDLED_DELETE_ERROR;default:return u.default.error(m,"[OperatorError::_mapActionToErrorDetails] Uncaught error mapping error action type to server error. Please try again later."),"Something failed. Please try again later."}}(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 u.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=b[e.errorType]}}j.apiErrorDetails=b,function(e){e.UnsupportedToken="UnsupportedToken",e.InsufficientLiquidity="InsufficientLiquidity",e.FeeExceedsFrom="FeeExceedsFrom",e.ZeroPrice="ZeroPrice",e.UNHANDLED_ERROR="UNHANDLED_ERROR"}(R||(R={})),function(e){e.UnsupportedToken="One of the tokens you are trading is unsupported. Please read the FAQ for more info.",e.InsufficientLiquidity="Token pair selected has insufficient liquidity",e.FeeExceedsFrom='Current fee exceeds entered "from" amount',e.ZeroPrice="Quoted price is zero. This is likely due to a significant price difference between the two tokens. Please try increasing amounts.",e.UNHANDLED_ERROR="Quote fetch failed. This may be due to a server or network connectivity issue. Please try again later."}(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:(u.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 u.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 u.default.error(m,"[QuoteError::getErrorFromStatusCode] Error fetching quote, status code:",e.status||"unknown"),Promise.resolve("Error fetching quote")}return Promise.resolve()}catch(e){return Promise.reject(e)}}constructor(e){super(e.description,e.errorType),this.name="QuoteErrorObject",this.description=void 0,this.data=void 0,this.description=e.description,this.message=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.GNOSIS_CHAIN]:new V("WXDAI","0xe91D153E0b41518A2Ce8Dd3D7944Fa863463a97d")},B={[exports.SupportedChainId.MAINNET]:"ETH",[exports.SupportedChainId.RINKEBY]:"ETH",[exports.SupportedChainId.GNOSIS_CHAIN]:"XDAI"};function $(e,t){let r=e;return e===B[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}const M=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 U.NotFound:case U.NoLiquidity:return{errorType:R.InsufficientLiquidity,description:L.InsufficientLiquidity};case U.SellAmountDoesNotCoverFee:return{errorType:R.FeeExceedsFrom,description:L.FeeExceedsFrom,data:null==e?void 0:e.data};case U.UnsupportedToken:return{errorType:R.UnsupportedToken,description:e.description};case U.SellAmountDoesNotCoverFee:return{errorType:R.FeeExceedsFrom,description:e.description};default:return{errorType:R.UNHANDLED_ERROR,description:L.UNHANDLED_ERROR}}}(e),n=new H(r);if(t){const{sellToken:e,buyToken:r}=t;u.default.error(m,`Error querying fee from API - sellToken: ${e}, buyToken: ${r}`)}throw n})}catch(e){return Promise.reject(e)}},G={errorType:R.UNHANDLED_ERROR,description:L.UNHANDLED_ERROR},K={errorType:U.UNHANDLED_CREATE_ERROR,description:b.UNHANDLED_CREATE_ERROR};class Q{constructor(e){this.context=void 0,this.API_NAME="CoW Protocol",this.context=e}get DEFAULT_HEADERS(){return{"Content-Type":"application/json","X-AppId":this.context.appDataHash}}get API_BASE_URL(){return this.context.isDevEnvironment?{[exports.SupportedChainId.MAINNET]:"https://barn.api.cow.fi/mainnet/api",[exports.SupportedChainId.RINKEBY]:"https://barn.api.cow.fi/rinkeby/api",[exports.SupportedChainId.GNOSIS_CHAIN]:"https://barn.api.cow.fi/xdai/api"}:{[exports.SupportedChainId.MAINNET]:"https://api.cow.fi/mainnet/api",[exports.SupportedChainId.RINKEBY]:"https://api.cow.fi/rinkeby/api",[exports.SupportedChainId.GNOSIS_CHAIN]:"https://api.cow.fi/xdai/api"}}get PROFILE_API_BASE_URL(){return this.context.isDevEnvironment?{[exports.SupportedChainId.MAINNET]:"https://barn.api.cow.fi/affiliate/api"}:{[exports.SupportedChainId.MAINNET]:"https://api.cow.fi/affiliate/api"}}getProfileData(e){try{const t=this;return Promise.resolve(t.context.chainId).then(function(r){return u.default.debug(m,`[api:${t.API_NAME}] Get profile data for`,r,e),r!==exports.SupportedChainId.MAINNET?(u.default.info(m,"Profile data is only available for mainnet"),null):Promise.resolve(t.getProfile(`/profile/${e}`)).then(function(e){return e.ok?e.json():Promise.resolve(e.json()).then(function(e){throw u.default.error(m,e),new h(null==e?void 0:e.description)})})})}catch(e){return Promise.reject(e)}}getTrades(e){try{const t=this,{owner:r,limit:n,offset:o}=e,i=p({owner:r,limit:n,offset:o});return Promise.resolve(t.context.chainId).then(function(e){return u.default.debug(m,"[util:operator] Get trades for",e,r,{limit:n,offset:o}),q(function(){return Promise.resolve(t.get(`/trades${i}`)).then(function(e){return e.ok?e.json():Promise.resolve(e.json()).then(function(e){throw new j(e)})})},function(e){if(u.default.error(m,"Error getting trades:",e),e instanceof j)throw e;throw new h("Error getting trades: "+e)})})}catch(e){return Promise.reject(e)}}getOrders(e){try{const t=this,{owner:r,limit:n=1e3,offset:o=0}=e,i=p({limit:n,offset:o});return Promise.resolve(t.context.chainId).then(function(e){return u.default.debug(m,`[api:${t.API_NAME}] Get orders for `,e,r,n,o),q(function(){return Promise.resolve(t.get(`/account/${r}/orders/${i}`)).then(function(e){return e.ok?e.json():Promise.resolve(e.json()).then(function(e){throw new j(e)})})},function(e){if(u.default.error(m,"Error getting orders information:",e),e instanceof j)throw e;throw new j(K)})})}catch(e){return Promise.reject(e)}}getTxOrders(e){try{const t=this;return Promise.resolve(t.context.chainId).then(function(r){return u.default.debug(`[api:${t.API_NAME}] Get tx orders for `,r,e),q(function(){return Promise.resolve(t.get(`/transactions/${e}/orders`)).then(function(e){return e.ok?e.json():Promise.resolve(e.json()).then(function(e){throw new j(e)})})},function(e){if(u.default.error("Error getting transaction orders information:",e),e instanceof j)throw e;throw new j(K)})})}catch(e){return Promise.reject(e)}}getOrder(e){try{const t=this;return Promise.resolve(t.context.chainId).then(function(r){return u.default.debug(m,`[api:${t.API_NAME}] Get order for `,r,e),q(function(){return Promise.resolve(t.get(`/orders/${e}`)).then(function(e){return e.ok?e.json():Promise.resolve(e.json()).then(function(e){throw new j(e)})})},function(e){if(u.default.error(m,"Error getting order information:",e),e instanceof j)throw e;throw new j(K)})})}catch(e){return Promise.reject(e)}}getPriceQuoteLegacy(e){try{const t=this,{baseToken:r,quoteToken:n,amount:o,kind:i}=e;return Promise.resolve(t.context.chainId).then(function(s){return u.default.debug(m,`[api:${t.API_NAME}] Get price from API`,e,"for",s),Promise.resolve(t.get(`/markets/${$(r,s)}-${$(n,s)}/${i}/${o}`).catch(e=>{throw u.default.error(m,"Error getting price quote:",e),new H(G)})).then(M)})}catch(e){return Promise.reject(e)}}getQuote(e){try{const t=this;return Promise.resolve(t.context.chainId).then(function(r){const n=t.mapNewToLegacyParams(e,r);return Promise.resolve(t.post("/quote",n)).then(M)})}catch(e){return Promise.reject(e)}}sendSignedOrderCancellation(e){try{const t=this,{cancellation:r,owner:n}=e;return Promise.resolve(t.context.chainId).then(function(e){return u.default.debug(m,`[api:${t.API_NAME}] Delete signed order for network`,e,r),Promise.resolve(t.delete(`/orders/${r.orderUid}`,{signature:r.signature,signingScheme:_(r.signingScheme),from:n})).then(function(n){function o(n){u.default.debug(m,`[api:${t.API_NAME}] Cancelled order`,r.orderUid,e)}const i=function(){if(!n.ok)return Promise.resolve(j.getErrorFromStatusCode(n,"delete")).then(function(e){throw new h(e)})}();return i&&i.then?i.then(o):o()})})}catch(e){return Promise.reject(e)}}sendOrder(e){try{const t=this,r={...e.order,appData:t.context.appDataHash};return Promise.resolve(t.context.chainId).then(function(n){const{owner:o}=e;return u.default.debug(m,`[api:${t.API_NAME}] Post signed order for network`,n,r),Promise.resolve(t.post("/orders",{...r,signingScheme:_(r.signingScheme),from:o})).then(function(e){function r(r){return Promise.resolve(e.json()).then(function(e){return u.default.debug(m,`[api:${t.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(r):r()})})}catch(e){return Promise.reject(e)}}getOrderLink(e){return this.getApiBaseUrl()+`/orders/${e}`}mapNewToLegacyParams(e,t){const{amount:n,kind:o,userAddress:i,receiver:s,validTo:a,sellToken:u,buyToken:c}=e,d=i||"0x0000000000000000000000000000000000000000",l={sellToken:$(u,t),buyToken:$(c,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)}}getProfileApiBaseUrl(){try{const e=this;return Promise.resolve(e.context.chainId).then(function(t){const r=e.PROFILE_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){try{const n=this;return Promise.resolve(n.getApiBaseUrl()).then(function(o){return c.default(o+e,{headers:n.DEFAULT_HEADERS,method:t,body:void 0!==r?JSON.stringify(r):r})})}catch(e){return Promise.reject(e)}}fetchProfile(e,t,r){try{const n=this;return Promise.resolve(n.getProfileApiBaseUrl()).then(function(o){return c.default(o+e,{headers:n.DEFAULT_HEADERS,method:t,body:void 0!==r?JSON.stringify(r):r})})}catch(e){return Promise.reject(e)}}post(e,t){return this.fetch(e,"POST",t)}get(e){return this.fetch(e,"GET")}getProfile(e){return this.fetchProfile(e,"GET")}delete(e,t){return this.fetch(e,"DELETE",t)}}const Y=o.gql`
|
|
2
2
|
query Totals {
|
|
3
3
|
totals {
|
|
4
4
|
tokens
|
|
@@ -11,19 +11,19 @@ var e=require("loglevel"),t=require("cross-fetch"),r=require("@gnosis.pm/gp-v2-c
|
|
|
11
11
|
feesEth
|
|
12
12
|
}
|
|
13
13
|
}
|
|
14
|
-
`,W=
|
|
14
|
+
`,W=o.gql`
|
|
15
15
|
query LastDaysVolume($days: Int!) {
|
|
16
16
|
dailyTotals(orderBy: timestamp, orderDirection: desc, first: $days) {
|
|
17
17
|
timestamp
|
|
18
18
|
volumeUsd
|
|
19
19
|
}
|
|
20
20
|
}
|
|
21
|
-
`,J=
|
|
21
|
+
`,J=o.gql`
|
|
22
22
|
query LastHoursVolume($hours: Int!) {
|
|
23
23
|
hourlyTotals(orderBy: timestamp, orderDirection: desc, first: $hours) {
|
|
24
24
|
timestamp
|
|
25
25
|
volumeUsd
|
|
26
26
|
}
|
|
27
27
|
}
|
|
28
|
-
`,Z={[exports.SupportedChainId.MAINNET]:"https://api.thegraph.com/subgraphs/name/cowprotocol/cow",[exports.SupportedChainId.RINKEBY]:"https://api.thegraph.com/subgraphs/name/cowprotocol/cow-rinkeby",[exports.SupportedChainId.GNOSIS_CHAIN]:"https://api.thegraph.com/subgraphs/name/cowprotocol/cow-gc"};class z{constructor(e){this.context=void 0,this.clients=void 0,this.API_NAME="CoW Protocol Subgraph",this.context=e,this.clients=this.createClients()}createClients(){return{[exports.SupportedChainId.MAINNET]:new n.GraphQLClient(Z[exports.SupportedChainId.MAINNET],{fetch:c.default}),[exports.SupportedChainId.RINKEBY]:new n.GraphQLClient(Z[exports.SupportedChainId.RINKEBY],{fetch:c.default}),[exports.SupportedChainId.GNOSIS_CHAIN]:new n.GraphQLClient(Z[exports.SupportedChainId.GNOSIS_CHAIN],{fetch:c.default})}}getBaseUrl(){try{return Promise.resolve(this.context.chainId).then(function(e){return Z[e]})}catch(e){return Promise.reject(e)}}getTotals(){try{const e=this;return Promise.resolve(e.context.chainId).then(function(t){return u.default.debug(`[subgraph:${e.API_NAME}] Get totals for:`,t),Promise.resolve(e.runQuery(Y)).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 u.default.debug(`[subgraph:${t.API_NAME}] Get last ${e} days volume for:`,r),t.runQuery(W,{days:e})})}catch(e){return Promise.reject(e)}}getLastHoursVolume(e){try{const t=this;return Promise.resolve(t.context.chainId).then(function(r){return u.default.debug(`[subgraph:${t.API_NAME}] Get last ${e} hours volume for:`,r),t.runQuery(J,{hours:e})})}catch(e){return Promise.reject(e)}}runQuery(e,t){try{const r=this;return Promise.resolve(function(o,n){try{var i=Promise.resolve(r.context.chainId).then(function(o){return Promise.resolve(r.clients[o].request(e,t))})}catch(e){return n(e)}return i&&i.then?i.then(void 0,n):i}(0,function(o){return u.default.error(o),Promise.resolve(r.getBaseUrl()).then(function(r){throw new h(`Error running query: ${e}. Variables: ${JSON.stringify(t)}. API: ${r}. Inner Error: ${o}`)})}))}catch(e){return Promise.reject(e)}}}const X=function(e){return Promise.resolve(te()).then(function({ajv:t,validate:r}){var o;return{result:!!r(e),errors:null!==(o=t.errors)&&void 0!==o?o:void 0}})},ee=function(e){try{const t=1,r=112,o=18,n=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,o,n,...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)}},te=function(){try{function e(){return{ajv:oe,validate:re}}oe||(oe=new l.default);const t=function(){if(!re)return Promise.resolve(Promise.resolve().then(function(){return require("./appData.schema-d44994e0.js")})).then(function(e){re=oe.compile(e)})}();return Promise.resolve(t&&t.then?t.then(e):e())}catch(r){return Promise.reject(r)}};let re,oe;class ne{constructor(e){this.context=void 0,this.context=e}generateAppDataDoc(e={},t="CowSwap"){return{version:"0.1.0",appCode:t,metadata:{...e}}}decodeAppData(e){try{return Promise.resolve(function(t,r){try{var o=Promise.resolve(ee(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)})}catch(e){return r(e)}return o&&o.then?o.then(void 0,r):o}(0,function(e){const t=e;throw u.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(ee(e)).then(function(e){if(!e)throw new h("Error getting serialized CID");return e})}catch(e){return Promise.reject(e)}}uploadMetadataDocToIpfs(e){try{const t=this;return Promise.resolve(function(e,{uri:t,pinataApiKey:r="",pinataApiSecret:o=""}){try{return Promise.resolve(Promise.resolve().then(function(){/*#__PURE__*/return a(require("cross-fetch"))})).then(function({default:n}){if(!r||!o)throw new h("You need to pass IPFS api credentials.");const i=JSON.stringify({pinataContent:e,pinataMetadata:{name:"appData-affiliate"}});return Promise.resolve(n(`${t}/pinning/pinJSONToIPFS`,{method:"POST",body:i,headers:{"Content-Type":"application/json",pinata_api_key:r,pinata_secret_api_key:o}})).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 ie=0;function se(e){return"__private_"+ie+++"_"+e}function ae(e,t){if(!Object.prototype.hasOwnProperty.call(e,t))throw new TypeError("attempted to use private field on non-instance");return e}const ue={appDataHash:"0x0000000000000000000000000000000000000000000000000000000000000000",isDevEnvironment:!1,ipfs:{uri:"https://gnosis.mypinata.cloud/ipfs",apiKey:void 0,apiSecret:void 0}};var ce,de,le,he,pe,me,fe,ge,Ee,Te,ve,ye,Pe,Ie,Ae,we,Ne,Se,ke=/*#__PURE__*/se("context"),De=/*#__PURE__*/se("chainId");class Oe{constructor(e,t){Object.defineProperty(this,ke,{writable:!0,value:void 0}),Object.defineProperty(this,De,{writable:!0,value:void 0}),ae(this,De)[De]=this.updateChainId(e),ae(this,ke)[ke]={...ue,...t}}updateChainId(e){if(!exports.SupportedChainId[e])throw new h(`Invalid chainId: ${e}`);return u.default.debug(m,`Updating chainId to: ${e}`),ae(this,De)[De]=e,e}get chainId(){const e=this;var t;const r=null==(t=ae(this,ke)[ke].signer)?void 0:t.provider;return r?(u.default.debug(m,"Getting chainId from provider"),function(){try{return Promise.resolve(r.getNetwork()).then(function(t){const r=t.chainId;return r!==ae(e,De)[De]&&(u.default.debug(m,`ChainId mismatch: Provider's chainId: ${r} vs Context's chainId: ${ae(e,De)[De]}. Updating Context's chainId`),e.updateChainId(r)),r})}catch(e){return Promise.reject(e)}}()):Promise.resolve(ae(this,De)[De])}get appDataHash(){var e;return null!==(e=ae(this,ke)[ke].appDataHash)&&void 0!==e?e:ue.appDataHash}get isDevEnvironment(){var e;return null!==(e=ae(this,ke)[ke].isDevEnvironment)&&void 0!==e?e:ue.isDevEnvironment}get signer(){return ae(this,ke)[ke].signer}get ipfs(){var e;return null!==(e=ae(this,ke)[ke].ipfs)&&void 0!==e?e:ue.ipfs}}!function(e){e.EthPriceUsd="ethPriceUSD",e.Id="id"}(ce||(ce={})),function(e){e.FeesEth="feesEth",e.FeesUsd="feesUsd",e.Id="id",e.Orders="orders",e.Settlements="settlements",e.Timestamp="timestamp",e.Tokens="tokens",e.TotalTokens="totalTokens",e.VolumeEth="volumeEth",e.VolumeUsd="volumeUsd"}(de||(de={})),function(e){e.FeesEth="feesEth",e.FeesUsd="feesUsd",e.Id="id",e.Orders="orders",e.Settlements="settlements",e.Timestamp="timestamp",e.Tokens="tokens",e.TotalTokens="totalTokens",e.VolumeEth="volumeEth",e.VolumeUsd="volumeUsd"}(le||(le={})),function(e){e.Asc="asc",e.Desc="desc"}(he||(he={})),function(e){e.Id="id",e.InvalidateTimestamp="invalidateTimestamp",e.IsValid="isValid",e.Owner="owner",e.PresignTimestamp="presignTimestamp",e.Trades="trades",e.TradesTimestamp="tradesTimestamp"}(pe||(pe={})),function(e){e.Id="id",e.Timestamp="timestamp",e.Token0="token0",e.Token1="token1",e.VolumeToken0="volumeToken0",e.VolumeToken1="volumeToken1",e.VolumeTradedEth="volumeTradedEth",e.VolumeTradedUsd="volumeTradedUsd"}(me||(me={})),function(e){e.Id="id",e.Timestamp="timestamp",e.Token0="token0",e.Token1="token1",e.VolumeToken0="volumeToken0",e.VolumeToken1="volumeToken1",e.VolumeTradedEth="volumeTradedEth",e.VolumeTradedUsd="volumeTradedUsd"}(fe||(fe={})),function(e){e.Id="id",e.Token0="token0",e.Token1="token1",e.VolumeToken0="volumeToken0",e.VolumeToken1="volumeToken1",e.VolumeTradedEth="volumeTradedEth",e.VolumeTradedUsd="volumeTradedUsd"}(ge||(ge={})),function(e){e.FirstTradeTimestamp="firstTradeTimestamp",e.Id="id",e.Solver="solver",e.Trades="trades",e.TxHash="txHash"}(Ee||(Ee={})),function(e){e.AveragePrice="averagePrice",e.ClosePrice="closePrice",e.HigherPrice="higherPrice",e.Id="id",e.LowerPrice="lowerPrice",e.OpenPrice="openPrice",e.Timestamp="timestamp",e.Token="token",e.TotalTrades="totalTrades",e.TotalVolume="totalVolume",e.TotalVolumeEth="totalVolumeEth",e.TotalVolumeUsd="totalVolumeUsd"}(Te||(Te={})),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"}(ve||(ve={})),function(e){e.AmountEth="amountEth",e.AmountUsd="amountUsd",e.Id="id",e.Timestamp="timestamp",e.Token="token",e.Trade="trade"}(ye||(ye={})),function(e){e.Address="address",e.AllowedPools="allowedPools",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"}(Pe||(Pe={})),function(e){e.FeesEth="feesEth",e.FeesUsd="feesUsd",e.Id="id",e.Orders="orders",e.Settlements="settlements",e.Tokens="tokens",e.Traders="traders",e.VolumeEth="volumeEth",e.VolumeUsd="volumeUsd"}(Ie||(Ie={})),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"}(Ae||(Ae={})),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"}(we||(we={})),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"}(Ne||(Ne={})),function(e){e.Allow="allow",e.Deny="deny"}(Se||(Se={}));var _e={__proto__:null,get Bundle_OrderBy(){return ce},get DailyTotal_OrderBy(){return de},get HourlyTotal_OrderBy(){return le},get OrderDirection(){return he},get Order_OrderBy(){return pe},get PairDaily_OrderBy(){return me},get PairHourly_OrderBy(){return fe},get Pair_OrderBy(){return ge},get Settlement_OrderBy(){return Ee},get TokenDailyTotal_OrderBy(){return Te},get TokenHourlyTotal_OrderBy(){return ve},get TokenTradingEvent_OrderBy(){return ye},get Token_OrderBy(){return Pe},get Total_OrderBy(){return Ie},get Trade_OrderBy(){return Ae},get UniswapPool_OrderBy(){return we},get User_OrderBy(){return Ne},get _SubgraphErrorPolicy_(){return Se}};Object.defineProperty(exports,"OrderKind",{enumerable:!0,get:function(){return r.OrderKind}}),exports.ALL_SUPPORTED_CHAIN_IDS=g,exports.CowError=h,exports.CowSdk=class{constructor(e,t={},r={}){this.context=void 0,this.cowApi=void 0,this.metadataApi=void 0,this.cowSubgraphApi=void 0,this.updateChainId=e=>{this.context.updateChainId(e)},this.validateAppDataDocument=X,this.context=new Oe(e,{...t}),this.cowApi=new Q(this.context),this.cowSubgraphApi=new z(this.context),this.metadataApi=new ne(this.context),u.default.setLevel(r.loglevel||"error")}signOrder(e){try{const t=this,r=t._checkSigner();return Promise.resolve(t.context.chainId).then(function(o){return function(e,t,r){return v({order:e,chainId:t},P,r)}({...e,appData:t.context.appDataHash},o,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 v({orderId:e,chainId:t},y,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=_e,exports.Token=V;
|
|
28
|
+
`,Z={[exports.SupportedChainId.MAINNET]:"https://api.thegraph.com/subgraphs/name/cowprotocol/cow",[exports.SupportedChainId.RINKEBY]:"https://api.thegraph.com/subgraphs/name/cowprotocol/cow-rinkeby",[exports.SupportedChainId.GNOSIS_CHAIN]:"https://api.thegraph.com/subgraphs/name/cowprotocol/cow-gc"};class z{constructor(e){this.context=void 0,this.clients=void 0,this.API_NAME="CoW Protocol Subgraph",this.context=e,this.clients=this.createClients()}createClients(){return{[exports.SupportedChainId.MAINNET]:new o.GraphQLClient(Z[exports.SupportedChainId.MAINNET],{fetch:c.default}),[exports.SupportedChainId.RINKEBY]:new o.GraphQLClient(Z[exports.SupportedChainId.RINKEBY],{fetch:c.default}),[exports.SupportedChainId.GNOSIS_CHAIN]:new o.GraphQLClient(Z[exports.SupportedChainId.GNOSIS_CHAIN],{fetch:c.default})}}getBaseUrl(){try{return Promise.resolve(this.context.chainId).then(function(e){return Z[e]})}catch(e){return Promise.reject(e)}}getTotals(){try{const e=this;return Promise.resolve(e.context.chainId).then(function(t){return u.default.debug(`[subgraph:${e.API_NAME}] Get totals for:`,t),Promise.resolve(e.runQuery(Y)).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 u.default.debug(`[subgraph:${t.API_NAME}] Get last ${e} days volume for:`,r),t.runQuery(W,{days:e})})}catch(e){return Promise.reject(e)}}getLastHoursVolume(e){try{const t=this;return Promise.resolve(t.context.chainId).then(function(r){return u.default.debug(`[subgraph:${t.API_NAME}] Get last ${e} hours volume for:`,r),t.runQuery(J,{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 u.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 X=function(e){return Promise.resolve(te()).then(function({ajv:t,validate:r}){var n;return{result:!!r(e),errors:null!==(n=t.errors)&&void 0!==n?n:void 0}})},ee=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)}},te=function(){try{function e(){return{ajv:ne,validate:re}}ne||(ne=new l.default);const t=function(){if(!re)return Promise.resolve(Promise.resolve().then(function(){return require("./appData.schema-d44994e0.js")})).then(function(e){re=ne.compile(e)})}();return Promise.resolve(t&&t.then?t.then(e):e())}catch(r){return Promise.reject(r)}};let re,ne;class oe{constructor(e){this.context=void 0,this.context=e}generateAppDataDoc(e={},t="CowSwap"){return{version:"0.1.0",appCode:t,metadata:{...e}}}decodeAppData(e){try{return Promise.resolve(function(t,r){try{var n=Promise.resolve(ee(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)})}catch(e){return r(e)}return n&&n.then?n.then(void 0,r):n}(0,function(e){const t=e;throw u.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(ee(e)).then(function(e){if(!e)throw new h("Error getting serialized CID");return e})}catch(e){return Promise.reject(e)}}uploadMetadataDocToIpfs(e){try{const t=this;return Promise.resolve(function(e,{uri:t,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-affiliate"}});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 ie=0;function se(e){return"__private_"+ie+++"_"+e}function ae(e,t){if(!Object.prototype.hasOwnProperty.call(e,t))throw new TypeError("attempted to use private field on non-instance");return e}const ue={appDataHash:"0x0000000000000000000000000000000000000000000000000000000000000000",isDevEnvironment:!1,ipfs:{uri:"https://gnosis.mypinata.cloud/ipfs",apiKey:void 0,apiSecret:void 0}};var ce,de,le,he,pe,me,fe,ge,Ee,Te,ve,ye,Pe,Ie,Ae,we,Ne,Se,ke=/*#__PURE__*/se("context"),De=/*#__PURE__*/se("chainId");class Oe{constructor(e,t){Object.defineProperty(this,ke,{writable:!0,value:void 0}),Object.defineProperty(this,De,{writable:!0,value:void 0}),ae(this,De)[De]=this.updateChainId(e),ae(this,ke)[ke]={...ue,...t}}updateChainId(e){if(!exports.SupportedChainId[e])throw new h(`Invalid chainId: ${e}`);return u.default.debug(m,`Updating chainId to: ${e}`),ae(this,De)[De]=e,e}get chainId(){const e=this;var t;const r=null==(t=ae(this,ke)[ke].signer)?void 0:t.provider;return r?(u.default.debug(m,"Getting chainId from provider"),function(){try{return Promise.resolve(r.getNetwork()).then(function(t){const r=t.chainId;return r!==ae(e,De)[De]&&(u.default.debug(m,`ChainId mismatch: Provider's chainId: ${r} vs Context's chainId: ${ae(e,De)[De]}. Updating Context's chainId`),e.updateChainId(r)),r})}catch(e){return Promise.reject(e)}}()):Promise.resolve(ae(this,De)[De])}get appDataHash(){var e;return null!==(e=ae(this,ke)[ke].appDataHash)&&void 0!==e?e:ue.appDataHash}get isDevEnvironment(){var e;return null!==(e=ae(this,ke)[ke].isDevEnvironment)&&void 0!==e?e:ue.isDevEnvironment}get signer(){return ae(this,ke)[ke].signer}get ipfs(){var e;return null!==(e=ae(this,ke)[ke].ipfs)&&void 0!==e?e:ue.ipfs}}!function(e){e.EthPriceUsd="ethPriceUSD",e.Id="id"}(ce||(ce={})),function(e){e.FeesEth="feesEth",e.FeesUsd="feesUsd",e.Id="id",e.Orders="orders",e.Settlements="settlements",e.Timestamp="timestamp",e.Tokens="tokens",e.TotalTokens="totalTokens",e.VolumeEth="volumeEth",e.VolumeUsd="volumeUsd"}(de||(de={})),function(e){e.FeesEth="feesEth",e.FeesUsd="feesUsd",e.Id="id",e.Orders="orders",e.Settlements="settlements",e.Timestamp="timestamp",e.Tokens="tokens",e.TotalTokens="totalTokens",e.VolumeEth="volumeEth",e.VolumeUsd="volumeUsd"}(le||(le={})),function(e){e.Asc="asc",e.Desc="desc"}(he||(he={})),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"}(pe||(pe={})),function(e){e.Id="id",e.Timestamp="timestamp",e.Token0="token0",e.Token1="token1",e.VolumeToken0="volumeToken0",e.VolumeToken1="volumeToken1",e.VolumeTradedEth="volumeTradedEth",e.VolumeTradedUsd="volumeTradedUsd"}(me||(me={})),function(e){e.Id="id",e.Timestamp="timestamp",e.Token0="token0",e.Token1="token1",e.VolumeToken0="volumeToken0",e.VolumeToken1="volumeToken1",e.VolumeTradedEth="volumeTradedEth",e.VolumeTradedUsd="volumeTradedUsd"}(fe||(fe={})),function(e){e.Id="id",e.Token0="token0",e.Token1="token1",e.VolumeToken0="volumeToken0",e.VolumeToken1="volumeToken1",e.VolumeTradedEth="volumeTradedEth",e.VolumeTradedUsd="volumeTradedUsd"}(ge||(ge={})),function(e){e.FirstTradeTimestamp="firstTradeTimestamp",e.Id="id",e.Solver="solver",e.Trades="trades",e.TxHash="txHash"}(Ee||(Ee={})),function(e){e.AveragePrice="averagePrice",e.ClosePrice="closePrice",e.HigherPrice="higherPrice",e.Id="id",e.LowerPrice="lowerPrice",e.OpenPrice="openPrice",e.Timestamp="timestamp",e.Token="token",e.TotalTrades="totalTrades",e.TotalVolume="totalVolume",e.TotalVolumeEth="totalVolumeEth",e.TotalVolumeUsd="totalVolumeUsd"}(Te||(Te={})),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"}(ve||(ve={})),function(e){e.AmountEth="amountEth",e.AmountUsd="amountUsd",e.Id="id",e.Timestamp="timestamp",e.Token="token",e.Trade="trade"}(ye||(ye={})),function(e){e.Address="address",e.AllowedPools="allowedPools",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"}(Pe||(Pe={})),function(e){e.FeesEth="feesEth",e.FeesUsd="feesUsd",e.Id="id",e.Orders="orders",e.Settlements="settlements",e.Tokens="tokens",e.Traders="traders",e.VolumeEth="volumeEth",e.VolumeUsd="volumeUsd"}(Ie||(Ie={})),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"}(Ae||(Ae={})),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"}(we||(we={})),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"}(Ne||(Ne={})),function(e){e.Allow="allow",e.Deny="deny"}(Se||(Se={}));var _e={__proto__:null,get Bundle_OrderBy(){return ce},get DailyTotal_OrderBy(){return de},get HourlyTotal_OrderBy(){return le},get OrderDirection(){return he},get Order_OrderBy(){return pe},get PairDaily_OrderBy(){return me},get PairHourly_OrderBy(){return fe},get Pair_OrderBy(){return ge},get Settlement_OrderBy(){return Ee},get TokenDailyTotal_OrderBy(){return Te},get TokenHourlyTotal_OrderBy(){return ve},get TokenTradingEvent_OrderBy(){return ye},get Token_OrderBy(){return Pe},get Total_OrderBy(){return Ie},get Trade_OrderBy(){return Ae},get UniswapPool_OrderBy(){return we},get User_OrderBy(){return Ne},get _SubgraphErrorPolicy_(){return Se}};Object.defineProperty(exports,"OrderKind",{enumerable:!0,get:function(){return r.OrderKind}}),exports.ALL_SUPPORTED_CHAIN_IDS=g,exports.CowError=h,exports.CowSdk=class{constructor(e,t={},r={}){this.context=void 0,this.cowApi=void 0,this.metadataApi=void 0,this.cowSubgraphApi=void 0,this.updateChainId=e=>{this.context.updateChainId(e)},this.validateAppDataDocument=X,this.context=new Oe(e,{...t}),this.cowApi=new Q(this.context),this.cowSubgraphApi=new z(this.context),this.metadataApi=new oe(this.context),u.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 v({order:e,chainId:t},P,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 v({orderId:e,chainId:t},y,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=_e,exports.Token=V;
|
|
29
29
|
//# sourceMappingURL=index.js.map
|