@cowprotocol/cow-sdk 5.3.3 → 5.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{index-41ff23de.js → index-18d1e1e2.js} +5 -5
- package/dist/index-18d1e1e2.js.map +1 -0
- package/dist/index.js +4 -4
- package/dist/index.js.map +1 -1
- package/dist/index.modern.mjs +1 -1
- package/dist/index.module.js +4 -4
- package/dist/index.module.js.map +1 -1
- package/dist/order-book/api.d.ts +5 -1
- package/dist/order-book/generated/index.d.ts +2 -0
- package/dist/order-book/generated/models/Auction.d.ts +6 -0
- package/dist/order-book/generated/models/CompetitionOrderStatus.d.ts +26 -0
- package/dist/order-book/generated/models/ExecutedAmounts.d.ts +5 -0
- package/dist/order-book/generated/models/OrderPostError.d.ts +1 -0
- package/dist/order-book/generated/models/PriceEstimationError.d.ts +1 -0
- package/dist/order-book/generated/models/Trade.d.ts +6 -0
- package/dist/package.json +3 -3
- package/dist/{utils-7951fc9a.js → utils-230852ee.js} +1 -1
- package/dist/{utils-7951fc9a.js.map → utils-230852ee.js.map} +1 -1
- package/dist/{utils-4846d038.js → utils-8c04641d.js} +2 -2
- package/dist/{utils-4846d038.js.map → utils-8c04641d.js.map} +1 -1
- package/dist/{utils-bf12253d.js → utils-b3d4ea76.js} +1 -1
- package/dist/{utils-bf12253d.js.map → utils-b3d4ea76.js.map} +1 -1
- package/package.json +3 -3
- package/dist/index-41ff23de.js.map +0 -1
package/dist/index.modern.mjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
export{A as ALL_SUPPORTED_CHAIN_IDS,B as BUY_ETH_ADDRESS,o as BuyTokenDestination,f as COMPOSABLE_COW,j as COMPOSABLE_COW_CONTRACT_ADDRESS,
|
|
1
|
+
export{A as ALL_SUPPORTED_CHAIN_IDS,B as BUY_ETH_ADDRESS,o as BuyTokenDestination,f as COMPOSABLE_COW,j as COMPOSABLE_COW_CONTRACT_ADDRESS,U as CONDITIONAL_ORDER_PARAMS_ABI,a as COW_PROTOCOL_SETTLEMENT_CONTRACT_ADDRESS,h as COW_PROTOCOL_VAULT_RELAYER_ADDRESS,aa as CURRENT_BLOCK_TIMESTAMP_FACTORY_ADDRESS,p as CompetitionOrderStatus,a5 as ConditionalOrder,a7 as ConditionalOrderFactory,C as CowError,H as DEFAULT_BACKOFF_OPTIONS,a8 as DEFAULT_CONDITIONAL_ORDER_REGISTRY,D as DEFAULT_COW_API_CONTEXT,c as DEFAULT_IPFS_READ_URI,d as DEFAULT_IPFS_WRITE_URI,I as DEFAULT_LIMITER_OPTIONS,V as DEFAULT_TOKEN_FORMATTER,ad as DurationType,b as ENVS_LIST,e as EXTENSIBLE_FALLBACK_HANDLER,i as EXTENSIBLE_FALLBACK_HANDLER_CONTRACT_ADDRESS,E as EcdsaSigningScheme,ac as MAX_FREQUENCY,ab as MAX_UINT32,a6 as Multiplexer,O as ORDER_BOOK_PROD_CONFIG,k as ORDER_BOOK_STAGING_CONFIG,q as OnchainOrderData,n as OrderBookApi,G as OrderBookApiError,r as OrderCancellationError,s as OrderClass,t as OrderKind,u as OrderPostError,v as OrderQuoteSideKindBuy,w as OrderQuoteSideKindSell,Q as OrderSigningUtils,x as OrderStatus,T as PollResultCode,P as PriceEstimationError,y as PriceQuality,R as ProofLocation,L as SUBGRAPH_PROD_CONFIG,M as SUBGRAPH_STAGING_CONFIG,z as SellTokenSource,F as SigningScheme,ae as StartTimeValue,N as SubgraphApi,S as SupportedChainId,a9 as TWAP_ADDRESS,af as Twap,Z as createSetDomainVerifierTx,a0 as decodeParams,$ as encodeParams,a3 as formatEpoch,a4 as fromStructToOrder,a2 as getBlockInfo,Y as getDomainVerifier,K as getQuoteAmountsAndCosts,X as isComposableCow,W as isExtensibleFallbackHandler,a1 as isValidAbi,l as logPrefix,g as mapAddressToSupportedNetworks,m as mapSupportedNetworks,J as request,ag as transformDataToStruct,ah as transformStructToData}from"./index-18d1e1e2.js";import"cross-fetch/polyfill";import"limiter";import"exponential-backoff";import"graphql-request";import"ethers";import"@cowprotocol/contracts";import"@openzeppelin/merkle-tree";
|
|
2
2
|
//# sourceMappingURL=index.modern.mjs.map
|
package/dist/index.module.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import"cross-fetch/polyfill";import{RateLimiter as e}from"limiter";import{backOff as t}from"exponential-backoff";import{gql as n,request as r}from"graphql-request";import{utils as a,Contract as i,ethers as s,constants as o,BigNumber as u}from"ethers";import{OrderBalance as p,OrderKind as d}from"@cowprotocol/contracts";import{StandardMerkleTree as l}from"@openzeppelin/merkle-tree";var c;!function(e){e[e.MAINNET=1]="MAINNET",e[e.GNOSIS_CHAIN=100]="GNOSIS_CHAIN",e[e.ARBITRUM_ONE=42161]="ARBITRUM_ONE",e[e.SEPOLIA=11155111]="SEPOLIA"}(c||(c={}));const y=["prod","staging"],m={env:"prod",chainId:c.MAINNET};class T extends Error{constructor(e,t){super(e),this.error_code=void 0,this.error_code=t}}const h="cow-sdk:",f="https://gnosis.mypinata.cloud/ipfs",b="https://api.pinata.cloud",I="0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE",E="0x2f55e8b20D0B9FEFA187AA7d00B6Cbe563605bF5",A="0xfdaFc9d1902f4e0b84f65F49f244b32b31013b74",O=Object.values(c).filter(e=>"number"==typeof e);function v(e){return O.reduce((t,n)=>({...t,[n]:"function"==typeof e?e(n):e}),{})}function P(e){return v(e)}const g=P("0x9008D19f58AAbD9eD0D60971565AA8510560ab41"),S=P("0xC92E8bdf79f0507f65a392b0ab4667716BFE0110"),N=P(E),_=P(A),w=function(e,{path:n,query:r,method:a,body:i},s,o){try{const u={Accept:"application/json","Content-Type":"application/json"},p=`${e}${n}${r?"?"+r:""}`,d={method:a,body:(()=>{if(i)return"string"==typeof i?i:JSON.stringify(i)})(),headers:u};return Promise.resolve(t(function(){try{return Promise.resolve(s.removeTokens(1)).then(function(){return Promise.resolve(fetch(p,d)).then(function(e){return Promise.resolve(x(e)).then(function(t){return e.status>=200&&e.status<300?t:Promise.reject(new R(e,t))})})})}catch(e){return Promise.reject(e)}},o))}catch(e){return Promise.reject(e)}};class R extends Error{constructor(e,t){super("string"==typeof t?t:e.statusText),this.response=void 0,this.body=void 0,this.response=e,this.body=t}}const C=[408,425,429,500,502,503,504],D={numOfAttempts:10,maxDelay:Infinity,jitter:"none",retry:e=>!(e instanceof R)||C.includes(e.response.status)},M={tokensPerInterval:5,interval:"second"},x=function(e){try{let t;const n=function(){if(204!==e.status)return function(n,r){try{var a=function(){const n=e.headers.get("Content-Type");return function(){if(n)return n.toLowerCase().startsWith("application/json")?Promise.resolve(e.json()).then(function(e){return t=1,e}):Promise.resolve(e.text()).then(function(e){return t=1,e})}()}()}catch(e){return r(e)}return a&&a.then?a.then(void 0,r):a}(0,function(e){console.error(e)})}();return Promise.resolve(n&&n.then?n.then(function(e){return t?e:void 0}):t?n:void 0)}catch(e){return Promise.reject(e)}};function U(e){return function(e){const{ethflowData:t}=e;if(!t)return e;const{userValidTo:n}=t,r=e.onchainUser||e.owner,a=I;return{...e,validTo:n,owner:r,sellToken:a}}(function(e){const{executedFeeAmount:t,executedSurplusFee:n}=e,r=BigInt(t||"0"),a=BigInt(n||"0"),i=String(r+a);return{...e,totalFee:i}}(e))}const L={[c.MAINNET]:"https://api.cow.fi/mainnet",[c.GNOSIS_CHAIN]:"https://api.cow.fi/xdai",[c.ARBITRUM_ONE]:"https://api.cow.fi/arbitrum_one",[c.SEPOLIA]:"https://api.cow.fi/sepolia"},k={[c.MAINNET]:"https://barn.api.cow.fi/mainnet",[c.GNOSIS_CHAIN]:"https://barn.api.cow.fi/xdai",[c.ARBITRUM_ONE]:"https://barn.api.cow.fi/arbitrum_one",[c.SEPOLIA]:"https://barn.api.cow.fi/sepolia"};function B(e){return Object.keys(e).reduce((t,n)=>{const r=e[n];return void 0!==r&&(t[n]=r),t},{})}class F{constructor(t={}){this.context=void 0,this.rateLimiter=void 0,this.context={...m,...t},this.rateLimiter=new e(t.limiterOpts||M)}getVersion(e={}){return this.fetch({path:"/api/v1/version",method:"GET"},e)}getTrades(e,t={}){if(e.owner&&e.orderUid)return Promise.reject(new T("Cannot specify both owner and orderId"));if(!e.owner&&!e.orderUid)return Promise.reject(new T("Must specify either owner or orderId"));const n=new URLSearchParams(B(e));return this.fetch({path:"/api/v1/trades",method:"GET",query:n},t)}getOrders({owner:e,offset:t=0,limit:n=1e3},r={}){const a=new URLSearchParams(B({offset:t.toString(),limit:n.toString()}));return this.fetch({path:`/api/v1/account/${e}/orders`,method:"GET",query:a},r).then(e=>e.map(U))}getTxOrders(e,t={}){return this.fetch({path:`/api/v1/transactions/${e}/orders`,method:"GET"},t).then(e=>e.map(U))}getOrder(e,t={}){return this.fetch({path:`/api/v1/orders/${e}`,method:"GET"},t).then(e=>U(e))}getOrderMultiEnv(e,t={}){const{env:n}=this.getContextWithOverride(t),r=y.filter(e=>e!==n);let a=0;const i=n=>{const s=r[a];return n instanceof R&&404===n.response.status&&s?(a++,this.getOrder(e,{...t,env:s}).catch(i)):Promise.reject(n)};return this.getOrder(e,{...t,env:n}).catch(i)}getQuote(e,t={}){return this.fetch({path:"/api/v1/quote",method:"POST",body:e},t)}sendSignedOrderCancellations(e,t={}){return this.fetch({path:"/api/v1/orders",method:"DELETE",body:e},t)}sendOrder(e,t={}){return this.fetch({path:"/api/v1/orders",method:"POST",body:e},t)}getNativePrice(e,t={}){return this.fetch({path:`/api/v1/token/${e}/native_price`,method:"GET"},t)}getTotalSurplus(e,t={}){return this.fetch({path:`/api/v1/users/${e}/total_surplus`,method:"GET"},t)}getAppData(e,t={}){return this.fetch({path:`/api/v1/app_data/${e}`,method:"GET"},t)}uploadAppData(e,t,n={}){return this.fetch({path:`/api/v1/app_data/${e}`,method:"PUT",body:{fullAppData:t}},n)}getSolverCompetition(e,t={}){return this.fetch({path:`/api/v1/solver_competition${"string"==typeof e?"/by_tx_hash":""}/${e}`,method:"GET"},t)}getOrderLink(e,t){const{chainId:n,env:r}=this.getContextWithOverride(t);return this.getApiBaseUrls(r)[n]+`/api/v1/orders/${e}`}getContextWithOverride(e={}){return{...this.context,...e}}getApiBaseUrls(e){return this.context.baseUrls?this.context.baseUrls:"prod"===e?L:k}fetch(t,n={}){const{chainId:r,env:a,backoffOpts:i}=this.getContextWithOverride(n),s=this.getApiBaseUrls(a)[r],o=i||D,u=n.limiterOpts?new e(n.limiterOpts):this.rateLimiter;return w(s,t,u,o)}}var V,$,G,W,j,H,Y,Z,K,X,q,z,J,Q;!function(e){e.ERC20="erc20",e.INTERNAL="internal"}(V||(V={})),function(e){e.EIP712="eip712",e.ETHSIGN="ethsign"}($||($={})),function(e){var t;(t=e.placementError||(e.placementError={})).QUOTE_NOT_FOUND="QuoteNotFound",t.VALID_TO_TOO_FAR_IN_FUTURE="ValidToTooFarInFuture",t.PRE_VALIDATION_ERROR="PreValidationError"}(G||(G={})),function(e){var t;(t=e.errorType||(e.errorType={})).INVALID_SIGNATURE="InvalidSignature",t.WRONG_OWNER="WrongOwner",t.ORDER_NOT_FOUND="OrderNotFound",t.ALREADY_CANCELLED="AlreadyCancelled",t.ORDER_FULLY_EXECUTED="OrderFullyExecuted",t.ORDER_EXPIRED="OrderExpired",t.ON_CHAIN_ORDER="OnChainOrder"}(W||(W={})),function(e){e.MARKET="market",e.LIMIT="limit",e.LIQUIDITY="liquidity"}(j||(j={})),function(e){e.BUY="buy",e.SELL="sell"}(H||(H={})),function(e){var t;(t=e.errorType||(e.errorType={})).DUPLICATED_ORDER="DuplicatedOrder",t.QUOTE_NOT_FOUND="QuoteNotFound",t.INVALID_QUOTE="InvalidQuote",t.MISSING_FROM="MissingFrom",t.WRONG_OWNER="WrongOwner",t.INVALID_EIP1271SIGNATURE="InvalidEip1271Signature",t.INSUFFICIENT_BALANCE="InsufficientBalance",t.INSUFFICIENT_ALLOWANCE="InsufficientAllowance",t.INVALID_SIGNATURE="InvalidSignature",t.SELL_AMOUNT_OVERFLOW="SellAmountOverflow",t.TRANSFER_SIMULATION_FAILED="TransferSimulationFailed",t.ZERO_AMOUNT="ZeroAmount",t.INCOMPATIBLE_SIGNING_SCHEME="IncompatibleSigningScheme",t.TOO_MANY_LIMIT_ORDERS="TooManyLimitOrders",t.TOO_MUCH_GAS="TooMuchGas",t.UNSUPPORTED_BUY_TOKEN_DESTINATION="UnsupportedBuyTokenDestination",t.UNSUPPORTED_SELL_TOKEN_SOURCE="UnsupportedSellTokenSource",t.UNSUPPORTED_ORDER_TYPE="UnsupportedOrderType",t.INSUFFICIENT_VALID_TO="InsufficientValidTo",t.EXCESSIVE_VALID_TO="ExcessiveValidTo",t.INVALID_NATIVE_SELL_TOKEN="InvalidNativeSellToken",t.SAME_BUY_AND_SELL_TOKEN="SameBuyAndSellToken",t.UNSUPPORTED_TOKEN="UnsupportedToken",t.INVALID_APP_DATA="InvalidAppData",t.APP_DATA_HASH_MISMATCH="AppDataHashMismatch",t.APPDATA_FROM_MISMATCH="AppdataFromMismatch"}(Y||(Y={})),function(e){e.BUY="buy"}(Z||(Z={})),function(e){e.SELL="sell"}(K||(K={})),function(e){e.PRESIGNATURE_PENDING="presignaturePending",e.OPEN="open",e.FULFILLED="fulfilled",e.CANCELLED="cancelled",e.EXPIRED="expired"}(X||(X={})),function(e){var t;(t=e.errorType||(e.errorType={})).UNSUPPORTED_TOKEN="UnsupportedToken",t.ZERO_AMOUNT="ZeroAmount",t.UNSUPPORTED_ORDER_TYPE="UnsupportedOrderType"}(q||(q={})),function(e){e.FAST="fast",e.OPTIMAL="optimal",e.VERIFIED="verified"}(z||(z={})),function(e){e.ERC20="erc20",e.INTERNAL="internal",e.EXTERNAL="external"}(J||(J={})),function(e){e.EIP712="eip712",e.ETHSIGN="ethsign",e.PRESIGN="presign",e.EIP1271="eip1271"}(Q||(Q={}));const ee=BigInt(1e4);function te(e){var t;const{orderParams:n,sellDecimals:r,buyDecimals:a,slippagePercentBps:i}=e,s=null!==(t=e.partnerFeeBps)&&void 0!==t?t:0,o=n.kind===H.SELL,u=ne(n.feeAmount,r),p=ne(n.sellAmount,r),d=ne(n.buyAmount,a),l=d.num/p.num,c=ne(p.big+u.big,r),y=ne(l*c.num,a),m=s>0?(o?y.big:p.big)*BigInt(s)/ee:BigInt(0),T=o?{sellAmount:c.big,buyAmount:d.big-m}:{sellAmount:c.big+m,buyAmount:d.big},h=e=>e*BigInt(i)/ee,f=o?{sellAmount:T.sellAmount,buyAmount:T.buyAmount-h(T.buyAmount)}:{sellAmount:T.sellAmount+h(T.sellAmount),buyAmount:T.buyAmount};return{isSell:o,costs:{networkFee:{amountInSellCurrency:u.big,amountInBuyCurrency:ne(l*u.num,a).big},partnerFee:{amount:m,bps:s}},beforeNetworkCosts:{sellAmount:p.big,buyAmount:y.big},afterNetworkCosts:{sellAmount:c.big,buyAmount:d.big},afterPartnerFees:T,afterSlippage:f}}function ne(e,t){if("number"==typeof e){const n=e*10**t,r=n.toFixed();return{big:BigInt(r.includes("e")?n:r),num:e}}const n=BigInt(e);return{big:n,num:Number(n)/10**t}}const re=n`
|
|
1
|
+
import"cross-fetch/polyfill";import{RateLimiter as e}from"limiter";import{backOff as t}from"exponential-backoff";import{gql as n,request as r}from"graphql-request";import{utils as a,Contract as i,ethers as s,constants as o,BigNumber as u}from"ethers";import{OrderBalance as p,OrderKind as d}from"@cowprotocol/contracts";import{StandardMerkleTree as l}from"@openzeppelin/merkle-tree";var c;!function(e){e[e.MAINNET=1]="MAINNET",e[e.GNOSIS_CHAIN=100]="GNOSIS_CHAIN",e[e.ARBITRUM_ONE=42161]="ARBITRUM_ONE",e[e.SEPOLIA=11155111]="SEPOLIA"}(c||(c={}));const y=["prod","staging"],m={env:"prod",chainId:c.MAINNET};class T extends Error{constructor(e,t){super(e),this.error_code=void 0,this.error_code=t}}const h="cow-sdk:",f="https://gnosis.mypinata.cloud/ipfs",b="https://api.pinata.cloud",I="0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE",E="0x2f55e8b20D0B9FEFA187AA7d00B6Cbe563605bF5",A="0xfdaFc9d1902f4e0b84f65F49f244b32b31013b74",O=Object.values(c).filter(e=>"number"==typeof e);function v(e){return O.reduce((t,n)=>({...t,[n]:"function"==typeof e?e(n):e}),{})}function P(e){return v(e)}const g=P("0x9008D19f58AAbD9eD0D60971565AA8510560ab41"),S=P("0xC92E8bdf79f0507f65a392b0ab4667716BFE0110"),N=P(E),_=P(A),R=function(e,{path:n,query:r,method:a,body:i},s,o){try{const u={Accept:"application/json","Content-Type":"application/json"},p=`${e}${n}${r?"?"+r:""}`,d={method:a,body:(()=>{if(i)return"string"==typeof i?i:JSON.stringify(i)})(),headers:u};return Promise.resolve(t(function(){try{return Promise.resolve(s.removeTokens(1)).then(function(){return Promise.resolve(fetch(p,d)).then(function(e){return Promise.resolve(U(e)).then(function(t){return e.status>=200&&e.status<300?t:Promise.reject(new w(e,t))})})})}catch(e){return Promise.reject(e)}},o))}catch(e){return Promise.reject(e)}};class w extends Error{constructor(e,t){super("string"==typeof t?t:e.statusText),this.response=void 0,this.body=void 0,this.response=e,this.body=t}}const C=[408,425,429,500,502,503,504],D={numOfAttempts:10,maxDelay:Infinity,jitter:"none",retry:e=>!(e instanceof w)||C.includes(e.response.status)},M={tokensPerInterval:5,interval:"second"},U=function(e){try{let t;const n=function(){if(204!==e.status)return function(n,r){try{var a=function(){const n=e.headers.get("Content-Type");return function(){if(n)return n.toLowerCase().startsWith("application/json")?Promise.resolve(e.json()).then(function(e){return t=1,e}):Promise.resolve(e.text()).then(function(e){return t=1,e})}()}()}catch(e){return r(e)}return a&&a.then?a.then(void 0,r):a}(0,function(e){console.error(e)})}();return Promise.resolve(n&&n.then?n.then(function(e){return t?e:void 0}):t?n:void 0)}catch(e){return Promise.reject(e)}};function x(e){return function(e){const{ethflowData:t}=e;if(!t)return e;const{userValidTo:n}=t,r=e.onchainUser||e.owner,a=I;return{...e,validTo:n,owner:r,sellToken:a}}(function(e){const{executedFeeAmount:t,executedSurplusFee:n}=e,r=BigInt(t||"0"),a=BigInt(n||"0"),i=String(r+a);return{...e,totalFee:i}}(e))}const L={[c.MAINNET]:"https://api.cow.fi/mainnet",[c.GNOSIS_CHAIN]:"https://api.cow.fi/xdai",[c.ARBITRUM_ONE]:"https://api.cow.fi/arbitrum_one",[c.SEPOLIA]:"https://api.cow.fi/sepolia"},k={[c.MAINNET]:"https://barn.api.cow.fi/mainnet",[c.GNOSIS_CHAIN]:"https://barn.api.cow.fi/xdai",[c.ARBITRUM_ONE]:"https://barn.api.cow.fi/arbitrum_one",[c.SEPOLIA]:"https://barn.api.cow.fi/sepolia"};function B(e){return Object.keys(e).reduce((t,n)=>{const r=e[n];return void 0!==r&&(t[n]=r),t},{})}class V{constructor(t={}){this.context=void 0,this.rateLimiter=void 0,this.context={...m,...t},this.rateLimiter=new e(t.limiterOpts||M)}getVersion(e={}){return this.fetch({path:"/api/v1/version",method:"GET"},e)}getTrades(e,t={}){if(e.owner&&e.orderUid)return Promise.reject(new T("Cannot specify both owner and orderId"));if(!e.owner&&!e.orderUid)return Promise.reject(new T("Must specify either owner or orderId"));const n=new URLSearchParams(B(e));return this.fetch({path:"/api/v1/trades",method:"GET",query:n},t)}getOrders({owner:e,offset:t=0,limit:n=1e3},r={}){const a=new URLSearchParams(B({offset:t.toString(),limit:n.toString()}));return this.fetch({path:`/api/v1/account/${e}/orders`,method:"GET",query:a},r).then(e=>e.map(x))}getTxOrders(e,t={}){return this.fetch({path:`/api/v1/transactions/${e}/orders`,method:"GET"},t).then(e=>e.map(x))}getOrder(e,t={}){return this.fetch({path:`/api/v1/orders/${e}`,method:"GET"},t).then(e=>x(e))}getOrderCompetitionStatus(e,t={}){return this.fetch({path:`/api/v1/orders/${e}/status`,method:"GET"},t)}getOrderMultiEnv(e,t={}){const{env:n}=this.getContextWithOverride(t),r=y.filter(e=>e!==n);let a=0;const i=n=>{const s=r[a];return n instanceof w&&404===n.response.status&&s?(a++,this.getOrder(e,{...t,env:s}).catch(i)):Promise.reject(n)};return this.getOrder(e,{...t,env:n}).catch(i)}getQuote(e,t={}){return this.fetch({path:"/api/v1/quote",method:"POST",body:e},t)}sendSignedOrderCancellations(e,t={}){return this.fetch({path:"/api/v1/orders",method:"DELETE",body:e},t)}sendOrder(e,t={}){return this.fetch({path:"/api/v1/orders",method:"POST",body:e},t)}getNativePrice(e,t={}){return this.fetch({path:`/api/v1/token/${e}/native_price`,method:"GET"},t)}getTotalSurplus(e,t={}){return this.fetch({path:`/api/v1/users/${e}/total_surplus`,method:"GET"},t)}getAppData(e,t={}){return this.fetch({path:`/api/v1/app_data/${e}`,method:"GET"},t)}uploadAppData(e,t,n={}){return this.fetch({path:`/api/v1/app_data/${e}`,method:"PUT",body:{fullAppData:t}},n)}getSolverCompetition(e,t={}){return this.fetch({path:`/api/v1/solver_competition${"string"==typeof e?"/by_tx_hash":""}/${e}`,method:"GET"},t)}getOrderLink(e,t){const{chainId:n,env:r}=this.getContextWithOverride(t);return this.getApiBaseUrls(r)[n]+`/api/v1/orders/${e}`}getContextWithOverride(e={}){return{...this.context,...e}}getApiBaseUrls(e){return this.context.baseUrls?this.context.baseUrls:"prod"===e?L:k}fetch(t,n={}){const{chainId:r,env:a,backoffOpts:i}=this.getContextWithOverride(n),s=this.getApiBaseUrls(a)[r],o=i||D,u=n.limiterOpts?new e(n.limiterOpts):this.rateLimiter;return R(s,t,u,o)}}var F,G,$,W,j,H,Y,Z,K,Q,X,q,z,J,ee;!function(e){e.ERC20="erc20",e.INTERNAL="internal"}(F||(F={})),function(e){var t;(t=e.type||(e.type={})).OPEN="Open",t.SCHEDULED="Scheduled",t.ACTIVE="Active",t.SOLVED="Solved",t.EXECUTING="Executing",t.TRADED="Traded",t.CANCELLED="Cancelled"}(G||(G={})),function(e){e.EIP712="eip712",e.ETHSIGN="ethsign"}($||($={})),function(e){var t;(t=e.placementError||(e.placementError={})).QUOTE_NOT_FOUND="QuoteNotFound",t.VALID_TO_TOO_FAR_IN_FUTURE="ValidToTooFarInFuture",t.PRE_VALIDATION_ERROR="PreValidationError"}(W||(W={})),function(e){var t;(t=e.errorType||(e.errorType={})).INVALID_SIGNATURE="InvalidSignature",t.WRONG_OWNER="WrongOwner",t.ORDER_NOT_FOUND="OrderNotFound",t.ALREADY_CANCELLED="AlreadyCancelled",t.ORDER_FULLY_EXECUTED="OrderFullyExecuted",t.ORDER_EXPIRED="OrderExpired",t.ON_CHAIN_ORDER="OnChainOrder"}(j||(j={})),function(e){e.MARKET="market",e.LIMIT="limit",e.LIQUIDITY="liquidity"}(H||(H={})),function(e){e.BUY="buy",e.SELL="sell"}(Y||(Y={})),function(e){var t;(t=e.errorType||(e.errorType={})).DUPLICATED_ORDER="DuplicatedOrder",t.QUOTE_NOT_FOUND="QuoteNotFound",t.QUOTE_NOT_VERIFIED="QuoteNotVerified",t.INVALID_QUOTE="InvalidQuote",t.MISSING_FROM="MissingFrom",t.WRONG_OWNER="WrongOwner",t.INVALID_EIP1271SIGNATURE="InvalidEip1271Signature",t.INSUFFICIENT_BALANCE="InsufficientBalance",t.INSUFFICIENT_ALLOWANCE="InsufficientAllowance",t.INVALID_SIGNATURE="InvalidSignature",t.SELL_AMOUNT_OVERFLOW="SellAmountOverflow",t.TRANSFER_SIMULATION_FAILED="TransferSimulationFailed",t.ZERO_AMOUNT="ZeroAmount",t.INCOMPATIBLE_SIGNING_SCHEME="IncompatibleSigningScheme",t.TOO_MANY_LIMIT_ORDERS="TooManyLimitOrders",t.TOO_MUCH_GAS="TooMuchGas",t.UNSUPPORTED_BUY_TOKEN_DESTINATION="UnsupportedBuyTokenDestination",t.UNSUPPORTED_SELL_TOKEN_SOURCE="UnsupportedSellTokenSource",t.UNSUPPORTED_ORDER_TYPE="UnsupportedOrderType",t.INSUFFICIENT_VALID_TO="InsufficientValidTo",t.EXCESSIVE_VALID_TO="ExcessiveValidTo",t.INVALID_NATIVE_SELL_TOKEN="InvalidNativeSellToken",t.SAME_BUY_AND_SELL_TOKEN="SameBuyAndSellToken",t.UNSUPPORTED_TOKEN="UnsupportedToken",t.INVALID_APP_DATA="InvalidAppData",t.APP_DATA_HASH_MISMATCH="AppDataHashMismatch",t.APPDATA_FROM_MISMATCH="AppdataFromMismatch"}(Z||(Z={})),function(e){e.BUY="buy"}(K||(K={})),function(e){e.SELL="sell"}(Q||(Q={})),function(e){e.PRESIGNATURE_PENDING="presignaturePending",e.OPEN="open",e.FULFILLED="fulfilled",e.CANCELLED="cancelled",e.EXPIRED="expired"}(X||(X={})),function(e){var t;(t=e.errorType||(e.errorType={})).QUOTE_NOT_VERIFIED="QuoteNotVerified",t.UNSUPPORTED_TOKEN="UnsupportedToken",t.ZERO_AMOUNT="ZeroAmount",t.UNSUPPORTED_ORDER_TYPE="UnsupportedOrderType"}(q||(q={})),function(e){e.FAST="fast",e.OPTIMAL="optimal",e.VERIFIED="verified"}(z||(z={})),function(e){e.ERC20="erc20",e.INTERNAL="internal",e.EXTERNAL="external"}(J||(J={})),function(e){e.EIP712="eip712",e.ETHSIGN="ethsign",e.PRESIGN="presign",e.EIP1271="eip1271"}(ee||(ee={}));const te=BigInt(1e4);function ne(e){var t;const{orderParams:n,sellDecimals:r,buyDecimals:a,slippagePercentBps:i}=e,s=null!==(t=e.partnerFeeBps)&&void 0!==t?t:0,o=n.kind===Y.SELL,u=re(n.feeAmount,r),p=re(n.sellAmount,r),d=re(n.buyAmount,a),l=d.num/p.num,c=re(p.big+u.big,r),y=re(l*c.num,a),m=s>0?(o?y.big:p.big)*BigInt(s)/te:BigInt(0),T=o?{sellAmount:c.big,buyAmount:d.big-m}:{sellAmount:c.big+m,buyAmount:d.big},h=e=>e*BigInt(i)/te,f=o?{sellAmount:T.sellAmount,buyAmount:T.buyAmount-h(T.buyAmount)}:{sellAmount:T.sellAmount+h(T.sellAmount),buyAmount:T.buyAmount};return{isSell:o,costs:{networkFee:{amountInSellCurrency:u.big,amountInBuyCurrency:re(l*u.num,a).big},partnerFee:{amount:m,bps:s}},beforeNetworkCosts:{sellAmount:p.big,buyAmount:y.big},afterNetworkCosts:{sellAmount:c.big,buyAmount:d.big},afterPartnerFees:T,afterSlippage:f}}function re(e,t){if("number"==typeof e){const n=e*10**t,r=n.toFixed();return{big:BigInt(r.includes("e")?n:r),num:e}}const n=BigInt(e);return{big:n,num:Number(n)/10**t}}const ae=n`
|
|
2
2
|
query Totals {
|
|
3
3
|
totals {
|
|
4
4
|
tokens
|
|
@@ -11,19 +11,19 @@ import"cross-fetch/polyfill";import{RateLimiter as e}from"limiter";import{backOf
|
|
|
11
11
|
feesEth
|
|
12
12
|
}
|
|
13
13
|
}
|
|
14
|
-
`,
|
|
14
|
+
`,ie=n`
|
|
15
15
|
query LastDaysVolume($days: Int!) {
|
|
16
16
|
dailyTotals(orderBy: timestamp, orderDirection: desc, first: $days) {
|
|
17
17
|
timestamp
|
|
18
18
|
volumeUsd
|
|
19
19
|
}
|
|
20
20
|
}
|
|
21
|
-
`,
|
|
21
|
+
`,se=n`
|
|
22
22
|
query LastHoursVolume($hours: Int!) {
|
|
23
23
|
hourlyTotals(orderBy: timestamp, orderDirection: desc, first: $hours) {
|
|
24
24
|
timestamp
|
|
25
25
|
volumeUsd
|
|
26
26
|
}
|
|
27
27
|
}
|
|
28
|
-
`,se="https://api.thegraph.com/subgraphs/name/cowprotocol",oe={[c.MAINNET]:se+"/cow",[c.GNOSIS_CHAIN]:se+"/cow-gc",[c.ARBITRUM_ONE]:null,[c.SEPOLIA]:null},ue={[c.MAINNET]:se+"/cow-staging",[c.GNOSIS_CHAIN]:se+"/cow-gc-staging",[c.ARBITRUM_ONE]:null,[c.SEPOLIA]:null};class pe{constructor(e={}){this.API_NAME="CoW Protocol Subgraph",this.context=void 0,this.context={...m,...e}}getTotals(e={}){try{return Promise.resolve(this.runQuery(re,void 0,e)).then(function(e){return e.totals[0]})}catch(e){return Promise.reject(e)}}getLastDaysVolume(e,t={}){try{return Promise.resolve(this.runQuery(ae,{days:e},t))}catch(e){return Promise.reject(e)}}getLastHoursVolume(e,t={}){try{return Promise.resolve(this.runQuery(ie,{hours:e},t))}catch(e){return Promise.reject(e)}}runQuery(e,t=undefined,n={}){try{const a=this,{chainId:i,env:s}=a.getContextWithOverride(n),o=a.getEnvConfigs(s)[i];if(null===o)throw new Error("Unsupported Network. The subgraph API is not available in the Network "+i);return Promise.resolve(function(n,a){try{var i=Promise.resolve(r(o,e,t))}catch(e){return a(e)}return i&&i.then?i.then(void 0,a):i}(0,function(n){throw console.error(`[subgraph:${a.API_NAME}]`,n),new T(`Error running query: ${e}. Variables: ${JSON.stringify(t)}. API: ${o}. Inner Error: ${n}`)}))}catch(e){return Promise.reject(e)}}getContextWithOverride(e={}){return{...this.context,...e}}getEnvConfigs(e){return this.context.baseUrls?this.context.baseUrls:"prod"===e?oe:ue}}const de=()=>import("./utils-7951fc9a.js");class le{static signOrder(e,t,n){try{return Promise.resolve(de()).then(function({signOrder:r}){return r(e,t,n)})}catch(e){return Promise.reject(e)}}static signOrderCancellation(e,t,n){try{return Promise.resolve(de()).then(function({signOrderCancellation:r}){return r(e,t,n)})}catch(e){return Promise.reject(e)}}static signOrderCancellations(e,t,n){try{return Promise.resolve(de()).then(function({signOrderCancellations:r}){return r(e,t,n)})}catch(e){return Promise.reject(e)}}static getDomain(e){try{return Promise.resolve(de()).then(function({getDomain:t}){return t(e)})}catch(e){return Promise.reject(e)}}static getDomainSeparator(e){try{return Promise.resolve(de()).then(function({getDomain:t}){return Promise.resolve(import("ethers/lib/utils")).then(function({_TypedDataEncoder:n}){return n.hashDomain(t(e))})})}catch(e){return Promise.reject(e)}}static getEIP712Types(){return{Order:[{name:"sellToken",type:"address"},{name:"buyToken",type:"address"},{name:"receiver",type:"address"},{name:"sellAmount",type:"uint256"},{name:"buyAmount",type:"uint256"},{name:"validTo",type:"uint32"},{name:"appData",type:"bytes32"},{name:"feeAmount",type:"uint256"},{name:"kind",type:"string"},{name:"partiallyFillable",type:"bool"},{name:"sellTokenBalance",type:"string"},{name:"buyTokenBalance",type:"string"}]}}}var ce,ye;!function(e){e[e.PRIVATE=0]="PRIVATE",e[e.EMITTED=1]="EMITTED",e[e.SWARM=2]="SWARM",e[e.WAKU=3]="WAKU",e[e.RESERVED=4]="RESERVED",e[e.IPFS=5]="IPFS"}(ce||(ce={})),function(e){e.SUCCESS="SUCCESS",e.UNEXPECTED_ERROR="UNEXPECTED_ERROR",e.TRY_NEXT_BLOCK="TRY_NEXT_BLOCK",e.TRY_ON_BLOCK="TRY_ON_BLOCK",e.TRY_AT_EPOCH="TRY_AT_EPOCH",e.DONT_TRY_AGAIN="DONT_TRY_AGAIN"}(ye||(ye={}));const me=[{inputs:[{internalType:"address",name:"_settlement",type:"address"}],stateMutability:"nonpayable",type:"constructor"},{inputs:[],name:"InterfaceNotSupported",type:"error"},{inputs:[],name:"InvalidHandler",type:"error"},{inputs:[],name:"ProofNotAuthed",type:"error"},{inputs:[],name:"SingleOrderNotAuthed",type:"error"},{inputs:[],name:"SwapGuardRestricted",type:"error"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"owner",type:"address"},{components:[{internalType:"contract IConditionalOrder",name:"handler",type:"address"},{internalType:"bytes32",name:"salt",type:"bytes32"},{internalType:"bytes",name:"staticInput",type:"bytes"}],indexed:!1,internalType:"struct IConditionalOrder.ConditionalOrderParams",name:"params",type:"tuple"}],name:"ConditionalOrderCreated",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"owner",type:"address"},{indexed:!1,internalType:"bytes32",name:"root",type:"bytes32"},{components:[{internalType:"uint256",name:"location",type:"uint256"},{internalType:"bytes",name:"data",type:"bytes"}],indexed:!1,internalType:"struct ComposableCoW.Proof",name:"proof",type:"tuple"}],name:"MerkleRootSet",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"owner",type:"address"},{indexed:!1,internalType:"contract ISwapGuard",name:"swapGuard",type:"address"}],name:"SwapGuardSet",type:"event"},{inputs:[{internalType:"address",name:"",type:"address"},{internalType:"bytes32",name:"",type:"bytes32"}],name:"cabinet",outputs:[{internalType:"bytes32",name:"",type:"bytes32"}],stateMutability:"view",type:"function"},{inputs:[{components:[{internalType:"contract IConditionalOrder",name:"handler",type:"address"},{internalType:"bytes32",name:"salt",type:"bytes32"},{internalType:"bytes",name:"staticInput",type:"bytes"}],internalType:"struct IConditionalOrder.ConditionalOrderParams",name:"params",type:"tuple"},{internalType:"bool",name:"dispatch",type:"bool"}],name:"create",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{components:[{internalType:"contract IConditionalOrder",name:"handler",type:"address"},{internalType:"bytes32",name:"salt",type:"bytes32"},{internalType:"bytes",name:"staticInput",type:"bytes"}],internalType:"struct IConditionalOrder.ConditionalOrderParams",name:"params",type:"tuple"},{internalType:"contract IValueFactory",name:"factory",type:"address"},{internalType:"bytes",name:"data",type:"bytes"},{internalType:"bool",name:"dispatch",type:"bool"}],name:"createWithContext",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[],name:"domainSeparator",outputs:[{internalType:"bytes32",name:"",type:"bytes32"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"owner",type:"address"},{components:[{internalType:"contract IConditionalOrder",name:"handler",type:"address"},{internalType:"bytes32",name:"salt",type:"bytes32"},{internalType:"bytes",name:"staticInput",type:"bytes"}],internalType:"struct IConditionalOrder.ConditionalOrderParams",name:"params",type:"tuple"},{internalType:"bytes",name:"offchainInput",type:"bytes"},{internalType:"bytes32[]",name:"proof",type:"bytes32[]"}],name:"getTradeableOrderWithSignature",outputs:[{components:[{internalType:"contract IERC20",name:"sellToken",type:"address"},{internalType:"contract IERC20",name:"buyToken",type:"address"},{internalType:"address",name:"receiver",type:"address"},{internalType:"uint256",name:"sellAmount",type:"uint256"},{internalType:"uint256",name:"buyAmount",type:"uint256"},{internalType:"uint32",name:"validTo",type:"uint32"},{internalType:"bytes32",name:"appData",type:"bytes32"},{internalType:"uint256",name:"feeAmount",type:"uint256"},{internalType:"bytes32",name:"kind",type:"bytes32"},{internalType:"bool",name:"partiallyFillable",type:"bool"},{internalType:"bytes32",name:"sellTokenBalance",type:"bytes32"},{internalType:"bytes32",name:"buyTokenBalance",type:"bytes32"}],internalType:"struct GPv2Order.Data",name:"order",type:"tuple"},{internalType:"bytes",name:"signature",type:"bytes"}],stateMutability:"view",type:"function"},{inputs:[{components:[{internalType:"contract IConditionalOrder",name:"handler",type:"address"},{internalType:"bytes32",name:"salt",type:"bytes32"},{internalType:"bytes",name:"staticInput",type:"bytes"}],internalType:"struct IConditionalOrder.ConditionalOrderParams",name:"params",type:"tuple"}],name:"hash",outputs:[{internalType:"bytes32",name:"",type:"bytes32"}],stateMutability:"pure",type:"function"},{inputs:[{internalType:"contract Safe",name:"safe",type:"address"},{internalType:"address",name:"sender",type:"address"},{internalType:"bytes32",name:"_hash",type:"bytes32"},{internalType:"bytes32",name:"_domainSeparator",type:"bytes32"},{internalType:"bytes32",name:"",type:"bytes32"},{internalType:"bytes",name:"encodeData",type:"bytes"},{internalType:"bytes",name:"payload",type:"bytes"}],name:"isValidSafeSignature",outputs:[{internalType:"bytes4",name:"magic",type:"bytes4"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"bytes32",name:"singleOrderHash",type:"bytes32"}],name:"remove",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"",type:"address"}],name:"roots",outputs:[{internalType:"bytes32",name:"",type:"bytes32"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"bytes32",name:"root",type:"bytes32"},{components:[{internalType:"uint256",name:"location",type:"uint256"},{internalType:"bytes",name:"data",type:"bytes"}],internalType:"struct ComposableCoW.Proof",name:"proof",type:"tuple"}],name:"setRoot",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"bytes32",name:"root",type:"bytes32"},{components:[{internalType:"uint256",name:"location",type:"uint256"},{internalType:"bytes",name:"data",type:"bytes"}],internalType:"struct ComposableCoW.Proof",name:"proof",type:"tuple"},{internalType:"contract IValueFactory",name:"factory",type:"address"},{internalType:"bytes",name:"data",type:"bytes"}],name:"setRootWithContext",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"contract ISwapGuard",name:"swapGuard",type:"address"}],name:"setSwapGuard",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"",type:"address"},{internalType:"bytes32",name:"",type:"bytes32"}],name:"singleOrders",outputs:[{internalType:"bool",name:"",type:"bool"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"",type:"address"}],name:"swapGuards",outputs:[{internalType:"contract ISwapGuard",name:"",type:"address"}],stateMutability:"view",type:"function"}];class Te{static createInterface(){return new a.Interface(me)}static connect(e,t){return new i(e,me,t)}}Te.abi=me;const he=[{anonymous:!1,inputs:[{indexed:!0,internalType:"contract Safe",name:"safe",type:"address"},{indexed:!1,internalType:"bytes32",name:"domainSeparator",type:"bytes32"},{indexed:!1,internalType:"contract ISafeSignatureVerifier",name:"verifier",type:"address"}],name:"AddedDomainVerifier",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"contract Safe",name:"safe",type:"address"},{indexed:!1,internalType:"bytes4",name:"interfaceId",type:"bytes4"}],name:"AddedInterface",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"contract Safe",name:"safe",type:"address"},{indexed:!1,internalType:"bytes4",name:"selector",type:"bytes4"},{indexed:!1,internalType:"bytes32",name:"method",type:"bytes32"}],name:"AddedSafeMethod",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"contract Safe",name:"safe",type:"address"},{indexed:!1,internalType:"bytes32",name:"domainSeparator",type:"bytes32"},{indexed:!1,internalType:"contract ISafeSignatureVerifier",name:"oldVerifier",type:"address"},{indexed:!1,internalType:"contract ISafeSignatureVerifier",name:"newVerifier",type:"address"}],name:"ChangedDomainVerifier",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"contract Safe",name:"safe",type:"address"},{indexed:!1,internalType:"bytes4",name:"selector",type:"bytes4"},{indexed:!1,internalType:"bytes32",name:"oldMethod",type:"bytes32"},{indexed:!1,internalType:"bytes32",name:"newMethod",type:"bytes32"}],name:"ChangedSafeMethod",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"contract Safe",name:"safe",type:"address"},{indexed:!1,internalType:"bytes32",name:"domainSeparator",type:"bytes32"}],name:"RemovedDomainVerifier",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"contract Safe",name:"safe",type:"address"},{indexed:!1,internalType:"bytes4",name:"interfaceId",type:"bytes4"}],name:"RemovedInterface",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"contract Safe",name:"safe",type:"address"},{indexed:!1,internalType:"bytes4",name:"selector",type:"bytes4"}],name:"RemovedSafeMethod",type:"event"},{stateMutability:"nonpayable",type:"fallback"},{inputs:[{internalType:"contract Safe",name:"",type:"address"},{internalType:"bytes32",name:"",type:"bytes32"}],name:"domainVerifiers",outputs:[{internalType:"contract ISafeSignatureVerifier",name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"bytes32",name:"_hash",type:"bytes32"},{internalType:"bytes",name:"signature",type:"bytes"}],name:"isValidSignature",outputs:[{internalType:"bytes4",name:"magic",type:"bytes4"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"",type:"address"},{internalType:"address",name:"",type:"address"},{internalType:"uint256[]",name:"",type:"uint256[]"},{internalType:"uint256[]",name:"",type:"uint256[]"},{internalType:"bytes",name:"",type:"bytes"}],name:"onERC1155BatchReceived",outputs:[{internalType:"bytes4",name:"",type:"bytes4"}],stateMutability:"pure",type:"function"},{inputs:[{internalType:"address",name:"",type:"address"},{internalType:"address",name:"",type:"address"},{internalType:"uint256",name:"",type:"uint256"},{internalType:"uint256",name:"",type:"uint256"},{internalType:"bytes",name:"",type:"bytes"}],name:"onERC1155Received",outputs:[{internalType:"bytes4",name:"",type:"bytes4"}],stateMutability:"pure",type:"function"},{inputs:[{internalType:"address",name:"",type:"address"},{internalType:"address",name:"",type:"address"},{internalType:"uint256",name:"",type:"uint256"},{internalType:"bytes",name:"",type:"bytes"}],name:"onERC721Received",outputs:[{internalType:"bytes4",name:"",type:"bytes4"}],stateMutability:"pure",type:"function"},{inputs:[{internalType:"contract Safe",name:"",type:"address"},{internalType:"bytes4",name:"",type:"bytes4"}],name:"safeInterfaces",outputs:[{internalType:"bool",name:"",type:"bool"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"contract Safe",name:"",type:"address"},{internalType:"bytes4",name:"",type:"bytes4"}],name:"safeMethods",outputs:[{internalType:"bytes32",name:"",type:"bytes32"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"bytes32",name:"domainSeparator",type:"bytes32"},{internalType:"contract ISafeSignatureVerifier",name:"newVerifier",type:"address"}],name:"setDomainVerifier",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"bytes4",name:"selector",type:"bytes4"},{internalType:"bytes32",name:"newMethod",type:"bytes32"}],name:"setSafeMethod",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"bytes4",name:"interfaceId",type:"bytes4"},{internalType:"bool",name:"supported",type:"bool"}],name:"setSupportedInterface",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"bytes4",name:"_interfaceId",type:"bytes4"},{internalType:"bytes32[]",name:"handlerWithSelectors",type:"bytes32[]"}],name:"setSupportedInterfaceBatch",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"bytes4",name:"interfaceId",type:"bytes4"}],name:"supportsInterface",outputs:[{internalType:"bool",name:"",type:"bool"}],stateMutability:"view",type:"function"}];class fe{static createInterface(){return new a.Interface(he)}static connect(e,t){return new i(e,he,t)}}fe.abi=he;const be=function(e){try{return Promise.resolve(e.getBlock("latest")).then(function(e){return{blockNumber:e.number,blockTimestamp:e.timestamp}})}catch(e){return Promise.reject(e)}},Ie=function(e,t,n,r){try{const a=fe.connect(N[n],r);return Promise.resolve(a.callStatic.domainVerifiers(e,t))}catch(e){return Promise.reject(e)}},Ee=["erc20","0x5a28e9363bb942b639270062aa6bb295f434bcdfc42c97267bf003f272060dc9"],Ae=["external","0xabee3b73373acd583a130924aad6dc38cfdc44ba0555ba94ce2ff63980ea0632"],Oe=["internal","0x4ac99ace14ee0a5ef932dc609df0943ab7ac16b7583634612f8dc35a4289a6ce"],ve=["sell","0xf3b277728b3fee749481eb3e0b3b48980dbbab78658fc419025cb16eee346775"],Pe=["buy","0x6ed88e868af0a1983e3886d5f3e95a2fafbd6c3450bc229e27342283dc429ccc"],ge=["tuple(address handler, bytes32 salt, bytes staticInput)"],Se=(e,t)=>`${t}@${e}`;function Ne(e,t){return e===N[t]}function _e(e,t){return e===_[t]}function we(e,t){return fe.createInterface().encodeFunctionData("setDomainVerifier",[e,t])}function Re(e){return a.defaultAbiCoder.encode(ge,[e])}function Ce(e){const{handler:t,salt:n,staticInput:r}=a.defaultAbiCoder.decode(ge,e)[0];return{handler:t,salt:n,staticInput:r}}function De(e,t){try{a.defaultAbiCoder.encode(e,t)}catch(e){return!1}return!0}function Me(e){return new Date(1e3*e).toISOString()}function xe(e){if(Ee.includes(e))return p.ERC20;if(Ae.includes(e))return p.EXTERNAL;if(Oe.includes(e))return p.INTERNAL;throw new Error(`Unknown balance type: ${e}`)}function Ue(e){if(ve.includes(e))return d.SELL;if(Pe.includes(e))return d.BUY;throw new Error(`Unknown kind: ${e}`)}function Le(e){const{sellToken:t,sellAmount:n,buyToken:r,buyAmount:a,buyTokenBalance:i,sellTokenBalance:s,feeAmount:o,kind:u,receiver:p,validTo:d,partiallyFillable:l,appData:c}=e;return{sellToken:t,sellAmount:n,buyToken:r,buyAmount:a,feeAmount:o,receiver:p,partiallyFillable:l,appData:c,validTo:Number(d),kind:Ue(u.toString()),sellTokenBalance:xe(s.toString()),buyTokenBalance:xe(i.toString())}}let ke,Be;function Fe(){return ke||(ke=Te.createInterface()),ke}function Ve(e,t){return Be||(Be=Te.connect(_[e],t)),Be}class $e{constructor(e){this.handler=void 0,this.salt=void 0,this.data=void 0,this.staticInput=void 0,this.hasOffChainInput=void 0;const{handler:t,salt:n=a.keccak256(a.randomBytes(32)),data:r,hasOffChainInput:i=!1}=e;if(!s.utils.isAddress(t))throw new Error(`Invalid handler: ${t}`);if(!s.utils.isHexString(n)||32!==s.utils.hexDataLength(n))throw new Error(`Invalid salt: ${n}`);this.handler=t,this.salt=n,this.data=r,this.staticInput=this.transformDataToStruct(r),this.hasOffChainInput=i}get context(){}assertIsValid(){const e=this.isValid();if(!e.isValid)throw new Error(`Invalid order: ${e.reason}`)}get createCalldata(){this.assertIsValid();const e=this.context,t=Fe(),n={handler:this.handler,salt:this.salt,staticInput:this.encodeStaticInput()};if(e){const r=e.factoryArgs?a.defaultAbiCoder.encode(e.factoryArgs.argsType,e.factoryArgs.args):"0x";return t.encodeFunctionData("createWithContext",[n,e.address,r,!0])}return t.encodeFunctionData("create",[n,!0])}get removeCalldata(){return this.assertIsValid(),Fe().encodeFunctionData("remove",[this.id])}get id(){return a.keccak256(this.serialize())}get ctx(){return this.isSingleOrder?this.id:o.HashZero}get leaf(){return{handler:this.handler,salt:this.salt,staticInput:this.encodeStaticInput()}}static leafToId(e){return a.keccak256(Re(e))}get offChainInput(){return"0x"}encodeStaticInputHelper(e,t){return a.defaultAbiCoder.encode(e,[t])}poll(e){try{const t=this,{chainId:n,owner:r,provider:a,orderBookApi:i}=e,s=Ve(n,a);return Promise.resolve(function(a,o){try{var u=function(){const a=t.isValid();return a.isValid?Promise.resolve(t.pollValidate(e)).then(function(a){return a||Promise.resolve(t.isAuthorized(e)).then(function(a){return a?Promise.resolve(s.getTradeableOrderWithSignature(r,t.leaf,t.offChainInput,[])).then(function([a,s]){return Promise.resolve(function(e,t,n){try{return Promise.resolve(import("@cowprotocol/contracts")).then(function({computeOrderUid:r}){return Promise.resolve(le.getDomain(e)).then(function(e){return r(e,n,t)})})}catch(e){return Promise.reject(e)}}(n,r,Le(a))).then(function(n){return Promise.resolve(i.getOrder(n).then(()=>!0).catch(()=>!1)).then(function(r){let i;function o(e){return i?e:{result:ye.SUCCESS,order:a,signature:s}}const u=function(){if(r)return Promise.resolve(t.handlePollFailedAlreadyPresent(n,a,e)).then(function(e){return e?(i=1,e):(i=1,{result:ye.TRY_NEXT_BLOCK,reason:"Order already in orderbook"})})}();return u&&u.then?u.then(o):o(u)})})}):{result:ye.DONT_TRY_AGAIN,reason:`NotAuthorized: Order ${t.id} is not authorized for ${r} on chain ${n}`}})}):{result:ye.DONT_TRY_AGAIN,reason:`InvalidConditionalOrder. Reason: ${a.reason}`}}()}catch(e){return o(e)}return u&&u.then?u.then(void 0,o):u}(0,function(e){return{result:ye.UNEXPECTED_ERROR,error:e}}))}catch(e){return Promise.reject(e)}}isAuthorized(e){const{chainId:t,owner:n,provider:r}=e;return Ve(t,r).callStatic.singleOrders(n,this.id)}cabinet(e){const{chainId:t,owner:n,provider:r}=e;return Ve(t,r).callStatic.cabinet(n,this.ctx)}static deserializeHelper(e,t,n,r){try{const{handler:i,salt:s,staticInput:o}=Ce(e);if(i!=t)throw new Error("HandlerMismatch");const[u]=a.defaultAbiCoder.decode(n,o);return r(u,s)}catch(e){throw"HandlerMismatch"===e.message?e:new Error("InvalidSerializedConditionalOrder")}}}const Ge=["address","bytes32","bytes"],We=["tuple(bytes32[] proof, tuple(address handler, bytes32 salt, bytes staticInput) params)[]"];class je{constructor(e,t,n,r=ce.PRIVATE){if(this.chain=void 0,this.location=void 0,this.orders={},this.tree=void 0,this.ctx=void 0,this.chain=e,this.location=r,t&&0===Object.keys(t).length)throw new Error("orders must have non-zero length");if(t&&!n||!t&&n)throw new Error("orders cannot have undefined root");for(const e in t)if(t.hasOwnProperty(e)){const n=t[e];if(!je.orderTypeRegistry.hasOwnProperty(n.orderType))throw new Error(`Unknown order type: ${n.orderType}`)}if(t&&(this.orders=t,this.getOrGenerateTree().root!==n))throw new Error("root mismatch")}static fromJSON(e){const{chain:t,orders:n,root:r,location:a}=JSON.parse(e,(e,t)=>{if("orders"===e&&"object"==typeof t&&null!==t){const e={};for(const n in t)if(t.hasOwnProperty(n)){const{orderType:r,...a}=t[n];if(!je.orderTypeRegistry.hasOwnProperty(r))throw new Error(`Unknown order type: ${r}`);e[n]=new(0,je.orderTypeRegistry[r])(a)}return e}return"object"==typeof t&&null!==t&&t.hasOwnProperty("type")&&t.hasOwnProperty("hex")&&"BigNumber"===t.type?u.from(t):t}),i=new je(t,n,r);return i.location=a,i}toJSON(){const e=this.getOrGenerateTree().root;return JSON.stringify({...this,root:e},(e,t)=>{if("tree"!==e){if("object"==typeof t&&null!==t&&"orderType"in t){const e=t;return{...e,orderType:e.orderType}}return t}})}add(e){e.assertIsValid(),this.orders[e.id]=e,this.reset()}remove(e){delete this.orders[e],this.reset()}update(e,t){const n=t(this.orders[e],this.ctx);delete this.orders[e],this.orders[n.id]=n,this.reset()}getById(e){return this.orders[e]}getByIndex(e){return this.orders[this.orderIds[e]]}get orderIds(){return Object.keys(this.orders)}get root(){return this.getOrGenerateTree().root}getOrGenerateTree(){return this.tree||(this.tree=l.of(Object.values(this.orders).map(e=>[...Object.values(e.leaf)]),Ge)),this.tree}static decodeFromJSON(e){return JSON.parse(e)}prepareProofStruct(e,t,n){try{const r=this;void 0===e&&(e=r.location);const i=function(){try{switch(e){case ce.PRIVATE:return Promise.resolve("0x");case ce.EMITTED:return Promise.resolve(r.encodeToABI(t));case ce.SWARM:case ce.WAKU:case ce.IPFS:if(!n)throw new Error("Must provide an uploader function");return Promise.resolve(function(e,a){try{var i=Promise.resolve(n(r.encodeToJSON(t)))}catch(e){return a(e)}return i&&i.then?i.then(void 0,a):i}(0,function(t){throw new Error(`Error uploading to decentralized storage ${e}: ${t}`)}));default:throw new Error("Unsupported location")}}catch(e){return Promise.reject(e)}};return Promise.resolve(i().then(t=>{try{return a.hexlify(a.arrayify(t)),r.location=e,{location:e,data:t}}catch(e){throw new Error("data returned by uploader is invalid")}}).catch(e=>{throw new Error(`Error preparing proof struct: ${e}`)}))}catch(e){return Promise.reject(e)}}static poll(e,t,n,r,a){try{function i(n){return Promise.resolve(s.getTradeableOrderWithSignature(e,t.params,n,t.proof))}const s=Ve(n,r);return Promise.resolve(a?Promise.resolve(a(e,t.params)).then(i):i("0x"))}catch(o){return Promise.reject(o)}}dumpProofs(e){return this.encodeToJSON(e)}dumpProofsAndParams(e){return this.getProofs(e)}getProofs(e){return[...this.getOrGenerateTree().entries()].map(([t,n])=>e&&e(n)||void 0===e?{idx:t,value:n}:void 0).reduce((e,t)=>{if(t){const n={handler:t.value[0],salt:t.value[1],staticInput:t.value[2]};e.push({proof:this.getOrGenerateTree().getProof(t.idx),params:n})}return e},[])}encodeToABI(e){return a.defaultAbiCoder.encode(We,[this.getProofs(e)])}encodeToJSON(e){return JSON.stringify(this.getProofs(e))}reset(){this.tree=void 0}static registerOrderType(e,t){je.orderTypeRegistry[e]=t}static resetOrderTypeRegistry(){je.orderTypeRegistry={}}}je.orderTypeRegistry={};class He{constructor(e){this.knownOrderTypes=void 0,this.knownOrderTypes=e}fromParams(e){const{handler:t}=e,n=this.knownOrderTypes[t];if(n)return n(e)}}const Ye="0x6cF1e9cA41f7611dEf408122793c358a3d11E5a5",Ze="0x52eD56Da04309Aca4c3FECC595298d80C2f16BAc",Ke=u.from(2).pow(32).sub(1),Xe=u.from(31536e3),qe=["tuple(address sellToken, address buyToken, address receiver, uint256 partSellAmount, uint256 minPartLimit, uint256 t0, uint256 n, uint256 t, uint256 span, bytes32 appData)"];var ze,Je;!function(e){e.AUTO="AUTO",e.LIMIT_DURATION="LIMIT_DURATION"}(ze||(ze={})),function(e){e.AT_MINING_TIME="AT_MINING_TIME",e.AT_EPOCH="AT_EPOCH"}(Je||(Je={}));const Qe={startType:Je.AT_MINING_TIME},et={durationType:ze.AUTO};class tt extends $e{constructor(e){const{handler:t,salt:n,data:r,hasOffChainInput:a}=e;if(t!==Ye)throw new Error(`InvalidHandler: Expected: ${Ye}, provided: ${t}`);super({handler:Ye,salt:n,data:r,hasOffChainInput:a}),this.isSingleOrder=!0}static fromData(e,t){return new tt({handler:Ye,data:e,salt:t})}static fromParams(e){return tt.deserialize(Re(e))}get context(){return this.staticInput.t0.gt(0)?super.context:{address:Ze,factoryArgs:void 0}}get orderType(){return"twap"}isValid(){const e=(()=>{const{sellToken:e,sellAmount:t,buyToken:n,buyAmount:r,startTime:a=Qe,numberOfParts:i,timeBetweenParts:s,durationOfPart:u=et}=this.data;if(e==n)return"InvalidSameToken";if(e==o.AddressZero||n==o.AddressZero)return"InvalidToken";if(!t.gt(o.Zero))return"InvalidSellAmount";if(!r.gt(o.Zero))return"InvalidMinBuyAmount";if(a.startType===Je.AT_EPOCH){const e=a.epoch;if(!e.gte(o.Zero)||!e.lt(Ke))return"InvalidStartTime"}return i.gt(o.One)&&i.lte(Ke)?s.gt(o.Zero)&&s.lte(Xe)?u.durationType!==ze.LIMIT_DURATION||u.duration.lte(s)?De(qe,[this.staticInput])?void 0:"InvalidData":"InvalidSpan":"InvalidFrequency":"InvalidNumParts"})();return e?{isValid:!1,reason:e}:{isValid:!0}}startTimestamp(e){try{const t=this,{startTime:n}=t.data;return n?.startType===Je.AT_EPOCH?Promise.resolve(n.epoch.toNumber()):Promise.resolve(t.cabinet(e)).then(function(e){const t=a.defaultAbiCoder.decode(["uint256"],e)[0];if(t.gt(Ke))throw new Error(`Cabinet epoch out of range: ${t.toString()}`);const n=t.toNumber();if(0===n)throw new Error("Cabinet is not set. Required for TWAP orders that start at mining time.");return n})}catch(e){return Promise.reject(e)}}endTimestamp(e){const{numberOfParts:t,timeBetweenParts:n,durationOfPart:r}=this.data;return r&&r.durationType===ze.LIMIT_DURATION?e+t.sub(1).mul(n).add(r.duration).toNumber():e+t.mul(n).toNumber()}pollValidate(e){try{const t=this;return Promise.resolve(be(e.provider)).then(function(n){const{blockInfo:r=n}=e,{blockTimestamp:a}=r;return function(n,r){try{var i=Promise.resolve(t.startTimestamp(e)).then(function(e){if(e>a)return{result:ye.TRY_AT_EPOCH,epoch:e,reason:`TWAP hasn't started yet. Starts at ${e} (${Me(e)})`};const n=t.endTimestamp(e);return a>=n?{result:ye.DONT_TRY_AGAIN,reason:`TWAP has expired. Expired at ${n} (${Me(n)})`}:void 0})}catch(e){return r(e)}return i&&i.then?i.then(void 0,r):i}(0,function(e){return e?.message?.includes("Cabinet is not set")?{result:ye.DONT_TRY_AGAIN,reason:`${e?.message}. User likely removed the order.`}:e?.message?.includes("Cabinet epoch out of range")?{result:ye.DONT_TRY_AGAIN,reason:`${e?.message}`}:{result:ye.UNEXPECTED_ERROR,reason:`Unexpected error: ${e.message}`,error:e}})})}catch(e){return Promise.reject(e)}}handlePollFailedAlreadyPresent(e,t,n){try{const e=this;return Promise.resolve(be(n.provider)).then(function(t){const{blockInfo:r=t}=n,{blockTimestamp:a}=r,i=e.data.timeBetweenParts.toNumber(),{numberOfParts:s}=e.data;return Promise.resolve(e.startTimestamp(n)).then(function(e){if(a<e)return{result:ye.UNEXPECTED_ERROR,reason:`TWAP part hash't started. First TWAP part start at ${e} (${Me(e)})`,error:void 0};const t=s.mul(i).add(e).toNumber();if(a>=t)return{result:ye.UNEXPECTED_ERROR,reason:`TWAP is expired. Expired at ${t} (${Me(t)})`,error:void 0};const n=Math.floor((a-e)/i);if(n===s.toNumber()-1)return{result:ye.DONT_TRY_AGAIN,reason:`Current active TWAP part (${n+1}/${s}) is already in the Order Book. This was the last TWAP part, no more orders need to be placed`};const r=e+(n+1)*i;return{result:ye.TRY_AT_EPOCH,epoch:r,reason:`Current active TWAP part (${n+1}/${s}) is already in the Order Book. TWAP part ${n+2} doesn't start until ${r} (${Me(r)})`}})})}catch(e){return Promise.reject(e)}}serialize(){return Re(this.leaf)}encodeStaticInput(){return super.encodeStaticInputHelper(qe,this.staticInput)}static deserialize(e){return super.deserializeHelper(e,Ye,qe,(e,t)=>new tt({handler:Ye,salt:t,data:rt(e)}))}toString(){const{sellAmount:e,sellToken:t,buyAmount:n,buyToken:r,numberOfParts:a,startTime:i=Qe,timeBetweenParts:s,durationOfPart:o=et,receiver:u,appData:p}=this.data,d=i.startType===Je.AT_MINING_TIME?"AT_MINING_TIME":i.epoch.toNumber(),l=o.durationType===ze.AUTO?"AUTO":o.duration.toNumber(),c={sellAmount:e.toString(),sellToken:t,buyAmount:n.toString(),buyToken:r,numberOfParts:a.toString(),startTime:d,timeBetweenParts:s.toNumber(),durationOfPart:l,receiver:u,appData:p};return`${this.orderType} (${this.id}): ${JSON.stringify(c)}`}transformDataToStruct(e){return nt(e)}transformStructToData(e){return rt(e)}}function nt(e){const{sellAmount:t,buyAmount:n,numberOfParts:r,startTime:a=Qe,timeBetweenParts:i,durationOfPart:s=et,...u}=e,{partSellAmount:p,minPartLimit:d}=r&&!r.isZero()?{partSellAmount:t.div(r),minPartLimit:n.div(r)}:{partSellAmount:o.Zero,minPartLimit:o.Zero};return{partSellAmount:p,minPartLimit:d,t0:a.startType===Je.AT_MINING_TIME?o.Zero:a.epoch,n:r,t:i,span:s.durationType===ze.AUTO?o.Zero:s.duration,...u}}function rt(e){const{n:t,partSellAmount:n,minPartLimit:r,t:a,t0:i,span:s,...o}=e,u=s.isZero()?{durationType:ze.AUTO}:{durationType:ze.LIMIT_DURATION,duration:s},p=s.isZero()?{startType:Je.AT_MINING_TIME}:{startType:Je.AT_EPOCH,epoch:i};return{sellAmount:n.mul(t),buyAmount:r.mul(t),startTime:p,numberOfParts:t,timeBetweenParts:a,durationOfPart:u,...o}}const at={[Ye]:e=>tt.fromParams(e)};export{O as ALL_SUPPORTED_CHAIN_IDS,I as BUY_ETH_ADDRESS,V as BuyTokenDestination,A as COMPOSABLE_COW,_ as COMPOSABLE_COW_CONTRACT_ADDRESS,ge as CONDITIONAL_ORDER_PARAMS_ABI,g as COW_PROTOCOL_SETTLEMENT_CONTRACT_ADDRESS,S as COW_PROTOCOL_VAULT_RELAYER_ADDRESS,Ze as CURRENT_BLOCK_TIMESTAMP_FACTORY_ADDRESS,$e as ConditionalOrder,He as ConditionalOrderFactory,T as CowError,D as DEFAULT_BACKOFF_OPTIONS,at as DEFAULT_CONDITIONAL_ORDER_REGISTRY,m as DEFAULT_COW_API_CONTEXT,f as DEFAULT_IPFS_READ_URI,b as DEFAULT_IPFS_WRITE_URI,M as DEFAULT_LIMITER_OPTIONS,Se as DEFAULT_TOKEN_FORMATTER,ze as DurationType,y as ENVS_LIST,E as EXTENSIBLE_FALLBACK_HANDLER,N as EXTENSIBLE_FALLBACK_HANDLER_CONTRACT_ADDRESS,$ as EcdsaSigningScheme,Xe as MAX_FREQUENCY,Ke as MAX_UINT32,je as Multiplexer,L as ORDER_BOOK_PROD_CONFIG,k as ORDER_BOOK_STAGING_CONFIG,G as OnchainOrderData,F as OrderBookApi,R as OrderBookApiError,W as OrderCancellationError,j as OrderClass,H as OrderKind,Y as OrderPostError,Z as OrderQuoteSideKindBuy,K as OrderQuoteSideKindSell,le as OrderSigningUtils,X as OrderStatus,ye as PollResultCode,q as PriceEstimationError,z as PriceQuality,ce as ProofLocation,oe as SUBGRAPH_PROD_CONFIG,ue as SUBGRAPH_STAGING_CONFIG,J as SellTokenSource,Q as SigningScheme,Je as StartTimeValue,pe as SubgraphApi,c as SupportedChainId,Ye as TWAP_ADDRESS,tt as Twap,we as createSetDomainVerifierTx,Ce as decodeParams,Re as encodeParams,Me as formatEpoch,Le as fromStructToOrder,be as getBlockInfo,Ie as getDomainVerifier,te as getQuoteAmountsAndCosts,_e as isComposableCow,Ne as isExtensibleFallbackHandler,De as isValidAbi,h as logPrefix,P as mapAddressToSupportedNetworks,v as mapSupportedNetworks,w as request,nt as transformDataToStruct,rt as transformStructToData};
|
|
28
|
+
`,oe="https://api.thegraph.com/subgraphs/name/cowprotocol",ue={[c.MAINNET]:oe+"/cow",[c.GNOSIS_CHAIN]:oe+"/cow-gc",[c.ARBITRUM_ONE]:null,[c.SEPOLIA]:null},pe={[c.MAINNET]:oe+"/cow-staging",[c.GNOSIS_CHAIN]:oe+"/cow-gc-staging",[c.ARBITRUM_ONE]:null,[c.SEPOLIA]:null};class de{constructor(e={}){this.API_NAME="CoW Protocol Subgraph",this.context=void 0,this.context={...m,...e}}getTotals(e={}){try{return Promise.resolve(this.runQuery(ae,void 0,e)).then(function(e){return e.totals[0]})}catch(e){return Promise.reject(e)}}getLastDaysVolume(e,t={}){try{return Promise.resolve(this.runQuery(ie,{days:e},t))}catch(e){return Promise.reject(e)}}getLastHoursVolume(e,t={}){try{return Promise.resolve(this.runQuery(se,{hours:e},t))}catch(e){return Promise.reject(e)}}runQuery(e,t=undefined,n={}){try{const a=this,{chainId:i,env:s}=a.getContextWithOverride(n),o=a.getEnvConfigs(s)[i];if(null===o)throw new Error("Unsupported Network. The subgraph API is not available in the Network "+i);return Promise.resolve(function(n,a){try{var i=Promise.resolve(r(o,e,t))}catch(e){return a(e)}return i&&i.then?i.then(void 0,a):i}(0,function(n){throw console.error(`[subgraph:${a.API_NAME}]`,n),new T(`Error running query: ${e}. Variables: ${JSON.stringify(t)}. API: ${o}. Inner Error: ${n}`)}))}catch(e){return Promise.reject(e)}}getContextWithOverride(e={}){return{...this.context,...e}}getEnvConfigs(e){return this.context.baseUrls?this.context.baseUrls:"prod"===e?ue:pe}}const le=()=>import("./utils-230852ee.js");class ce{static signOrder(e,t,n){try{return Promise.resolve(le()).then(function({signOrder:r}){return r(e,t,n)})}catch(e){return Promise.reject(e)}}static signOrderCancellation(e,t,n){try{return Promise.resolve(le()).then(function({signOrderCancellation:r}){return r(e,t,n)})}catch(e){return Promise.reject(e)}}static signOrderCancellations(e,t,n){try{return Promise.resolve(le()).then(function({signOrderCancellations:r}){return r(e,t,n)})}catch(e){return Promise.reject(e)}}static getDomain(e){try{return Promise.resolve(le()).then(function({getDomain:t}){return t(e)})}catch(e){return Promise.reject(e)}}static getDomainSeparator(e){try{return Promise.resolve(le()).then(function({getDomain:t}){return Promise.resolve(import("ethers/lib/utils")).then(function({_TypedDataEncoder:n}){return n.hashDomain(t(e))})})}catch(e){return Promise.reject(e)}}static getEIP712Types(){return{Order:[{name:"sellToken",type:"address"},{name:"buyToken",type:"address"},{name:"receiver",type:"address"},{name:"sellAmount",type:"uint256"},{name:"buyAmount",type:"uint256"},{name:"validTo",type:"uint32"},{name:"appData",type:"bytes32"},{name:"feeAmount",type:"uint256"},{name:"kind",type:"string"},{name:"partiallyFillable",type:"bool"},{name:"sellTokenBalance",type:"string"},{name:"buyTokenBalance",type:"string"}]}}}var ye,me;!function(e){e[e.PRIVATE=0]="PRIVATE",e[e.EMITTED=1]="EMITTED",e[e.SWARM=2]="SWARM",e[e.WAKU=3]="WAKU",e[e.RESERVED=4]="RESERVED",e[e.IPFS=5]="IPFS"}(ye||(ye={})),function(e){e.SUCCESS="SUCCESS",e.UNEXPECTED_ERROR="UNEXPECTED_ERROR",e.TRY_NEXT_BLOCK="TRY_NEXT_BLOCK",e.TRY_ON_BLOCK="TRY_ON_BLOCK",e.TRY_AT_EPOCH="TRY_AT_EPOCH",e.DONT_TRY_AGAIN="DONT_TRY_AGAIN"}(me||(me={}));const Te=[{inputs:[{internalType:"address",name:"_settlement",type:"address"}],stateMutability:"nonpayable",type:"constructor"},{inputs:[],name:"InterfaceNotSupported",type:"error"},{inputs:[],name:"InvalidHandler",type:"error"},{inputs:[],name:"ProofNotAuthed",type:"error"},{inputs:[],name:"SingleOrderNotAuthed",type:"error"},{inputs:[],name:"SwapGuardRestricted",type:"error"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"owner",type:"address"},{components:[{internalType:"contract IConditionalOrder",name:"handler",type:"address"},{internalType:"bytes32",name:"salt",type:"bytes32"},{internalType:"bytes",name:"staticInput",type:"bytes"}],indexed:!1,internalType:"struct IConditionalOrder.ConditionalOrderParams",name:"params",type:"tuple"}],name:"ConditionalOrderCreated",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"owner",type:"address"},{indexed:!1,internalType:"bytes32",name:"root",type:"bytes32"},{components:[{internalType:"uint256",name:"location",type:"uint256"},{internalType:"bytes",name:"data",type:"bytes"}],indexed:!1,internalType:"struct ComposableCoW.Proof",name:"proof",type:"tuple"}],name:"MerkleRootSet",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"owner",type:"address"},{indexed:!1,internalType:"contract ISwapGuard",name:"swapGuard",type:"address"}],name:"SwapGuardSet",type:"event"},{inputs:[{internalType:"address",name:"",type:"address"},{internalType:"bytes32",name:"",type:"bytes32"}],name:"cabinet",outputs:[{internalType:"bytes32",name:"",type:"bytes32"}],stateMutability:"view",type:"function"},{inputs:[{components:[{internalType:"contract IConditionalOrder",name:"handler",type:"address"},{internalType:"bytes32",name:"salt",type:"bytes32"},{internalType:"bytes",name:"staticInput",type:"bytes"}],internalType:"struct IConditionalOrder.ConditionalOrderParams",name:"params",type:"tuple"},{internalType:"bool",name:"dispatch",type:"bool"}],name:"create",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{components:[{internalType:"contract IConditionalOrder",name:"handler",type:"address"},{internalType:"bytes32",name:"salt",type:"bytes32"},{internalType:"bytes",name:"staticInput",type:"bytes"}],internalType:"struct IConditionalOrder.ConditionalOrderParams",name:"params",type:"tuple"},{internalType:"contract IValueFactory",name:"factory",type:"address"},{internalType:"bytes",name:"data",type:"bytes"},{internalType:"bool",name:"dispatch",type:"bool"}],name:"createWithContext",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[],name:"domainSeparator",outputs:[{internalType:"bytes32",name:"",type:"bytes32"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"owner",type:"address"},{components:[{internalType:"contract IConditionalOrder",name:"handler",type:"address"},{internalType:"bytes32",name:"salt",type:"bytes32"},{internalType:"bytes",name:"staticInput",type:"bytes"}],internalType:"struct IConditionalOrder.ConditionalOrderParams",name:"params",type:"tuple"},{internalType:"bytes",name:"offchainInput",type:"bytes"},{internalType:"bytes32[]",name:"proof",type:"bytes32[]"}],name:"getTradeableOrderWithSignature",outputs:[{components:[{internalType:"contract IERC20",name:"sellToken",type:"address"},{internalType:"contract IERC20",name:"buyToken",type:"address"},{internalType:"address",name:"receiver",type:"address"},{internalType:"uint256",name:"sellAmount",type:"uint256"},{internalType:"uint256",name:"buyAmount",type:"uint256"},{internalType:"uint32",name:"validTo",type:"uint32"},{internalType:"bytes32",name:"appData",type:"bytes32"},{internalType:"uint256",name:"feeAmount",type:"uint256"},{internalType:"bytes32",name:"kind",type:"bytes32"},{internalType:"bool",name:"partiallyFillable",type:"bool"},{internalType:"bytes32",name:"sellTokenBalance",type:"bytes32"},{internalType:"bytes32",name:"buyTokenBalance",type:"bytes32"}],internalType:"struct GPv2Order.Data",name:"order",type:"tuple"},{internalType:"bytes",name:"signature",type:"bytes"}],stateMutability:"view",type:"function"},{inputs:[{components:[{internalType:"contract IConditionalOrder",name:"handler",type:"address"},{internalType:"bytes32",name:"salt",type:"bytes32"},{internalType:"bytes",name:"staticInput",type:"bytes"}],internalType:"struct IConditionalOrder.ConditionalOrderParams",name:"params",type:"tuple"}],name:"hash",outputs:[{internalType:"bytes32",name:"",type:"bytes32"}],stateMutability:"pure",type:"function"},{inputs:[{internalType:"contract Safe",name:"safe",type:"address"},{internalType:"address",name:"sender",type:"address"},{internalType:"bytes32",name:"_hash",type:"bytes32"},{internalType:"bytes32",name:"_domainSeparator",type:"bytes32"},{internalType:"bytes32",name:"",type:"bytes32"},{internalType:"bytes",name:"encodeData",type:"bytes"},{internalType:"bytes",name:"payload",type:"bytes"}],name:"isValidSafeSignature",outputs:[{internalType:"bytes4",name:"magic",type:"bytes4"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"bytes32",name:"singleOrderHash",type:"bytes32"}],name:"remove",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"",type:"address"}],name:"roots",outputs:[{internalType:"bytes32",name:"",type:"bytes32"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"bytes32",name:"root",type:"bytes32"},{components:[{internalType:"uint256",name:"location",type:"uint256"},{internalType:"bytes",name:"data",type:"bytes"}],internalType:"struct ComposableCoW.Proof",name:"proof",type:"tuple"}],name:"setRoot",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"bytes32",name:"root",type:"bytes32"},{components:[{internalType:"uint256",name:"location",type:"uint256"},{internalType:"bytes",name:"data",type:"bytes"}],internalType:"struct ComposableCoW.Proof",name:"proof",type:"tuple"},{internalType:"contract IValueFactory",name:"factory",type:"address"},{internalType:"bytes",name:"data",type:"bytes"}],name:"setRootWithContext",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"contract ISwapGuard",name:"swapGuard",type:"address"}],name:"setSwapGuard",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"",type:"address"},{internalType:"bytes32",name:"",type:"bytes32"}],name:"singleOrders",outputs:[{internalType:"bool",name:"",type:"bool"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"",type:"address"}],name:"swapGuards",outputs:[{internalType:"contract ISwapGuard",name:"",type:"address"}],stateMutability:"view",type:"function"}];class he{static createInterface(){return new a.Interface(Te)}static connect(e,t){return new i(e,Te,t)}}he.abi=Te;const fe=[{anonymous:!1,inputs:[{indexed:!0,internalType:"contract Safe",name:"safe",type:"address"},{indexed:!1,internalType:"bytes32",name:"domainSeparator",type:"bytes32"},{indexed:!1,internalType:"contract ISafeSignatureVerifier",name:"verifier",type:"address"}],name:"AddedDomainVerifier",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"contract Safe",name:"safe",type:"address"},{indexed:!1,internalType:"bytes4",name:"interfaceId",type:"bytes4"}],name:"AddedInterface",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"contract Safe",name:"safe",type:"address"},{indexed:!1,internalType:"bytes4",name:"selector",type:"bytes4"},{indexed:!1,internalType:"bytes32",name:"method",type:"bytes32"}],name:"AddedSafeMethod",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"contract Safe",name:"safe",type:"address"},{indexed:!1,internalType:"bytes32",name:"domainSeparator",type:"bytes32"},{indexed:!1,internalType:"contract ISafeSignatureVerifier",name:"oldVerifier",type:"address"},{indexed:!1,internalType:"contract ISafeSignatureVerifier",name:"newVerifier",type:"address"}],name:"ChangedDomainVerifier",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"contract Safe",name:"safe",type:"address"},{indexed:!1,internalType:"bytes4",name:"selector",type:"bytes4"},{indexed:!1,internalType:"bytes32",name:"oldMethod",type:"bytes32"},{indexed:!1,internalType:"bytes32",name:"newMethod",type:"bytes32"}],name:"ChangedSafeMethod",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"contract Safe",name:"safe",type:"address"},{indexed:!1,internalType:"bytes32",name:"domainSeparator",type:"bytes32"}],name:"RemovedDomainVerifier",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"contract Safe",name:"safe",type:"address"},{indexed:!1,internalType:"bytes4",name:"interfaceId",type:"bytes4"}],name:"RemovedInterface",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"contract Safe",name:"safe",type:"address"},{indexed:!1,internalType:"bytes4",name:"selector",type:"bytes4"}],name:"RemovedSafeMethod",type:"event"},{stateMutability:"nonpayable",type:"fallback"},{inputs:[{internalType:"contract Safe",name:"",type:"address"},{internalType:"bytes32",name:"",type:"bytes32"}],name:"domainVerifiers",outputs:[{internalType:"contract ISafeSignatureVerifier",name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"bytes32",name:"_hash",type:"bytes32"},{internalType:"bytes",name:"signature",type:"bytes"}],name:"isValidSignature",outputs:[{internalType:"bytes4",name:"magic",type:"bytes4"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"",type:"address"},{internalType:"address",name:"",type:"address"},{internalType:"uint256[]",name:"",type:"uint256[]"},{internalType:"uint256[]",name:"",type:"uint256[]"},{internalType:"bytes",name:"",type:"bytes"}],name:"onERC1155BatchReceived",outputs:[{internalType:"bytes4",name:"",type:"bytes4"}],stateMutability:"pure",type:"function"},{inputs:[{internalType:"address",name:"",type:"address"},{internalType:"address",name:"",type:"address"},{internalType:"uint256",name:"",type:"uint256"},{internalType:"uint256",name:"",type:"uint256"},{internalType:"bytes",name:"",type:"bytes"}],name:"onERC1155Received",outputs:[{internalType:"bytes4",name:"",type:"bytes4"}],stateMutability:"pure",type:"function"},{inputs:[{internalType:"address",name:"",type:"address"},{internalType:"address",name:"",type:"address"},{internalType:"uint256",name:"",type:"uint256"},{internalType:"bytes",name:"",type:"bytes"}],name:"onERC721Received",outputs:[{internalType:"bytes4",name:"",type:"bytes4"}],stateMutability:"pure",type:"function"},{inputs:[{internalType:"contract Safe",name:"",type:"address"},{internalType:"bytes4",name:"",type:"bytes4"}],name:"safeInterfaces",outputs:[{internalType:"bool",name:"",type:"bool"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"contract Safe",name:"",type:"address"},{internalType:"bytes4",name:"",type:"bytes4"}],name:"safeMethods",outputs:[{internalType:"bytes32",name:"",type:"bytes32"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"bytes32",name:"domainSeparator",type:"bytes32"},{internalType:"contract ISafeSignatureVerifier",name:"newVerifier",type:"address"}],name:"setDomainVerifier",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"bytes4",name:"selector",type:"bytes4"},{internalType:"bytes32",name:"newMethod",type:"bytes32"}],name:"setSafeMethod",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"bytes4",name:"interfaceId",type:"bytes4"},{internalType:"bool",name:"supported",type:"bool"}],name:"setSupportedInterface",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"bytes4",name:"_interfaceId",type:"bytes4"},{internalType:"bytes32[]",name:"handlerWithSelectors",type:"bytes32[]"}],name:"setSupportedInterfaceBatch",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"bytes4",name:"interfaceId",type:"bytes4"}],name:"supportsInterface",outputs:[{internalType:"bool",name:"",type:"bool"}],stateMutability:"view",type:"function"}];class be{static createInterface(){return new a.Interface(fe)}static connect(e,t){return new i(e,fe,t)}}be.abi=fe;const Ie=function(e){try{return Promise.resolve(e.getBlock("latest")).then(function(e){return{blockNumber:e.number,blockTimestamp:e.timestamp}})}catch(e){return Promise.reject(e)}},Ee=function(e,t,n,r){try{const a=be.connect(N[n],r);return Promise.resolve(a.callStatic.domainVerifiers(e,t))}catch(e){return Promise.reject(e)}},Ae=["erc20","0x5a28e9363bb942b639270062aa6bb295f434bcdfc42c97267bf003f272060dc9"],Oe=["external","0xabee3b73373acd583a130924aad6dc38cfdc44ba0555ba94ce2ff63980ea0632"],ve=["internal","0x4ac99ace14ee0a5ef932dc609df0943ab7ac16b7583634612f8dc35a4289a6ce"],Pe=["sell","0xf3b277728b3fee749481eb3e0b3b48980dbbab78658fc419025cb16eee346775"],ge=["buy","0x6ed88e868af0a1983e3886d5f3e95a2fafbd6c3450bc229e27342283dc429ccc"],Se=["tuple(address handler, bytes32 salt, bytes staticInput)"],Ne=(e,t)=>`${t}@${e}`;function _e(e,t){return e===N[t]}function Re(e,t){return e===_[t]}function we(e,t){return be.createInterface().encodeFunctionData("setDomainVerifier",[e,t])}function Ce(e){return a.defaultAbiCoder.encode(Se,[e])}function De(e){const{handler:t,salt:n,staticInput:r}=a.defaultAbiCoder.decode(Se,e)[0];return{handler:t,salt:n,staticInput:r}}function Me(e,t){try{a.defaultAbiCoder.encode(e,t)}catch(e){return!1}return!0}function Ue(e){return new Date(1e3*e).toISOString()}function xe(e){if(Ae.includes(e))return p.ERC20;if(Oe.includes(e))return p.EXTERNAL;if(ve.includes(e))return p.INTERNAL;throw new Error(`Unknown balance type: ${e}`)}function Le(e){if(Pe.includes(e))return d.SELL;if(ge.includes(e))return d.BUY;throw new Error(`Unknown kind: ${e}`)}function ke(e){const{sellToken:t,sellAmount:n,buyToken:r,buyAmount:a,buyTokenBalance:i,sellTokenBalance:s,feeAmount:o,kind:u,receiver:p,validTo:d,partiallyFillable:l,appData:c}=e;return{sellToken:t,sellAmount:n,buyToken:r,buyAmount:a,feeAmount:o,receiver:p,partiallyFillable:l,appData:c,validTo:Number(d),kind:Le(u.toString()),sellTokenBalance:xe(s.toString()),buyTokenBalance:xe(i.toString())}}let Be,Ve;function Fe(){return Be||(Be=he.createInterface()),Be}function Ge(e,t){return Ve||(Ve=he.connect(_[e],t)),Ve}class $e{constructor(e){this.handler=void 0,this.salt=void 0,this.data=void 0,this.staticInput=void 0,this.hasOffChainInput=void 0;const{handler:t,salt:n=a.keccak256(a.randomBytes(32)),data:r,hasOffChainInput:i=!1}=e;if(!s.utils.isAddress(t))throw new Error(`Invalid handler: ${t}`);if(!s.utils.isHexString(n)||32!==s.utils.hexDataLength(n))throw new Error(`Invalid salt: ${n}`);this.handler=t,this.salt=n,this.data=r,this.staticInput=this.transformDataToStruct(r),this.hasOffChainInput=i}get context(){}assertIsValid(){const e=this.isValid();if(!e.isValid)throw new Error(`Invalid order: ${e.reason}`)}get createCalldata(){this.assertIsValid();const e=this.context,t=Fe(),n={handler:this.handler,salt:this.salt,staticInput:this.encodeStaticInput()};if(e){const r=e.factoryArgs?a.defaultAbiCoder.encode(e.factoryArgs.argsType,e.factoryArgs.args):"0x";return t.encodeFunctionData("createWithContext",[n,e.address,r,!0])}return t.encodeFunctionData("create",[n,!0])}get removeCalldata(){return this.assertIsValid(),Fe().encodeFunctionData("remove",[this.id])}get id(){return a.keccak256(this.serialize())}get ctx(){return this.isSingleOrder?this.id:o.HashZero}get leaf(){return{handler:this.handler,salt:this.salt,staticInput:this.encodeStaticInput()}}static leafToId(e){return a.keccak256(Ce(e))}get offChainInput(){return"0x"}encodeStaticInputHelper(e,t){return a.defaultAbiCoder.encode(e,[t])}poll(e){try{const t=this,{chainId:n,owner:r,provider:a,orderBookApi:i}=e,s=Ge(n,a);return Promise.resolve(function(a,o){try{var u=function(){const a=t.isValid();return a.isValid?Promise.resolve(t.pollValidate(e)).then(function(a){return a||Promise.resolve(t.isAuthorized(e)).then(function(a){return a?Promise.resolve(s.getTradeableOrderWithSignature(r,t.leaf,t.offChainInput,[])).then(function([a,s]){return Promise.resolve(function(e,t,n){try{return Promise.resolve(import("@cowprotocol/contracts")).then(function({computeOrderUid:r}){return Promise.resolve(ce.getDomain(e)).then(function(e){return r(e,n,t)})})}catch(e){return Promise.reject(e)}}(n,r,ke(a))).then(function(n){return Promise.resolve(i.getOrder(n).then(()=>!0).catch(()=>!1)).then(function(r){let i;function o(e){return i?e:{result:me.SUCCESS,order:a,signature:s}}const u=function(){if(r)return Promise.resolve(t.handlePollFailedAlreadyPresent(n,a,e)).then(function(e){return e?(i=1,e):(i=1,{result:me.TRY_NEXT_BLOCK,reason:"Order already in orderbook"})})}();return u&&u.then?u.then(o):o(u)})})}):{result:me.DONT_TRY_AGAIN,reason:`NotAuthorized: Order ${t.id} is not authorized for ${r} on chain ${n}`}})}):{result:me.DONT_TRY_AGAIN,reason:`InvalidConditionalOrder. Reason: ${a.reason}`}}()}catch(e){return o(e)}return u&&u.then?u.then(void 0,o):u}(0,function(e){return{result:me.UNEXPECTED_ERROR,error:e}}))}catch(e){return Promise.reject(e)}}isAuthorized(e){const{chainId:t,owner:n,provider:r}=e;return Ge(t,r).callStatic.singleOrders(n,this.id)}cabinet(e){const{chainId:t,owner:n,provider:r}=e;return Ge(t,r).callStatic.cabinet(n,this.ctx)}static deserializeHelper(e,t,n,r){try{const{handler:i,salt:s,staticInput:o}=De(e);if(i!=t)throw new Error("HandlerMismatch");const[u]=a.defaultAbiCoder.decode(n,o);return r(u,s)}catch(e){throw"HandlerMismatch"===e.message?e:new Error("InvalidSerializedConditionalOrder")}}}const We=["address","bytes32","bytes"],je=["tuple(bytes32[] proof, tuple(address handler, bytes32 salt, bytes staticInput) params)[]"];class He{constructor(e,t,n,r=ye.PRIVATE){if(this.chain=void 0,this.location=void 0,this.orders={},this.tree=void 0,this.ctx=void 0,this.chain=e,this.location=r,t&&0===Object.keys(t).length)throw new Error("orders must have non-zero length");if(t&&!n||!t&&n)throw new Error("orders cannot have undefined root");for(const e in t)if(t.hasOwnProperty(e)){const n=t[e];if(!He.orderTypeRegistry.hasOwnProperty(n.orderType))throw new Error(`Unknown order type: ${n.orderType}`)}if(t&&(this.orders=t,this.getOrGenerateTree().root!==n))throw new Error("root mismatch")}static fromJSON(e){const{chain:t,orders:n,root:r,location:a}=JSON.parse(e,(e,t)=>{if("orders"===e&&"object"==typeof t&&null!==t){const e={};for(const n in t)if(t.hasOwnProperty(n)){const{orderType:r,...a}=t[n];if(!He.orderTypeRegistry.hasOwnProperty(r))throw new Error(`Unknown order type: ${r}`);e[n]=new(0,He.orderTypeRegistry[r])(a)}return e}return"object"==typeof t&&null!==t&&t.hasOwnProperty("type")&&t.hasOwnProperty("hex")&&"BigNumber"===t.type?u.from(t):t}),i=new He(t,n,r);return i.location=a,i}toJSON(){const e=this.getOrGenerateTree().root;return JSON.stringify({...this,root:e},(e,t)=>{if("tree"!==e){if("object"==typeof t&&null!==t&&"orderType"in t){const e=t;return{...e,orderType:e.orderType}}return t}})}add(e){e.assertIsValid(),this.orders[e.id]=e,this.reset()}remove(e){delete this.orders[e],this.reset()}update(e,t){const n=t(this.orders[e],this.ctx);delete this.orders[e],this.orders[n.id]=n,this.reset()}getById(e){return this.orders[e]}getByIndex(e){return this.orders[this.orderIds[e]]}get orderIds(){return Object.keys(this.orders)}get root(){return this.getOrGenerateTree().root}getOrGenerateTree(){return this.tree||(this.tree=l.of(Object.values(this.orders).map(e=>[...Object.values(e.leaf)]),We)),this.tree}static decodeFromJSON(e){return JSON.parse(e)}prepareProofStruct(e,t,n){try{const r=this;void 0===e&&(e=r.location);const i=function(){try{switch(e){case ye.PRIVATE:return Promise.resolve("0x");case ye.EMITTED:return Promise.resolve(r.encodeToABI(t));case ye.SWARM:case ye.WAKU:case ye.IPFS:if(!n)throw new Error("Must provide an uploader function");return Promise.resolve(function(e,a){try{var i=Promise.resolve(n(r.encodeToJSON(t)))}catch(e){return a(e)}return i&&i.then?i.then(void 0,a):i}(0,function(t){throw new Error(`Error uploading to decentralized storage ${e}: ${t}`)}));default:throw new Error("Unsupported location")}}catch(e){return Promise.reject(e)}};return Promise.resolve(i().then(t=>{try{return a.hexlify(a.arrayify(t)),r.location=e,{location:e,data:t}}catch(e){throw new Error("data returned by uploader is invalid")}}).catch(e=>{throw new Error(`Error preparing proof struct: ${e}`)}))}catch(e){return Promise.reject(e)}}static poll(e,t,n,r,a){try{function i(n){return Promise.resolve(s.getTradeableOrderWithSignature(e,t.params,n,t.proof))}const s=Ge(n,r);return Promise.resolve(a?Promise.resolve(a(e,t.params)).then(i):i("0x"))}catch(o){return Promise.reject(o)}}dumpProofs(e){return this.encodeToJSON(e)}dumpProofsAndParams(e){return this.getProofs(e)}getProofs(e){return[...this.getOrGenerateTree().entries()].map(([t,n])=>e&&e(n)||void 0===e?{idx:t,value:n}:void 0).reduce((e,t)=>{if(t){const n={handler:t.value[0],salt:t.value[1],staticInput:t.value[2]};e.push({proof:this.getOrGenerateTree().getProof(t.idx),params:n})}return e},[])}encodeToABI(e){return a.defaultAbiCoder.encode(je,[this.getProofs(e)])}encodeToJSON(e){return JSON.stringify(this.getProofs(e))}reset(){this.tree=void 0}static registerOrderType(e,t){He.orderTypeRegistry[e]=t}static resetOrderTypeRegistry(){He.orderTypeRegistry={}}}He.orderTypeRegistry={};class Ye{constructor(e){this.knownOrderTypes=void 0,this.knownOrderTypes=e}fromParams(e){const{handler:t}=e,n=this.knownOrderTypes[t];if(n)return n(e)}}const Ze="0x6cF1e9cA41f7611dEf408122793c358a3d11E5a5",Ke="0x52eD56Da04309Aca4c3FECC595298d80C2f16BAc",Qe=u.from(2).pow(32).sub(1),Xe=u.from(31536e3),qe=["tuple(address sellToken, address buyToken, address receiver, uint256 partSellAmount, uint256 minPartLimit, uint256 t0, uint256 n, uint256 t, uint256 span, bytes32 appData)"];var ze,Je;!function(e){e.AUTO="AUTO",e.LIMIT_DURATION="LIMIT_DURATION"}(ze||(ze={})),function(e){e.AT_MINING_TIME="AT_MINING_TIME",e.AT_EPOCH="AT_EPOCH"}(Je||(Je={}));const et={startType:Je.AT_MINING_TIME},tt={durationType:ze.AUTO};class nt extends $e{constructor(e){const{handler:t,salt:n,data:r,hasOffChainInput:a}=e;if(t!==Ze)throw new Error(`InvalidHandler: Expected: ${Ze}, provided: ${t}`);super({handler:Ze,salt:n,data:r,hasOffChainInput:a}),this.isSingleOrder=!0}static fromData(e,t){return new nt({handler:Ze,data:e,salt:t})}static fromParams(e){return nt.deserialize(Ce(e))}get context(){return this.staticInput.t0.gt(0)?super.context:{address:Ke,factoryArgs:void 0}}get orderType(){return"twap"}isValid(){const e=(()=>{const{sellToken:e,sellAmount:t,buyToken:n,buyAmount:r,startTime:a=et,numberOfParts:i,timeBetweenParts:s,durationOfPart:u=tt}=this.data;if(e==n)return"InvalidSameToken";if(e==o.AddressZero||n==o.AddressZero)return"InvalidToken";if(!t.gt(o.Zero))return"InvalidSellAmount";if(!r.gt(o.Zero))return"InvalidMinBuyAmount";if(a.startType===Je.AT_EPOCH){const e=a.epoch;if(!e.gte(o.Zero)||!e.lt(Qe))return"InvalidStartTime"}return i.gt(o.One)&&i.lte(Qe)?s.gt(o.Zero)&&s.lte(Xe)?u.durationType!==ze.LIMIT_DURATION||u.duration.lte(s)?Me(qe,[this.staticInput])?void 0:"InvalidData":"InvalidSpan":"InvalidFrequency":"InvalidNumParts"})();return e?{isValid:!1,reason:e}:{isValid:!0}}startTimestamp(e){try{const t=this,{startTime:n}=t.data;return n?.startType===Je.AT_EPOCH?Promise.resolve(n.epoch.toNumber()):Promise.resolve(t.cabinet(e)).then(function(e){const t=a.defaultAbiCoder.decode(["uint256"],e)[0];if(t.gt(Qe))throw new Error(`Cabinet epoch out of range: ${t.toString()}`);const n=t.toNumber();if(0===n)throw new Error("Cabinet is not set. Required for TWAP orders that start at mining time.");return n})}catch(e){return Promise.reject(e)}}endTimestamp(e){const{numberOfParts:t,timeBetweenParts:n,durationOfPart:r}=this.data;return r&&r.durationType===ze.LIMIT_DURATION?e+t.sub(1).mul(n).add(r.duration).toNumber():e+t.mul(n).toNumber()}pollValidate(e){try{const t=this;return Promise.resolve(Ie(e.provider)).then(function(n){const{blockInfo:r=n}=e,{blockTimestamp:a}=r;return function(n,r){try{var i=Promise.resolve(t.startTimestamp(e)).then(function(e){if(e>a)return{result:me.TRY_AT_EPOCH,epoch:e,reason:`TWAP hasn't started yet. Starts at ${e} (${Ue(e)})`};const n=t.endTimestamp(e);return a>=n?{result:me.DONT_TRY_AGAIN,reason:`TWAP has expired. Expired at ${n} (${Ue(n)})`}:void 0})}catch(e){return r(e)}return i&&i.then?i.then(void 0,r):i}(0,function(e){return e?.message?.includes("Cabinet is not set")?{result:me.DONT_TRY_AGAIN,reason:`${e?.message}. User likely removed the order.`}:e?.message?.includes("Cabinet epoch out of range")?{result:me.DONT_TRY_AGAIN,reason:`${e?.message}`}:{result:me.UNEXPECTED_ERROR,reason:`Unexpected error: ${e.message}`,error:e}})})}catch(e){return Promise.reject(e)}}handlePollFailedAlreadyPresent(e,t,n){try{const e=this;return Promise.resolve(Ie(n.provider)).then(function(t){const{blockInfo:r=t}=n,{blockTimestamp:a}=r,i=e.data.timeBetweenParts.toNumber(),{numberOfParts:s}=e.data;return Promise.resolve(e.startTimestamp(n)).then(function(e){if(a<e)return{result:me.UNEXPECTED_ERROR,reason:`TWAP part hash't started. First TWAP part start at ${e} (${Ue(e)})`,error:void 0};const t=s.mul(i).add(e).toNumber();if(a>=t)return{result:me.UNEXPECTED_ERROR,reason:`TWAP is expired. Expired at ${t} (${Ue(t)})`,error:void 0};const n=Math.floor((a-e)/i);if(n===s.toNumber()-1)return{result:me.DONT_TRY_AGAIN,reason:`Current active TWAP part (${n+1}/${s}) is already in the Order Book. This was the last TWAP part, no more orders need to be placed`};const r=e+(n+1)*i;return{result:me.TRY_AT_EPOCH,epoch:r,reason:`Current active TWAP part (${n+1}/${s}) is already in the Order Book. TWAP part ${n+2} doesn't start until ${r} (${Ue(r)})`}})})}catch(e){return Promise.reject(e)}}serialize(){return Ce(this.leaf)}encodeStaticInput(){return super.encodeStaticInputHelper(qe,this.staticInput)}static deserialize(e){return super.deserializeHelper(e,Ze,qe,(e,t)=>new nt({handler:Ze,salt:t,data:at(e)}))}toString(){const{sellAmount:e,sellToken:t,buyAmount:n,buyToken:r,numberOfParts:a,startTime:i=et,timeBetweenParts:s,durationOfPart:o=tt,receiver:u,appData:p}=this.data,d=i.startType===Je.AT_MINING_TIME?"AT_MINING_TIME":i.epoch.toNumber(),l=o.durationType===ze.AUTO?"AUTO":o.duration.toNumber(),c={sellAmount:e.toString(),sellToken:t,buyAmount:n.toString(),buyToken:r,numberOfParts:a.toString(),startTime:d,timeBetweenParts:s.toNumber(),durationOfPart:l,receiver:u,appData:p};return`${this.orderType} (${this.id}): ${JSON.stringify(c)}`}transformDataToStruct(e){return rt(e)}transformStructToData(e){return at(e)}}function rt(e){const{sellAmount:t,buyAmount:n,numberOfParts:r,startTime:a=et,timeBetweenParts:i,durationOfPart:s=tt,...u}=e,{partSellAmount:p,minPartLimit:d}=r&&!r.isZero()?{partSellAmount:t.div(r),minPartLimit:n.div(r)}:{partSellAmount:o.Zero,minPartLimit:o.Zero};return{partSellAmount:p,minPartLimit:d,t0:a.startType===Je.AT_MINING_TIME?o.Zero:a.epoch,n:r,t:i,span:s.durationType===ze.AUTO?o.Zero:s.duration,...u}}function at(e){const{n:t,partSellAmount:n,minPartLimit:r,t:a,t0:i,span:s,...o}=e,u=s.isZero()?{durationType:ze.AUTO}:{durationType:ze.LIMIT_DURATION,duration:s},p=s.isZero()?{startType:Je.AT_MINING_TIME}:{startType:Je.AT_EPOCH,epoch:i};return{sellAmount:n.mul(t),buyAmount:r.mul(t),startTime:p,numberOfParts:t,timeBetweenParts:a,durationOfPart:u,...o}}const it={[Ze]:e=>nt.fromParams(e)};export{O as ALL_SUPPORTED_CHAIN_IDS,I as BUY_ETH_ADDRESS,F as BuyTokenDestination,A as COMPOSABLE_COW,_ as COMPOSABLE_COW_CONTRACT_ADDRESS,Se as CONDITIONAL_ORDER_PARAMS_ABI,g as COW_PROTOCOL_SETTLEMENT_CONTRACT_ADDRESS,S as COW_PROTOCOL_VAULT_RELAYER_ADDRESS,Ke as CURRENT_BLOCK_TIMESTAMP_FACTORY_ADDRESS,G as CompetitionOrderStatus,$e as ConditionalOrder,Ye as ConditionalOrderFactory,T as CowError,D as DEFAULT_BACKOFF_OPTIONS,it as DEFAULT_CONDITIONAL_ORDER_REGISTRY,m as DEFAULT_COW_API_CONTEXT,f as DEFAULT_IPFS_READ_URI,b as DEFAULT_IPFS_WRITE_URI,M as DEFAULT_LIMITER_OPTIONS,Ne as DEFAULT_TOKEN_FORMATTER,ze as DurationType,y as ENVS_LIST,E as EXTENSIBLE_FALLBACK_HANDLER,N as EXTENSIBLE_FALLBACK_HANDLER_CONTRACT_ADDRESS,$ as EcdsaSigningScheme,Xe as MAX_FREQUENCY,Qe as MAX_UINT32,He as Multiplexer,L as ORDER_BOOK_PROD_CONFIG,k as ORDER_BOOK_STAGING_CONFIG,W as OnchainOrderData,V as OrderBookApi,w as OrderBookApiError,j as OrderCancellationError,H as OrderClass,Y as OrderKind,Z as OrderPostError,K as OrderQuoteSideKindBuy,Q as OrderQuoteSideKindSell,ce as OrderSigningUtils,X as OrderStatus,me as PollResultCode,q as PriceEstimationError,z as PriceQuality,ye as ProofLocation,ue as SUBGRAPH_PROD_CONFIG,pe as SUBGRAPH_STAGING_CONFIG,J as SellTokenSource,ee as SigningScheme,Je as StartTimeValue,de as SubgraphApi,c as SupportedChainId,Ze as TWAP_ADDRESS,nt as Twap,we as createSetDomainVerifierTx,De as decodeParams,Ce as encodeParams,Ue as formatEpoch,ke as fromStructToOrder,Ie as getBlockInfo,Ee as getDomainVerifier,ne as getQuoteAmountsAndCosts,Re as isComposableCow,_e as isExtensibleFallbackHandler,Me as isValidAbi,h as logPrefix,P as mapAddressToSupportedNetworks,v as mapSupportedNetworks,R as request,rt as transformDataToStruct,at as transformStructToData};
|
|
29
29
|
//# sourceMappingURL=index.module.js.map
|