@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.
Files changed (53) hide show
  1. package/dist/api/0x/error/index.d.ts +21 -0
  2. package/dist/api/0x/index.d.ts +11 -0
  3. package/dist/api/0x/utils.d.ts +17 -0
  4. package/dist/api/base/index.d.ts +25 -0
  5. package/dist/api/cow/index.d.ts +5 -3
  6. package/dist/api/cow/types.d.ts +1 -1
  7. package/dist/api/cow-subgraph/graphql.d.ts +24 -2
  8. package/dist/appData.schema-0c8db23b.js +2 -0
  9. package/dist/appData.schema-0c8db23b.js.map +1 -0
  10. package/dist/appData.schema-412cbfbf.js +2 -0
  11. package/dist/appData.schema-412cbfbf.js.map +1 -0
  12. package/dist/appData.schema-4c010c50.js +2 -0
  13. package/dist/appData.schema-4c010c50.js.map +1 -0
  14. package/dist/appData.schema-adfc1c6f.js +2 -0
  15. package/dist/appData.schema-adfc1c6f.js.map +1 -0
  16. package/dist/index.js +2 -2
  17. package/dist/index.js.map +1 -1
  18. package/dist/index.modern.js +2 -2
  19. package/dist/index.modern.js.map +1 -1
  20. package/dist/index.modern.mjs +29 -0
  21. package/dist/index.modern.mjs.map +1 -0
  22. package/dist/index.module.js +2 -2
  23. package/dist/index.module.js.map +1 -1
  24. package/dist/src/appData.schema-d44994e0.js +2 -0
  25. package/dist/src/appData.schema-d44994e0.js.map +1 -0
  26. package/dist/src/appData.schema-fb2df827.js +2 -0
  27. package/dist/src/appData.schema-fb2df827.js.map +1 -0
  28. package/dist/src/cow-sdk.esm.js +2 -0
  29. package/dist/src/cow-sdk.esm.js.map +1 -0
  30. package/dist/src/cow-sdk.js +2 -0
  31. package/dist/src/cow-sdk.js.map +1 -0
  32. package/dist/src/cow-sdk.modern.js +2 -0
  33. package/dist/src/cow-sdk.modern.js.map +1 -0
  34. package/dist/src/src/CowSdk.d.ts +16 -0
  35. package/dist/src/src/api/cow/errors/OperatorError.d.ts +63 -0
  36. package/dist/src/src/api/cow/errors/QuoteError.d.ts +32 -0
  37. package/dist/src/src/api/cow/index.d.ts +38 -0
  38. package/dist/src/src/api/cow/types.d.ts +73 -0
  39. package/dist/src/src/api/index.d.ts +1 -0
  40. package/dist/src/src/constants/chains.d.ts +6 -0
  41. package/dist/src/src/constants/index.d.ts +3 -0
  42. package/dist/src/src/constants/tokens.d.ts +5 -0
  43. package/dist/src/src/index.d.ts +4 -0
  44. package/dist/src/src/types/index.d.ts +7 -0
  45. package/dist/src/src/utils/appData.d.ts +7 -0
  46. package/dist/src/src/utils/common.d.ts +5 -0
  47. package/dist/src/src/utils/context.d.ts +24 -0
  48. package/dist/src/src/utils/sign.d.ts +54 -0
  49. package/dist/src/src/utils/tokens.d.ts +2 -0
  50. package/dist/utils/market.d.ts +16 -0
  51. package/package.json +1 -1
  52. package/LICENSE-APACHE +0 -201
  53. package/LICENSE-MIT +0 -21
@@ -1,4 +1,4 @@
1
- import e from"loglevel";import r from"cross-fetch";import{SigningScheme as t,IntChainIdTypedDataV4Signer as n,TypedDataV3Signer as o,domain as i,signOrderCancellation as s,signOrder as a,OrderKind as c}from"@cowprotocol/contracts";export{OrderKind}from"@cowprotocol/contracts";import u from"@cowprotocol/contracts/networks.json";import{gql as d,GraphQLClient as l}from"graphql-request";import h from"ajv";class m extends Error{constructor(e,r){super(e),this.error_code=void 0,this.error_code=r}}function p(e){if(!e)return"";const r=new URLSearchParams;for(const t of Object.keys(e)){const n=e[t];n&&r.append(t,n.toString())}const t=r.toString();return t?`?${t}`:""}const f="cow-sdk:";var v;!function(e){e[e.MAINNET=1]="MAINNET",e[e.RINKEBY=4]="RINKEBY",e[e.GOERLI=5]="GOERLI",e[e.GNOSIS_CHAIN=100]="GNOSIS_CHAIN"}(v||(v={}));const E=[v.MAINNET,v.RINKEBY,v.GOERLI,v.GNOSIS_CHAIN],{GPv2Settlement:T}=u,g={[v.MAINNET]:T[v.MAINNET].address,[v.RINKEBY]:T[v.RINKEBY].address,[v.GOERLI]:T[v.GOERLI].address,[v.GNOSIS_CHAIN]:T[v.GNOSIS_CHAIN].address},P=function(r,i,s,a="v4"){try{let u;function c(e){var r;return u?e:{signature:null==(r=h)?void 0:r.data.toString(),signingScheme:d}}const d="eth_sign"===a?t.ETHSIGN:t.EIP712;let l,h=null;try{switch(a){case"v3":l=new o(s);break;case"int_v4":l=new n(s);break;default:l=s}}catch(v){throw e.error(f,"Wallet not supported:",v),new m("Wallet not supported")}const p=function(e,t){try{var n=Promise.resolve(i({...r,signer:l,signingScheme:d})).then(function(e){h=e})}catch(e){return t(e)}return n&&n.then?n.then(void 0,t):n}(0,function(t){if(void 0===(n=t).code&&void 0===n.message)throw e.error(f,t),t;var n;if(t.code===w||D.test(t.message))switch(a){case"v4":const e=P(r,i,s,"v3");return u=1,e;case"v3":const n=P(r,i,s,"eth_sign");return u=1,n;default:throw t}else{if(O.test(t.message)){const e=P(r,i,s,"int_v4");return u=1,e}if(t.code===A){const e=P(r,i,s,"eth_sign");return u=1,e}if(N.test(t.message)){const e=P(r,i,s,"v3");return u=1,e}if(k.test(t.message)){const e=P(r,i,s,"eth_sign");return u=1,e}}});return Promise.resolve(p&&p.then?p.then(c):c(p))}catch(E){return Promise.reject(E)}},y=function(e){try{const{chainId:r,signer:t,signingScheme:n,orderId:o}=e,i=U(r);return Promise.resolve(s(i,o,t,R(n)))}catch(e){return Promise.reject(e)}},I=function(e){try{const{chainId:r,signer:t,order:n,signingScheme:o}=e,i=U(r);return Promise.resolve(a(i,n,t,R(o)))}catch(e){return Promise.reject(e)}},A=-32603,w=-32601,N=/eth_signTypedData_v4 does not exist/i,k=/eth_signTypedData_v3 does not exist/i,D=/RPC request failed/i,O=/provided chainid .* must match the active chainid/i,_=new Map([[t.EIP712,{libraryValue:0,apiValue:"eip712"}],[t.ETHSIGN,{libraryValue:1,apiValue:"ethsign"}],[t.EIP1271,{libraryValue:2,apiValue:"eip1271"}],[t.PRESIGN,{libraryValue:3,apiValue:"presign"}]]);function b(e){const r=_.get(e);if(void 0===r)throw new m("Unknown schema "+e);return r}function S(e){return b(e).apiValue}function R(e){return b(e).libraryValue}function U(e){const r=g[e];if(!r)throw new m("Unsupported network. Settlement contract is not deployed");return i(e,r)}var x,C,L,H;!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"}(x||(x={})),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"}(C||(C={}));class j extends m{static getErrorMessage(r,t){try{return Promise.resolve(function(t,n){try{var o=Promise.resolve(r.json()).then(function(r){return r.errorType?j.apiErrorDetails[r.errorType]||r.errorType:(e.error(f,"Unknown reason for bad order submission",r),r.description)})}catch(e){return n()}return o&&o.then?o.then(void 0,n):o}(0,function(){return e.error(f,"Error handling a 400 error. Likely a problem deserialising the JSON response"),function(r){switch(r){case"get":return C.UNHANDLED_GET_ERROR;case"create":return C.UNHANDLED_CREATE_ERROR;case"delete":return C.UNHANDLED_DELETE_ERROR;default:return e.error(f,"[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(r,t){try{const n=this;switch(r.status){case 400:case 404:return Promise.resolve(n.getErrorMessage(r,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 e.error(f,`[OperatorError::getErrorFromStatusCode] Error ${"create"===t?"creating":"cancelling"} the order, status code:`,r.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=C[e.errorType]}}j.apiErrorDetails=C,function(e){e.UnsupportedToken="UnsupportedToken",e.InsufficientLiquidity="InsufficientLiquidity",e.FeeExceedsFrom="FeeExceedsFrom",e.ZeroPrice="ZeroPrice",e.UNHANDLED_ERROR="UNHANDLED_ERROR"}(L||(L={})),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."}(H||(H={}));class V extends m{static getErrorMessage(r){try{return Promise.resolve(function(t,n){try{var o=Promise.resolve(r.json()).then(function(r){return r.errorType?V.quoteErrorDetails[r.errorType]||r.errorType:(e.error(f,"Unknown reason for bad quote fetch",r),r.description)})}catch(e){return n()}return o&&o.then?o.then(void 0,n):o}(0,function(){return e.error(f,"Error handling 400/404 error. Likely a problem deserialising the JSON response"),V.quoteErrorDetails.UNHANDLED_ERROR}))}catch(e){return Promise.reject(e)}}static getErrorFromStatusCode(r){try{const t=this;switch(r.status){case 400:case 404:return Promise.resolve(t.getErrorMessage(r));default:return e.error(f,"[QuoteError::getErrorFromStatusCode] Error fetching quote, status code:",r.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=V.quoteErrorDetails[e.errorType],this.data=null==e?void 0:e.data}}V.quoteErrorDetails=H;class F{constructor(e,r){this.symbol=void 0,this.address=void 0,this.symbol=e,this.address=r}}const $={[v.MAINNET]:new F("WETH","0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2"),[v.RINKEBY]:new F("WETH","0xc778417E063141139Fce010982780140Aa0cD5Ab"),[v.GOERLI]:new F("WETH","0xb4fbf271143f4fbf7b91a5ded31805e42b2208d6"),[v.GNOSIS_CHAIN]:new F("WXDAI","0xe91D153E0b41518A2Ce8Dd3D7944Fa863463a97d")},B={[v.MAINNET]:"ETH",[v.RINKEBY]:"ETH",[v.GOERLI]:"ETH",[v.GNOSIS_CHAIN]:"XDAI"};function G(e,r){let t=e;return e===B[r]&&(t=$[r].address),t}function M(e,r){try{var t=e()}catch(e){return r(e)}return t&&t.then?t.then(void 0,r):t}function q(e){return e?{[v.MAINNET]:"https://barn.api.cow.fi/mainnet/api",[v.RINKEBY]:"https://barn.api.cow.fi/rinkeby/api",[v.GOERLI]:"https://barn.api.cow.fi/goerli/api",[v.GNOSIS_CHAIN]:"https://barn.api.cow.fi/xdai/api"}:{[v.MAINNET]:"https://api.cow.fi/mainnet/api",[v.RINKEBY]:"https://api.cow.fi/rinkeby/api",[v.GOERLI]:"https://api.cow.fi/goerli/api",[v.GNOSIS_CHAIN]:"https://api.cow.fi/xdai/api"}}function K(e){return e?{[v.MAINNET]:"https://barn.api.cow.fi/affiliate/api"}:{[v.MAINNET]:"https://api.cow.fi/affiliate/api"}}const Y=function(r,t){try{return r.ok?Promise.resolve(r.json()):Promise.resolve(r.json()).then(function(r){const n=function(e){switch(null==e?void 0:e.errorType){case x.NotFound:case x.NoLiquidity:return{errorType:L.InsufficientLiquidity,description:H.InsufficientLiquidity};case x.SellAmountDoesNotCoverFee:return{errorType:L.FeeExceedsFrom,description:H.FeeExceedsFrom,data:null==e?void 0:e.data};case x.UnsupportedToken:return{errorType:L.UnsupportedToken,description:e.description};case x.SellAmountDoesNotCoverFee:return{errorType:L.FeeExceedsFrom,description:e.description};default:return{errorType:L.UNHANDLED_ERROR,description:H.UNHANDLED_ERROR}}}(r),o=new V(n);if(t){const{sellToken:r,buyToken:n}=t;e.error(f,`Error querying fee from API - sellToken: ${r}, buyToken: ${n}`)}throw o})}catch(e){return Promise.reject(e)}},Q={errorType:L.UNHANDLED_ERROR,description:H.UNHANDLED_ERROR},W={errorType:x.UNHANDLED_CREATE_ERROR,description:C.UNHANDLED_CREATE_ERROR};class J{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 q(this.context.isDevEnvironment)}getProfileData(r,t={}){try{const n=this;function o(t){return e.debug(f,`[api:${n.API_NAME}] Get profile data for`,t,r),t!==v.MAINNET?(e.info(f,"Profile data is only available for mainnet"),null):Promise.resolve(n.getProfile(`/profile/${r}`,{chainId:t,isDevEnvironment:s})).then(function(r){return r.ok?r.json():Promise.resolve(r.json()).then(function(r){throw e.error(f,r),new m(null==r?void 0:r.description)})})}const{chainId:i,isDevEnvironment:s}=t;return Promise.resolve(i?o(i):Promise.resolve(n.context.chainId).then(o))}catch(a){return Promise.reject(a)}}getTrades(r,t={}){try{const n=this;function o(r){return e.debug(f,"[util:operator] Get trades for",r,{owner:a,orderId:c,limit:u,offset:d}),M(function(){return Promise.resolve(n.get(`/trades${l}`,{chainId:r,isDevEnvironment:s})).then(function(e){return e.ok?e.json():Promise.resolve(e.json()).then(function(e){throw new j(e)})})},function(r){if(e.error(f,"Error getting trades:",r),r instanceof j)throw r;throw new m("Error getting trades: "+r)})}const{chainId:i,isDevEnvironment:s=n.context.isDevEnvironment}=t,{owner:a,orderId:c,limit:u,offset:d}=r;if(a&&c)throw new m("Cannot specify both owner and orderId");const l=p({owner:a,orderUid:c,limit:u,offset:d});return Promise.resolve(i?o(i):Promise.resolve(n.context.chainId).then(o))}catch(h){return Promise.reject(h)}}getOrders(r,t={}){try{const n=this;function o(r){return e.debug(f,`[api:${n.API_NAME}] Get orders for `,r,a,c,u),M(function(){return Promise.resolve(n.get(`/account/${a}/orders/${d}`,{chainId:r,isDevEnvironment:s})).then(function(e){return e.ok?e.json():Promise.resolve(e.json()).then(function(e){throw new j(e)})})},function(r){if(e.error(f,"Error getting orders information:",r),r instanceof j)throw r;throw new j(W)})}const{chainId:i,isDevEnvironment:s=n.context.isDevEnvironment}=t,{owner:a,limit:c=1e3,offset:u=0}=r,d=p({limit:c,offset:u});return Promise.resolve(i?o(i):Promise.resolve(n.context.chainId).then(o))}catch(l){return Promise.reject(l)}}getTxOrders(r,t={}){try{const n=this;function o(t){return e.debug(`[api:${n.API_NAME}] Get tx orders for `,t,r),M(function(){return Promise.resolve(n.get(`/transactions/${r}/orders`,{chainId:t,isDevEnvironment:s})).then(function(e){return e.ok?e.json():Promise.resolve(e.json()).then(function(e){throw new j(e)})})},function(r){if(e.error("Error getting transaction orders information:",r),r instanceof j)throw r;throw new j(W)})}const{chainId:i,isDevEnvironment:s}=t;return Promise.resolve(i?o(i):Promise.resolve(n.context.chainId).then(o))}catch(a){return Promise.reject(a)}}getOrder(r,t={}){try{const n=this;function o(t){return e.debug(f,`[api:${n.API_NAME}] Get order for `,t,r),M(function(){return Promise.resolve(n.get(`/orders/${r}`,{chainId:t,isDevEnvironment:s})).then(function(e){return e.ok?e.json():Promise.resolve(e.json()).then(function(e){throw new j(e)})})},function(r){if(e.error(f,"Error getting order information:",r),r instanceof j)throw r;throw new j(W)})}const{chainId:i,isDevEnvironment:s}=t;return Promise.resolve(i?o(i):Promise.resolve(n.context.chainId).then(o))}catch(a){return Promise.reject(a)}}getPriceQuoteLegacy(r,t={}){try{const n=this;function o(t){return e.debug(f,`[api:${n.API_NAME}] Get price from API`,r,"for",t),Promise.resolve(n.get(`/markets/${G(a,t)}-${G(c,t)}/${d}/${u}`,{chainId:t,isDevEnvironment:s}).catch(r=>{throw e.error(f,"Error getting price quote:",r),new V(Q)})).then(Y)}const{chainId:i,isDevEnvironment:s}=t,{baseToken:a,quoteToken:c,amount:u,kind:d}=r;return Promise.resolve(i?o(i):Promise.resolve(n.context.chainId).then(o))}catch(l){return Promise.reject(l)}}getQuote(e,r={}){try{const t=this;function n(r){const n=t.mapNewToLegacyParams(e,r);return Promise.resolve(t.post("/quote",n,{chainId:r,isDevEnvironment:i})).then(Y)}const{chainId:o,isDevEnvironment:i}=r;return Promise.resolve(o?n(o):Promise.resolve(t.context.chainId).then(n))}catch(s){return Promise.reject(s)}}sendSignedOrderCancellation(r,t={}){try{const n=this;function o(r){return e.debug(f,`[api:${n.API_NAME}] Delete signed order for network`,r,a),Promise.resolve(n.delete(`/orders/${a.orderUid}`,{signature:a.signature,signingScheme:S(a.signingScheme),from:c},{chainId:r,isDevEnvironment:s})).then(function(t){function o(t){e.debug(f,`[api:${n.API_NAME}] Cancelled order`,a.orderUid,r)}const i=function(){if(!t.ok)return Promise.resolve(j.getErrorFromStatusCode(t,"delete")).then(function(e){throw new m(e)})}();return i&&i.then?i.then(o):o()})}const{chainId:i,isDevEnvironment:s}=t,{cancellation:a,owner:c}=r;return Promise.resolve(i?o(i):Promise.resolve(n.context.chainId).then(o))}catch(u){return Promise.reject(u)}}sendOrder(r,t={}){try{const n=this;function o(t){const{owner:o}=r;return e.debug(f,`[api:${n.API_NAME}] Post signed order for network`,t,i),Promise.resolve(n.post("/orders",{...i,signingScheme:S(i.signingScheme),from:o},{chainId:t,isDevEnvironment:a})).then(function(r){function t(t){return Promise.resolve(r.json()).then(function(r){return e.debug(f,`[api:${n.API_NAME}] Success posting the signed order`,r),r})}const o=function(){if(!r.ok)return Promise.resolve(j.getErrorFromStatusCode(r,"create")).then(function(e){throw new m(e)})}();return o&&o.then?o.then(t):t()})}const i={...r.order,appData:n.context.appDataHash},{chainId:s,isDevEnvironment:a}=t;return Promise.resolve(s?o(s):Promise.resolve(n.context.chainId).then(o))}catch(c){return Promise.reject(c)}}getOrderLink(e){try{return Promise.resolve(this.getApiBaseUrl()).then(function(r){return r+`/orders/${e}`})}catch(e){return Promise.reject(e)}}mapNewToLegacyParams(e,r){const{amount:t,kind:n,userAddress:o,receiver:i,validTo:s,sellToken:a,buyToken:u}=e,d=o||"0x0000000000000000000000000000000000000000",l={sellToken:G(a,r),buyToken:G(u,r),from:d,receiver:i||d,appData:this.context.appDataHash,validTo:s,partiallyFillable:!1};return n===c.SELL?{kind:c.SELL,sellAmountBeforeFee:t,...l}:{kind:c.BUY,buyAmountAfterFee:t,...l}}getApiBaseUrl(){try{const e=this;return Promise.resolve(e.context.chainId).then(function(r){const t=e.API_BASE_URL[r];if(t)return t+"/v1";throw new m(`Unsupported Network. The ${e.API_NAME} API is not deployed in the Network `+r)})}catch(e){return Promise.reject(e)}}fetch(e,t,n,o){try{return Promise.resolve(r(n+e,{headers:this.DEFAULT_HEADERS,method:t,body:void 0!==o?JSON.stringify(o):o}))}catch(e){return Promise.reject(e)}}fetchProfile(e,t,n,o){try{return Promise.resolve(r(n+e,{headers:this.DEFAULT_HEADERS,method:t,body:void 0!==o?JSON.stringify(o):o}))}catch(e){return Promise.reject(e)}}post(e,r,t={}){return this.handleMethod(e,"POST",this.fetch.bind(this),q,t,r)}get(e,r={}){return this.handleMethod(e,"GET",this.fetch.bind(this),q,r)}getProfile(e,r={}){return this.handleMethod(e,"GET",this.fetchProfile.bind(this),K,r)}delete(e,r,t={}){return this.handleMethod(e,"DELETE",this.fetch.bind(this),q,t,r)}handleMethod(e,r,t,n,o={},i){try{const s=this;function a(n){let o;const s=function(){if(void 0!==u)return Promise.resolve(t(e,r,`${(u?l:d)[n]}/v1`,i)).then(function(e){o=e});{const s=M(function(){return Promise.resolve(t(e,r,`${d[n]}/v1`,i)).then(function(e){o=e})},function(){return Promise.resolve(t(e,r,`${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 Z=d`
1
+ import e from"loglevel";import r from"cross-fetch";import{SigningScheme as t,IntChainIdTypedDataV4Signer as n,TypedDataV3Signer as o,domain as i,signOrderCancellation as s,signOrder as a,OrderKind as c}from"@cowprotocol/contracts";export{OrderKind}from"@cowprotocol/contracts";import u from"@cowprotocol/contracts/networks.json";import{gql as d,GraphQLClient as l}from"graphql-request";import h from"ajv";class m extends Error{constructor(e,r){super(e),this.error_code=void 0,this.error_code=r}}function p(e){if(!e)return"";const r=new URLSearchParams;for(const t of Object.keys(e)){const n=e[t];n&&r.append(t,n.toString())}const t=r.toString();return t?`?${t}`:""}const f="cow-sdk:";var v;!function(e){e[e.MAINNET=1]="MAINNET",e[e.RINKEBY=4]="RINKEBY",e[e.GOERLI=5]="GOERLI",e[e.GNOSIS_CHAIN=100]="GNOSIS_CHAIN"}(v||(v={}));const E=[v.MAINNET,v.RINKEBY,v.GOERLI,v.GNOSIS_CHAIN],{GPv2Settlement:T}=u,g={[v.MAINNET]:T[v.MAINNET].address,[v.RINKEBY]:T[v.RINKEBY].address,[v.GOERLI]:T[v.GOERLI].address,[v.GNOSIS_CHAIN]:T[v.GNOSIS_CHAIN].address},P=function(r,i,s,a="v4"){try{let u;function c(e){return u?e:{signature:h?.data.toString(),signingScheme:d}}const d="eth_sign"===a?t.ETHSIGN:t.EIP712;let l,h=null;try{switch(a){case"v3":l=new o(s);break;case"int_v4":l=new n(s);break;default:l=s}}catch(v){throw e.error(f,"Wallet not supported:",v),new m("Wallet not supported")}const p=function(e,t){try{var n=Promise.resolve(i({...r,signer:l,signingScheme:d})).then(function(e){h=e})}catch(e){return t(e)}return n&&n.then?n.then(void 0,t):n}(0,function(t){if(void 0===(n=t).code&&void 0===n.message)throw e.error(f,t),t;var n;if(t.code===w||D.test(t.message))switch(a){case"v4":const e=P(r,i,s,"v3");return u=1,e;case"v3":const n=P(r,i,s,"eth_sign");return u=1,n;default:throw t}else{if(O.test(t.message)){const e=P(r,i,s,"int_v4");return u=1,e}if(t.code===A){const e=P(r,i,s,"eth_sign");return u=1,e}if(N.test(t.message)){const e=P(r,i,s,"v3");return u=1,e}if(k.test(t.message)){const e=P(r,i,s,"eth_sign");return u=1,e}}});return Promise.resolve(p&&p.then?p.then(c):c(p))}catch(E){return Promise.reject(E)}},y=function(e){try{const{chainId:r,signer:t,signingScheme:n,orderId:o}=e,i=U(r);return Promise.resolve(s(i,o,t,R(n)))}catch(e){return Promise.reject(e)}},I=function(e){try{const{chainId:r,signer:t,order:n,signingScheme:o}=e,i=U(r);return Promise.resolve(a(i,n,t,R(o)))}catch(e){return Promise.reject(e)}},A=-32603,w=-32601,N=/eth_signTypedData_v4 does not exist/i,k=/eth_signTypedData_v3 does not exist/i,D=/RPC request failed/i,O=/provided chainid .* must match the active chainid/i,_=new Map([[t.EIP712,{libraryValue:0,apiValue:"eip712"}],[t.ETHSIGN,{libraryValue:1,apiValue:"ethsign"}],[t.EIP1271,{libraryValue:2,apiValue:"eip1271"}],[t.PRESIGN,{libraryValue:3,apiValue:"presign"}]]);function b(e){const r=_.get(e);if(void 0===r)throw new m("Unknown schema "+e);return r}function S(e){return b(e).apiValue}function R(e){return b(e).libraryValue}function U(e){const r=g[e];if(!r)throw new m("Unsupported network. Settlement contract is not deployed");return i(e,r)}var x,C,L,H;!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"}(x||(x={})),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"}(C||(C={}));class j extends m{static getErrorMessage(r,t){try{return Promise.resolve(function(t,n){try{var o=Promise.resolve(r.json()).then(function(r){return r.errorType?j.apiErrorDetails[r.errorType]||r.errorType:(e.error(f,"Unknown reason for bad order submission",r),r.description)})}catch(e){return n()}return o&&o.then?o.then(void 0,n):o}(0,function(){return e.error(f,"Error handling a 400 error. Likely a problem deserialising the JSON response"),function(r){switch(r){case"get":return C.UNHANDLED_GET_ERROR;case"create":return C.UNHANDLED_CREATE_ERROR;case"delete":return C.UNHANDLED_DELETE_ERROR;default:return e.error(f,"[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(r,t){try{const n=this;switch(r.status){case 400:case 404:return Promise.resolve(n.getErrorMessage(r,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 e.error(f,`[OperatorError::getErrorFromStatusCode] Error ${"create"===t?"creating":"cancelling"} the order, status code:`,r.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=C[e.errorType]}}j.apiErrorDetails=C,function(e){e.UnsupportedToken="UnsupportedToken",e.InsufficientLiquidity="InsufficientLiquidity",e.FeeExceedsFrom="FeeExceedsFrom",e.ZeroPrice="ZeroPrice",e.UNHANDLED_ERROR="UNHANDLED_ERROR"}(L||(L={})),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."}(H||(H={}));class V extends m{static getErrorMessage(r){try{return Promise.resolve(function(t,n){try{var o=Promise.resolve(r.json()).then(function(r){return r.errorType?V.quoteErrorDetails[r.errorType]||r.errorType:(e.error(f,"Unknown reason for bad quote fetch",r),r.description)})}catch(e){return n()}return o&&o.then?o.then(void 0,n):o}(0,function(){return e.error(f,"Error handling 400/404 error. Likely a problem deserialising the JSON response"),V.quoteErrorDetails.UNHANDLED_ERROR}))}catch(e){return Promise.reject(e)}}static getErrorFromStatusCode(r){try{const t=this;switch(r.status){case 400:case 404:return Promise.resolve(t.getErrorMessage(r));default:return e.error(f,"[QuoteError::getErrorFromStatusCode] Error fetching quote, status code:",r.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=V.quoteErrorDetails[e.errorType],this.data=e?.data}}V.quoteErrorDetails=H;class F{constructor(e,r){this.symbol=void 0,this.address=void 0,this.symbol=e,this.address=r}}const $={[v.MAINNET]:new F("WETH","0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2"),[v.RINKEBY]:new F("WETH","0xc778417E063141139Fce010982780140Aa0cD5Ab"),[v.GOERLI]:new F("WETH","0xb4fbf271143f4fbf7b91a5ded31805e42b2208d6"),[v.GNOSIS_CHAIN]:new F("WXDAI","0xe91D153E0b41518A2Ce8Dd3D7944Fa863463a97d")},B={[v.MAINNET]:"ETH",[v.RINKEBY]:"ETH",[v.GOERLI]:"ETH",[v.GNOSIS_CHAIN]:"XDAI"};function G(e,r){let t=e;return e===B[r]&&(t=$[r].address),t}function M(e,r){try{var t=e()}catch(e){return r(e)}return t&&t.then?t.then(void 0,r):t}function q(e){return e?{[v.MAINNET]:"https://barn.api.cow.fi/mainnet/api",[v.RINKEBY]:"https://barn.api.cow.fi/rinkeby/api",[v.GOERLI]:"https://barn.api.cow.fi/goerli/api",[v.GNOSIS_CHAIN]:"https://barn.api.cow.fi/xdai/api"}:{[v.MAINNET]:"https://api.cow.fi/mainnet/api",[v.RINKEBY]:"https://api.cow.fi/rinkeby/api",[v.GOERLI]:"https://api.cow.fi/goerli/api",[v.GNOSIS_CHAIN]:"https://api.cow.fi/xdai/api"}}function K(e){return e?{[v.MAINNET]:"https://barn.api.cow.fi/affiliate/api"}:{[v.MAINNET]:"https://api.cow.fi/affiliate/api"}}const Y=function(r,t){try{return r.ok?Promise.resolve(r.json()):"application/json"===r.headers.get("Content-Type")?Promise.resolve(r.json()).then(function(r){const n=function(e){switch(e?.errorType){case x.NotFound:case x.NoLiquidity:return{errorType:L.InsufficientLiquidity,description:H.InsufficientLiquidity};case x.SellAmountDoesNotCoverFee:return{errorType:L.FeeExceedsFrom,description:H.FeeExceedsFrom,data:e?.data};case x.UnsupportedToken:return{errorType:L.UnsupportedToken,description:e.description};case x.SellAmountDoesNotCoverFee:return{errorType:L.FeeExceedsFrom,description:e.description};default:return{errorType:L.UNHANDLED_ERROR,description:H.UNHANDLED_ERROR}}}(r),o=new V(n);if(t){const{sellToken:r,buyToken:n}=t;e.error(f,`Error querying fee from API - sellToken: ${r}, buyToken: ${n}`)}throw o}):Promise.resolve(r.text()).then(function(e){throw new V({description:e,errorType:L.UNHANDLED_ERROR})})}catch(e){return Promise.reject(e)}},Q={errorType:L.UNHANDLED_ERROR,description:H.UNHANDLED_ERROR},W={errorType:x.UNHANDLED_CREATE_ERROR,description:C.UNHANDLED_CREATE_ERROR};class J{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 q(this.context.isDevEnvironment)}getProfileData(r,t={}){try{const n=this;function o(t){return e.debug(f,`[api:${n.API_NAME}] Get profile data for`,t,r),t!==v.MAINNET?(e.info(f,"Profile data is only available for mainnet"),null):Promise.resolve(n.getProfile(`/profile/${r}`,{chainId:t,isDevEnvironment:s})).then(function(r){return r.ok?r.json():Promise.resolve(r.json()).then(function(r){throw e.error(f,r),new m(r?.description)})})}const{chainId:i,isDevEnvironment:s}=t;return Promise.resolve(i?o(i):Promise.resolve(n.context.chainId).then(o))}catch(a){return Promise.reject(a)}}getTrades(r,t={}){try{const n=this;function o(r){return e.debug(f,"[util:operator] Get trades for",r,{owner:a,orderId:c,limit:u,offset:d}),M(function(){return Promise.resolve(n.get(`/trades${l}`,{chainId:r,isDevEnvironment:s})).then(function(e){return e.ok?e.json():Promise.resolve(e.json()).then(function(e){throw new j(e)})})},function(r){if(e.error(f,"Error getting trades:",r),r instanceof j)throw r;throw new m("Error getting trades: "+r)})}const{chainId:i,isDevEnvironment:s=n.context.isDevEnvironment}=t,{owner:a,orderId:c,limit:u,offset:d}=r;if(a&&c)throw new m("Cannot specify both owner and orderId");const l=p({owner:a,orderUid:c,limit:u,offset:d});return Promise.resolve(i?o(i):Promise.resolve(n.context.chainId).then(o))}catch(h){return Promise.reject(h)}}getOrders(r,t={}){try{const n=this;function o(r){return e.debug(f,`[api:${n.API_NAME}] Get orders for `,r,a,c,u),M(function(){return Promise.resolve(n.get(`/account/${a}/orders/${d}`,{chainId:r,isDevEnvironment:s})).then(function(e){return e.ok?e.json():Promise.resolve(e.json()).then(function(e){throw new j(e)})})},function(r){if(e.error(f,"Error getting orders information:",r),r instanceof j)throw r;throw new j(W)})}const{chainId:i,isDevEnvironment:s=n.context.isDevEnvironment}=t,{owner:a,limit:c=1e3,offset:u=0}=r,d=p({limit:c,offset:u});return Promise.resolve(i?o(i):Promise.resolve(n.context.chainId).then(o))}catch(l){return Promise.reject(l)}}getTxOrders(r,t={}){try{const n=this;function o(t){return e.debug(`[api:${n.API_NAME}] Get tx orders for `,t,r),M(function(){return Promise.resolve(n.get(`/transactions/${r}/orders`,{chainId:t,isDevEnvironment:s})).then(function(e){return e.ok?e.json():Promise.resolve(e.json()).then(function(e){throw new j(e)})})},function(r){if(e.error("Error getting transaction orders information:",r),r instanceof j)throw r;throw new j(W)})}const{chainId:i,isDevEnvironment:s}=t;return Promise.resolve(i?o(i):Promise.resolve(n.context.chainId).then(o))}catch(a){return Promise.reject(a)}}getOrder(r,t={}){try{const n=this;function o(t){return e.debug(f,`[api:${n.API_NAME}] Get order for `,t,r),M(function(){return Promise.resolve(n.get(`/orders/${r}`,{chainId:t,isDevEnvironment:s})).then(function(e){return e.ok?e.json():Promise.resolve(e.json()).then(function(e){throw new j(e)})})},function(r){if(e.error(f,"Error getting order information:",r),r instanceof j)throw r;throw new j(W)})}const{chainId:i,isDevEnvironment:s}=t;return Promise.resolve(i?o(i):Promise.resolve(n.context.chainId).then(o))}catch(a){return Promise.reject(a)}}getPriceQuoteLegacy(r,t={}){try{const n=this;function o(t){return e.debug(f,`[api:${n.API_NAME}] Get price from API`,r,"for",t),Promise.resolve(n.get(`/markets/${G(a,t)}-${G(c,t)}/${d}/${u}`,{chainId:t,isDevEnvironment:s}).catch(r=>{throw e.error(f,"Error getting price quote:",r),new V(Q)})).then(Y)}const{chainId:i,isDevEnvironment:s}=t,{baseToken:a,quoteToken:c,amount:u,kind:d}=r;return Promise.resolve(i?o(i):Promise.resolve(n.context.chainId).then(o))}catch(l){return Promise.reject(l)}}getQuoteLegacyParams(e,r={}){try{const t=this;function n(r){const n=t.mapNewToLegacyParams(e,r);return Promise.resolve(t.post("/quote",n,{chainId:r,isDevEnvironment:i})).then(Y)}const{chainId:o,isDevEnvironment:i}=r;return Promise.resolve(o?n(o):Promise.resolve(t.context.chainId).then(n))}catch(s){return Promise.reject(s)}}getQuote(e,r={}){try{const t=this;function n(r){return Promise.resolve(t.post("/quote",e,{chainId:r,isDevEnvironment:i})).then(Y)}const{chainId:o,isDevEnvironment:i}=r;return Promise.resolve(o?n(o):Promise.resolve(t.context.chainId).then(n))}catch(s){return Promise.reject(s)}}sendSignedOrderCancellation(r,t={}){try{const n=this;function o(r){return e.debug(f,`[api:${n.API_NAME}] Delete signed order for network`,r,a),Promise.resolve(n.delete(`/orders/${a.orderUid}`,{signature:a.signature,signingScheme:S(a.signingScheme),from:c},{chainId:r,isDevEnvironment:s})).then(function(t){function o(t){e.debug(f,`[api:${n.API_NAME}] Cancelled order`,a.orderUid,r)}const i=function(){if(!t.ok)return Promise.resolve(j.getErrorFromStatusCode(t,"delete")).then(function(e){throw new m(e)})}();return i&&i.then?i.then(o):o()})}const{chainId:i,isDevEnvironment:s}=t,{cancellation:a,owner:c}=r;return Promise.resolve(i?o(i):Promise.resolve(n.context.chainId).then(o))}catch(u){return Promise.reject(u)}}sendOrder(r,t={}){try{const n=this;function o(t){const{owner:o}=r;return e.debug(f,`[api:${n.API_NAME}] Post signed order for network`,t,i),Promise.resolve(n.post("/orders",{...i,signingScheme:S(i.signingScheme),from:o},{chainId:t,isDevEnvironment:a})).then(function(r){function t(t){return Promise.resolve(r.json()).then(function(r){return e.debug(f,`[api:${n.API_NAME}] Success posting the signed order`,r),r})}const o=function(){if(!r.ok)return Promise.resolve(j.getErrorFromStatusCode(r,"create")).then(function(e){throw new m(e)})}();return o&&o.then?o.then(t):t()})}const i={...r.order,appData:n.context.appDataHash},{chainId:s,isDevEnvironment:a}=t;return Promise.resolve(s?o(s):Promise.resolve(n.context.chainId).then(o))}catch(c){return Promise.reject(c)}}getOrderLink(e){try{return Promise.resolve(this.getApiBaseUrl()).then(function(r){return r+`/orders/${e}`})}catch(e){return Promise.reject(e)}}mapNewToLegacyParams(e,r){const{amount:t,kind:n,userAddress:o,receiver:i,validTo:s,sellToken:a,buyToken:u}=e,d=o||"0x0000000000000000000000000000000000000000",l={sellToken:G(a,r),buyToken:G(u,r),from:d,receiver:i||d,appData:this.context.appDataHash,validTo:s,partiallyFillable:!1};return n===c.SELL?{kind:c.SELL,sellAmountBeforeFee:t,...l}:{kind:c.BUY,buyAmountAfterFee:t,...l}}getApiBaseUrl(){try{const e=this;return Promise.resolve(e.context.chainId).then(function(r){const t=e.API_BASE_URL[r];if(t)return t+"/v1";throw new m(`Unsupported Network. The ${e.API_NAME} API is not deployed in the Network `+r)})}catch(e){return Promise.reject(e)}}fetch(e,t,n,o){try{return Promise.resolve(r(n+e,{headers:this.DEFAULT_HEADERS,method:t,body:void 0!==o?JSON.stringify(o):o}))}catch(e){return Promise.reject(e)}}fetchProfile(e,t,n,o){try{return Promise.resolve(r(n+e,{headers:this.DEFAULT_HEADERS,method:t,body:void 0!==o?JSON.stringify(o):o}))}catch(e){return Promise.reject(e)}}post(e,r,t={}){return this.handleMethod(e,"POST",this.fetch.bind(this),q,t,r)}get(e,r={}){return this.handleMethod(e,"GET",this.fetch.bind(this),q,r)}getProfile(e,r={}){return this.handleMethod(e,"GET",this.fetchProfile.bind(this),K,r)}delete(e,r,t={}){return this.handleMethod(e,"DELETE",this.fetch.bind(this),q,t,r)}handleMethod(e,r,t,n,o={},i){try{const s=this;function a(n){let o;const s=function(){if(void 0!==u)return Promise.resolve(t(e,r,`${(u?l:d)[n]}/v1`,i)).then(function(e){o=e});{const s=M(function(){return Promise.resolve(t(e,r,`${d[n]}/v1`,i)).then(function(e){o=e})},function(){return Promise.resolve(t(e,r,`${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 Z=d`
2
2
  query Totals {
3
3
  totals {
4
4
  tokens
@@ -25,5 +25,5 @@ import e from"loglevel";import r from"cross-fetch";import{SigningScheme as t,Int
25
25
  volumeUsd
26
26
  }
27
27
  }
28
- `,ee={[v.MAINNET]:"https://api.thegraph.com/subgraphs/name/cowprotocol/cow",[v.RINKEBY]:"https://api.thegraph.com/subgraphs/name/cowprotocol/cow-rinkeby",[v.GOERLI]:"https://api.thegraph.com/subgraphs/name/cowprotocol/cow-goerli",[v.GNOSIS_CHAIN]:"https://api.thegraph.com/subgraphs/name/cowprotocol/cow-gc"};class re{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{[v.MAINNET]:new l(ee[v.MAINNET],{fetch:r}),[v.RINKEBY]:new l(ee[v.RINKEBY],{fetch:r}),[v.GOERLI]:new l(ee[v.GOERLI],{fetch:r}),[v.GNOSIS_CHAIN]:new l(ee[v.GNOSIS_CHAIN],{fetch:r})}}getBaseUrl(){try{return Promise.resolve(this.context.chainId).then(function(e){return ee[e]})}catch(e){return Promise.reject(e)}}getTotals(){try{const r=this;return Promise.resolve(r.context.chainId).then(function(t){return e.debug(`[subgraph:${r.API_NAME}] Get totals for:`,t),Promise.resolve(r.runQuery(Z)).then(function(e){return e.totals[0]})})}catch(e){return Promise.reject(e)}}getLastDaysVolume(r){try{const t=this;return Promise.resolve(t.context.chainId).then(function(n){return e.debug(`[subgraph:${t.API_NAME}] Get last ${r} days volume for:`,n),t.runQuery(z,{days:r})})}catch(e){return Promise.reject(e)}}getLastHoursVolume(r){try{const t=this;return Promise.resolve(t.context.chainId).then(function(n){return e.debug(`[subgraph:${t.API_NAME}] Get last ${r} hours volume for:`,n),t.runQuery(X,{hours:r})})}catch(e){return Promise.reject(e)}}runQuery(r,t){try{const n=this;return Promise.resolve(function(e,o){try{var i=Promise.resolve(n.context.chainId).then(function(e){return Promise.resolve(n.clients[e].request(r,t))})}catch(e){return o(e)}return i&&i.then?i.then(void 0,o):i}(0,function(o){return e.error(o),Promise.resolve(n.getBaseUrl()).then(function(e){throw new m(`Error running query: ${r}. Variables: ${JSON.stringify(t)}. API: ${e}. Inner Error: ${o}`)})}))}catch(e){return Promise.reject(e)}}}const te=function(e){return Promise.resolve(oe()).then(function({ajv:r,validate:t}){return{result:!!t(e),errors:r.errors?r.errorsText(r.errors):void 0}})},ne=function(e){try{const r=1,t=112,n=18,o=32,i=function(e){const r=e.match(/.{1,2}/g);if(r)return new Uint8Array(r.map(e=>parseInt(e,16)))}(e.replace(/(^0x)/,""));if(!i)return Promise.resolve();const s=Uint8Array.from([r,t,n,o,...i]);return Promise.resolve(import("multiformats/cid")).then(function({CID:e}){return e.decode(s).toV0().toString()})}catch(e){return Promise.reject(e)}},oe=function(){try{function e(){return{ajv:se,validate:ie}}se||(se=new h);const r=function(){if(!ie)return Promise.resolve(import("./appData.schema-b8f018d7.js")).then(function(e){ie=se.compile(e)})}();return Promise.resolve(r&&r.then?r.then(e):e())}catch(t){return Promise.reject(t)}};let ie,se;function ae(e,r){try{var t=e()}catch(e){return r(e)}return t&&t.then?t.then(void 0,r):t}const ce="CowSwap";class ue{constructor(e){this.context=void 0,this.context=e}generateAppDataDoc(e={},r){const{appCode:t=ce,environment:n}=r||{};return{version:"0.4.0",appCode:t,environment:n,metadata:{...e}}}decodeAppData(r){try{return Promise.resolve(ae(function(){return Promise.resolve(ne(r)).then(function(e){if(!e)throw new m("Error getting serialized CID");return function(e,r="https://gnosis.mypinata.cloud/ipfs"){try{return Promise.resolve(import("cross-fetch")).then(function({default:t}){return Promise.resolve(t(`${r}/${e}`)).then(function(e){return Promise.resolve(e.json())})})}catch(e){return Promise.reject(e)}}(e)})},function(r){const t=r;throw e.error("Error decoding AppData:",t),new m("Error decoding AppData: "+t.message)}))}catch(e){return Promise.reject(e)}}cidToAppDataHex(e){try{return Promise.resolve(import("multiformats/cid")).then(function({CID:r}){const{digest:t}=r.parse(e).multihash;return`0x${Buffer.from(t).toString("hex")}`})}catch(e){return Promise.reject(e)}}appDataHexToCid(e){try{return Promise.resolve(ne(e)).then(function(e){if(!e)throw new m("Error getting serialized CID");return e})}catch(e){return Promise.reject(e)}}calculateAppDataHash(e){try{const r=this;return Promise.resolve(te(e)).then(function(t){if(null==t||!t.result)throw new m("Invalid appData provided",null==t?void 0:t.errors);return ae(function(){return Promise.resolve(function(e){try{const r=JSON.stringify(e);return Promise.resolve(import("ipfs-only-hash")).then(function({of:e}){return e(r,{cidVersion:0})})}catch(e){return Promise.reject(e)}}(e)).then(function(e){return Promise.resolve(r.cidToAppDataHex(e)).then(function(r){if(!r)throw new m(`Could not extract appDataHash from calculated cidV0 ${e}`);return{cidV0:e,appDataHash:r}})})},function(e){throw new m("Failed to calculate appDataHash",e.message)})})}catch(e){return Promise.reject(e)}}uploadMetadataDocToIpfs(e){try{const r=this;return Promise.resolve(function(e,{writeUri:r="https://api.pinata.cloud",pinataApiKey:t="",pinataApiSecret:n=""}){try{return Promise.resolve(import("cross-fetch")).then(function({default:o}){if(!t||!n)throw new m("You need to pass IPFS api credentials.");const i=JSON.stringify({pinataContent:e,pinataMetadata:{name:"appData"}});return Promise.resolve(o(`${r}/pinning/pinJSONToIPFS`,{method:"POST",body:i,headers:{"Content-Type":"application/json",pinata_api_key:t,pinata_secret_api_key:n}})).then(function(e){return Promise.resolve(e.json()).then(function(r){if(200!==e.status)throw new Error(r.error.details||r.error);return r})})})}catch(e){return Promise.reject(e)}}(e,r.context.ipfs)).then(function({IpfsHash:e}){return r.cidToAppDataHex(e)})}catch(e){return Promise.reject(e)}}}var de=0;function le(e){return"__private_"+de+++"_"+e}function he(e,r){if(!Object.prototype.hasOwnProperty.call(e,r))throw new TypeError("attempted to use private field on non-instance");return e}const me={appDataHash:"0x0000000000000000000000000000000000000000000000000000000000000000",isDevEnvironment:!1,ipfs:{readUri:"https://gnosis.mypinata.cloud/ipfs",writeUri:"https://api.pinata.cloud",apiKey:void 0,apiSecret:void 0}};var pe,fe,ve,Ee,Te,ge,Pe,ye,Ie,Ae,we,Ne,ke,De,Oe,_e,be,Se,Re,Ue=/*#__PURE__*/le("context"),xe=/*#__PURE__*/le("chainId");class Ce{updateContext(e,r){this.setParams(r,e)}constructor(e,r){Object.defineProperty(this,Ue,{writable:!0,value:{}}),Object.defineProperty(this,xe,{writable:!0,value:v.MAINNET}),this.setParams(e,r)}setParams(e,r){he(this,xe)[xe]=this.updateChainId(e),he(this,Ue)[Ue]={...me,...r,ipfs:{...me.ipfs,...r.ipfs}}}updateChainId(r){if(!v[r])throw new m(`Invalid chainId: ${r}`);return e.debug(f,`Updating chainId to: ${r}`),he(this,xe)[xe]=r,r}get chainId(){const r=this;var t;const n=null==(t=he(this,Ue)[Ue].signer)?void 0:t.provider;return n?(e.debug(f,"Getting chainId from provider"),function(){try{return Promise.resolve(n.getNetwork()).then(function(t){const n=t.chainId;return n!==he(r,xe)[xe]&&(e.debug(f,`ChainId mismatch: Provider's chainId: ${n} vs Context's chainId: ${he(r,xe)[xe]}. Updating Context's chainId`),r.updateChainId(n)),n})}catch(e){return Promise.reject(e)}}()):Promise.resolve(he(this,xe)[xe])}get appDataHash(){var e;return null!==(e=he(this,Ue)[Ue].appDataHash)&&void 0!==e?e:me.appDataHash}get isDevEnvironment(){var e;return null!==(e=he(this,Ue)[Ue].isDevEnvironment)&&void 0!==e?e:me.isDevEnvironment}get signer(){return he(this,Ue)[Ue].signer}get ipfs(){var e;return null!==(e=he(this,Ue)[Ue].ipfs)&&void 0!==e?e:me.ipfs}}class Le{constructor(r=v.MAINNET,t={},n={}){const o=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,r){try{return Promise.resolve(o.context.chainId).then(function(t){o.context.updateContext(e,r||t)})}catch(e){return Promise.reject(e)}},this.validateAppDataDocument=te,this.context=new Ce(r,{...t}),this.cowApi=new J(this.context),this.cowSubgraphApi=new re(this.context),this.metadataApi=new ue(this.context),e.setLevel(n.loglevel||"error")}signOrder(e){try{const r=this,t=r._checkSigner();return Promise.resolve(r.context.chainId).then(function(n){return function(e,r,t){return P({order:e,chainId:r},I,t)}({...e,appData:r.context.appDataHash},n,t)})}catch(e){return Promise.reject(e)}}signOrderCancellation(e){try{const r=this,t=r._checkSigner();return Promise.resolve(r.context.chainId).then(function(r){return function(e,r,t){return P({orderId:e,chainId:r},y,t)}(e,r,t)})}catch(e){return Promise.reject(e)}}_checkSigner(e=this.context.signer){if(!e)throw new m("No signer available");return e}}!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"}(fe||(fe={})),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"}(ve||(ve={})),function(e){e.Asc="asc",e.Desc="desc"}(Ee||(Ee={})),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"}(Te||(Te={})),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"}(Pe||(Pe={})),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"}(ye||(ye={})),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"}(Ae||(Ae={})),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"}(we||(we={})),function(e){e.AmountEth="amountEth",e.AmountUsd="amountUsd",e.Id="id",e.Timestamp="timestamp",e.Token="token",e.Trade="trade"}(Ne||(Ne={})),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"}(ke||(ke={})),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"}(De||(De={})),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"}(Oe||(Oe={})),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"}(_e||(_e={})),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"}(be||(be={})),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"}(Se||(Se={})),function(e){e.Allow="allow",e.Deny="deny"}(Re||(Re={}));var He={__proto__:null,get Bundle_OrderBy(){return pe},get DailyTotal_OrderBy(){return fe},get HourlyTotal_OrderBy(){return ve},get OrderDirection(){return Ee},get Order_OrderBy(){return Te},get PairDaily_OrderBy(){return ge},get PairHourly_OrderBy(){return Pe},get Pair_OrderBy(){return ye},get Settlement_OrderBy(){return Ie},get TokenDailyTotal_OrderBy(){return Ae},get TokenHourlyTotal_OrderBy(){return we},get TokenTradingEvent_OrderBy(){return Ne},get Token_OrderBy(){return ke},get Total_OrderBy(){return De},get Trade_OrderBy(){return Oe},get UniswapPool_OrderBy(){return _e},get UniswapToken_OrderBy(){return be},get User_OrderBy(){return Se},get _SubgraphErrorPolicy_(){return Re}};export{E as ALL_SUPPORTED_CHAIN_IDS,m as CowError,Le as CowSdk,He as GraphQL,v as SupportedChainId,F as Token};
28
+ `,ee={[v.MAINNET]:"https://api.thegraph.com/subgraphs/name/cowprotocol/cow",[v.RINKEBY]:"https://api.thegraph.com/subgraphs/name/cowprotocol/cow-rinkeby",[v.GOERLI]:"https://api.thegraph.com/subgraphs/name/cowprotocol/cow-goerli",[v.GNOSIS_CHAIN]:"https://api.thegraph.com/subgraphs/name/cowprotocol/cow-gc"};class re{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{[v.MAINNET]:new l(ee[v.MAINNET],{fetch:r}),[v.RINKEBY]:new l(ee[v.RINKEBY],{fetch:r}),[v.GOERLI]:new l(ee[v.GOERLI],{fetch:r}),[v.GNOSIS_CHAIN]:new l(ee[v.GNOSIS_CHAIN],{fetch:r})}}getBaseUrl(){try{return Promise.resolve(this.context.chainId).then(function(e){return ee[e]})}catch(e){return Promise.reject(e)}}getTotals(){try{const r=this;return Promise.resolve(r.context.chainId).then(function(t){return e.debug(`[subgraph:${r.API_NAME}] Get totals for:`,t),Promise.resolve(r.runQuery(Z)).then(function(e){return e.totals[0]})})}catch(e){return Promise.reject(e)}}getLastDaysVolume(r){try{const t=this;return Promise.resolve(t.context.chainId).then(function(n){return e.debug(`[subgraph:${t.API_NAME}] Get last ${r} days volume for:`,n),t.runQuery(z,{days:r})})}catch(e){return Promise.reject(e)}}getLastHoursVolume(r){try{const t=this;return Promise.resolve(t.context.chainId).then(function(n){return e.debug(`[subgraph:${t.API_NAME}] Get last ${r} hours volume for:`,n),t.runQuery(X,{hours:r})})}catch(e){return Promise.reject(e)}}runQuery(r,t){try{const n=this;return Promise.resolve(function(e,o){try{var i=Promise.resolve(n.context.chainId).then(function(e){return Promise.resolve(n.clients[e].request(r,t))})}catch(e){return o(e)}return i&&i.then?i.then(void 0,o):i}(0,function(o){return e.error(o),Promise.resolve(n.getBaseUrl()).then(function(e){throw new m(`Error running query: ${r}. Variables: ${JSON.stringify(t)}. API: ${e}. Inner Error: ${o}`)})}))}catch(e){return Promise.reject(e)}}}const te=function(e){return Promise.resolve(oe()).then(function({ajv:r,validate:t}){return{result:!!t(e),errors:r.errors?r.errorsText(r.errors):void 0}})},ne=function(e){try{const r=1,t=112,n=18,o=32,i=function(e){const r=e.match(/.{1,2}/g);if(r)return new Uint8Array(r.map(e=>parseInt(e,16)))}(e.replace(/(^0x)/,""));if(!i)return Promise.resolve();const s=Uint8Array.from([r,t,n,o,...i]);return Promise.resolve(import("multiformats/cid")).then(function({CID:e}){return e.decode(s).toV0().toString()})}catch(e){return Promise.reject(e)}},oe=function(){try{function e(){return{ajv:se,validate:ie}}se||(se=new h);const r=function(){if(!ie)return Promise.resolve(import("./appData.schema-b8f018d7.js")).then(function(e){ie=se.compile(e)})}();return Promise.resolve(r&&r.then?r.then(e):e())}catch(t){return Promise.reject(t)}};let ie,se;function ae(e,r){try{var t=e()}catch(e){return r(e)}return t&&t.then?t.then(void 0,r):t}const ce="CowSwap";class ue{constructor(e){this.context=void 0,this.context=e}generateAppDataDoc(e={},r){const{appCode:t=ce,environment:n}=r||{};return{version:"0.4.0",appCode:t,environment:n,metadata:{...e}}}decodeAppData(r){try{return Promise.resolve(ae(function(){return Promise.resolve(ne(r)).then(function(e){if(!e)throw new m("Error getting serialized CID");return function(e,r="https://gnosis.mypinata.cloud/ipfs"){try{return Promise.resolve(import("cross-fetch")).then(function({default:t}){return Promise.resolve(t(`${r}/${e}`)).then(function(e){return Promise.resolve(e.json())})})}catch(e){return Promise.reject(e)}}(e)})},function(r){const t=r;throw e.error("Error decoding AppData:",t),new m("Error decoding AppData: "+t.message)}))}catch(e){return Promise.reject(e)}}cidToAppDataHex(e){try{return Promise.resolve(import("multiformats/cid")).then(function({CID:r}){const{digest:t}=r.parse(e).multihash;return`0x${Buffer.from(t).toString("hex")}`})}catch(e){return Promise.reject(e)}}appDataHexToCid(e){try{return Promise.resolve(ne(e)).then(function(e){if(!e)throw new m("Error getting serialized CID");return e})}catch(e){return Promise.reject(e)}}calculateAppDataHash(e){try{const r=this;return Promise.resolve(te(e)).then(function(t){if(!t?.result)throw new m("Invalid appData provided",t?.errors);return ae(function(){return Promise.resolve(function(e){try{const r=JSON.stringify(e);return Promise.resolve(import("ipfs-only-hash")).then(function({of:e}){return e(r,{cidVersion:0})})}catch(e){return Promise.reject(e)}}(e)).then(function(e){return Promise.resolve(r.cidToAppDataHex(e)).then(function(r){if(!r)throw new m(`Could not extract appDataHash from calculated cidV0 ${e}`);return{cidV0:e,appDataHash:r}})})},function(e){throw new m("Failed to calculate appDataHash",e.message)})})}catch(e){return Promise.reject(e)}}uploadMetadataDocToIpfs(e){try{const r=this;return Promise.resolve(function(e,{writeUri:r="https://api.pinata.cloud",pinataApiKey:t="",pinataApiSecret:n=""}){try{return Promise.resolve(import("cross-fetch")).then(function({default:o}){if(!t||!n)throw new m("You need to pass IPFS api credentials.");const i=JSON.stringify({pinataContent:e,pinataMetadata:{name:"appData"}});return Promise.resolve(o(`${r}/pinning/pinJSONToIPFS`,{method:"POST",body:i,headers:{"Content-Type":"application/json",pinata_api_key:t,pinata_secret_api_key:n}})).then(function(e){return Promise.resolve(e.json()).then(function(r){if(200!==e.status)throw new Error(r.error.details||r.error);return r})})})}catch(e){return Promise.reject(e)}}(e,r.context.ipfs)).then(function({IpfsHash:e}){return r.cidToAppDataHex(e)})}catch(e){return Promise.reject(e)}}}var de=0;function le(e){return"__private_"+de+++"_"+e}function he(e,r){if(!Object.prototype.hasOwnProperty.call(e,r))throw new TypeError("attempted to use private field on non-instance");return e}const me={appDataHash:"0x0000000000000000000000000000000000000000000000000000000000000000",isDevEnvironment:!1,ipfs:{readUri:"https://gnosis.mypinata.cloud/ipfs",writeUri:"https://api.pinata.cloud",apiKey:void 0,apiSecret:void 0}};var pe,fe,ve,Ee,Te,ge,Pe,ye,Ie,Ae,we,Ne,ke,De,Oe,_e,be,Se,Re,Ue=/*#__PURE__*/le("context"),xe=/*#__PURE__*/le("chainId");class Ce{updateContext(e,r){this.setParams(r,e)}constructor(e,r){Object.defineProperty(this,Ue,{writable:!0,value:{}}),Object.defineProperty(this,xe,{writable:!0,value:v.MAINNET}),this.setParams(e,r)}setParams(e,r){he(this,xe)[xe]=this.updateChainId(e),he(this,Ue)[Ue]={...me,...r,ipfs:{...me.ipfs,...r.ipfs}}}updateChainId(r){if(!v[r])throw new m(`Invalid chainId: ${r}`);return e.debug(f,`Updating chainId to: ${r}`),he(this,xe)[xe]=r,r}get chainId(){const r=this,t=he(this,Ue)[Ue].signer?.provider;return t?(e.debug(f,"Getting chainId from provider"),function(){try{return Promise.resolve(t.getNetwork()).then(function(t){const n=t.chainId;return n!==he(r,xe)[xe]&&(e.debug(f,`ChainId mismatch: Provider's chainId: ${n} vs Context's chainId: ${he(r,xe)[xe]}. Updating Context's chainId`),r.updateChainId(n)),n})}catch(e){return Promise.reject(e)}}()):Promise.resolve(he(this,xe)[xe])}get appDataHash(){var e;return null!==(e=he(this,Ue)[Ue].appDataHash)&&void 0!==e?e:me.appDataHash}get isDevEnvironment(){var e;return null!==(e=he(this,Ue)[Ue].isDevEnvironment)&&void 0!==e?e:me.isDevEnvironment}get signer(){return he(this,Ue)[Ue].signer}get ipfs(){var e;return null!==(e=he(this,Ue)[Ue].ipfs)&&void 0!==e?e:me.ipfs}}class Le{constructor(r=v.MAINNET,t={},n={}){const o=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,r){try{return Promise.resolve(o.context.chainId).then(function(t){o.context.updateContext(e,r||t)})}catch(e){return Promise.reject(e)}},this.validateAppDataDocument=te,this.context=new Ce(r,{...t}),this.cowApi=new J(this.context),this.cowSubgraphApi=new re(this.context),this.metadataApi=new ue(this.context),e.setLevel(n.loglevel||"error")}signOrder(e){try{const r=this,t=r._checkSigner();return Promise.resolve(r.context.chainId).then(function(n){return function(e,r,t){return P({order:e,chainId:r},I,t)}({...e,appData:r.context.appDataHash},n,t)})}catch(e){return Promise.reject(e)}}signOrderCancellation(e){try{const r=this,t=r._checkSigner();return Promise.resolve(r.context.chainId).then(function(r){return function(e,r,t){return P({orderId:e,chainId:r},y,t)}(e,r,t)})}catch(e){return Promise.reject(e)}}_checkSigner(e=this.context.signer){if(!e)throw new m("No signer available");return e}}!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"}(fe||(fe={})),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"}(ve||(ve={})),function(e){e.Asc="asc",e.Desc="desc"}(Ee||(Ee={})),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"}(Te||(Te={})),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"}(Pe||(Pe={})),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"}(ye||(ye={})),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"}(Ae||(Ae={})),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"}(we||(we={})),function(e){e.AmountEth="amountEth",e.AmountUsd="amountUsd",e.Id="id",e.Timestamp="timestamp",e.Token="token",e.Trade="trade"}(Ne||(Ne={})),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"}(ke||(ke={})),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"}(De||(De={})),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"}(Oe||(Oe={})),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"}(_e||(_e={})),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"}(be||(be={})),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"}(Se||(Se={})),function(e){e.Allow="allow",e.Deny="deny"}(Re||(Re={}));var He={__proto__:null,get Bundle_OrderBy(){return pe},get DailyTotal_OrderBy(){return fe},get HourlyTotal_OrderBy(){return ve},get OrderDirection(){return Ee},get Order_OrderBy(){return Te},get PairDaily_OrderBy(){return ge},get PairHourly_OrderBy(){return Pe},get Pair_OrderBy(){return ye},get Settlement_OrderBy(){return Ie},get TokenDailyTotal_OrderBy(){return Ae},get TokenHourlyTotal_OrderBy(){return we},get TokenTradingEvent_OrderBy(){return Ne},get Token_OrderBy(){return ke},get Total_OrderBy(){return De},get Trade_OrderBy(){return Oe},get UniswapPool_OrderBy(){return _e},get UniswapToken_OrderBy(){return be},get User_OrderBy(){return Se},get _SubgraphErrorPolicy_(){return Re}};export{E as ALL_SUPPORTED_CHAIN_IDS,m as CowError,Le as CowSdk,He as GraphQL,v as SupportedChainId,F as Token};
29
29
  //# sourceMappingURL=index.module.js.map