@cowprotocol/cow-sdk 0.0.13 → 0.0.14

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.
@@ -1,4 +1,4 @@
1
- import e from"loglevel";import t from"cross-fetch";import{IntChainIdTypedDataV4Signer as r,TypedDataV3Signer as o,SigningScheme as n,domain as i,signOrder as a,signOrderCancellation as s,OrderKind as c}from"@gnosis.pm/gp-v2-contracts";export{OrderKind}from"@gnosis.pm/gp-v2-contracts";import d from"@gnosis.pm/gp-v2-contracts/networks.json";import{gql as u,GraphQLClient as l}from"graphql-request";import h from"ajv";function p(){return p=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var o in r)Object.prototype.hasOwnProperty.call(r,o)&&(e[o]=r[o])}return e},p.apply(this,arguments)}var m=0;function f(e){return"__private_"+m+++"_"+e}function g(e,t){if(!Object.prototype.hasOwnProperty.call(e,t))throw new TypeError("attempted to use private field on non-instance");return e}class T extends Error{constructor(e,t){super(e),this.error_code=void 0,this.error_code=t}}function E(e){if(!e)return"";const t=new URLSearchParams;for(const r of Object.keys(e)){const o=e[r];o&&t.append(r,o.toString())}const r=t.toString();return r?`?${r}`:""}const y="cow-sdk:";var w;!function(e){e[e.MAINNET=1]="MAINNET",e[e.RINKEBY=4]="RINKEBY",e[e.GNOSIS_CHAIN=100]="GNOSIS_CHAIN"}(w||(w={}));const A=[w.MAINNET,w.RINKEBY,w.GNOSIS_CHAIN],{GPv2Settlement:I}=d,N={[w.MAINNET]:I[w.MAINNET].address,[w.RINKEBY]:I[w.RINKEBY].address,[w.GNOSIS_CHAIN]:I[w.GNOSIS_CHAIN].address},v=/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([[n.EIP712,{libraryValue:0,apiValue:"eip712"}],[n.ETHSIGN,{libraryValue:1,apiValue:"ethsign"}],[n.EIP1271,{libraryValue:2,apiValue:"eip1271"}],[n.PRESIGN,{libraryValue:3,apiValue:"presign"}]]);function P(e){const t=_.get(e);if(void 0===t)throw new T("Unknown schema "+e);return t}function S(e){return P(e).apiValue}function U(e){return P(e).libraryValue}function b(e){const t=N[e];if(!t)throw new T("Unsupported network. Settlement contract is not deployed");return i(e,t)}async function R(e){const{chainId:t,signer:r,order:o,signingScheme:n}=e,i=b(t);return a(i,o,r,U(n))}async function x(e){const{chainId:t,signer:r,signingScheme:o,orderId:n}=e,i=b(t);return s(i,n,r,U(o))}async function C(t,i,a,s="v4"){var c;const d="eth_sign"===s?n.ETHSIGN:n.EIP712;let u,l=null;try{switch(s){case"v3":u=new o(a);break;case"int_v4":u=new r(a);break;default:u=a}}catch(t){throw e.error(y,"Wallet not supported:",t),new T("Wallet not supported")}try{l=await i(p({},t,{signer:u,signingScheme:d}))}catch(r){if(void 0===(h=r).code&&void 0===h.message)throw e.error(y,r),r;if(-32601===r.code||D.test(r.message))switch(s){case"v4":return C(t,i,a,"v3");case"v3":return C(t,i,a,"eth_sign");default:throw r}else{if(O.test(r.message))return C(t,i,a,"int_v4");if(-32603===r.code)return C(t,i,a,"eth_sign");if(v.test(r.message))return C(t,i,a,"v3");if(k.test(r.message))return C(t,i,a,"eth_sign")}}var h;return{signature:null==(c=l)?void 0:c.data.toString(),signingScheme:d}}var H,L,V,F;!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"}(H||(H={})),function(e){e.DuplicateOrder="There was another identical order already submitted. Please try again.",e.InsufficientFee="The signed fee is insufficient. It's possible that is higher now due to a change in the gas price, ether price, or the sell token price. Please try again to get an updated fee quote.",e.InvalidSignature="The order signature is invalid. Check whether your Wallet app supports off-chain signing.",e.MissingOrderData="The order has missing information",e.InsufficientValidTo="The order you are signing is already expired. This can happen if you set a short expiration in the settings and waited too long before signing the transaction. Please try again.",e.InsufficientAllowance="The account doesn't have enough funds",e.InsufficientBalance="The account needs to approve the selling token in order to trade",e.WrongOwner="The signature is invalid.\n\nIt's likely that the signing method provided by your wallet doesn't comply with the standards required by CowSwap.\n\nCheck whether your Wallet app supports off-chain signing (EIP-712 or ETHSIGN).",e.NotFound="Token pair selected has insufficient liquidity",e.OrderNotFound="The order you are trying to cancel does not exist",e.AlreadyCancelled="Order is already cancelled",e.OrderFullyExecuted="Order is already filled",e.OrderExpired="Order is expired",e.NoLiquidity="Token pair selected has insufficient liquidity",e.UnsupportedToken="One of the tokens you are trading is unsupported. Please read the FAQ for more info.",e.AmountIsZero="Amount is zero",e.SellAmountDoesNotCoverFee="Sell amount does not sufficiently cover the current fee",e.TransferEthToContract="Sending the native currency to smart contract wallets is not currently supported",e.UNHANDLED_GET_ERROR="Order fetch failed. This may be due to a server or network connectivity issue. Please try again later.",e.UNHANDLED_CREATE_ERROR="The order was not accepted by the network",e.UNHANDLED_DELETE_ERROR="The order cancellation was not accepted by the network"}(L||(L={}));class B extends T{static async getErrorMessage(t,r){try{const r=await t.json();return r.errorType?B.apiErrorDetails[r.errorType]||r.errorType:(e.error(y,"Unknown reason for bad order submission",r),r.description)}catch(t){return e.error(y,"Error handling a 400 error. Likely a problem deserialising the JSON response"),function(t){switch(t){case"get":return L.UNHANDLED_GET_ERROR;case"create":return L.UNHANDLED_CREATE_ERROR;case"delete":return L.UNHANDLED_DELETE_ERROR;default:return e.error(y,"[OperatorError::_mapActionToErrorDetails] Uncaught error mapping error action type to server error. Please try again later."),"Something failed. Please try again later."}}(r)}}static async getErrorFromStatusCode(t,r){switch(t.status){case 400:case 404:return this.getErrorMessage(t,r);case 403:return`The order cannot be ${"create"===r?"accepted":"cancelled"}. Your account is deny-listed.`;case 429:return`The order cannot be ${"create"===r?"accepted. Too many order placements":"cancelled. Too many order cancellations"}. Please, retry in a minute`;default:return e.error(y,`[OperatorError::getErrorFromStatusCode] Error ${"create"===r?"creating":"cancelling"} the order, status code:`,t.status||"unknown"),`Error ${"create"===r?"creating":"cancelling"} the order`}}constructor(e){super(e.description,e.errorType),this.name="OperatorError",this.description=void 0,this.description=e.description,this.message=L[e.errorType]}}B.apiErrorDetails=L,function(e){e.UnsupportedToken="UnsupportedToken",e.InsufficientLiquidity="InsufficientLiquidity",e.FeeExceedsFrom="FeeExceedsFrom",e.ZeroPrice="ZeroPrice",e.UNHANDLED_ERROR="UNHANDLED_ERROR"}(V||(V={})),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."}(F||(F={}));class $ extends T{static async getErrorMessage(t){try{const r=await t.json();return r.errorType?$.quoteErrorDetails[r.errorType]||r.errorType:(e.error(y,"Unknown reason for bad quote fetch",r),r.description)}catch(t){return e.error(y,"Error handling 400/404 error. Likely a problem deserialising the JSON response"),$.quoteErrorDetails.UNHANDLED_ERROR}}static async getErrorFromStatusCode(t){switch(t.status){case 400:case 404:return this.getErrorMessage(t);default:return e.error(y,"[QuoteError::getErrorFromStatusCode] Error fetching quote, status code:",t.status||"unknown"),"Error fetching quote"}}constructor(e){super(e.description,e.errorType),this.name="QuoteErrorObject",this.description=void 0,this.data=void 0,this.description=e.description,this.message=$.quoteErrorDetails[e.errorType],this.data=null==e?void 0:e.data}}$.quoteErrorDetails=F;class M{constructor(e,t){this.symbol=void 0,this.address=void 0,this.symbol=e,this.address=t}}const q={[w.MAINNET]:new M("WETH","0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2"),[w.RINKEBY]:new M("WETH","0xc778417E063141139Fce010982780140Aa0cD5Ab"),[w.GNOSIS_CHAIN]:new M("WXDAI","0xe91D153E0b41518A2Ce8Dd3D7944Fa863463a97d")},G={[w.MAINNET]:"ETH",[w.RINKEBY]:"ETH",[w.GNOSIS_CHAIN]:"XDAI"};function j(e,t){let r=e;return e===G[t]&&(r=q[t].address),r}const K={errorType:V.UNHANDLED_ERROR,description:F.UNHANDLED_ERROR},Y={errorType:H.UNHANDLED_CREATE_ERROR,description:L.UNHANDLED_CREATE_ERROR};async function Q(t,r){if(t.ok)return t.json();{const o=function(e){switch(null==e?void 0:e.errorType){case H.NotFound:case H.NoLiquidity:return{errorType:V.InsufficientLiquidity,description:F.InsufficientLiquidity};case H.SellAmountDoesNotCoverFee:return{errorType:V.FeeExceedsFrom,description:F.FeeExceedsFrom,data:null==e?void 0:e.data};case H.UnsupportedToken:return{errorType:V.UnsupportedToken,description:e.description};case H.SellAmountDoesNotCoverFee:return{errorType:V.FeeExceedsFrom,description:e.description};default:return{errorType:V.UNHANDLED_ERROR,description:F.UNHANDLED_ERROR}}}(await t.json()),n=new $(o);if(r){const{sellToken:t,buyToken:o}=r;e.error(y,`Error querying fee from API - sellToken: ${t}, buyToken: ${o}`)}throw n}}class W{constructor(e){this.context=void 0,this.API_NAME="CoW Protocol",this.context=e}get DEFAULT_HEADERS(){return{"Content-Type":"application/json","X-AppId":this.context.appDataHash}}get API_BASE_URL(){return this.context.isDevEnvironment?{[w.MAINNET]:"https://barn.api.cow.fi/mainnet/api",[w.RINKEBY]:"https://barn.api.cow.fi/rinkeby/api",[w.GNOSIS_CHAIN]:"https://barn.api.cow.fi/xdai/api"}:{[w.MAINNET]:"https://api.cow.fi/mainnet/api",[w.RINKEBY]:"https://api.cow.fi/rinkeby/api",[w.GNOSIS_CHAIN]:"https://api.cow.fi/xdai/api"}}get PROFILE_API_BASE_URL(){return this.context.isDevEnvironment?{[w.MAINNET]:"https://barn.api.cow.fi/affiliate/api"}:{[w.MAINNET]:"https://api.cow.fi/affiliate/api"}}async getProfileData(t){const r=await this.context.chainId;if(e.debug(y,`[api:${this.API_NAME}] Get profile data for`,r,t),r!==w.MAINNET)return e.info(y,"Profile data is only available for mainnet"),null;const o=await this.getProfile(`/profile/${t}`);if(o.ok)return o.json();{const t=await o.json();throw e.error(y,t),new T(null==t?void 0:t.description)}}async getTrades(t){const{owner:r,limit:o,offset:n}=t,i=E({owner:r,limit:o,offset:n}),a=await this.context.chainId;e.debug(y,"[util:operator] Get trades for",a,r,{limit:o,offset:n});try{const e=await this.get(`/trades${i}`);if(e.ok)return e.json();{const t=await e.json();throw new B(t)}}catch(t){if(e.error(y,"Error getting trades:",t),t instanceof B)throw t;throw new T("Error getting trades: "+t)}}async getOrders(t){const{owner:r,limit:o=1e3,offset:n=0}=t,i=E({limit:o,offset:n}),a=await this.context.chainId;e.debug(y,`[api:${this.API_NAME}] Get orders for `,a,r,o,n);try{const e=await this.get(`/account/${r}/orders/${i}`);if(e.ok)return e.json();{const t=await e.json();throw new B(t)}}catch(t){if(e.error(y,"Error getting orders information:",t),t instanceof B)throw t;throw new B(Y)}}async getTxOrders(t){const r=await this.context.chainId;e.debug(`[api:${this.API_NAME}] Get tx orders for `,r,t);try{const e=await this.get(`/transactions/${t}/orders`);if(e.ok)return e.json();{const t=await e.json();throw new B(t)}}catch(t){if(e.error("Error getting transaction orders information:",t),t instanceof B)throw t;throw new B(Y)}}async getOrder(t){const r=await this.context.chainId;e.debug(y,`[api:${this.API_NAME}] Get order for `,r,t);try{const e=await this.get(`/orders/${t}`);if(e.ok)return e.json();{const t=await e.json();throw new B(t)}}catch(t){if(e.error(y,"Error getting order information:",t),t instanceof B)throw t;throw new B(Y)}}async getPriceQuoteLegacy(t){const{baseToken:r,quoteToken:o,amount:n,kind:i}=t,a=await this.context.chainId;return e.debug(y,`[api:${this.API_NAME}] Get price from API`,t,"for",a),Q(await this.get(`/markets/${j(r,a)}-${j(o,a)}/${i}/${n}`).catch(t=>{throw e.error(y,"Error getting price quote:",t),new $(K)}))}async getQuote(e){const t=await this.context.chainId,r=this.mapNewToLegacyParams(e,t);return Q(await this.post("/quote",r))}async sendSignedOrderCancellation(t){const{cancellation:r,owner:o}=t,n=await this.context.chainId;e.debug(y,`[api:${this.API_NAME}] Delete signed order for network`,n,r);const i=await this.delete(`/orders/${r.orderUid}`,{signature:r.signature,signingScheme:S(r.signingScheme),from:o});if(!i.ok){const e=await B.getErrorFromStatusCode(i,"delete");throw new T(e)}e.debug(y,`[api:${this.API_NAME}] Cancelled order`,r.orderUid,n)}async sendOrder(t){const r=p({},t.order,{appData:this.context.appDataHash}),o=await this.context.chainId,{owner:n}=t;e.debug(y,`[api:${this.API_NAME}] Post signed order for network`,o,r);const i=await this.post("/orders",p({},r,{signingScheme:S(r.signingScheme),from:n}));if(!i.ok){const e=await B.getErrorFromStatusCode(i,"create");throw new T(e)}const a=await i.json();return e.debug(y,`[api:${this.API_NAME}] Success posting the signed order`,a),a}getOrderLink(e){return this.getApiBaseUrl()+`/orders/${e}`}mapNewToLegacyParams(e,t){const{amount:r,kind:o,userAddress:n,receiver:i,validTo:a,sellToken:s,buyToken:d}=e,u=n||"0x0000000000000000000000000000000000000000",l={sellToken:j(s,t),buyToken:j(d,t),from:u,receiver:i||u,appData:this.context.appDataHash,validTo:a,partiallyFillable:!1};return p(o===c.SELL?{kind:c.SELL,sellAmountBeforeFee:r}:{kind:c.BUY,buyAmountAfterFee:r},l)}async getApiBaseUrl(){const e=await this.context.chainId,t=this.API_BASE_URL[e];if(t)return t+"/v1";throw new T(`Unsupported Network. The ${this.API_NAME} API is not deployed in the Network `+e)}async getProfileApiBaseUrl(){const e=await this.context.chainId,t=this.PROFILE_API_BASE_URL[e];if(t)return t+"/v1";throw new T(`Unsupported Network. The ${this.API_NAME} API is not deployed in the Network `+e)}async fetch(e,r,o){const n=await this.getApiBaseUrl();return t(n+e,{headers:this.DEFAULT_HEADERS,method:r,body:void 0!==o?JSON.stringify(o):o})}async fetchProfile(e,r,o){const n=await this.getProfileApiBaseUrl();return t(n+e,{headers:this.DEFAULT_HEADERS,method:r,body:void 0!==o?JSON.stringify(o):o})}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)}}let J,Z,z,X=e=>e;const ee=u(J||(J=X`
1
+ import e from"loglevel";import t from"cross-fetch";import{IntChainIdTypedDataV4Signer as r,TypedDataV3Signer as o,SigningScheme as n,domain as i,signOrder as a,signOrderCancellation as s,OrderKind as c}from"@cowprotocol/contracts";export{OrderKind}from"@cowprotocol/contracts";import d from"@cowprotocol/contracts/networks.json";import{gql as u,GraphQLClient as l}from"graphql-request";import h from"ajv";function p(){return p=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var o in r)Object.prototype.hasOwnProperty.call(r,o)&&(e[o]=r[o])}return e},p.apply(this,arguments)}var m=0;function f(e){return"__private_"+m+++"_"+e}function T(e,t){if(!Object.prototype.hasOwnProperty.call(e,t))throw new TypeError("attempted to use private field on non-instance");return e}class g extends Error{constructor(e,t){super(e),this.error_code=void 0,this.error_code=t}}function E(e){if(!e)return"";const t=new URLSearchParams;for(const r of Object.keys(e)){const o=e[r];o&&t.append(r,o.toString())}const r=t.toString();return r?`?${r}`:""}const y="cow-sdk:";var w;!function(e){e[e.MAINNET=1]="MAINNET",e[e.RINKEBY=4]="RINKEBY",e[e.GNOSIS_CHAIN=100]="GNOSIS_CHAIN"}(w||(w={}));const A=[w.MAINNET,w.RINKEBY,w.GNOSIS_CHAIN],{GPv2Settlement:I}=d,v={[w.MAINNET]:I[w.MAINNET].address,[w.RINKEBY]:I[w.RINKEBY].address,[w.GNOSIS_CHAIN]:I[w.GNOSIS_CHAIN].address},N=/eth_signTypedData_v4 does not exist/i,k=/eth_signTypedData_v3 does not exist/i,P=/RPC request failed/i,D=/provided chainid .* must match the active chainid/i,O=new Map([[n.EIP712,{libraryValue:0,apiValue:"eip712"}],[n.ETHSIGN,{libraryValue:1,apiValue:"ethsign"}],[n.EIP1271,{libraryValue:2,apiValue:"eip1271"}],[n.PRESIGN,{libraryValue:3,apiValue:"presign"}]]);function _(e){const t=O.get(e);if(void 0===t)throw new g("Unknown schema "+e);return t}function S(e){return _(e).apiValue}function U(e){return _(e).libraryValue}function b(e){const t=v[e];if(!t)throw new g("Unsupported network. Settlement contract is not deployed");return i(e,t)}async function R(e){const{chainId:t,signer:r,order:o,signingScheme:n}=e,i=b(t);return a(i,o,r,U(n))}async function x(e){const{chainId:t,signer:r,signingScheme:o,orderId:n}=e,i=b(t);return s(i,n,r,U(o))}async function C(t,i,a,s="v4"){var c;const d="eth_sign"===s?n.ETHSIGN:n.EIP712;let u,l=null;try{switch(s){case"v3":u=new o(a);break;case"int_v4":u=new r(a);break;default:u=a}}catch(t){throw e.error(y,"Wallet not supported:",t),new g("Wallet not supported")}try{l=await i(p({},t,{signer:u,signingScheme:d}))}catch(r){if(void 0===(h=r).code&&void 0===h.message)throw e.error(y,r),r;if(-32601===r.code||P.test(r.message))switch(s){case"v4":return C(t,i,a,"v3");case"v3":return C(t,i,a,"eth_sign");default:throw r}else{if(D.test(r.message))return C(t,i,a,"int_v4");if(-32603===r.code)return C(t,i,a,"eth_sign");if(N.test(r.message))return C(t,i,a,"v3");if(k.test(r.message))return C(t,i,a,"eth_sign")}}var h;return{signature:null==(c=l)?void 0:c.data.toString(),signingScheme:d}}var H,L,V,F;!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"}(H||(H={})),function(e){e.DuplicateOrder="There was another identical order already submitted. Please try again.",e.InsufficientFee="The signed fee is insufficient. It's possible that is higher now due to a change in the gas price, ether price, or the sell token price. Please try again to get an updated fee quote.",e.InvalidSignature="The order signature is invalid. Check whether your Wallet app supports off-chain signing.",e.MissingOrderData="The order has missing information",e.InsufficientValidTo="The order you are signing is already expired. This can happen if you set a short expiration in the settings and waited too long before signing the transaction. Please try again.",e.InsufficientAllowance="The account doesn't have enough funds",e.InsufficientBalance="The account needs to approve the selling token in order to trade",e.WrongOwner="The signature is invalid.\n\nIt's likely that the signing method provided by your wallet doesn't comply with the standards required by CowSwap.\n\nCheck whether your Wallet app supports off-chain signing (EIP-712 or ETHSIGN).",e.NotFound="Token pair selected has insufficient liquidity",e.OrderNotFound="The order you are trying to cancel does not exist",e.AlreadyCancelled="Order is already cancelled",e.OrderFullyExecuted="Order is already filled",e.OrderExpired="Order is expired",e.NoLiquidity="Token pair selected has insufficient liquidity",e.UnsupportedToken="One of the tokens you are trading is unsupported. Please read the FAQ for more info.",e.AmountIsZero="Amount is zero",e.SellAmountDoesNotCoverFee="Sell amount does not sufficiently cover the current fee",e.TransferEthToContract="Sending the native currency to smart contract wallets is not currently supported",e.UNHANDLED_GET_ERROR="Order fetch failed. This may be due to a server or network connectivity issue. Please try again later.",e.UNHANDLED_CREATE_ERROR="The order was not accepted by the network",e.UNHANDLED_DELETE_ERROR="The order cancellation was not accepted by the network"}(L||(L={}));class B extends g{static async getErrorMessage(t,r){try{const r=await t.json();return r.errorType?B.apiErrorDetails[r.errorType]||r.errorType:(e.error(y,"Unknown reason for bad order submission",r),r.description)}catch(t){return e.error(y,"Error handling a 400 error. Likely a problem deserialising the JSON response"),function(t){switch(t){case"get":return L.UNHANDLED_GET_ERROR;case"create":return L.UNHANDLED_CREATE_ERROR;case"delete":return L.UNHANDLED_DELETE_ERROR;default:return e.error(y,"[OperatorError::_mapActionToErrorDetails] Uncaught error mapping error action type to server error. Please try again later."),"Something failed. Please try again later."}}(r)}}static async getErrorFromStatusCode(t,r){switch(t.status){case 400:case 404:return this.getErrorMessage(t,r);case 403:return`The order cannot be ${"create"===r?"accepted":"cancelled"}. Your account is deny-listed.`;case 429:return`The order cannot be ${"create"===r?"accepted. Too many order placements":"cancelled. Too many order cancellations"}. Please, retry in a minute`;default:return e.error(y,`[OperatorError::getErrorFromStatusCode] Error ${"create"===r?"creating":"cancelling"} the order, status code:`,t.status||"unknown"),`Error ${"create"===r?"creating":"cancelling"} the order`}}constructor(e){super(e.description,e.errorType),this.name="OperatorError",this.description=void 0,this.description=e.description,this.message=L[e.errorType]}}B.apiErrorDetails=L,function(e){e.UnsupportedToken="UnsupportedToken",e.InsufficientLiquidity="InsufficientLiquidity",e.FeeExceedsFrom="FeeExceedsFrom",e.ZeroPrice="ZeroPrice",e.UNHANDLED_ERROR="UNHANDLED_ERROR"}(V||(V={})),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."}(F||(F={}));class $ extends g{static async getErrorMessage(t){try{const r=await t.json();return r.errorType?$.quoteErrorDetails[r.errorType]||r.errorType:(e.error(y,"Unknown reason for bad quote fetch",r),r.description)}catch(t){return e.error(y,"Error handling 400/404 error. Likely a problem deserialising the JSON response"),$.quoteErrorDetails.UNHANDLED_ERROR}}static async getErrorFromStatusCode(t){switch(t.status){case 400:case 404:return this.getErrorMessage(t);default:return e.error(y,"[QuoteError::getErrorFromStatusCode] Error fetching quote, status code:",t.status||"unknown"),"Error fetching quote"}}constructor(e){super(e.description,e.errorType),this.name="QuoteErrorObject",this.description=void 0,this.data=void 0,this.description=e.description,this.message=$.quoteErrorDetails[e.errorType],this.data=null==e?void 0:e.data}}$.quoteErrorDetails=F;class M{constructor(e,t){this.symbol=void 0,this.address=void 0,this.symbol=e,this.address=t}}const q={[w.MAINNET]:new M("WETH","0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2"),[w.RINKEBY]:new M("WETH","0xc778417E063141139Fce010982780140Aa0cD5Ab"),[w.GNOSIS_CHAIN]:new M("WXDAI","0xe91D153E0b41518A2Ce8Dd3D7944Fa863463a97d")},G={[w.MAINNET]:"ETH",[w.RINKEBY]:"ETH",[w.GNOSIS_CHAIN]:"XDAI"};function j(e,t){let r=e;return e===G[t]&&(r=q[t].address),r}const K={errorType:V.UNHANDLED_ERROR,description:F.UNHANDLED_ERROR},Y={errorType:H.UNHANDLED_CREATE_ERROR,description:L.UNHANDLED_CREATE_ERROR};async function Q(t,r){if(t.ok)return t.json();{const o=function(e){switch(null==e?void 0:e.errorType){case H.NotFound:case H.NoLiquidity:return{errorType:V.InsufficientLiquidity,description:F.InsufficientLiquidity};case H.SellAmountDoesNotCoverFee:return{errorType:V.FeeExceedsFrom,description:F.FeeExceedsFrom,data:null==e?void 0:e.data};case H.UnsupportedToken:return{errorType:V.UnsupportedToken,description:e.description};case H.SellAmountDoesNotCoverFee:return{errorType:V.FeeExceedsFrom,description:e.description};default:return{errorType:V.UNHANDLED_ERROR,description:F.UNHANDLED_ERROR}}}(await t.json()),n=new $(o);if(r){const{sellToken:t,buyToken:o}=r;e.error(y,`Error querying fee from API - sellToken: ${t}, buyToken: ${o}`)}throw n}}class W{constructor(e){this.context=void 0,this.API_NAME="CoW Protocol",this.context=e}get DEFAULT_HEADERS(){return{"Content-Type":"application/json","X-AppId":this.context.appDataHash}}get API_BASE_URL(){return this.context.isDevEnvironment?{[w.MAINNET]:"https://barn.api.cow.fi/mainnet/api",[w.RINKEBY]:"https://barn.api.cow.fi/rinkeby/api",[w.GNOSIS_CHAIN]:"https://barn.api.cow.fi/xdai/api"}:{[w.MAINNET]:"https://api.cow.fi/mainnet/api",[w.RINKEBY]:"https://api.cow.fi/rinkeby/api",[w.GNOSIS_CHAIN]:"https://api.cow.fi/xdai/api"}}get PROFILE_API_BASE_URL(){return this.context.isDevEnvironment?{[w.MAINNET]:"https://barn.api.cow.fi/affiliate/api"}:{[w.MAINNET]:"https://api.cow.fi/affiliate/api"}}async getProfileData(t){const r=await this.context.chainId;if(e.debug(y,`[api:${this.API_NAME}] Get profile data for`,r,t),r!==w.MAINNET)return e.info(y,"Profile data is only available for mainnet"),null;const o=await this.getProfile(`/profile/${t}`);if(o.ok)return o.json();{const t=await o.json();throw e.error(y,t),new g(null==t?void 0:t.description)}}async getTrades(t){const{owner:r,orderId:o,limit:n,offset:i}=t;if(r&&o)throw new g("Cannot specify both owner and orderId");const a=E({owner:r,orderUid:o,limit:n,offset:i}),s=await this.context.chainId;e.debug(y,"[util:operator] Get trades for",s,{owner:r,orderId:o,limit:n,offset:i});try{const e=await this.get(`/trades${a}`);if(e.ok)return e.json();{const t=await e.json();throw new B(t)}}catch(t){if(e.error(y,"Error getting trades:",t),t instanceof B)throw t;throw new g("Error getting trades: "+t)}}async getOrders(t){const{owner:r,limit:o=1e3,offset:n=0}=t,i=E({limit:o,offset:n}),a=await this.context.chainId;e.debug(y,`[api:${this.API_NAME}] Get orders for `,a,r,o,n);try{const e=await this.get(`/account/${r}/orders/${i}`);if(e.ok)return e.json();{const t=await e.json();throw new B(t)}}catch(t){if(e.error(y,"Error getting orders information:",t),t instanceof B)throw t;throw new B(Y)}}async getTxOrders(t){const r=await this.context.chainId;e.debug(`[api:${this.API_NAME}] Get tx orders for `,r,t);try{const e=await this.get(`/transactions/${t}/orders`);if(e.ok)return e.json();{const t=await e.json();throw new B(t)}}catch(t){if(e.error("Error getting transaction orders information:",t),t instanceof B)throw t;throw new B(Y)}}async getOrder(t){const r=await this.context.chainId;e.debug(y,`[api:${this.API_NAME}] Get order for `,r,t);try{const e=await this.get(`/orders/${t}`);if(e.ok)return e.json();{const t=await e.json();throw new B(t)}}catch(t){if(e.error(y,"Error getting order information:",t),t instanceof B)throw t;throw new B(Y)}}async getPriceQuoteLegacy(t){const{baseToken:r,quoteToken:o,amount:n,kind:i}=t,a=await this.context.chainId;return e.debug(y,`[api:${this.API_NAME}] Get price from API`,t,"for",a),Q(await this.get(`/markets/${j(r,a)}-${j(o,a)}/${i}/${n}`).catch(t=>{throw e.error(y,"Error getting price quote:",t),new $(K)}))}async getQuote(e){const t=await this.context.chainId,r=this.mapNewToLegacyParams(e,t);return Q(await this.post("/quote",r))}async sendSignedOrderCancellation(t){const{cancellation:r,owner:o}=t,n=await this.context.chainId;e.debug(y,`[api:${this.API_NAME}] Delete signed order for network`,n,r);const i=await this.delete(`/orders/${r.orderUid}`,{signature:r.signature,signingScheme:S(r.signingScheme),from:o});if(!i.ok){const e=await B.getErrorFromStatusCode(i,"delete");throw new g(e)}e.debug(y,`[api:${this.API_NAME}] Cancelled order`,r.orderUid,n)}async sendOrder(t){const r=p({},t.order,{appData:this.context.appDataHash}),o=await this.context.chainId,{owner:n}=t;e.debug(y,`[api:${this.API_NAME}] Post signed order for network`,o,r);const i=await this.post("/orders",p({},r,{signingScheme:S(r.signingScheme),from:n}));if(!i.ok){const e=await B.getErrorFromStatusCode(i,"create");throw new g(e)}const a=await i.json();return e.debug(y,`[api:${this.API_NAME}] Success posting the signed order`,a),a}getOrderLink(e){return this.getApiBaseUrl()+`/orders/${e}`}mapNewToLegacyParams(e,t){const{amount:r,kind:o,userAddress:n,receiver:i,validTo:a,sellToken:s,buyToken:d}=e,u=n||"0x0000000000000000000000000000000000000000",l={sellToken:j(s,t),buyToken:j(d,t),from:u,receiver:i||u,appData:this.context.appDataHash,validTo:a,partiallyFillable:!1};return p(o===c.SELL?{kind:c.SELL,sellAmountBeforeFee:r}:{kind:c.BUY,buyAmountAfterFee:r},l)}async getApiBaseUrl(){const e=await this.context.chainId,t=this.API_BASE_URL[e];if(t)return t+"/v1";throw new g(`Unsupported Network. The ${this.API_NAME} API is not deployed in the Network `+e)}async getProfileApiBaseUrl(){const e=await this.context.chainId,t=this.PROFILE_API_BASE_URL[e];if(t)return t+"/v1";throw new g(`Unsupported Network. The ${this.API_NAME} API is not deployed in the Network `+e)}async fetch(e,r,o){const n=await this.getApiBaseUrl();return t(n+e,{headers:this.DEFAULT_HEADERS,method:r,body:void 0!==o?JSON.stringify(o):o})}async fetchProfile(e,r,o){const n=await this.getProfileApiBaseUrl();return t(n+e,{headers:this.DEFAULT_HEADERS,method:r,body:void 0!==o?JSON.stringify(o):o})}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)}}let J,Z,z,X=e=>e;const ee=u(J||(J=X`
2
2
  query Totals {
3
3
  totals {
4
4
  tokens
@@ -25,5 +25,5 @@ import e from"loglevel";import t from"cross-fetch";import{IntChainIdTypedDataV4S
25
25
  volumeUsd
26
26
  }
27
27
  }
28
- `)),oe={[w.MAINNET]:"https://api.thegraph.com/subgraphs/name/cowprotocol/cow",[w.RINKEBY]:"https://api.thegraph.com/subgraphs/name/cowprotocol/cow-rinkeby",[w.GNOSIS_CHAIN]:"https://api.thegraph.com/subgraphs/name/cowprotocol/cow-gc"};class ne{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{[w.MAINNET]:new l(oe[w.MAINNET],{fetch:t}),[w.RINKEBY]:new l(oe[w.RINKEBY],{fetch:t}),[w.GNOSIS_CHAIN]:new l(oe[w.GNOSIS_CHAIN],{fetch:t})}}async getBaseUrl(){const e=await this.context.chainId;return oe[e]}async getTotals(){const t=await this.context.chainId;return e.debug(`[subgraph:${this.API_NAME}] Get totals for:`,t),(await this.runQuery(ee)).totals[0]}async getLastDaysVolume(t){const r=await this.context.chainId;return e.debug(`[subgraph:${this.API_NAME}] Get last ${t} days volume for:`,r),this.runQuery(te,{days:t})}async getLastHoursVolume(t){const r=await this.context.chainId;return e.debug(`[subgraph:${this.API_NAME}] Get last ${t} hours volume for:`,r),this.runQuery(re,{hours:t})}async runQuery(t,r){try{const e=await this.context.chainId,o=this.clients[e];return await o.request(t,r)}catch(o){e.error(o);const n=await this.getBaseUrl();throw new T(`Error running query: ${t}. Variables: ${JSON.stringify(r)}. API: ${n}. Inner Error: ${o}`)}}}let ie,ae;async function se(){if(ae||(ae=new h),!ie){const e=await import("./appData.schema-adfc1c6f.js");ie=ae.compile(e)}return{ajv:ae,validate:ie}}async function ce(e){const t=function(e){const t=e.match(/.{1,2}/g);if(t)return new Uint8Array(t.map(e=>parseInt(e,16)))}(e.replace(/(^0x)/,""));if(!t)return;const r=Uint8Array.from([1,112,18,32,...t]),{CID:o}=await import("multiformats/cid");return o.decode(r).toV0().toString()}async function de(e){const{ajv:t,validate:r}=await se();return{result:!!r(e),errors:t.errors?t.errorsText(t.errors):void 0}}const ue="CowSwap";class le{constructor(e){this.context=void 0,this.context=e}generateAppDataDoc(e={},t){const{appCode:r=ue,environment:o}=t||{};return{version:"0.3.0",appCode:r,environment:o,metadata:p({},e)}}async decodeAppData(t){try{const e=await ce(t);if(!e)throw new T("Error getting serialized CID");return async function(e,t="https://gnosis.mypinata.cloud/ipfs"){const{default:r}=await import("cross-fetch"),o=await r(`${t}/${e}`);return await o.json()}(e)}catch(t){const r=t;throw e.error("Error decoding AppData:",r),new T("Error decoding AppData: "+r.message)}}async cidToAppDataHex(e){const{CID:t}=await import("multiformats/cid"),{digest:r}=t.parse(e).multihash;return`0x${Buffer.from(r).toString("hex")}`}async appDataHexToCid(e){const t=await ce(e);if(!t)throw new T("Error getting serialized CID");return t}async calculateAppDataHash(e){const t=await de(e);if(null==t||!t.result)throw new T("Invalid appData provided",null==t?void 0:t.errors);try{const t=await async function(e){const t=JSON.stringify(e),{of:r}=await import("ipfs-only-hash");return r(t,{cidVersion:0})}(e),r=await this.cidToAppDataHex(t);if(!r)throw new T(`Could not extract appDataHash from calculated cidV0 ${t}`);return{cidV0:t,appDataHash:r}}catch(e){throw new T("Failed to calculate appDataHash",e.message)}}async uploadMetadataDocToIpfs(e){const{IpfsHash:t}=await async function(e,{writeUri:t="https://api.pinata.cloud",pinataApiKey:r="",pinataApiSecret:o=""}){const{default:n}=await import("cross-fetch");if(!r||!o)throw new T("You need to pass IPFS api credentials.");const i=JSON.stringify({pinataContent:e,pinataMetadata:{name:"appData"}}),a=`${t}/pinning/pinJSONToIPFS`,s=await n(a,{method:"POST",body:i,headers:{"Content-Type":"application/json",pinata_api_key:r,pinata_secret_api_key:o}}),c=await s.json();if(200!==s.status)throw new Error(c.error.details||c.error);return c}(e,this.context.ipfs);return this.cidToAppDataHex(t)}}const he={appDataHash:"0x0000000000000000000000000000000000000000000000000000000000000000",isDevEnvironment:!1,ipfs:{readUri:"https://gnosis.mypinata.cloud/ipfs",writeUri:"https://api.pinata.cloud",apiKey:void 0,apiSecret:void 0}};var pe,me,fe,ge,Te,Ee,ye,we,Ae,Ie,Ne,ve,ke,De,Oe,_e,Pe,Se,Ue,be=/*#__PURE__*/f("context"),Re=/*#__PURE__*/f("chainId");class xe{constructor(e,t){Object.defineProperty(this,be,{writable:!0,value:void 0}),Object.defineProperty(this,Re,{writable:!0,value:void 0}),g(this,Re)[Re]=this.updateChainId(e),g(this,be)[be]=p({},he,t,{ipfs:p({},he.ipfs,t.ipfs)})}updateChainId(t){if(!w[t])throw new T(`Invalid chainId: ${t}`);return e.debug(y,`Updating chainId to: ${t}`),g(this,Re)[Re]=t,t}get chainId(){var t,r=this;const o=null==(t=g(this,be)[be].signer)?void 0:t.provider;return o?(e.debug(y,"Getting chainId from provider"),async function(){const t=(await o.getNetwork()).chainId;return t!==g(r,Re)[Re]&&(e.debug(y,`ChainId mismatch: Provider's chainId: ${t} vs Context's chainId: ${g(r,Re)[Re]}. Updating Context's chainId`),r.updateChainId(t)),t}()):Promise.resolve(g(this,Re)[Re])}get appDataHash(){var e;return null!==(e=g(this,be)[be].appDataHash)&&void 0!==e?e:he.appDataHash}get isDevEnvironment(){var e;return null!==(e=g(this,be)[be].isDevEnvironment)&&void 0!==e?e:he.isDevEnvironment}get signer(){return g(this,be)[be].signer}get ipfs(){var e;return null!==(e=g(this,be)[be].ipfs)&&void 0!==e?e:he.ipfs}}class Ce{constructor(t,r={},o={}){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=de,this.context=new xe(t,p({},r)),this.cowApi=new W(this.context),this.cowSubgraphApi=new ne(this.context),this.metadataApi=new le(this.context),e.setLevel(o.loglevel||"error")}async signOrder(e){const t=this._checkSigner(),r=await this.context.chainId;return async function(e,t,r){return C({order:e,chainId:t},R,r)}(p({},e,{appData:this.context.appDataHash}),r,t)}async signOrderCancellation(e){const t=this._checkSigner();return async function(e,t,r){return C({orderId:e,chainId:t},x,r)}(e,await this.context.chainId,t)}_checkSigner(e=this.context.signer){if(!e)throw new T("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"}(me||(me={})),function(e){e.FeesEth="feesEth",e.FeesUsd="feesUsd",e.Id="id",e.NumberOfTrades="numberOfTrades",e.Orders="orders",e.Settlements="settlements",e.Timestamp="timestamp",e.Tokens="tokens",e.TotalTokens="totalTokens",e.VolumeEth="volumeEth",e.VolumeUsd="volumeUsd"}(fe||(fe={})),function(e){e.Asc="asc",e.Desc="desc"}(ge||(ge={})),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.Token1="token1",e.VolumeToken0="volumeToken0",e.VolumeToken1="volumeToken1",e.VolumeTradedEth="volumeTradedEth",e.VolumeTradedUsd="volumeTradedUsd"}(Ee||(Ee={})),function(e){e.Id="id",e.Timestamp="timestamp",e.Token0="token0",e.Token1="token1",e.VolumeToken0="volumeToken0",e.VolumeToken1="volumeToken1",e.VolumeTradedEth="volumeTradedEth",e.VolumeTradedUsd="volumeTradedUsd"}(ye||(ye={})),function(e){e.Id="id",e.Token0="token0",e.Token1="token1",e.VolumeToken0="volumeToken0",e.VolumeToken1="volumeToken1",e.VolumeTradedEth="volumeTradedEth",e.VolumeTradedUsd="volumeTradedUsd"}(we||(we={})),function(e){e.FirstTradeTimestamp="firstTradeTimestamp",e.Id="id",e.Solver="solver",e.Trades="trades",e.TxHash="txHash"}(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"}(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"}(Ne||(Ne={})),function(e){e.AmountEth="amountEth",e.AmountUsd="amountUsd",e.Id="id",e.Timestamp="timestamp",e.Token="token",e.Trade="trade"}(ve||(ve={})),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"}(Pe||(Pe={})),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"}(Ue||(Ue={}));var He={__proto__:null,get Bundle_OrderBy(){return pe},get DailyTotal_OrderBy(){return me},get HourlyTotal_OrderBy(){return fe},get OrderDirection(){return ge},get Order_OrderBy(){return Te},get PairDaily_OrderBy(){return Ee},get PairHourly_OrderBy(){return ye},get Pair_OrderBy(){return we},get Settlement_OrderBy(){return Ae},get TokenDailyTotal_OrderBy(){return Ie},get TokenHourlyTotal_OrderBy(){return Ne},get TokenTradingEvent_OrderBy(){return ve},get Token_OrderBy(){return ke},get Total_OrderBy(){return De},get Trade_OrderBy(){return Oe},get UniswapPool_OrderBy(){return _e},get UniswapToken_OrderBy(){return Pe},get User_OrderBy(){return Se},get _SubgraphErrorPolicy_(){return Ue}};export{A as ALL_SUPPORTED_CHAIN_IDS,T as CowError,Ce as CowSdk,He as GraphQL,w as SupportedChainId,M as Token};
28
+ `)),oe={[w.MAINNET]:"https://api.thegraph.com/subgraphs/name/cowprotocol/cow",[w.RINKEBY]:"https://api.thegraph.com/subgraphs/name/cowprotocol/cow-rinkeby",[w.GNOSIS_CHAIN]:"https://api.thegraph.com/subgraphs/name/cowprotocol/cow-gc"};class ne{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{[w.MAINNET]:new l(oe[w.MAINNET],{fetch:t}),[w.RINKEBY]:new l(oe[w.RINKEBY],{fetch:t}),[w.GNOSIS_CHAIN]:new l(oe[w.GNOSIS_CHAIN],{fetch:t})}}async getBaseUrl(){const e=await this.context.chainId;return oe[e]}async getTotals(){const t=await this.context.chainId;return e.debug(`[subgraph:${this.API_NAME}] Get totals for:`,t),(await this.runQuery(ee)).totals[0]}async getLastDaysVolume(t){const r=await this.context.chainId;return e.debug(`[subgraph:${this.API_NAME}] Get last ${t} days volume for:`,r),this.runQuery(te,{days:t})}async getLastHoursVolume(t){const r=await this.context.chainId;return e.debug(`[subgraph:${this.API_NAME}] Get last ${t} hours volume for:`,r),this.runQuery(re,{hours:t})}async runQuery(t,r){try{const e=await this.context.chainId,o=this.clients[e];return await o.request(t,r)}catch(o){e.error(o);const n=await this.getBaseUrl();throw new g(`Error running query: ${t}. Variables: ${JSON.stringify(r)}. API: ${n}. Inner Error: ${o}`)}}}let ie,ae;async function se(){if(ae||(ae=new h),!ie){const e=await import("./appData.schema-adfc1c6f.js");ie=ae.compile(e)}return{ajv:ae,validate:ie}}async function ce(e){const t=function(e){const t=e.match(/.{1,2}/g);if(t)return new Uint8Array(t.map(e=>parseInt(e,16)))}(e.replace(/(^0x)/,""));if(!t)return;const r=Uint8Array.from([1,112,18,32,...t]),{CID:o}=await import("multiformats/cid");return o.decode(r).toV0().toString()}async function de(e){const{ajv:t,validate:r}=await se();return{result:!!r(e),errors:t.errors?t.errorsText(t.errors):void 0}}const ue="CowSwap";class le{constructor(e){this.context=void 0,this.context=e}generateAppDataDoc(e={},t){const{appCode:r=ue,environment:o}=t||{};return{version:"0.3.0",appCode:r,environment:o,metadata:p({},e)}}async decodeAppData(t){try{const e=await ce(t);if(!e)throw new g("Error getting serialized CID");return async function(e,t="https://gnosis.mypinata.cloud/ipfs"){const{default:r}=await import("cross-fetch"),o=await r(`${t}/${e}`);return await o.json()}(e)}catch(t){const r=t;throw e.error("Error decoding AppData:",r),new g("Error decoding AppData: "+r.message)}}async cidToAppDataHex(e){const{CID:t}=await import("multiformats/cid"),{digest:r}=t.parse(e).multihash;return`0x${Buffer.from(r).toString("hex")}`}async appDataHexToCid(e){const t=await ce(e);if(!t)throw new g("Error getting serialized CID");return t}async calculateAppDataHash(e){const t=await de(e);if(null==t||!t.result)throw new g("Invalid appData provided",null==t?void 0:t.errors);try{const t=await async function(e){const t=JSON.stringify(e),{of:r}=await import("ipfs-only-hash");return r(t,{cidVersion:0})}(e),r=await this.cidToAppDataHex(t);if(!r)throw new g(`Could not extract appDataHash from calculated cidV0 ${t}`);return{cidV0:t,appDataHash:r}}catch(e){throw new g("Failed to calculate appDataHash",e.message)}}async uploadMetadataDocToIpfs(e){const{IpfsHash:t}=await async function(e,{writeUri:t="https://api.pinata.cloud",pinataApiKey:r="",pinataApiSecret:o=""}){const{default:n}=await import("cross-fetch");if(!r||!o)throw new g("You need to pass IPFS api credentials.");const i=JSON.stringify({pinataContent:e,pinataMetadata:{name:"appData"}}),a=`${t}/pinning/pinJSONToIPFS`,s=await n(a,{method:"POST",body:i,headers:{"Content-Type":"application/json",pinata_api_key:r,pinata_secret_api_key:o}}),c=await s.json();if(200!==s.status)throw new Error(c.error.details||c.error);return c}(e,this.context.ipfs);return this.cidToAppDataHex(t)}}const he={appDataHash:"0x0000000000000000000000000000000000000000000000000000000000000000",isDevEnvironment:!1,ipfs:{readUri:"https://gnosis.mypinata.cloud/ipfs",writeUri:"https://api.pinata.cloud",apiKey:void 0,apiSecret:void 0}};var pe,me,fe,Te,ge,Ee,ye,we,Ae,Ie,ve,Ne,ke,Pe,De,Oe,_e,Se,Ue,be=/*#__PURE__*/f("context"),Re=/*#__PURE__*/f("chainId");class xe{constructor(e,t){Object.defineProperty(this,be,{writable:!0,value:void 0}),Object.defineProperty(this,Re,{writable:!0,value:void 0}),T(this,Re)[Re]=this.updateChainId(e),T(this,be)[be]=p({},he,t,{ipfs:p({},he.ipfs,t.ipfs)})}updateChainId(t){if(!w[t])throw new g(`Invalid chainId: ${t}`);return e.debug(y,`Updating chainId to: ${t}`),T(this,Re)[Re]=t,t}get chainId(){var t,r=this;const o=null==(t=T(this,be)[be].signer)?void 0:t.provider;return o?(e.debug(y,"Getting chainId from provider"),async function(){const t=(await o.getNetwork()).chainId;return t!==T(r,Re)[Re]&&(e.debug(y,`ChainId mismatch: Provider's chainId: ${t} vs Context's chainId: ${T(r,Re)[Re]}. Updating Context's chainId`),r.updateChainId(t)),t}()):Promise.resolve(T(this,Re)[Re])}get appDataHash(){var e;return null!==(e=T(this,be)[be].appDataHash)&&void 0!==e?e:he.appDataHash}get isDevEnvironment(){var e;return null!==(e=T(this,be)[be].isDevEnvironment)&&void 0!==e?e:he.isDevEnvironment}get signer(){return T(this,be)[be].signer}get ipfs(){var e;return null!==(e=T(this,be)[be].ipfs)&&void 0!==e?e:he.ipfs}}class Ce{constructor(t,r={},o={}){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=de,this.context=new xe(t,p({},r)),this.cowApi=new W(this.context),this.cowSubgraphApi=new ne(this.context),this.metadataApi=new le(this.context),e.setLevel(o.loglevel||"error")}async signOrder(e){const t=this._checkSigner(),r=await this.context.chainId;return async function(e,t,r){return C({order:e,chainId:t},R,r)}(p({},e,{appData:this.context.appDataHash}),r,t)}async signOrderCancellation(e){const t=this._checkSigner();return async function(e,t,r){return C({orderId:e,chainId:t},x,r)}(e,await this.context.chainId,t)}_checkSigner(e=this.context.signer){if(!e)throw new g("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"}(me||(me={})),function(e){e.FeesEth="feesEth",e.FeesUsd="feesUsd",e.Id="id",e.NumberOfTrades="numberOfTrades",e.Orders="orders",e.Settlements="settlements",e.Timestamp="timestamp",e.Tokens="tokens",e.TotalTokens="totalTokens",e.VolumeEth="volumeEth",e.VolumeUsd="volumeUsd"}(fe||(fe={})),function(e){e.Asc="asc",e.Desc="desc"}(Te||(Te={})),function(e){e.Id="id",e.InvalidateTimestamp="invalidateTimestamp",e.IsSigned="isSigned",e.IsValid="isValid",e.Owner="owner",e.PresignTimestamp="presignTimestamp",e.Trades="trades",e.TradesTimestamp="tradesTimestamp"}(ge||(ge={})),function(e){e.Id="id",e.Timestamp="timestamp",e.Token0="token0",e.Token0Price="token0Price",e.Token0relativePrice="token0relativePrice",e.Token1="token1",e.Token1Price="token1Price",e.Token1relativePrice="token1relativePrice",e.VolumeToken0="volumeToken0",e.VolumeToken1="volumeToken1",e.VolumeTradedEth="volumeTradedEth",e.VolumeTradedUsd="volumeTradedUsd"}(Ee||(Ee={})),function(e){e.Id="id",e.Timestamp="timestamp",e.Token0="token0",e.Token0Price="token0Price",e.Token0relativePrice="token0relativePrice",e.Token1="token1",e.Token1Price="token1Price",e.Token1relativePrice="token1relativePrice",e.VolumeToken0="volumeToken0",e.VolumeToken1="volumeToken1",e.VolumeTradedEth="volumeTradedEth",e.VolumeTradedUsd="volumeTradedUsd"}(ye||(ye={})),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"}(we||(we={})),function(e){e.FirstTradeTimestamp="firstTradeTimestamp",e.Id="id",e.Solver="solver",e.Trades="trades",e.TxHash="txHash"}(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"}(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"}(ve||(ve={})),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"}(Pe||(Pe={})),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"}(De||(De={})),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"}(Oe||(Oe={})),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"}(_e||(_e={})),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"}(Ue||(Ue={}));var He={__proto__:null,get Bundle_OrderBy(){return pe},get DailyTotal_OrderBy(){return me},get HourlyTotal_OrderBy(){return fe},get OrderDirection(){return Te},get Order_OrderBy(){return ge},get PairDaily_OrderBy(){return Ee},get PairHourly_OrderBy(){return ye},get Pair_OrderBy(){return we},get Settlement_OrderBy(){return Ae},get TokenDailyTotal_OrderBy(){return Ie},get TokenHourlyTotal_OrderBy(){return ve},get TokenTradingEvent_OrderBy(){return Ne},get Token_OrderBy(){return ke},get Total_OrderBy(){return Pe},get Trade_OrderBy(){return De},get UniswapPool_OrderBy(){return Oe},get UniswapToken_OrderBy(){return _e},get User_OrderBy(){return Se},get _SubgraphErrorPolicy_(){return Ue}};export{A as ALL_SUPPORTED_CHAIN_IDS,g as CowError,Ce as CowSdk,He as GraphQL,w as SupportedChainId,M as Token};
29
29
  //# sourceMappingURL=index.modern.js.map