Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

@cowprotocol/cow-sdk

Package Overview
Dependencies
Maintainers
5
Versions
100
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@cowprotocol/cow-sdk - npm Package Compare versions

Comparing version 5.1.0 to 5.2.0

dist/index-a464ca2c.js

6

dist/index.js

@@ -1,2 +0,2 @@

require("cross-fetch/polyfill");var e,t=require("limiter"),r=require("exponential-backoff"),n=require("graphql-request"),a=require("ethers"),o=require("@cowprotocol/contracts"),s=require("@openzeppelin/merkle-tree");function i(e){if(e&&e.__esModule)return e;var t=Object.create(null);return e&&Object.keys(e).forEach(function(r){if("default"!==r){var n=Object.getOwnPropertyDescriptor(e,r);Object.defineProperty(t,r,n.get?n:{enumerable:!0,get:function(){return e[r]}})}}),t.default=e,t}exports.SupportedChainId=void 0,(e=exports.SupportedChainId||(exports.SupportedChainId={}))[e.MAINNET=1]="MAINNET",e[e.GNOSIS_CHAIN=100]="GNOSIS_CHAIN",e[e.SEPOLIA=11155111]="SEPOLIA";const p=["prod","staging"],u={env:"prod",chainId:exports.SupportedChainId.MAINNET};class d extends Error{constructor(e,t){super(e),this.error_code=void 0,this.error_code=t}}const l="0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE",c="0x2f55e8b20D0B9FEFA187AA7d00B6Cbe563605bF5",y="0xfdaFc9d1902f4e0b84f65F49f244b32b31013b74",m=Object.values(exports.SupportedChainId).filter(e=>"number"==typeof e);function T(e){return m.reduce((t,r)=>({...t,[r]:"function"==typeof e?e(r):e}),{})}function h(e){return T(e)}const f=h("0x9008D19f58AAbD9eD0D60971565AA8510560ab41"),b=h("0xC92E8bdf79f0507f65a392b0ab4667716BFE0110"),E=h(c),O=h(y);function I(e){return function(e){const{ethflowData:t}=e;if(!t)return e;const{userValidTo:r}=t,n=e.onchainUser||e.owner,a=l;return{...e,validTo:r,owner:n,sellToken:a}}(function(e){const{executedFeeAmount:t,executedSurplusFee:r}=e,n=BigInt(t||"0"),a=BigInt(r||"0"),o=String(n+a);return{...e,totalFee:o}}(e))}const S=function(e,{path:t,query:n,method:a,body:o},s,i){try{const p={Accept:"application/json","Content-Type":"application/json"},u=`${e}${t}${n?"?"+n:""}`,d={method:a,body:(()=>{if(o)return"string"==typeof o?o:JSON.stringify(o)})(),headers:p};return Promise.resolve(r.backOff(function(){try{return Promise.resolve(s.removeTokens(1)).then(function(){return Promise.resolve(fetch(u,d)).then(function(e){return Promise.resolve(v(e)).then(function(t){return e.status>=200&&e.status<300?t:Promise.reject(new A(e,t))})})})}catch(e){return Promise.reject(e)}},i))}catch(e){return Promise.reject(e)}};class A 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 P=[408,425,429,500,502,503,504],x={numOfAttempts:10,maxDelay:Infinity,jitter:"none",retry:e=>!(e instanceof A)||P.includes(e.response.status)},_={tokensPerInterval:5,interval:"second"},v=function(e){try{let t;const r=function(){if(204!==e.status)return function(r,n){try{var a=function(){const r=e.headers.get("Content-Type");return function(){if(r)return r.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 n(e)}return a&&a.then?a.then(void 0,n):a}(0,function(e){console.error(e)})}();return Promise.resolve(r&&r.then?r.then(function(e){return t?e:void 0}):t?r:void 0)}catch(e){return Promise.reject(e)}},N={[exports.SupportedChainId.MAINNET]:"https://api.cow.fi/mainnet",[exports.SupportedChainId.GNOSIS_CHAIN]:"https://api.cow.fi/xdai",[exports.SupportedChainId.SEPOLIA]:"https://api.cow.fi/sepolia"},C={[exports.SupportedChainId.MAINNET]:"https://barn.api.cow.fi/mainnet",[exports.SupportedChainId.GNOSIS_CHAIN]:"https://barn.api.cow.fi/xdai",[exports.SupportedChainId.SEPOLIA]:"https://barn.api.cow.fi/sepolia"};function R(e){return Object.keys(e).reduce((t,r)=>{const n=e[r];return void 0!==n&&(t[r]=n),t},{})}var g,D,w,L,U,M,F,k,B,V,G,$,W,j,H;exports.BuyTokenDestination=void 0,(g=exports.BuyTokenDestination||(exports.BuyTokenDestination={})).ERC20="erc20",g.INTERNAL="internal",exports.EcdsaSigningScheme=void 0,(D=exports.EcdsaSigningScheme||(exports.EcdsaSigningScheme={})).EIP712="eip712",D.ETHSIGN="ethsign",exports.OnchainOrderData=void 0,(L=(w=exports.OnchainOrderData||(exports.OnchainOrderData={})).placementError||(w.placementError={})).QUOTE_NOT_FOUND="QuoteNotFound",L.VALID_TO_TOO_FAR_IN_FUTURE="ValidToTooFarInFuture",L.PRE_VALIDATION_ERROR="PreValidationError",exports.OrderCancellationError=void 0,(M=(U=exports.OrderCancellationError||(exports.OrderCancellationError={})).errorType||(U.errorType={})).INVALID_SIGNATURE="InvalidSignature",M.WRONG_OWNER="WrongOwner",M.ORDER_NOT_FOUND="OrderNotFound",M.ALREADY_CANCELLED="AlreadyCancelled",M.ORDER_FULLY_EXECUTED="OrderFullyExecuted",M.ORDER_EXPIRED="OrderExpired",M.ON_CHAIN_ORDER="OnChainOrder",exports.OrderClass=void 0,(F=exports.OrderClass||(exports.OrderClass={})).MARKET="market",F.LIMIT="limit",F.LIQUIDITY="liquidity",exports.OrderKind=void 0,(k=exports.OrderKind||(exports.OrderKind={})).BUY="buy",k.SELL="sell",exports.OrderPostError=void 0,function(e){e.DUPLICATED_ORDER="DuplicatedOrder",e.QUOTE_NOT_FOUND="QuoteNotFound",e.INVALID_QUOTE="InvalidQuote",e.MISSING_FROM="MissingFrom",e.WRONG_OWNER="WrongOwner",e.INVALID_EIP1271SIGNATURE="InvalidEip1271Signature",e.INSUFFICIENT_BALANCE="InsufficientBalance",e.INSUFFICIENT_ALLOWANCE="InsufficientAllowance",e.INVALID_SIGNATURE="InvalidSignature",e.INSUFFICIENT_FEE="InsufficientFee",e.SELL_AMOUNT_OVERFLOW="SellAmountOverflow",e.TRANSFER_SIMULATION_FAILED="TransferSimulationFailed",e.ZERO_AMOUNT="ZeroAmount",e.INCOMPATIBLE_SIGNING_SCHEME="IncompatibleSigningScheme",e.TOO_MANY_LIMIT_ORDERS_UNSUPPORTED_BUY_TOKEN_DESTINATION="TooManyLimitOrders UnsupportedBuyTokenDestination",e.UNSUPPORTED_SELL_TOKEN_SOURCE="UnsupportedSellTokenSource",e.UNSUPPORTED_ORDER_TYPE="UnsupportedOrderType",e.INSUFFICIENT_VALID_TO="InsufficientValidTo",e.EXCESSIVE_VALID_TO="ExcessiveValidTo",e.INVALID_NATIVE_SELL_TOKEN="InvalidNativeSellToken",e.SAME_BUY_AND_SELL_TOKEN="SameBuyAndSellToken",e.UNSUPPORTED_TOKEN="UnsupportedToken",e.INVALID_APP_DATA="InvalidAppData",e.APP_DATA_HASH_MISMATCH="AppDataHashMismatch",e.APPDATA_FROM_MISMATCH="AppdataFromMismatch"}((B=exports.OrderPostError||(exports.OrderPostError={})).errorType||(B.errorType={})),exports.OrderQuoteSideKindBuy=void 0,(exports.OrderQuoteSideKindBuy||(exports.OrderQuoteSideKindBuy={})).BUY="buy",exports.OrderQuoteSideKindSell=void 0,(exports.OrderQuoteSideKindSell||(exports.OrderQuoteSideKindSell={})).SELL="sell",exports.OrderStatus=void 0,(V=exports.OrderStatus||(exports.OrderStatus={})).PRESIGNATURE_PENDING="presignaturePending",V.OPEN="open",V.FULFILLED="fulfilled",V.CANCELLED="cancelled",V.EXPIRED="expired",exports.PriceEstimationError=void 0,function(e){e.UNSUPPORTED_TOKEN="UnsupportedToken",e.ZERO_AMOUNT="ZeroAmount",e.UNSUPPORTED_ORDER_TYPE="UnsupportedOrderType"}((G=exports.PriceEstimationError||(exports.PriceEstimationError={})).errorType||(G.errorType={})),exports.PriceQuality=void 0,($=exports.PriceQuality||(exports.PriceQuality={})).FAST="fast",$.OPTIMAL="optimal",$.VERIFIED="verified",exports.ReplaceOrderError=void 0,function(e){e.ALREADY_CANCELLED="AlreadyCancelled",e.ORDER_FULLY_EXECUTED="OrderFullyExecuted",e.ORDER_EXPIRED="OrderExpired",e.ON_CHAIN_ORDER="OnChainOrder",e.DUPLICATED_ORDER="DuplicatedOrder",e.INSUFFICIENT_FEE="InsufficientFee",e.INSUFFICIENT_ALLOWANCE="InsufficientAllowance",e.INSUFFICIENT_BALANCE="InsufficientBalance",e.INSUFFICIENT_VALID_TO="InsufficientValidTo",e.EXCESSIVE_VALID_TO="ExcessiveValidTo",e.INVALID_SIGNATURE="InvalidSignature",e.TRANSFER_SIMULATION_FAILED="TransferSimulationFailed",e.UNSUPPORTED_TOKEN="UnsupportedToken",e.WRONG_OWNER="WrongOwner",e.SAME_BUY_AND_SELL_TOKEN="SameBuyAndSellToken",e.ZERO_AMOUNT="ZeroAmount",e.UNSUPPORTED_BUY_TOKEN_DESTINATION="UnsupportedBuyTokenDestination",e.UNSUPPORTED_SELL_TOKEN_SOURCE="UnsupportedSellTokenSource",e.UNSUPPORTED_ORDER_TYPE="UnsupportedOrderType"}((W=exports.ReplaceOrderError||(exports.ReplaceOrderError={})).errorType||(W.errorType={})),exports.SellTokenSource=void 0,(j=exports.SellTokenSource||(exports.SellTokenSource={})).ERC20="erc20",j.INTERNAL="internal",j.EXTERNAL="external",exports.SigningScheme=void 0,(H=exports.SigningScheme||(exports.SigningScheme={})).EIP712="eip712",H.ETHSIGN="ethsign",H.PRESIGN="presign",H.EIP1271="eip1271";const Y=n.gql`
require("cross-fetch/polyfill");var e,t=require("limiter"),r=require("exponential-backoff"),n=require("graphql-request"),a=require("ethers"),o=require("@cowprotocol/contracts"),s=require("@openzeppelin/merkle-tree");function i(e){if(e&&e.__esModule)return e;var t=Object.create(null);return e&&Object.keys(e).forEach(function(r){if("default"!==r){var n=Object.getOwnPropertyDescriptor(e,r);Object.defineProperty(t,r,n.get?n:{enumerable:!0,get:function(){return e[r]}})}}),t.default=e,t}exports.SupportedChainId=void 0,(e=exports.SupportedChainId||(exports.SupportedChainId={}))[e.MAINNET=1]="MAINNET",e[e.GNOSIS_CHAIN=100]="GNOSIS_CHAIN",e[e.SEPOLIA=11155111]="SEPOLIA";const p=["prod","staging"],u={env:"prod",chainId:exports.SupportedChainId.MAINNET};class d extends Error{constructor(e,t){super(e),this.error_code=void 0,this.error_code=t}}const l="0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE",c="0x2f55e8b20D0B9FEFA187AA7d00B6Cbe563605bF5",y="0xfdaFc9d1902f4e0b84f65F49f244b32b31013b74",m=Object.values(exports.SupportedChainId).filter(e=>"number"==typeof e);function T(e){return m.reduce((t,r)=>({...t,[r]:"function"==typeof e?e(r):e}),{})}function h(e){return T(e)}const f=h("0x9008D19f58AAbD9eD0D60971565AA8510560ab41"),b=h("0xC92E8bdf79f0507f65a392b0ab4667716BFE0110"),O=h(c),I=h(y);function E(e){return function(e){const{ethflowData:t}=e;if(!t)return e;const{userValidTo:r}=t,n=e.onchainUser||e.owner,a=l;return{...e,validTo:r,owner:n,sellToken:a}}(function(e){const{executedFeeAmount:t,executedSurplusFee:r}=e,n=BigInt(t||"0"),a=BigInt(r||"0"),o=String(n+a);return{...e,totalFee:o}}(e))}const S=function(e,{path:t,query:n,method:a,body:o},s,i){try{const p={Accept:"application/json","Content-Type":"application/json"},u=`${e}${t}${n?"?"+n:""}`,d={method:a,body:(()=>{if(o)return"string"==typeof o?o:JSON.stringify(o)})(),headers:p};return Promise.resolve(r.backOff(function(){try{return Promise.resolve(s.removeTokens(1)).then(function(){return Promise.resolve(fetch(u,d)).then(function(e){return Promise.resolve(_(e)).then(function(t){return e.status>=200&&e.status<300?t:Promise.reject(new A(e,t))})})})}catch(e){return Promise.reject(e)}},i))}catch(e){return Promise.reject(e)}};class A 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 P=[408,425,429,500,502,503,504],x={numOfAttempts:10,maxDelay:Infinity,jitter:"none",retry:e=>!(e instanceof A)||P.includes(e.response.status)},v={tokensPerInterval:5,interval:"second"},_=function(e){try{let t;const r=function(){if(204!==e.status)return function(r,n){try{var a=function(){const r=e.headers.get("Content-Type");return function(){if(r)return r.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 n(e)}return a&&a.then?a.then(void 0,n):a}(0,function(e){console.error(e)})}();return Promise.resolve(r&&r.then?r.then(function(e){return t?e:void 0}):t?r:void 0)}catch(e){return Promise.reject(e)}},N={[exports.SupportedChainId.MAINNET]:"https://api.cow.fi/mainnet",[exports.SupportedChainId.GNOSIS_CHAIN]:"https://api.cow.fi/xdai",[exports.SupportedChainId.SEPOLIA]:"https://api.cow.fi/sepolia"},g={[exports.SupportedChainId.MAINNET]:"https://barn.api.cow.fi/mainnet",[exports.SupportedChainId.GNOSIS_CHAIN]:"https://barn.api.cow.fi/xdai",[exports.SupportedChainId.SEPOLIA]:"https://barn.api.cow.fi/sepolia"};function C(e){return Object.keys(e).reduce((t,r)=>{const n=e[r];return void 0!==n&&(t[r]=n),t},{})}var R,D,w,L,U,M,k,B,F,V,G,$,W,j;exports.BuyTokenDestination=void 0,(R=exports.BuyTokenDestination||(exports.BuyTokenDestination={})).ERC20="erc20",R.INTERNAL="internal",exports.EcdsaSigningScheme=void 0,(D=exports.EcdsaSigningScheme||(exports.EcdsaSigningScheme={})).EIP712="eip712",D.ETHSIGN="ethsign",exports.OnchainOrderData=void 0,(L=(w=exports.OnchainOrderData||(exports.OnchainOrderData={})).placementError||(w.placementError={})).QUOTE_NOT_FOUND="QuoteNotFound",L.VALID_TO_TOO_FAR_IN_FUTURE="ValidToTooFarInFuture",L.PRE_VALIDATION_ERROR="PreValidationError",exports.OrderCancellationError=void 0,(M=(U=exports.OrderCancellationError||(exports.OrderCancellationError={})).errorType||(U.errorType={})).INVALID_SIGNATURE="InvalidSignature",M.WRONG_OWNER="WrongOwner",M.ORDER_NOT_FOUND="OrderNotFound",M.ALREADY_CANCELLED="AlreadyCancelled",M.ORDER_FULLY_EXECUTED="OrderFullyExecuted",M.ORDER_EXPIRED="OrderExpired",M.ON_CHAIN_ORDER="OnChainOrder",exports.OrderClass=void 0,(k=exports.OrderClass||(exports.OrderClass={})).MARKET="market",k.LIMIT="limit",k.LIQUIDITY="liquidity",exports.OrderKind=void 0,(B=exports.OrderKind||(exports.OrderKind={})).BUY="buy",B.SELL="sell",exports.OrderPostError=void 0,function(e){e.DUPLICATED_ORDER="DuplicatedOrder",e.QUOTE_NOT_FOUND="QuoteNotFound",e.INVALID_QUOTE="InvalidQuote",e.MISSING_FROM="MissingFrom",e.WRONG_OWNER="WrongOwner",e.INVALID_EIP1271SIGNATURE="InvalidEip1271Signature",e.INSUFFICIENT_BALANCE="InsufficientBalance",e.INSUFFICIENT_ALLOWANCE="InsufficientAllowance",e.INVALID_SIGNATURE="InvalidSignature",e.SELL_AMOUNT_OVERFLOW="SellAmountOverflow",e.TRANSFER_SIMULATION_FAILED="TransferSimulationFailed",e.ZERO_AMOUNT="ZeroAmount",e.INCOMPATIBLE_SIGNING_SCHEME="IncompatibleSigningScheme",e.TOO_MANY_LIMIT_ORDERS="TooManyLimitOrders",e.TOO_MUCH_GAS="TooMuchGas",e.UNSUPPORTED_BUY_TOKEN_DESTINATION="UnsupportedBuyTokenDestination",e.UNSUPPORTED_SELL_TOKEN_SOURCE="UnsupportedSellTokenSource",e.UNSUPPORTED_ORDER_TYPE="UnsupportedOrderType",e.INSUFFICIENT_VALID_TO="InsufficientValidTo",e.EXCESSIVE_VALID_TO="ExcessiveValidTo",e.INVALID_NATIVE_SELL_TOKEN="InvalidNativeSellToken",e.SAME_BUY_AND_SELL_TOKEN="SameBuyAndSellToken",e.UNSUPPORTED_TOKEN="UnsupportedToken",e.INVALID_APP_DATA="InvalidAppData",e.APP_DATA_HASH_MISMATCH="AppDataHashMismatch",e.APPDATA_FROM_MISMATCH="AppdataFromMismatch"}((F=exports.OrderPostError||(exports.OrderPostError={})).errorType||(F.errorType={})),exports.OrderQuoteSideKindBuy=void 0,(exports.OrderQuoteSideKindBuy||(exports.OrderQuoteSideKindBuy={})).BUY="buy",exports.OrderQuoteSideKindSell=void 0,(exports.OrderQuoteSideKindSell||(exports.OrderQuoteSideKindSell={})).SELL="sell",exports.OrderStatus=void 0,(V=exports.OrderStatus||(exports.OrderStatus={})).PRESIGNATURE_PENDING="presignaturePending",V.OPEN="open",V.FULFILLED="fulfilled",V.CANCELLED="cancelled",V.EXPIRED="expired",exports.PriceEstimationError=void 0,function(e){e.UNSUPPORTED_TOKEN="UnsupportedToken",e.ZERO_AMOUNT="ZeroAmount",e.UNSUPPORTED_ORDER_TYPE="UnsupportedOrderType"}((G=exports.PriceEstimationError||(exports.PriceEstimationError={})).errorType||(G.errorType={})),exports.PriceQuality=void 0,($=exports.PriceQuality||(exports.PriceQuality={})).FAST="fast",$.OPTIMAL="optimal",$.VERIFIED="verified",exports.SellTokenSource=void 0,(W=exports.SellTokenSource||(exports.SellTokenSource={})).ERC20="erc20",W.INTERNAL="internal",W.EXTERNAL="external",exports.SigningScheme=void 0,(j=exports.SigningScheme||(exports.SigningScheme={})).EIP712="eip712",j.ETHSIGN="ethsign",j.PRESIGN="presign",j.EIP1271="eip1271";const H=n.gql`
query Totals {

@@ -21,3 +21,3 @@ totals {

}
`,q=n.gql`
`,Y=n.gql`
query LastHoursVolume($hours: Int!) {

@@ -29,3 +29,3 @@ hourlyTotals(orderBy: timestamp, orderDirection: desc, first: $hours) {

}
`,X="https://api.thegraph.com/subgraphs/name/cowprotocol",Q={[exports.SupportedChainId.MAINNET]:X+"/cow",[exports.SupportedChainId.GNOSIS_CHAIN]:X+"/cow-gc",[exports.SupportedChainId.SEPOLIA]:null},Z={[exports.SupportedChainId.MAINNET]:X+"/cow-staging",[exports.SupportedChainId.GNOSIS_CHAIN]:X+"/cow-gc-staging",[exports.SupportedChainId.SEPOLIA]:null},z=()=>Promise.resolve().then(function(){return require("./utils-34cb9a75.js")});class J{static signOrder(e,t,r){try{return Promise.resolve(z()).then(function({signOrder:n}){return n(e,t,r)})}catch(e){return Promise.reject(e)}}static signOrderCancellation(e,t,r){try{return Promise.resolve(z()).then(function({signOrderCancellation:n}){return n(e,t,r)})}catch(e){return Promise.reject(e)}}static signOrderCancellations(e,t,r){try{return Promise.resolve(z()).then(function({signOrderCancellations:n}){return n(e,t,r)})}catch(e){return Promise.reject(e)}}static getDomain(e){try{return Promise.resolve(z()).then(function({getDomain:t}){return t(e)})}catch(e){return Promise.reject(e)}}static getDomainSeparator(e){try{return Promise.resolve(z()).then(function({getDomain:t}){return Promise.resolve(Promise.resolve().then(function(){/*#__PURE__*/return i(require("ethers/lib/utils"))})).then(function({_TypedDataEncoder:r}){return r.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 ee,te;exports.ProofLocation=void 0,(ee=exports.ProofLocation||(exports.ProofLocation={}))[ee.PRIVATE=0]="PRIVATE",ee[ee.EMITTED=1]="EMITTED",ee[ee.SWARM=2]="SWARM",ee[ee.WAKU=3]="WAKU",ee[ee.RESERVED=4]="RESERVED",ee[ee.IPFS=5]="IPFS",exports.PollResultCode=void 0,(te=exports.PollResultCode||(exports.PollResultCode={})).SUCCESS="SUCCESS",te.UNEXPECTED_ERROR="UNEXPECTED_ERROR",te.TRY_NEXT_BLOCK="TRY_NEXT_BLOCK",te.TRY_ON_BLOCK="TRY_ON_BLOCK",te.TRY_AT_EPOCH="TRY_AT_EPOCH",te.DONT_TRY_AGAIN="DONT_TRY_AGAIN";const re=[{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 ne{static createInterface(){return new a.utils.Interface(re)}static connect(e,t){return new a.Contract(e,re,t)}}ne.abi=re;const ae=[{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 oe{static createInterface(){return new a.utils.Interface(ae)}static connect(e,t){return new a.Contract(e,ae,t)}}oe.abi=ae;const se=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=["erc20","0x5a28e9363bb942b639270062aa6bb295f434bcdfc42c97267bf003f272060dc9"],pe=["external","0xabee3b73373acd583a130924aad6dc38cfdc44ba0555ba94ce2ff63980ea0632"],ue=["internal","0x4ac99ace14ee0a5ef932dc609df0943ab7ac16b7583634612f8dc35a4289a6ce"],de=["sell","0xf3b277728b3fee749481eb3e0b3b48980dbbab78658fc419025cb16eee346775"],le=["buy","0x6ed88e868af0a1983e3886d5f3e95a2fafbd6c3450bc229e27342283dc429ccc"],ce=["tuple(address handler, bytes32 salt, bytes staticInput)"];function ye(e){return a.utils.defaultAbiCoder.encode(ce,[e])}function me(e){const{handler:t,salt:r,staticInput:n}=a.utils.defaultAbiCoder.decode(ce,e)[0];return{handler:t,salt:r,staticInput:n}}function Te(e,t){try{a.utils.defaultAbiCoder.encode(e,t)}catch(e){return!1}return!0}function he(e){return new Date(1e3*e).toISOString()}function fe(e){if(ie.includes(e))return o.OrderBalance.ERC20;if(pe.includes(e))return o.OrderBalance.EXTERNAL;if(ue.includes(e))return o.OrderBalance.INTERNAL;throw new Error(`Unknown balance type: ${e}`)}function be(e){if(de.includes(e))return o.OrderKind.SELL;if(le.includes(e))return o.OrderKind.BUY;throw new Error(`Unknown kind: ${e}`)}function Ee(e){const{sellToken:t,sellAmount:r,buyToken:n,buyAmount:a,buyTokenBalance:o,sellTokenBalance:s,feeAmount:i,kind:p,receiver:u,validTo:d,partiallyFillable:l,appData:c}=e;return{sellToken:t,sellAmount:r,buyToken:n,buyAmount:a,feeAmount:i,receiver:u,partiallyFillable:l,appData:c,validTo:Number(d),kind:be(p.toString()),sellTokenBalance:fe(s.toString()),buyTokenBalance:fe(o.toString())}}let Oe,Ie;function Se(){return Oe||(Oe=ne.createInterface()),Oe}function Ae(e,t){return Ie||(Ie=ne.connect(O[e],t)),Ie}class Pe{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:r=a.utils.keccak256(a.utils.randomBytes(32)),data:n,hasOffChainInput:o=!1}=e;if(!a.ethers.utils.isAddress(t))throw new Error(`Invalid handler: ${t}`);if(!a.ethers.utils.isHexString(r)||32!==a.ethers.utils.hexDataLength(r))throw new Error(`Invalid salt: ${r}`);this.handler=t,this.salt=r,this.data=n,this.staticInput=this.transformDataToStruct(n),this.hasOffChainInput=o}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=Se(),r={handler:this.handler,salt:this.salt,staticInput:this.encodeStaticInput()};if(e){const n=e.factoryArgs?a.utils.defaultAbiCoder.encode(e.factoryArgs.argsType,e.factoryArgs.args):"0x";return t.encodeFunctionData("createWithContext",[r,e.address,n,!0])}return t.encodeFunctionData("create",[r,!0])}get removeCalldata(){return this.assertIsValid(),Se().encodeFunctionData("remove",[this.id])}get id(){return a.utils.keccak256(this.serialize())}get ctx(){return this.isSingleOrder?this.id:a.constants.HashZero}get leaf(){return{handler:this.handler,salt:this.salt,staticInput:this.encodeStaticInput()}}static leafToId(e){return a.utils.keccak256(ye(e))}get offChainInput(){return"0x"}encodeStaticInputHelper(e,t){return a.utils.defaultAbiCoder.encode(e,[t])}poll(e){try{const t=this,{chainId:r,owner:n,provider:a,orderBookApi:o}=e,s=Ae(r,a);return Promise.resolve(function(a,p){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(n,t.leaf,t.offChainInput,[])).then(function([a,s]){return Promise.resolve(function(e,t,r){try{return Promise.resolve(Promise.resolve().then(function(){/*#__PURE__*/return i(require("@cowprotocol/contracts"))})).then(function({computeOrderUid:n}){return Promise.resolve(J.getDomain(e)).then(function(e){return n(e,r,t)})})}catch(e){return Promise.reject(e)}}(r,n,Ee(a))).then(function(r){return Promise.resolve(o.getOrder(r).then(()=>!0).catch(()=>!1)).then(function(n){let o;function i(e){return o?e:{result:exports.PollResultCode.SUCCESS,order:a,signature:s}}const p=function(){if(n)return Promise.resolve(t.handlePollFailedAlreadyPresent(r,a,e)).then(function(e){if(e)return o=1,e;const t={result:exports.PollResultCode.TRY_NEXT_BLOCK,reason:"Order already in orderbook"};return o=1,t})}();return p&&p.then?p.then(i):i(p)})})}):{result:exports.PollResultCode.DONT_TRY_AGAIN,reason:`NotAuthorized: Order ${t.id} is not authorized for ${n} on chain ${r}`}})}):{result:exports.PollResultCode.DONT_TRY_AGAIN,reason:`InvalidConditionalOrder. Reason: ${a.reason}`}}()}catch(e){return p(e)}return u&&u.then?u.then(void 0,p):u}(0,function(e){return{result:exports.PollResultCode.UNEXPECTED_ERROR,error:e}}))}catch(e){return Promise.reject(e)}}isAuthorized(e){const{chainId:t,owner:r,provider:n}=e;return Ae(t,n).callStatic.singleOrders(r,this.id)}cabinet(e){const{chainId:t,owner:r,provider:n}=e;return Ae(t,n).callStatic.cabinet(r,this.ctx)}static deserializeHelper(e,t,r,n){try{const{handler:o,salt:s,staticInput:i}=me(e);if(o!=t)throw new Error("HandlerMismatch");const[p]=a.utils.defaultAbiCoder.decode(r,i);return n(p,s)}catch(e){throw"HandlerMismatch"===e.message?e:new Error("InvalidSerializedConditionalOrder")}}}const xe=["address","bytes32","bytes"],_e=["tuple(bytes32[] proof, tuple(address handler, bytes32 salt, bytes staticInput) params)[]"];class ve{constructor(e,t,r,n=exports.ProofLocation.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=n,t&&0===Object.keys(t).length)throw new Error("orders must have non-zero length");if(t&&!r||!t&&r)throw new Error("orders cannot have undefined root");for(const e in t)if(t.hasOwnProperty(e)){const r=t[e];if(!ve.orderTypeRegistry.hasOwnProperty(r.orderType))throw new Error(`Unknown order type: ${r.orderType}`)}if(t&&(this.orders=t,this.getOrGenerateTree().root!==r))throw new Error("root mismatch")}static fromJSON(e){const{chain:t,orders:r,root:n,location:o}=JSON.parse(e,(e,t)=>{if("orders"===e&&"object"==typeof t&&null!==t){const e={};for(const r in t)if(t.hasOwnProperty(r)){const{orderType:n,...a}=t[r];if(!ve.orderTypeRegistry.hasOwnProperty(n))throw new Error(`Unknown order type: ${n}`);e[r]=new(0,ve.orderTypeRegistry[n])(a)}return e}return"object"==typeof t&&null!==t&&t.hasOwnProperty("type")&&t.hasOwnProperty("hex")&&"BigNumber"===t.type?a.BigNumber.from(t):t}),s=new ve(t,r,n);return s.location=o,s}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 r=t(this.orders[e],this.ctx);delete this.orders[e],this.orders[r.id]=r,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=s.StandardMerkleTree.of(Object.values(this.orders).map(e=>[...Object.values(e.leaf)]),xe)),this.tree}static decodeFromJSON(e){return JSON.parse(e)}prepareProofStruct(e,t,r){try{const n=this;void 0===e&&(e=n.location);const o=function(){try{switch(e){case exports.ProofLocation.PRIVATE:return Promise.resolve("0x");case exports.ProofLocation.EMITTED:return Promise.resolve(n.encodeToABI(t));case exports.ProofLocation.SWARM:case exports.ProofLocation.WAKU:case exports.ProofLocation.IPFS:if(!r)throw new Error("Must provide an uploader function");return Promise.resolve(function(e,a){try{var o=Promise.resolve(r(n.encodeToJSON(t)))}catch(e){return a(e)}return o&&o.then?o.then(void 0,a):o}(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(o().then(t=>{try{return a.utils.hexlify(a.utils.arrayify(t)),n.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,r,n,a){try{function o(r){return Promise.resolve(s.getTradeableOrderWithSignature(e,t.params,r,t.proof))}const s=Ae(r,n);return Promise.resolve(a?Promise.resolve(a(e,t.params)).then(o):o("0x"))}catch(i){return Promise.reject(i)}}dumpProofs(e){return this.encodeToJSON(e)}dumpProofsAndParams(e){return this.getProofs(e)}getProofs(e){return[...this.getOrGenerateTree().entries()].map(([t,r])=>e&&e(r)||void 0===e?{idx:t,value:r}:void 0).reduce((e,t)=>{if(t){const r={handler:t.value[0],salt:t.value[1],staticInput:t.value[2]};e.push({proof:this.getOrGenerateTree().getProof(t.idx),params:r})}return e},[])}encodeToABI(e){return a.utils.defaultAbiCoder.encode(_e,[this.getProofs(e)])}encodeToJSON(e){return JSON.stringify(this.getProofs(e))}reset(){this.tree=void 0}static registerOrderType(e,t){ve.orderTypeRegistry[e]=t}static resetOrderTypeRegistry(){ve.orderTypeRegistry={}}}ve.orderTypeRegistry={};const Ne="0x6cF1e9cA41f7611dEf408122793c358a3d11E5a5",Ce="0x52eD56Da04309Aca4c3FECC595298d80C2f16BAc",Re=a.BigNumber.from(2).pow(32).sub(1),ge=a.BigNumber.from(31536e3),De=["tuple(address sellToken, address buyToken, address receiver, uint256 partSellAmount, uint256 minPartLimit, uint256 t0, uint256 n, uint256 t, uint256 span, bytes32 appData)"];var we,Le;exports.DurationType=void 0,(we=exports.DurationType||(exports.DurationType={})).AUTO="AUTO",we.LIMIT_DURATION="LIMIT_DURATION",exports.StartTimeValue=void 0,(Le=exports.StartTimeValue||(exports.StartTimeValue={})).AT_MINING_TIME="AT_MINING_TIME",Le.AT_EPOCH="AT_EPOCH";const Ue={startType:exports.StartTimeValue.AT_MINING_TIME},Me={durationType:exports.DurationType.AUTO};class Fe extends Pe{constructor(e){const{handler:t,salt:r,data:n,hasOffChainInput:a}=e;if(t!==Ne)throw new Error(`InvalidHandler: Expected: ${Ne}, provided: ${t}`);super({handler:Ne,salt:r,data:n,hasOffChainInput:a}),this.isSingleOrder=!0}static fromData(e,t){return new Fe({handler:Ne,data:e,salt:t})}static fromParams(e){return Fe.deserialize(ye(e))}get context(){return this.staticInput.t0.gt(0)?super.context:{address:Ce,factoryArgs:void 0}}get orderType(){return"twap"}isValid(){const e=(()=>{const{sellToken:e,sellAmount:t,buyToken:r,buyAmount:n,startTime:o=Ue,numberOfParts:s,timeBetweenParts:i,durationOfPart:p=Me}=this.data;if(e==r)return"InvalidSameToken";if(e==a.constants.AddressZero||r==a.constants.AddressZero)return"InvalidToken";if(!t.gt(a.constants.Zero))return"InvalidSellAmount";if(!n.gt(a.constants.Zero))return"InvalidMinBuyAmount";if(o.startType===exports.StartTimeValue.AT_EPOCH){const e=o.epoch;if(!e.gte(a.constants.Zero)||!e.lt(Re))return"InvalidStartTime"}return s.gt(a.constants.One)&&s.lte(Re)?i.gt(a.constants.Zero)&&i.lte(ge)?p.durationType!==exports.DurationType.LIMIT_DURATION||p.duration.lte(i)?Te(De,[this.staticInput])?void 0:"InvalidData":"InvalidSpan":"InvalidFrequency":"InvalidNumParts"})();return e?{isValid:!1,reason:e}:{isValid:!0}}startTimestamp(e){try{const t=this,{startTime:r}=t.data;return r?.startType===exports.StartTimeValue.AT_EPOCH?Promise.resolve(r.epoch.toNumber()):Promise.resolve(t.cabinet(e)).then(function(e){const t=a.utils.defaultAbiCoder.decode(["uint256"],e)[0];if(t.gt(Re))throw new Error(`Cabinet epoch out of range: ${t.toString()}`);const r=t.toNumber();if(0===r)throw new Error("Cabinet is not set. Required for TWAP orders that start at mining time.");return r})}catch(e){return Promise.reject(e)}}endTimestamp(e){const{numberOfParts:t,timeBetweenParts:r,durationOfPart:n}=this.data;return n&&n.durationType===exports.DurationType.LIMIT_DURATION?e+t.sub(1).mul(r).add(n.duration).toNumber():e+t.mul(r).toNumber()}pollValidate(e){try{const t=this;return Promise.resolve(se(e.provider)).then(function(r){const{blockInfo:n=r}=e,{blockTimestamp:a}=n;return function(r,n){try{var o=Promise.resolve(t.startTimestamp(e)).then(function(e){if(e>a)return{result:exports.PollResultCode.TRY_AT_EPOCH,epoch:e,reason:`TWAP hasn't started yet. Starts at ${e} (${he(e)})`};const r=t.endTimestamp(e);return a>=r?{result:exports.PollResultCode.DONT_TRY_AGAIN,reason:`TWAP has expired. Expired at ${r} (${he(r)})`}:void 0})}catch(e){return n(e)}return o&&o.then?o.then(void 0,n):o}(0,function(e){return e?.message?.includes("Cabinet is not set")?{result:exports.PollResultCode.DONT_TRY_AGAIN,reason:`${e?.message}. User likely removed the order.`}:e?.message?.includes("Cabinet epoch out of range")?{result:exports.PollResultCode.DONT_TRY_AGAIN,reason:`${e?.message}`}:{result:exports.PollResultCode.UNEXPECTED_ERROR,reason:`Unexpected error: ${e.message}`,error:e}})})}catch(e){return Promise.reject(e)}}handlePollFailedAlreadyPresent(e,t,r){try{const e=this;return Promise.resolve(se(r.provider)).then(function(t){const{blockInfo:n=t}=r,{blockTimestamp:a}=n,o=e.data.timeBetweenParts.toNumber(),{numberOfParts:s}=e.data;return Promise.resolve(e.startTimestamp(r)).then(function(e){if(a<e)return{result:exports.PollResultCode.UNEXPECTED_ERROR,reason:`TWAP part hash't started. First TWAP part start at ${e} (${he(e)})`,error:void 0};const t=s.mul(o).add(e).toNumber();if(a>=t)return{result:exports.PollResultCode.UNEXPECTED_ERROR,reason:`TWAP is expired. Expired at ${t} (${he(t)})`,error:void 0};const r=Math.floor((a-e)/o);if(r===s.toNumber()-1)return{result:exports.PollResultCode.DONT_TRY_AGAIN,reason:`Current active TWAP part (${r+1}/${s}) is already in the Order Book. This was the last TWAP part, no more orders need to be placed`};const n=e+(r+1)*o;return{result:exports.PollResultCode.TRY_AT_EPOCH,epoch:n,reason:`Current active TWAP part (${r+1}/${s}) is already in the Order Book. TWAP part ${r+2} doesn't start until ${n} (${he(n)})`}})})}catch(e){return Promise.reject(e)}}serialize(){return ye(this.leaf)}encodeStaticInput(){return super.encodeStaticInputHelper(De,this.staticInput)}static deserialize(e){return super.deserializeHelper(e,Ne,De,(e,t)=>new Fe({handler:Ne,salt:t,data:Be(e)}))}toString(){const{sellAmount:e,sellToken:t,buyAmount:r,buyToken:n,numberOfParts:a,startTime:o=Ue,timeBetweenParts:s,durationOfPart:i=Me,receiver:p,appData:u}=this.data,d=o.startType===exports.StartTimeValue.AT_MINING_TIME?"AT_MINING_TIME":o.epoch.toNumber(),l=i.durationType===exports.DurationType.AUTO?"AUTO":i.duration.toNumber(),c={sellAmount:e.toString(),sellToken:t,buyAmount:r.toString(),buyToken:n,numberOfParts:a.toString(),startTime:d,timeBetweenParts:s.toNumber(),durationOfPart:l,receiver:p,appData:u};return`${this.orderType} (${this.id}): ${JSON.stringify(c)}`}transformDataToStruct(e){return ke(e)}transformStructToData(e){return Be(e)}}function ke(e){const{sellAmount:t,buyAmount:r,numberOfParts:n,startTime:o=Ue,timeBetweenParts:s,durationOfPart:i=Me,...p}=e,{partSellAmount:u,minPartLimit:d}=n&&!n.isZero()?{partSellAmount:t.div(n),minPartLimit:r.div(n)}:{partSellAmount:a.constants.Zero,minPartLimit:a.constants.Zero},l=i.durationType===exports.DurationType.AUTO?a.constants.Zero:i.duration;return{partSellAmount:u,minPartLimit:d,t0:o.startType===exports.StartTimeValue.AT_MINING_TIME?a.constants.Zero:o.epoch,n:n,t:s,span:l,...p}}function Be(e){const{n:t,partSellAmount:r,minPartLimit:n,t:a,t0:o,span:s,...i}=e,p=s.isZero()?{durationType:exports.DurationType.AUTO}:{durationType:exports.DurationType.LIMIT_DURATION,duration:s},u=s.isZero()?{startType:exports.StartTimeValue.AT_MINING_TIME}:{startType:exports.StartTimeValue.AT_EPOCH,epoch:o};return{sellAmount:r.mul(t),buyAmount:n.mul(t),startTime:u,numberOfParts:t,timeBetweenParts:a,durationOfPart:p,...i}}const Ve={[Ne]:e=>Fe.fromParams(e)};exports.ALL_SUPPORTED_CHAIN_IDS=m,exports.BUY_ETH_ADDRESS=l,exports.COMPOSABLE_COW=y,exports.COMPOSABLE_COW_CONTRACT_ADDRESS=O,exports.CONDITIONAL_ORDER_PARAMS_ABI=ce,exports.COW_PROTOCOL_SETTLEMENT_CONTRACT_ADDRESS=f,exports.COW_PROTOCOL_VAULT_RELAYER_ADDRESS=b,exports.CURRENT_BLOCK_TIMESTAMP_FACTORY_ADDRESS=Ce,exports.ConditionalOrder=Pe,exports.ConditionalOrderFactory=class{constructor(e){this.knownOrderTypes=void 0,this.knownOrderTypes=e}fromParams(e){const{handler:t}=e,r=this.knownOrderTypes[t];if(r)return r(e)}},exports.CowError=d,exports.DEFAULT_BACKOFF_OPTIONS=x,exports.DEFAULT_CONDITIONAL_ORDER_REGISTRY=Ve,exports.DEFAULT_COW_API_CONTEXT=u,exports.DEFAULT_IPFS_READ_URI="https://gnosis.mypinata.cloud/ipfs",exports.DEFAULT_IPFS_WRITE_URI="https://api.pinata.cloud",exports.DEFAULT_LIMITER_OPTIONS=_,exports.DEFAULT_TOKEN_FORMATTER=(e,t)=>`${t}@${e}`,exports.ENVS_LIST=p,exports.EXTENSIBLE_FALLBACK_HANDLER=c,exports.EXTENSIBLE_FALLBACK_HANDLER_CONTRACT_ADDRESS=E,exports.MAX_FREQUENCY=ge,exports.MAX_UINT32=Re,exports.Multiplexer=ve,exports.ORDER_BOOK_PROD_CONFIG=N,exports.ORDER_BOOK_STAGING_CONFIG=C,exports.OrderBookApi=class{constructor(e={}){this.context=void 0,this.rateLimiter=void 0,this.context={...u,...e},this.rateLimiter=new t.RateLimiter(e.limiterOpts||_)}getVersion(e={}){return this.fetch({path:"/api/v1/version",method:"GET"},e)}getTrades(e,t={}){if(e.owner&&e.orderUid)return Promise.reject(new d("Cannot specify both owner and orderId"));if(!e.owner&&!e.orderUid)return Promise.reject(new d("Must specify either owner or orderId"));const r=new URLSearchParams(R(e));return this.fetch({path:"/api/v1/trades",method:"GET",query:r},t)}getOrders({owner:e,offset:t=0,limit:r=1e3},n={}){const a=new URLSearchParams(R({offset:t.toString(),limit:r.toString()}));return this.fetch({path:`/api/v1/account/${e}/orders`,method:"GET",query:a},n).then(e=>e.map(I))}getTxOrders(e,t={}){return this.fetch({path:`/api/v1/transactions/${e}/orders`,method:"GET"},t).then(e=>e.map(I))}getOrder(e,t={}){return this.fetch({path:`/api/v1/orders/${e}`,method:"GET"},t).then(e=>I(e))}getOrderMultiEnv(e,t={}){const{env:r}=this.getContextWithOverride(t),n=p.filter(e=>e!==r);let a=0;const o=r=>{const s=n[a];return r instanceof A&&404===r.response.status&&s?(a++,this.getOrder(e,{...t,env:s}).catch(o)):Promise.reject(r)};return this.getOrder(e,{...t,env:r}).catch(o)}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,r={}){return this.fetch({path:`/api/v1/app_data/${e}`,method:"PUT",body:{fullAppData:t}},r)}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:r,env:n}=this.getContextWithOverride(t);return this.getApiBaseUrls(n)[r]+`/api/v1/orders/${e}`}getContextWithOverride(e={}){return{...this.context,...e}}getApiBaseUrls(e){return this.context.baseUrls?this.context.baseUrls:"prod"===e?N:C}fetch(e,t={}){const{chainId:r,env:n}=this.getContextWithOverride(t),a=this.getApiBaseUrls(n)[r];return S(a,e,this.rateLimiter,this.context.backoffOpts||x)}},exports.OrderBookApiError=A,exports.OrderSigningUtils=J,exports.SUBGRAPH_PROD_CONFIG=Q,exports.SUBGRAPH_STAGING_CONFIG=Z,exports.SubgraphApi=class{constructor(e={}){this.API_NAME="CoW Protocol Subgraph",this.context=void 0,this.context={...u,...e}}getTotals(e={}){try{return Promise.resolve(this.runQuery(Y,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(K,{days:e},t))}catch(e){return Promise.reject(e)}}getLastHoursVolume(e,t={}){try{return Promise.resolve(this.runQuery(q,{hours:e},t))}catch(e){return Promise.reject(e)}}runQuery(e,t=undefined,r={}){try{const a=this,{chainId:o,env:s}=a.getContextWithOverride(r),i=a.getEnvConfigs(s)[o];if(null===i)throw new Error("Unsupported Network. The subgraph API is not available in the Network "+o);return Promise.resolve(function(r,a){try{var o=Promise.resolve(n.request(i,e,t))}catch(e){return a(e)}return o&&o.then?o.then(void 0,a):o}(0,function(r){throw console.error(`[subgraph:${a.API_NAME}]`,r),new d(`Error running query: ${e}. Variables: ${JSON.stringify(t)}. API: ${i}. Inner Error: ${r}`)}))}catch(e){return Promise.reject(e)}}getContextWithOverride(e={}){return{...this.context,...e}}getEnvConfigs(e){return this.context.baseUrls?this.context.baseUrls:"prod"===e?Q:Z}},exports.TWAP_ADDRESS=Ne,exports.Twap=Fe,exports.createSetDomainVerifierTx=function(e,t){return oe.createInterface().encodeFunctionData("setDomainVerifier",[e,t])},exports.decodeParams=me,exports.encodeParams=ye,exports.formatEpoch=he,exports.fromStructToOrder=Ee,exports.getBlockInfo=se,exports.getDomainVerifier=function(e,t,r,n){try{const a=oe.connect(E[r],n);return Promise.resolve(a.callStatic.domainVerifiers(e,t))}catch(e){return Promise.reject(e)}},exports.isComposableCow=function(e,t){return e===O[t]},exports.isExtensibleFallbackHandler=function(e,t){return e===E[t]},exports.isValidAbi=Te,exports.logPrefix="cow-sdk:",exports.mapAddressToSupportedNetworks=h,exports.mapSupportedNetworks=T,exports.request=S,exports.transformDataToStruct=ke,exports.transformStructToData=Be;
`,q="https://api.thegraph.com/subgraphs/name/cowprotocol",Q={[exports.SupportedChainId.MAINNET]:q+"/cow",[exports.SupportedChainId.GNOSIS_CHAIN]:q+"/cow-gc",[exports.SupportedChainId.SEPOLIA]:null},X={[exports.SupportedChainId.MAINNET]:q+"/cow-staging",[exports.SupportedChainId.GNOSIS_CHAIN]:q+"/cow-gc-staging",[exports.SupportedChainId.SEPOLIA]:null},Z=()=>Promise.resolve().then(function(){return require("./utils-61d4384b.js")});class z{static signOrder(e,t,r){try{return Promise.resolve(Z()).then(function({signOrder:n}){return n(e,t,r)})}catch(e){return Promise.reject(e)}}static signOrderCancellation(e,t,r){try{return Promise.resolve(Z()).then(function({signOrderCancellation:n}){return n(e,t,r)})}catch(e){return Promise.reject(e)}}static signOrderCancellations(e,t,r){try{return Promise.resolve(Z()).then(function({signOrderCancellations:n}){return n(e,t,r)})}catch(e){return Promise.reject(e)}}static getDomain(e){try{return Promise.resolve(Z()).then(function({getDomain:t}){return t(e)})}catch(e){return Promise.reject(e)}}static getDomainSeparator(e){try{return Promise.resolve(Z()).then(function({getDomain:t}){return Promise.resolve(Promise.resolve().then(function(){/*#__PURE__*/return i(require("ethers/lib/utils"))})).then(function({_TypedDataEncoder:r}){return r.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 J,ee;exports.ProofLocation=void 0,(J=exports.ProofLocation||(exports.ProofLocation={}))[J.PRIVATE=0]="PRIVATE",J[J.EMITTED=1]="EMITTED",J[J.SWARM=2]="SWARM",J[J.WAKU=3]="WAKU",J[J.RESERVED=4]="RESERVED",J[J.IPFS=5]="IPFS",exports.PollResultCode=void 0,(ee=exports.PollResultCode||(exports.PollResultCode={})).SUCCESS="SUCCESS",ee.UNEXPECTED_ERROR="UNEXPECTED_ERROR",ee.TRY_NEXT_BLOCK="TRY_NEXT_BLOCK",ee.TRY_ON_BLOCK="TRY_ON_BLOCK",ee.TRY_AT_EPOCH="TRY_AT_EPOCH",ee.DONT_TRY_AGAIN="DONT_TRY_AGAIN";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 re{static createInterface(){return new a.utils.Interface(te)}static connect(e,t){return new a.Contract(e,te,t)}}re.abi=te;const ne=[{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 ae{static createInterface(){return new a.utils.Interface(ne)}static connect(e,t){return new a.Contract(e,ne,t)}}ae.abi=ne;const oe=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)}},se=["erc20","0x5a28e9363bb942b639270062aa6bb295f434bcdfc42c97267bf003f272060dc9"],ie=["external","0xabee3b73373acd583a130924aad6dc38cfdc44ba0555ba94ce2ff63980ea0632"],pe=["internal","0x4ac99ace14ee0a5ef932dc609df0943ab7ac16b7583634612f8dc35a4289a6ce"],ue=["sell","0xf3b277728b3fee749481eb3e0b3b48980dbbab78658fc419025cb16eee346775"],de=["buy","0x6ed88e868af0a1983e3886d5f3e95a2fafbd6c3450bc229e27342283dc429ccc"],le=["tuple(address handler, bytes32 salt, bytes staticInput)"];function ce(e){return a.utils.defaultAbiCoder.encode(le,[e])}function ye(e){const{handler:t,salt:r,staticInput:n}=a.utils.defaultAbiCoder.decode(le,e)[0];return{handler:t,salt:r,staticInput:n}}function me(e,t){try{a.utils.defaultAbiCoder.encode(e,t)}catch(e){return!1}return!0}function Te(e){return new Date(1e3*e).toISOString()}function he(e){if(se.includes(e))return o.OrderBalance.ERC20;if(ie.includes(e))return o.OrderBalance.EXTERNAL;if(pe.includes(e))return o.OrderBalance.INTERNAL;throw new Error(`Unknown balance type: ${e}`)}function fe(e){if(ue.includes(e))return o.OrderKind.SELL;if(de.includes(e))return o.OrderKind.BUY;throw new Error(`Unknown kind: ${e}`)}function be(e){const{sellToken:t,sellAmount:r,buyToken:n,buyAmount:a,buyTokenBalance:o,sellTokenBalance:s,feeAmount:i,kind:p,receiver:u,validTo:d,partiallyFillable:l,appData:c}=e;return{sellToken:t,sellAmount:r,buyToken:n,buyAmount:a,feeAmount:i,receiver:u,partiallyFillable:l,appData:c,validTo:Number(d),kind:fe(p.toString()),sellTokenBalance:he(s.toString()),buyTokenBalance:he(o.toString())}}let Oe,Ie;function Ee(){return Oe||(Oe=re.createInterface()),Oe}function Se(e,t){return Ie||(Ie=re.connect(I[e],t)),Ie}class Ae{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:r=a.utils.keccak256(a.utils.randomBytes(32)),data:n,hasOffChainInput:o=!1}=e;if(!a.ethers.utils.isAddress(t))throw new Error(`Invalid handler: ${t}`);if(!a.ethers.utils.isHexString(r)||32!==a.ethers.utils.hexDataLength(r))throw new Error(`Invalid salt: ${r}`);this.handler=t,this.salt=r,this.data=n,this.staticInput=this.transformDataToStruct(n),this.hasOffChainInput=o}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=Ee(),r={handler:this.handler,salt:this.salt,staticInput:this.encodeStaticInput()};if(e){const n=e.factoryArgs?a.utils.defaultAbiCoder.encode(e.factoryArgs.argsType,e.factoryArgs.args):"0x";return t.encodeFunctionData("createWithContext",[r,e.address,n,!0])}return t.encodeFunctionData("create",[r,!0])}get removeCalldata(){return this.assertIsValid(),Ee().encodeFunctionData("remove",[this.id])}get id(){return a.utils.keccak256(this.serialize())}get ctx(){return this.isSingleOrder?this.id:a.constants.HashZero}get leaf(){return{handler:this.handler,salt:this.salt,staticInput:this.encodeStaticInput()}}static leafToId(e){return a.utils.keccak256(ce(e))}get offChainInput(){return"0x"}encodeStaticInputHelper(e,t){return a.utils.defaultAbiCoder.encode(e,[t])}poll(e){try{const t=this,{chainId:r,owner:n,provider:a,orderBookApi:o}=e,s=Se(r,a);return Promise.resolve(function(a,p){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(n,t.leaf,t.offChainInput,[])).then(function([a,s]){return Promise.resolve(function(e,t,r){try{return Promise.resolve(Promise.resolve().then(function(){/*#__PURE__*/return i(require("@cowprotocol/contracts"))})).then(function({computeOrderUid:n}){return Promise.resolve(z.getDomain(e)).then(function(e){return n(e,r,t)})})}catch(e){return Promise.reject(e)}}(r,n,be(a))).then(function(r){return Promise.resolve(o.getOrder(r).then(()=>!0).catch(()=>!1)).then(function(n){let o;function i(e){return o?e:{result:exports.PollResultCode.SUCCESS,order:a,signature:s}}const p=function(){if(n)return Promise.resolve(t.handlePollFailedAlreadyPresent(r,a,e)).then(function(e){if(e)return o=1,e;const t={result:exports.PollResultCode.TRY_NEXT_BLOCK,reason:"Order already in orderbook"};return o=1,t})}();return p&&p.then?p.then(i):i(p)})})}):{result:exports.PollResultCode.DONT_TRY_AGAIN,reason:`NotAuthorized: Order ${t.id} is not authorized for ${n} on chain ${r}`}})}):{result:exports.PollResultCode.DONT_TRY_AGAIN,reason:`InvalidConditionalOrder. Reason: ${a.reason}`}}()}catch(e){return p(e)}return u&&u.then?u.then(void 0,p):u}(0,function(e){return{result:exports.PollResultCode.UNEXPECTED_ERROR,error:e}}))}catch(e){return Promise.reject(e)}}isAuthorized(e){const{chainId:t,owner:r,provider:n}=e;return Se(t,n).callStatic.singleOrders(r,this.id)}cabinet(e){const{chainId:t,owner:r,provider:n}=e;return Se(t,n).callStatic.cabinet(r,this.ctx)}static deserializeHelper(e,t,r,n){try{const{handler:o,salt:s,staticInput:i}=ye(e);if(o!=t)throw new Error("HandlerMismatch");const[p]=a.utils.defaultAbiCoder.decode(r,i);return n(p,s)}catch(e){throw"HandlerMismatch"===e.message?e:new Error("InvalidSerializedConditionalOrder")}}}const Pe=["address","bytes32","bytes"],xe=["tuple(bytes32[] proof, tuple(address handler, bytes32 salt, bytes staticInput) params)[]"];class ve{constructor(e,t,r,n=exports.ProofLocation.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=n,t&&0===Object.keys(t).length)throw new Error("orders must have non-zero length");if(t&&!r||!t&&r)throw new Error("orders cannot have undefined root");for(const e in t)if(t.hasOwnProperty(e)){const r=t[e];if(!ve.orderTypeRegistry.hasOwnProperty(r.orderType))throw new Error(`Unknown order type: ${r.orderType}`)}if(t&&(this.orders=t,this.getOrGenerateTree().root!==r))throw new Error("root mismatch")}static fromJSON(e){const{chain:t,orders:r,root:n,location:o}=JSON.parse(e,(e,t)=>{if("orders"===e&&"object"==typeof t&&null!==t){const e={};for(const r in t)if(t.hasOwnProperty(r)){const{orderType:n,...a}=t[r];if(!ve.orderTypeRegistry.hasOwnProperty(n))throw new Error(`Unknown order type: ${n}`);e[r]=new(0,ve.orderTypeRegistry[n])(a)}return e}return"object"==typeof t&&null!==t&&t.hasOwnProperty("type")&&t.hasOwnProperty("hex")&&"BigNumber"===t.type?a.BigNumber.from(t):t}),s=new ve(t,r,n);return s.location=o,s}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 r=t(this.orders[e],this.ctx);delete this.orders[e],this.orders[r.id]=r,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=s.StandardMerkleTree.of(Object.values(this.orders).map(e=>[...Object.values(e.leaf)]),Pe)),this.tree}static decodeFromJSON(e){return JSON.parse(e)}prepareProofStruct(e,t,r){try{const n=this;void 0===e&&(e=n.location);const o=function(){try{switch(e){case exports.ProofLocation.PRIVATE:return Promise.resolve("0x");case exports.ProofLocation.EMITTED:return Promise.resolve(n.encodeToABI(t));case exports.ProofLocation.SWARM:case exports.ProofLocation.WAKU:case exports.ProofLocation.IPFS:if(!r)throw new Error("Must provide an uploader function");return Promise.resolve(function(e,a){try{var o=Promise.resolve(r(n.encodeToJSON(t)))}catch(e){return a(e)}return o&&o.then?o.then(void 0,a):o}(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(o().then(t=>{try{return a.utils.hexlify(a.utils.arrayify(t)),n.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,r,n,a){try{function o(r){return Promise.resolve(s.getTradeableOrderWithSignature(e,t.params,r,t.proof))}const s=Se(r,n);return Promise.resolve(a?Promise.resolve(a(e,t.params)).then(o):o("0x"))}catch(i){return Promise.reject(i)}}dumpProofs(e){return this.encodeToJSON(e)}dumpProofsAndParams(e){return this.getProofs(e)}getProofs(e){return[...this.getOrGenerateTree().entries()].map(([t,r])=>e&&e(r)||void 0===e?{idx:t,value:r}:void 0).reduce((e,t)=>{if(t){const r={handler:t.value[0],salt:t.value[1],staticInput:t.value[2]};e.push({proof:this.getOrGenerateTree().getProof(t.idx),params:r})}return e},[])}encodeToABI(e){return a.utils.defaultAbiCoder.encode(xe,[this.getProofs(e)])}encodeToJSON(e){return JSON.stringify(this.getProofs(e))}reset(){this.tree=void 0}static registerOrderType(e,t){ve.orderTypeRegistry[e]=t}static resetOrderTypeRegistry(){ve.orderTypeRegistry={}}}ve.orderTypeRegistry={};const _e="0x6cF1e9cA41f7611dEf408122793c358a3d11E5a5",Ne="0x52eD56Da04309Aca4c3FECC595298d80C2f16BAc",ge=a.BigNumber.from(2).pow(32).sub(1),Ce=a.BigNumber.from(31536e3),Re=["tuple(address sellToken, address buyToken, address receiver, uint256 partSellAmount, uint256 minPartLimit, uint256 t0, uint256 n, uint256 t, uint256 span, bytes32 appData)"];var De,we;exports.DurationType=void 0,(De=exports.DurationType||(exports.DurationType={})).AUTO="AUTO",De.LIMIT_DURATION="LIMIT_DURATION",exports.StartTimeValue=void 0,(we=exports.StartTimeValue||(exports.StartTimeValue={})).AT_MINING_TIME="AT_MINING_TIME",we.AT_EPOCH="AT_EPOCH";const Le={startType:exports.StartTimeValue.AT_MINING_TIME},Ue={durationType:exports.DurationType.AUTO};class Me extends Ae{constructor(e){const{handler:t,salt:r,data:n,hasOffChainInput:a}=e;if(t!==_e)throw new Error(`InvalidHandler: Expected: ${_e}, provided: ${t}`);super({handler:_e,salt:r,data:n,hasOffChainInput:a}),this.isSingleOrder=!0}static fromData(e,t){return new Me({handler:_e,data:e,salt:t})}static fromParams(e){return Me.deserialize(ce(e))}get context(){return this.staticInput.t0.gt(0)?super.context:{address:Ne,factoryArgs:void 0}}get orderType(){return"twap"}isValid(){const e=(()=>{const{sellToken:e,sellAmount:t,buyToken:r,buyAmount:n,startTime:o=Le,numberOfParts:s,timeBetweenParts:i,durationOfPart:p=Ue}=this.data;if(e==r)return"InvalidSameToken";if(e==a.constants.AddressZero||r==a.constants.AddressZero)return"InvalidToken";if(!t.gt(a.constants.Zero))return"InvalidSellAmount";if(!n.gt(a.constants.Zero))return"InvalidMinBuyAmount";if(o.startType===exports.StartTimeValue.AT_EPOCH){const e=o.epoch;if(!e.gte(a.constants.Zero)||!e.lt(ge))return"InvalidStartTime"}return s.gt(a.constants.One)&&s.lte(ge)?i.gt(a.constants.Zero)&&i.lte(Ce)?p.durationType!==exports.DurationType.LIMIT_DURATION||p.duration.lte(i)?me(Re,[this.staticInput])?void 0:"InvalidData":"InvalidSpan":"InvalidFrequency":"InvalidNumParts"})();return e?{isValid:!1,reason:e}:{isValid:!0}}startTimestamp(e){try{const t=this,{startTime:r}=t.data;return r?.startType===exports.StartTimeValue.AT_EPOCH?Promise.resolve(r.epoch.toNumber()):Promise.resolve(t.cabinet(e)).then(function(e){const t=a.utils.defaultAbiCoder.decode(["uint256"],e)[0];if(t.gt(ge))throw new Error(`Cabinet epoch out of range: ${t.toString()}`);const r=t.toNumber();if(0===r)throw new Error("Cabinet is not set. Required for TWAP orders that start at mining time.");return r})}catch(e){return Promise.reject(e)}}endTimestamp(e){const{numberOfParts:t,timeBetweenParts:r,durationOfPart:n}=this.data;return n&&n.durationType===exports.DurationType.LIMIT_DURATION?e+t.sub(1).mul(r).add(n.duration).toNumber():e+t.mul(r).toNumber()}pollValidate(e){try{const t=this;return Promise.resolve(oe(e.provider)).then(function(r){const{blockInfo:n=r}=e,{blockTimestamp:a}=n;return function(r,n){try{var o=Promise.resolve(t.startTimestamp(e)).then(function(e){if(e>a)return{result:exports.PollResultCode.TRY_AT_EPOCH,epoch:e,reason:`TWAP hasn't started yet. Starts at ${e} (${Te(e)})`};const r=t.endTimestamp(e);return a>=r?{result:exports.PollResultCode.DONT_TRY_AGAIN,reason:`TWAP has expired. Expired at ${r} (${Te(r)})`}:void 0})}catch(e){return n(e)}return o&&o.then?o.then(void 0,n):o}(0,function(e){return e?.message?.includes("Cabinet is not set")?{result:exports.PollResultCode.DONT_TRY_AGAIN,reason:`${e?.message}. User likely removed the order.`}:e?.message?.includes("Cabinet epoch out of range")?{result:exports.PollResultCode.DONT_TRY_AGAIN,reason:`${e?.message}`}:{result:exports.PollResultCode.UNEXPECTED_ERROR,reason:`Unexpected error: ${e.message}`,error:e}})})}catch(e){return Promise.reject(e)}}handlePollFailedAlreadyPresent(e,t,r){try{const e=this;return Promise.resolve(oe(r.provider)).then(function(t){const{blockInfo:n=t}=r,{blockTimestamp:a}=n,o=e.data.timeBetweenParts.toNumber(),{numberOfParts:s}=e.data;return Promise.resolve(e.startTimestamp(r)).then(function(e){if(a<e)return{result:exports.PollResultCode.UNEXPECTED_ERROR,reason:`TWAP part hash't started. First TWAP part start at ${e} (${Te(e)})`,error:void 0};const t=s.mul(o).add(e).toNumber();if(a>=t)return{result:exports.PollResultCode.UNEXPECTED_ERROR,reason:`TWAP is expired. Expired at ${t} (${Te(t)})`,error:void 0};const r=Math.floor((a-e)/o);if(r===s.toNumber()-1)return{result:exports.PollResultCode.DONT_TRY_AGAIN,reason:`Current active TWAP part (${r+1}/${s}) is already in the Order Book. This was the last TWAP part, no more orders need to be placed`};const n=e+(r+1)*o;return{result:exports.PollResultCode.TRY_AT_EPOCH,epoch:n,reason:`Current active TWAP part (${r+1}/${s}) is already in the Order Book. TWAP part ${r+2} doesn't start until ${n} (${Te(n)})`}})})}catch(e){return Promise.reject(e)}}serialize(){return ce(this.leaf)}encodeStaticInput(){return super.encodeStaticInputHelper(Re,this.staticInput)}static deserialize(e){return super.deserializeHelper(e,_e,Re,(e,t)=>new Me({handler:_e,salt:t,data:Be(e)}))}toString(){const{sellAmount:e,sellToken:t,buyAmount:r,buyToken:n,numberOfParts:a,startTime:o=Le,timeBetweenParts:s,durationOfPart:i=Ue,receiver:p,appData:u}=this.data,d=o.startType===exports.StartTimeValue.AT_MINING_TIME?"AT_MINING_TIME":o.epoch.toNumber(),l=i.durationType===exports.DurationType.AUTO?"AUTO":i.duration.toNumber(),c={sellAmount:e.toString(),sellToken:t,buyAmount:r.toString(),buyToken:n,numberOfParts:a.toString(),startTime:d,timeBetweenParts:s.toNumber(),durationOfPart:l,receiver:p,appData:u};return`${this.orderType} (${this.id}): ${JSON.stringify(c)}`}transformDataToStruct(e){return ke(e)}transformStructToData(e){return Be(e)}}function ke(e){const{sellAmount:t,buyAmount:r,numberOfParts:n,startTime:o=Le,timeBetweenParts:s,durationOfPart:i=Ue,...p}=e,{partSellAmount:u,minPartLimit:d}=n&&!n.isZero()?{partSellAmount:t.div(n),minPartLimit:r.div(n)}:{partSellAmount:a.constants.Zero,minPartLimit:a.constants.Zero},l=i.durationType===exports.DurationType.AUTO?a.constants.Zero:i.duration;return{partSellAmount:u,minPartLimit:d,t0:o.startType===exports.StartTimeValue.AT_MINING_TIME?a.constants.Zero:o.epoch,n:n,t:s,span:l,...p}}function Be(e){const{n:t,partSellAmount:r,minPartLimit:n,t:a,t0:o,span:s,...i}=e,p=s.isZero()?{durationType:exports.DurationType.AUTO}:{durationType:exports.DurationType.LIMIT_DURATION,duration:s},u=s.isZero()?{startType:exports.StartTimeValue.AT_MINING_TIME}:{startType:exports.StartTimeValue.AT_EPOCH,epoch:o};return{sellAmount:r.mul(t),buyAmount:n.mul(t),startTime:u,numberOfParts:t,timeBetweenParts:a,durationOfPart:p,...i}}const Fe={[_e]:e=>Me.fromParams(e)};exports.ALL_SUPPORTED_CHAIN_IDS=m,exports.BUY_ETH_ADDRESS=l,exports.COMPOSABLE_COW=y,exports.COMPOSABLE_COW_CONTRACT_ADDRESS=I,exports.CONDITIONAL_ORDER_PARAMS_ABI=le,exports.COW_PROTOCOL_SETTLEMENT_CONTRACT_ADDRESS=f,exports.COW_PROTOCOL_VAULT_RELAYER_ADDRESS=b,exports.CURRENT_BLOCK_TIMESTAMP_FACTORY_ADDRESS=Ne,exports.ConditionalOrder=Ae,exports.ConditionalOrderFactory=class{constructor(e){this.knownOrderTypes=void 0,this.knownOrderTypes=e}fromParams(e){const{handler:t}=e,r=this.knownOrderTypes[t];if(r)return r(e)}},exports.CowError=d,exports.DEFAULT_BACKOFF_OPTIONS=x,exports.DEFAULT_CONDITIONAL_ORDER_REGISTRY=Fe,exports.DEFAULT_COW_API_CONTEXT=u,exports.DEFAULT_IPFS_READ_URI="https://gnosis.mypinata.cloud/ipfs",exports.DEFAULT_IPFS_WRITE_URI="https://api.pinata.cloud",exports.DEFAULT_LIMITER_OPTIONS=v,exports.DEFAULT_TOKEN_FORMATTER=(e,t)=>`${t}@${e}`,exports.ENVS_LIST=p,exports.EXTENSIBLE_FALLBACK_HANDLER=c,exports.EXTENSIBLE_FALLBACK_HANDLER_CONTRACT_ADDRESS=O,exports.MAX_FREQUENCY=Ce,exports.MAX_UINT32=ge,exports.Multiplexer=ve,exports.ORDER_BOOK_PROD_CONFIG=N,exports.ORDER_BOOK_STAGING_CONFIG=g,exports.OrderBookApi=class{constructor(e={}){this.context=void 0,this.rateLimiter=void 0,this.context={...u,...e},this.rateLimiter=new t.RateLimiter(e.limiterOpts||v)}getVersion(e={}){return this.fetch({path:"/api/v1/version",method:"GET"},e)}getTrades(e,t={}){if(e.owner&&e.orderUid)return Promise.reject(new d("Cannot specify both owner and orderId"));if(!e.owner&&!e.orderUid)return Promise.reject(new d("Must specify either owner or orderId"));const r=new URLSearchParams(C(e));return this.fetch({path:"/api/v1/trades",method:"GET",query:r},t)}getOrders({owner:e,offset:t=0,limit:r=1e3},n={}){const a=new URLSearchParams(C({offset:t.toString(),limit:r.toString()}));return this.fetch({path:`/api/v1/account/${e}/orders`,method:"GET",query:a},n).then(e=>e.map(E))}getTxOrders(e,t={}){return this.fetch({path:`/api/v1/transactions/${e}/orders`,method:"GET"},t).then(e=>e.map(E))}getOrder(e,t={}){return this.fetch({path:`/api/v1/orders/${e}`,method:"GET"},t).then(e=>E(e))}getOrderMultiEnv(e,t={}){const{env:r}=this.getContextWithOverride(t),n=p.filter(e=>e!==r);let a=0;const o=r=>{const s=n[a];return r instanceof A&&404===r.response.status&&s?(a++,this.getOrder(e,{...t,env:s}).catch(o)):Promise.reject(r)};return this.getOrder(e,{...t,env:r}).catch(o)}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,r={}){return this.fetch({path:`/api/v1/app_data/${e}`,method:"PUT",body:{fullAppData:t}},r)}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:r,env:n}=this.getContextWithOverride(t);return this.getApiBaseUrls(n)[r]+`/api/v1/orders/${e}`}getContextWithOverride(e={}){return{...this.context,...e}}getApiBaseUrls(e){return this.context.baseUrls?this.context.baseUrls:"prod"===e?N:g}fetch(e,t={}){const{chainId:r,env:n}=this.getContextWithOverride(t),a=this.getApiBaseUrls(n)[r];return S(a,e,this.rateLimiter,this.context.backoffOpts||x)}},exports.OrderBookApiError=A,exports.OrderSigningUtils=z,exports.SUBGRAPH_PROD_CONFIG=Q,exports.SUBGRAPH_STAGING_CONFIG=X,exports.SubgraphApi=class{constructor(e={}){this.API_NAME="CoW Protocol Subgraph",this.context=void 0,this.context={...u,...e}}getTotals(e={}){try{return Promise.resolve(this.runQuery(H,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(K,{days:e},t))}catch(e){return Promise.reject(e)}}getLastHoursVolume(e,t={}){try{return Promise.resolve(this.runQuery(Y,{hours:e},t))}catch(e){return Promise.reject(e)}}runQuery(e,t=undefined,r={}){try{const a=this,{chainId:o,env:s}=a.getContextWithOverride(r),i=a.getEnvConfigs(s)[o];if(null===i)throw new Error("Unsupported Network. The subgraph API is not available in the Network "+o);return Promise.resolve(function(r,a){try{var o=Promise.resolve(n.request(i,e,t))}catch(e){return a(e)}return o&&o.then?o.then(void 0,a):o}(0,function(r){throw console.error(`[subgraph:${a.API_NAME}]`,r),new d(`Error running query: ${e}. Variables: ${JSON.stringify(t)}. API: ${i}. Inner Error: ${r}`)}))}catch(e){return Promise.reject(e)}}getContextWithOverride(e={}){return{...this.context,...e}}getEnvConfigs(e){return this.context.baseUrls?this.context.baseUrls:"prod"===e?Q:X}},exports.TWAP_ADDRESS=_e,exports.Twap=Me,exports.createSetDomainVerifierTx=function(e,t){return ae.createInterface().encodeFunctionData("setDomainVerifier",[e,t])},exports.decodeParams=ye,exports.encodeParams=ce,exports.formatEpoch=Te,exports.fromStructToOrder=be,exports.getBlockInfo=oe,exports.getDomainVerifier=function(e,t,r,n){try{const a=ae.connect(O[r],n);return Promise.resolve(a.callStatic.domainVerifiers(e,t))}catch(e){return Promise.reject(e)}},exports.isComposableCow=function(e,t){return e===I[t]},exports.isExtensibleFallbackHandler=function(e,t){return e===O[t]},exports.isValidAbi=me,exports.logPrefix="cow-sdk:",exports.mapAddressToSupportedNetworks=h,exports.mapSupportedNetworks=T,exports.request=S,exports.transformDataToStruct=ke,exports.transformStructToData=Be;
//# sourceMappingURL=index.js.map

@@ -1,2 +0,2 @@

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 c}from"@openzeppelin/merkle-tree";var l;!function(e){e[e.MAINNET=1]="MAINNET",e[e.GNOSIS_CHAIN=100]="GNOSIS_CHAIN",e[e.SEPOLIA=11155111]="SEPOLIA"}(l||(l={}));const y=["prod","staging"],m={env:"prod",chainId:l.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",O="0xfdaFc9d1902f4e0b84f65F49f244b32b31013b74",A=Object.values(l).filter(e=>"number"==typeof e);function v(e){return A.reduce((t,n)=>({...t,[n]:"function"==typeof e?e(n):e}),{})}function P(e){return v(e)}const S=P("0x9008D19f58AAbD9eD0D60971565AA8510560ab41"),N=P("0xC92E8bdf79f0507f65a392b0ab4667716BFE0110"),_=P(E),g=P(O);function R(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 C=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(L(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 D=[408,425,429,500,502,503,504],U={numOfAttempts:10,maxDelay:Infinity,jitter:"none",retry:e=>!(e instanceof w)||D.includes(e.response.status)},x={tokensPerInterval:5,interval:"second"},L=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)}},M={[l.MAINNET]:"https://api.cow.fi/mainnet",[l.GNOSIS_CHAIN]:"https://api.cow.fi/xdai",[l.SEPOLIA]:"https://api.cow.fi/sepolia"},k={[l.MAINNET]:"https://barn.api.cow.fi/mainnet",[l.GNOSIS_CHAIN]:"https://barn.api.cow.fi/xdai",[l.SEPOLIA]:"https://barn.api.cow.fi/sepolia"};function F(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||x)}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(F(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(F({offset:t.toString(),limit:n.toString()}));return this.fetch({path:`/api/v1/account/${e}/orders`,method:"GET",query:a},r).then(e=>e.map(R))}getTxOrders(e,t={}){return this.fetch({path:`/api/v1/transactions/${e}/orders`,method:"GET"},t).then(e=>e.map(R))}getOrder(e,t={}){return this.fetch({path:`/api/v1/orders/${e}`,method:"GET"},t).then(e=>R(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 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?M:k}fetch(e,t={}){const{chainId:n,env:r}=this.getContextWithOverride(t),a=this.getApiBaseUrls(r)[n];return C(a,e,this.rateLimiter,this.context.backoffOpts||U)}}var $,G,B,W,j,H,Y,K,Z,X,q,z,J,Q,ee;!function(e){e.ERC20="erc20",e.INTERNAL="internal"}($||($={})),function(e){e.EIP712="eip712",e.ETHSIGN="ethsign"}(G||(G={})),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"}(B||(B={})),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.INSUFFICIENT_FEE="InsufficientFee",t.SELL_AMOUNT_OVERFLOW="SellAmountOverflow",t.TRANSFER_SIMULATION_FAILED="TransferSimulationFailed",t.ZERO_AMOUNT="ZeroAmount",t.INCOMPATIBLE_SIGNING_SCHEME="IncompatibleSigningScheme",t.TOO_MANY_LIMIT_ORDERS_UNSUPPORTED_BUY_TOKEN_DESTINATION="TooManyLimitOrders 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"}(K||(K={})),function(e){e.SELL="sell"}(Z||(Z={})),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){var t;(t=e.errorType||(e.errorType={})).ALREADY_CANCELLED="AlreadyCancelled",t.ORDER_FULLY_EXECUTED="OrderFullyExecuted",t.ORDER_EXPIRED="OrderExpired",t.ON_CHAIN_ORDER="OnChainOrder",t.DUPLICATED_ORDER="DuplicatedOrder",t.INSUFFICIENT_FEE="InsufficientFee",t.INSUFFICIENT_ALLOWANCE="InsufficientAllowance",t.INSUFFICIENT_BALANCE="InsufficientBalance",t.INSUFFICIENT_VALID_TO="InsufficientValidTo",t.EXCESSIVE_VALID_TO="ExcessiveValidTo",t.INVALID_SIGNATURE="InvalidSignature",t.TRANSFER_SIMULATION_FAILED="TransferSimulationFailed",t.UNSUPPORTED_TOKEN="UnsupportedToken",t.WRONG_OWNER="WrongOwner",t.SAME_BUY_AND_SELL_TOKEN="SameBuyAndSellToken",t.ZERO_AMOUNT="ZeroAmount",t.UNSUPPORTED_BUY_TOKEN_DESTINATION="UnsupportedBuyTokenDestination",t.UNSUPPORTED_SELL_TOKEN_SOURCE="UnsupportedSellTokenSource",t.UNSUPPORTED_ORDER_TYPE="UnsupportedOrderType"}(J||(J={})),function(e){e.ERC20="erc20",e.INTERNAL="internal",e.EXTERNAL="external"}(Q||(Q={})),function(e){e.EIP712="eip712",e.ETHSIGN="ethsign",e.PRESIGN="presign",e.EIP1271="eip1271"}(ee||(ee={}));const te=n`
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 c}from"@openzeppelin/merkle-tree";var l;!function(e){e[e.MAINNET=1]="MAINNET",e[e.GNOSIS_CHAIN=100]="GNOSIS_CHAIN",e[e.SEPOLIA=11155111]="SEPOLIA"}(l||(l={}));const y=["prod","staging"],m={env:"prod",chainId:l.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",O="0xfdaFc9d1902f4e0b84f65F49f244b32b31013b74",A=Object.values(l).filter(e=>"number"==typeof e);function v(e){return A.reduce((t,n)=>({...t,[n]:"function"==typeof e?e(n):e}),{})}function P(e){return v(e)}const S=P("0x9008D19f58AAbD9eD0D60971565AA8510560ab41"),g=P("0xC92E8bdf79f0507f65a392b0ab4667716BFE0110"),N=P(E),_=P(O);function w(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 C=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 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 D=[408,425,429,500,502,503,504],x={numOfAttempts:10,maxDelay:Infinity,jitter:"none",retry:e=>!(e instanceof R)||D.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)}},L={[l.MAINNET]:"https://api.cow.fi/mainnet",[l.GNOSIS_CHAIN]:"https://api.cow.fi/xdai",[l.SEPOLIA]:"https://api.cow.fi/sepolia"},k={[l.MAINNET]:"https://barn.api.cow.fi/mainnet",[l.GNOSIS_CHAIN]:"https://barn.api.cow.fi/xdai",[l.SEPOLIA]:"https://barn.api.cow.fi/sepolia"};function V(e){return Object.keys(e).reduce((t,n)=>{const r=e[n];return void 0!==r&&(t[n]=r),t},{})}class ${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(V(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(V({offset:t.toString(),limit:n.toString()}));return this.fetch({path:`/api/v1/account/${e}/orders`,method:"GET",query:a},r).then(e=>e.map(w))}getTxOrders(e,t={}){return this.fetch({path:`/api/v1/transactions/${e}/orders`,method:"GET"},t).then(e=>e.map(w))}getOrder(e,t={}){return this.fetch({path:`/api/v1/orders/${e}`,method:"GET"},t).then(e=>w(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(e,t={}){const{chainId:n,env:r}=this.getContextWithOverride(t),a=this.getApiBaseUrls(r)[n];return C(a,e,this.rateLimiter,this.context.backoffOpts||x)}}var G,F,B,W,j,H,Y,Z,K,X,q,z,J,Q;!function(e){e.ERC20="erc20",e.INTERNAL="internal"}(G||(G={})),function(e){e.EIP712="eip712",e.ETHSIGN="ethsign"}(F||(F={})),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"}(B||(B={})),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=n`
query Totals {

@@ -14,3 +14,3 @@ totals {

}
`,ne=n`
`,te=n`
query LastDaysVolume($days: Int!) {

@@ -22,3 +22,3 @@ dailyTotals(orderBy: timestamp, orderDirection: desc, first: $days) {

}
`,re=n`
`,ne=n`
query LastHoursVolume($hours: Int!) {

@@ -30,3 +30,3 @@ hourlyTotals(orderBy: timestamp, orderDirection: desc, first: $hours) {

}
`,ae="https://api.thegraph.com/subgraphs/name/cowprotocol",ie={[l.MAINNET]:ae+"/cow",[l.GNOSIS_CHAIN]:ae+"/cow-gc",[l.SEPOLIA]:null},se={[l.MAINNET]:ae+"/cow-staging",[l.GNOSIS_CHAIN]:ae+"/cow-gc-staging",[l.SEPOLIA]:null};class oe{constructor(e={}){this.API_NAME="CoW Protocol Subgraph",this.context=void 0,this.context={...m,...e}}getTotals(e={}){try{return Promise.resolve(this.runQuery(te,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(ne,{days:e},t))}catch(e){return Promise.reject(e)}}getLastHoursVolume(e,t={}){try{return Promise.resolve(this.runQuery(re,{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?ie:se}}const ue=()=>import("./utils-48a69310.js");class pe{static signOrder(e,t,n){try{return Promise.resolve(ue()).then(function({signOrder:r}){return r(e,t,n)})}catch(e){return Promise.reject(e)}}static signOrderCancellation(e,t,n){try{return Promise.resolve(ue()).then(function({signOrderCancellation:r}){return r(e,t,n)})}catch(e){return Promise.reject(e)}}static signOrderCancellations(e,t,n){try{return Promise.resolve(ue()).then(function({signOrderCancellations:r}){return r(e,t,n)})}catch(e){return Promise.reject(e)}}static getDomain(e){try{return Promise.resolve(ue()).then(function({getDomain:t}){return t(e)})}catch(e){return Promise.reject(e)}}static getDomainSeparator(e){try{return Promise.resolve(ue()).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 de,ce;!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"}(de||(de={})),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"}(ce||(ce={}));const le=[{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 ye{static createInterface(){return new a.Interface(le)}static connect(e,t){return new i(e,le,t)}}ye.abi=le;const me=[{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 Te{static createInterface(){return new a.Interface(me)}static connect(e,t){return new i(e,me,t)}}Te.abi=me;const he=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)}},fe=function(e,t,n,r){try{const a=Te.connect(_[n],r);return Promise.resolve(a.callStatic.domainVerifiers(e,t))}catch(e){return Promise.reject(e)}},be=["erc20","0x5a28e9363bb942b639270062aa6bb295f434bcdfc42c97267bf003f272060dc9"],Ie=["external","0xabee3b73373acd583a130924aad6dc38cfdc44ba0555ba94ce2ff63980ea0632"],Ee=["internal","0x4ac99ace14ee0a5ef932dc609df0943ab7ac16b7583634612f8dc35a4289a6ce"],Oe=["sell","0xf3b277728b3fee749481eb3e0b3b48980dbbab78658fc419025cb16eee346775"],Ae=["buy","0x6ed88e868af0a1983e3886d5f3e95a2fafbd6c3450bc229e27342283dc429ccc"],ve=["tuple(address handler, bytes32 salt, bytes staticInput)"],Pe=(e,t)=>`${t}@${e}`;function Se(e,t){return e===_[t]}function Ne(e,t){return e===g[t]}function _e(e,t){return Te.createInterface().encodeFunctionData("setDomainVerifier",[e,t])}function ge(e){return a.defaultAbiCoder.encode(ve,[e])}function Re(e){const{handler:t,salt:n,staticInput:r}=a.defaultAbiCoder.decode(ve,e)[0];return{handler:t,salt:n,staticInput:r}}function Ce(e,t){try{a.defaultAbiCoder.encode(e,t)}catch(e){return!1}return!0}function we(e){return new Date(1e3*e).toISOString()}function De(e){if(be.includes(e))return p.ERC20;if(Ie.includes(e))return p.EXTERNAL;if(Ee.includes(e))return p.INTERNAL;throw new Error(`Unknown balance type: ${e}`)}function Ue(e){if(Oe.includes(e))return d.SELL;if(Ae.includes(e))return d.BUY;throw new Error(`Unknown kind: ${e}`)}function xe(e){const{sellToken:t,sellAmount:n,buyToken:r,buyAmount:a,buyTokenBalance:i,sellTokenBalance:s,feeAmount:o,kind:u,receiver:p,validTo:d,partiallyFillable:c,appData:l}=e;return{sellToken:t,sellAmount:n,buyToken:r,buyAmount:a,feeAmount:o,receiver:p,partiallyFillable:c,appData:l,validTo:Number(d),kind:Ue(u.toString()),sellTokenBalance:De(s.toString()),buyTokenBalance:De(i.toString())}}let Le,Me;function ke(){return Le||(Le=ye.createInterface()),Le}function Fe(e,t){return Me||(Me=ye.connect(g[e],t)),Me}class Ve{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=ke(),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(),ke().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(ge(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=Fe(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(pe.getDomain(e)).then(function(e){return r(e,n,t)})})}catch(e){return Promise.reject(e)}}(n,r,xe(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:ce.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:ce.TRY_NEXT_BLOCK,reason:"Order already in orderbook"})})}();return u&&u.then?u.then(o):o(u)})})}):{result:ce.DONT_TRY_AGAIN,reason:`NotAuthorized: Order ${t.id} is not authorized for ${r} on chain ${n}`}})}):{result:ce.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:ce.UNEXPECTED_ERROR,error:e}}))}catch(e){return Promise.reject(e)}}isAuthorized(e){const{chainId:t,owner:n,provider:r}=e;return Fe(t,r).callStatic.singleOrders(n,this.id)}cabinet(e){const{chainId:t,owner:n,provider:r}=e;return Fe(t,r).callStatic.cabinet(n,this.ctx)}static deserializeHelper(e,t,n,r){try{const{handler:i,salt:s,staticInput:o}=Re(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 $e=["address","bytes32","bytes"],Ge=["tuple(bytes32[] proof, tuple(address handler, bytes32 salt, bytes staticInput) params)[]"];class Be{constructor(e,t,n,r=de.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(!Be.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(!Be.orderTypeRegistry.hasOwnProperty(r))throw new Error(`Unknown order type: ${r}`);e[n]=new(0,Be.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 Be(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=c.of(Object.values(this.orders).map(e=>[...Object.values(e.leaf)]),$e)),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 de.PRIVATE:return Promise.resolve("0x");case de.EMITTED:return Promise.resolve(r.encodeToABI(t));case de.SWARM:case de.WAKU:case de.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=Fe(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(Ge,[this.getProofs(e)])}encodeToJSON(e){return JSON.stringify(this.getProofs(e))}reset(){this.tree=void 0}static registerOrderType(e,t){Be.orderTypeRegistry[e]=t}static resetOrderTypeRegistry(){Be.orderTypeRegistry={}}}Be.orderTypeRegistry={};class We{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 je="0x6cF1e9cA41f7611dEf408122793c358a3d11E5a5",He="0x52eD56Da04309Aca4c3FECC595298d80C2f16BAc",Ye=u.from(2).pow(32).sub(1),Ke=u.from(31536e3),Ze=["tuple(address sellToken, address buyToken, address receiver, uint256 partSellAmount, uint256 minPartLimit, uint256 t0, uint256 n, uint256 t, uint256 span, bytes32 appData)"];var Xe,qe;!function(e){e.AUTO="AUTO",e.LIMIT_DURATION="LIMIT_DURATION"}(Xe||(Xe={})),function(e){e.AT_MINING_TIME="AT_MINING_TIME",e.AT_EPOCH="AT_EPOCH"}(qe||(qe={}));const ze={startType:qe.AT_MINING_TIME},Je={durationType:Xe.AUTO};class Qe extends Ve{constructor(e){const{handler:t,salt:n,data:r,hasOffChainInput:a}=e;if(t!==je)throw new Error(`InvalidHandler: Expected: ${je}, provided: ${t}`);super({handler:je,salt:n,data:r,hasOffChainInput:a}),this.isSingleOrder=!0}static fromData(e,t){return new Qe({handler:je,data:e,salt:t})}static fromParams(e){return Qe.deserialize(ge(e))}get context(){return this.staticInput.t0.gt(0)?super.context:{address:He,factoryArgs:void 0}}get orderType(){return"twap"}isValid(){const e=(()=>{const{sellToken:e,sellAmount:t,buyToken:n,buyAmount:r,startTime:a=ze,numberOfParts:i,timeBetweenParts:s,durationOfPart:u=Je}=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===qe.AT_EPOCH){const e=a.epoch;if(!e.gte(o.Zero)||!e.lt(Ye))return"InvalidStartTime"}return i.gt(o.One)&&i.lte(Ye)?s.gt(o.Zero)&&s.lte(Ke)?u.durationType!==Xe.LIMIT_DURATION||u.duration.lte(s)?Ce(Ze,[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===qe.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(Ye))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===Xe.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(he(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:ce.TRY_AT_EPOCH,epoch:e,reason:`TWAP hasn't started yet. Starts at ${e} (${we(e)})`};const n=t.endTimestamp(e);return a>=n?{result:ce.DONT_TRY_AGAIN,reason:`TWAP has expired. Expired at ${n} (${we(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:ce.DONT_TRY_AGAIN,reason:`${e?.message}. User likely removed the order.`}:e?.message?.includes("Cabinet epoch out of range")?{result:ce.DONT_TRY_AGAIN,reason:`${e?.message}`}:{result:ce.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(he(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:ce.UNEXPECTED_ERROR,reason:`TWAP part hash't started. First TWAP part start at ${e} (${we(e)})`,error:void 0};const t=s.mul(i).add(e).toNumber();if(a>=t)return{result:ce.UNEXPECTED_ERROR,reason:`TWAP is expired. Expired at ${t} (${we(t)})`,error:void 0};const n=Math.floor((a-e)/i);if(n===s.toNumber()-1)return{result:ce.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:ce.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} (${we(r)})`}})})}catch(e){return Promise.reject(e)}}serialize(){return ge(this.leaf)}encodeStaticInput(){return super.encodeStaticInputHelper(Ze,this.staticInput)}static deserialize(e){return super.deserializeHelper(e,je,Ze,(e,t)=>new Qe({handler:je,salt:t,data:tt(e)}))}toString(){const{sellAmount:e,sellToken:t,buyAmount:n,buyToken:r,numberOfParts:a,startTime:i=ze,timeBetweenParts:s,durationOfPart:o=Je,receiver:u,appData:p}=this.data,d=i.startType===qe.AT_MINING_TIME?"AT_MINING_TIME":i.epoch.toNumber(),c=o.durationType===Xe.AUTO?"AUTO":o.duration.toNumber(),l={sellAmount:e.toString(),sellToken:t,buyAmount:n.toString(),buyToken:r,numberOfParts:a.toString(),startTime:d,timeBetweenParts:s.toNumber(),durationOfPart:c,receiver:u,appData:p};return`${this.orderType} (${this.id}): ${JSON.stringify(l)}`}transformDataToStruct(e){return et(e)}transformStructToData(e){return tt(e)}}function et(e){const{sellAmount:t,buyAmount:n,numberOfParts:r,startTime:a=ze,timeBetweenParts:i,durationOfPart:s=Je,...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===qe.AT_MINING_TIME?o.Zero:a.epoch,n:r,t:i,span:s.durationType===Xe.AUTO?o.Zero:s.duration,...u}}function tt(e){const{n:t,partSellAmount:n,minPartLimit:r,t:a,t0:i,span:s,...o}=e,u=s.isZero()?{durationType:Xe.AUTO}:{durationType:Xe.LIMIT_DURATION,duration:s},p=s.isZero()?{startType:qe.AT_MINING_TIME}:{startType:qe.AT_EPOCH,epoch:i};return{sellAmount:n.mul(t),buyAmount:r.mul(t),startTime:p,numberOfParts:t,timeBetweenParts:a,durationOfPart:u,...o}}const nt={[je]:e=>Qe.fromParams(e)};export{A as ALL_SUPPORTED_CHAIN_IDS,I as BUY_ETH_ADDRESS,$ as BuyTokenDestination,O as COMPOSABLE_COW,g as COMPOSABLE_COW_CONTRACT_ADDRESS,ve as CONDITIONAL_ORDER_PARAMS_ABI,S as COW_PROTOCOL_SETTLEMENT_CONTRACT_ADDRESS,N as COW_PROTOCOL_VAULT_RELAYER_ADDRESS,He as CURRENT_BLOCK_TIMESTAMP_FACTORY_ADDRESS,Ve as ConditionalOrder,We as ConditionalOrderFactory,T as CowError,U as DEFAULT_BACKOFF_OPTIONS,nt as DEFAULT_CONDITIONAL_ORDER_REGISTRY,m as DEFAULT_COW_API_CONTEXT,f as DEFAULT_IPFS_READ_URI,b as DEFAULT_IPFS_WRITE_URI,x as DEFAULT_LIMITER_OPTIONS,Pe as DEFAULT_TOKEN_FORMATTER,Xe as DurationType,y as ENVS_LIST,E as EXTENSIBLE_FALLBACK_HANDLER,_ as EXTENSIBLE_FALLBACK_HANDLER_CONTRACT_ADDRESS,G as EcdsaSigningScheme,Ke as MAX_FREQUENCY,Ye as MAX_UINT32,Be as Multiplexer,M as ORDER_BOOK_PROD_CONFIG,k as ORDER_BOOK_STAGING_CONFIG,B as OnchainOrderData,V as OrderBookApi,w as OrderBookApiError,W as OrderCancellationError,j as OrderClass,H as OrderKind,Y as OrderPostError,K as OrderQuoteSideKindBuy,Z as OrderQuoteSideKindSell,pe as OrderSigningUtils,X as OrderStatus,ce as PollResultCode,q as PriceEstimationError,z as PriceQuality,de as ProofLocation,J as ReplaceOrderError,ie as SUBGRAPH_PROD_CONFIG,se as SUBGRAPH_STAGING_CONFIG,Q as SellTokenSource,ee as SigningScheme,qe as StartTimeValue,oe as SubgraphApi,l as SupportedChainId,je as TWAP_ADDRESS,Qe as Twap,_e as createSetDomainVerifierTx,Re as decodeParams,ge as encodeParams,we as formatEpoch,xe as fromStructToOrder,he as getBlockInfo,fe as getDomainVerifier,Ne as isComposableCow,Se as isExtensibleFallbackHandler,Ce as isValidAbi,h as logPrefix,P as mapAddressToSupportedNetworks,v as mapSupportedNetworks,C as request,et as transformDataToStruct,tt as transformStructToData};
`,re="https://api.thegraph.com/subgraphs/name/cowprotocol",ae={[l.MAINNET]:re+"/cow",[l.GNOSIS_CHAIN]:re+"/cow-gc",[l.SEPOLIA]:null},ie={[l.MAINNET]:re+"/cow-staging",[l.GNOSIS_CHAIN]:re+"/cow-gc-staging",[l.SEPOLIA]:null};class se{constructor(e={}){this.API_NAME="CoW Protocol Subgraph",this.context=void 0,this.context={...m,...e}}getTotals(e={}){try{return Promise.resolve(this.runQuery(ee,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(te,{days:e},t))}catch(e){return Promise.reject(e)}}getLastHoursVolume(e,t={}){try{return Promise.resolve(this.runQuery(ne,{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?ae:ie}}const oe=()=>import("./utils-d4ac1aa5.js");class ue{static signOrder(e,t,n){try{return Promise.resolve(oe()).then(function({signOrder:r}){return r(e,t,n)})}catch(e){return Promise.reject(e)}}static signOrderCancellation(e,t,n){try{return Promise.resolve(oe()).then(function({signOrderCancellation:r}){return r(e,t,n)})}catch(e){return Promise.reject(e)}}static signOrderCancellations(e,t,n){try{return Promise.resolve(oe()).then(function({signOrderCancellations:r}){return r(e,t,n)})}catch(e){return Promise.reject(e)}}static getDomain(e){try{return Promise.resolve(oe()).then(function({getDomain:t}){return t(e)})}catch(e){return Promise.reject(e)}}static getDomainSeparator(e){try{return Promise.resolve(oe()).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 pe,de;!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"}(pe||(pe={})),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"}(de||(de={}));const ce=[{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 le{static createInterface(){return new a.Interface(ce)}static connect(e,t){return new i(e,ce,t)}}le.abi=ce;const ye=[{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 me{static createInterface(){return new a.Interface(ye)}static connect(e,t){return new i(e,ye,t)}}me.abi=ye;const Te=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)}},he=function(e,t,n,r){try{const a=me.connect(N[n],r);return Promise.resolve(a.callStatic.domainVerifiers(e,t))}catch(e){return Promise.reject(e)}},fe=["erc20","0x5a28e9363bb942b639270062aa6bb295f434bcdfc42c97267bf003f272060dc9"],be=["external","0xabee3b73373acd583a130924aad6dc38cfdc44ba0555ba94ce2ff63980ea0632"],Ie=["internal","0x4ac99ace14ee0a5ef932dc609df0943ab7ac16b7583634612f8dc35a4289a6ce"],Ee=["sell","0xf3b277728b3fee749481eb3e0b3b48980dbbab78658fc419025cb16eee346775"],Oe=["buy","0x6ed88e868af0a1983e3886d5f3e95a2fafbd6c3450bc229e27342283dc429ccc"],Ae=["tuple(address handler, bytes32 salt, bytes staticInput)"],ve=(e,t)=>`${t}@${e}`;function Pe(e,t){return e===N[t]}function Se(e,t){return e===_[t]}function ge(e,t){return me.createInterface().encodeFunctionData("setDomainVerifier",[e,t])}function Ne(e){return a.defaultAbiCoder.encode(Ae,[e])}function _e(e){const{handler:t,salt:n,staticInput:r}=a.defaultAbiCoder.decode(Ae,e)[0];return{handler:t,salt:n,staticInput:r}}function we(e,t){try{a.defaultAbiCoder.encode(e,t)}catch(e){return!1}return!0}function Ce(e){return new Date(1e3*e).toISOString()}function Re(e){if(fe.includes(e))return p.ERC20;if(be.includes(e))return p.EXTERNAL;if(Ie.includes(e))return p.INTERNAL;throw new Error(`Unknown balance type: ${e}`)}function De(e){if(Ee.includes(e))return d.SELL;if(Oe.includes(e))return d.BUY;throw new Error(`Unknown kind: ${e}`)}function xe(e){const{sellToken:t,sellAmount:n,buyToken:r,buyAmount:a,buyTokenBalance:i,sellTokenBalance:s,feeAmount:o,kind:u,receiver:p,validTo:d,partiallyFillable:c,appData:l}=e;return{sellToken:t,sellAmount:n,buyToken:r,buyAmount:a,feeAmount:o,receiver:p,partiallyFillable:c,appData:l,validTo:Number(d),kind:De(u.toString()),sellTokenBalance:Re(s.toString()),buyTokenBalance:Re(i.toString())}}let Me,Ue;function Le(){return Me||(Me=le.createInterface()),Me}function ke(e,t){return Ue||(Ue=le.connect(_[e],t)),Ue}class Ve{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=Le(),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(),Le().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(Ne(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=ke(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(ue.getDomain(e)).then(function(e){return r(e,n,t)})})}catch(e){return Promise.reject(e)}}(n,r,xe(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:de.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:de.TRY_NEXT_BLOCK,reason:"Order already in orderbook"})})}();return u&&u.then?u.then(o):o(u)})})}):{result:de.DONT_TRY_AGAIN,reason:`NotAuthorized: Order ${t.id} is not authorized for ${r} on chain ${n}`}})}):{result:de.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:de.UNEXPECTED_ERROR,error:e}}))}catch(e){return Promise.reject(e)}}isAuthorized(e){const{chainId:t,owner:n,provider:r}=e;return ke(t,r).callStatic.singleOrders(n,this.id)}cabinet(e){const{chainId:t,owner:n,provider:r}=e;return ke(t,r).callStatic.cabinet(n,this.ctx)}static deserializeHelper(e,t,n,r){try{const{handler:i,salt:s,staticInput:o}=_e(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 $e=["address","bytes32","bytes"],Ge=["tuple(bytes32[] proof, tuple(address handler, bytes32 salt, bytes staticInput) params)[]"];class Fe{constructor(e,t,n,r=pe.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(!Fe.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(!Fe.orderTypeRegistry.hasOwnProperty(r))throw new Error(`Unknown order type: ${r}`);e[n]=new(0,Fe.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 Fe(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=c.of(Object.values(this.orders).map(e=>[...Object.values(e.leaf)]),$e)),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 pe.PRIVATE:return Promise.resolve("0x");case pe.EMITTED:return Promise.resolve(r.encodeToABI(t));case pe.SWARM:case pe.WAKU:case pe.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=ke(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(Ge,[this.getProofs(e)])}encodeToJSON(e){return JSON.stringify(this.getProofs(e))}reset(){this.tree=void 0}static registerOrderType(e,t){Fe.orderTypeRegistry[e]=t}static resetOrderTypeRegistry(){Fe.orderTypeRegistry={}}}Fe.orderTypeRegistry={};class Be{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 We="0x6cF1e9cA41f7611dEf408122793c358a3d11E5a5",je="0x52eD56Da04309Aca4c3FECC595298d80C2f16BAc",He=u.from(2).pow(32).sub(1),Ye=u.from(31536e3),Ze=["tuple(address sellToken, address buyToken, address receiver, uint256 partSellAmount, uint256 minPartLimit, uint256 t0, uint256 n, uint256 t, uint256 span, bytes32 appData)"];var Ke,Xe;!function(e){e.AUTO="AUTO",e.LIMIT_DURATION="LIMIT_DURATION"}(Ke||(Ke={})),function(e){e.AT_MINING_TIME="AT_MINING_TIME",e.AT_EPOCH="AT_EPOCH"}(Xe||(Xe={}));const qe={startType:Xe.AT_MINING_TIME},ze={durationType:Ke.AUTO};class Je extends Ve{constructor(e){const{handler:t,salt:n,data:r,hasOffChainInput:a}=e;if(t!==We)throw new Error(`InvalidHandler: Expected: ${We}, provided: ${t}`);super({handler:We,salt:n,data:r,hasOffChainInput:a}),this.isSingleOrder=!0}static fromData(e,t){return new Je({handler:We,data:e,salt:t})}static fromParams(e){return Je.deserialize(Ne(e))}get context(){return this.staticInput.t0.gt(0)?super.context:{address:je,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=ze}=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===Xe.AT_EPOCH){const e=a.epoch;if(!e.gte(o.Zero)||!e.lt(He))return"InvalidStartTime"}return i.gt(o.One)&&i.lte(He)?s.gt(o.Zero)&&s.lte(Ye)?u.durationType!==Ke.LIMIT_DURATION||u.duration.lte(s)?we(Ze,[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===Xe.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(He))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===Ke.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(Te(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:de.TRY_AT_EPOCH,epoch:e,reason:`TWAP hasn't started yet. Starts at ${e} (${Ce(e)})`};const n=t.endTimestamp(e);return a>=n?{result:de.DONT_TRY_AGAIN,reason:`TWAP has expired. Expired at ${n} (${Ce(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:de.DONT_TRY_AGAIN,reason:`${e?.message}. User likely removed the order.`}:e?.message?.includes("Cabinet epoch out of range")?{result:de.DONT_TRY_AGAIN,reason:`${e?.message}`}:{result:de.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(Te(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:de.UNEXPECTED_ERROR,reason:`TWAP part hash't started. First TWAP part start at ${e} (${Ce(e)})`,error:void 0};const t=s.mul(i).add(e).toNumber();if(a>=t)return{result:de.UNEXPECTED_ERROR,reason:`TWAP is expired. Expired at ${t} (${Ce(t)})`,error:void 0};const n=Math.floor((a-e)/i);if(n===s.toNumber()-1)return{result:de.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:de.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} (${Ce(r)})`}})})}catch(e){return Promise.reject(e)}}serialize(){return Ne(this.leaf)}encodeStaticInput(){return super.encodeStaticInputHelper(Ze,this.staticInput)}static deserialize(e){return super.deserializeHelper(e,We,Ze,(e,t)=>new Je({handler:We,salt:t,data:et(e)}))}toString(){const{sellAmount:e,sellToken:t,buyAmount:n,buyToken:r,numberOfParts:a,startTime:i=qe,timeBetweenParts:s,durationOfPart:o=ze,receiver:u,appData:p}=this.data,d=i.startType===Xe.AT_MINING_TIME?"AT_MINING_TIME":i.epoch.toNumber(),c=o.durationType===Ke.AUTO?"AUTO":o.duration.toNumber(),l={sellAmount:e.toString(),sellToken:t,buyAmount:n.toString(),buyToken:r,numberOfParts:a.toString(),startTime:d,timeBetweenParts:s.toNumber(),durationOfPart:c,receiver:u,appData:p};return`${this.orderType} (${this.id}): ${JSON.stringify(l)}`}transformDataToStruct(e){return Qe(e)}transformStructToData(e){return et(e)}}function Qe(e){const{sellAmount:t,buyAmount:n,numberOfParts:r,startTime:a=qe,timeBetweenParts:i,durationOfPart:s=ze,...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===Xe.AT_MINING_TIME?o.Zero:a.epoch,n:r,t:i,span:s.durationType===Ke.AUTO?o.Zero:s.duration,...u}}function et(e){const{n:t,partSellAmount:n,minPartLimit:r,t:a,t0:i,span:s,...o}=e,u=s.isZero()?{durationType:Ke.AUTO}:{durationType:Ke.LIMIT_DURATION,duration:s},p=s.isZero()?{startType:Xe.AT_MINING_TIME}:{startType:Xe.AT_EPOCH,epoch:i};return{sellAmount:n.mul(t),buyAmount:r.mul(t),startTime:p,numberOfParts:t,timeBetweenParts:a,durationOfPart:u,...o}}const tt={[We]:e=>Je.fromParams(e)};export{A as ALL_SUPPORTED_CHAIN_IDS,I as BUY_ETH_ADDRESS,G as BuyTokenDestination,O as COMPOSABLE_COW,_ as COMPOSABLE_COW_CONTRACT_ADDRESS,Ae as CONDITIONAL_ORDER_PARAMS_ABI,S as COW_PROTOCOL_SETTLEMENT_CONTRACT_ADDRESS,g as COW_PROTOCOL_VAULT_RELAYER_ADDRESS,je as CURRENT_BLOCK_TIMESTAMP_FACTORY_ADDRESS,Ve as ConditionalOrder,Be as ConditionalOrderFactory,T as CowError,x as DEFAULT_BACKOFF_OPTIONS,tt 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,ve as DEFAULT_TOKEN_FORMATTER,Ke as DurationType,y as ENVS_LIST,E as EXTENSIBLE_FALLBACK_HANDLER,N as EXTENSIBLE_FALLBACK_HANDLER_CONTRACT_ADDRESS,F as EcdsaSigningScheme,Ye as MAX_FREQUENCY,He as MAX_UINT32,Fe as Multiplexer,L as ORDER_BOOK_PROD_CONFIG,k as ORDER_BOOK_STAGING_CONFIG,B as OnchainOrderData,$ as OrderBookApi,R as OrderBookApiError,W as OrderCancellationError,j as OrderClass,H as OrderKind,Y as OrderPostError,Z as OrderQuoteSideKindBuy,K as OrderQuoteSideKindSell,ue as OrderSigningUtils,X as OrderStatus,de as PollResultCode,q as PriceEstimationError,z as PriceQuality,pe as ProofLocation,ae as SUBGRAPH_PROD_CONFIG,ie as SUBGRAPH_STAGING_CONFIG,J as SellTokenSource,Q as SigningScheme,Xe as StartTimeValue,se as SubgraphApi,l as SupportedChainId,We as TWAP_ADDRESS,Je as Twap,ge as createSetDomainVerifierTx,_e as decodeParams,Ne as encodeParams,Ce as formatEpoch,xe as fromStructToOrder,Te as getBlockInfo,he as getDomainVerifier,Se as isComposableCow,Pe as isExtensibleFallbackHandler,we as isValidAbi,h as logPrefix,P as mapAddressToSupportedNetworks,v as mapSupportedNetworks,C as request,Qe as transformDataToStruct,et as transformStructToData};
//# sourceMappingURL=index.module.js.map

@@ -38,5 +38,5 @@ export type { Address } from './models/Address';

export { PriceEstimationError } from './models/PriceEstimationError';
export type { PriceImprovement } from './models/PriceImprovement';
export { PriceQuality } from './models/PriceQuality';
export type { ProtocolAppData } from './models/ProtocolAppData';
export { ReplaceOrderError } from './models/ReplaceOrderError';
export { SellTokenSource } from './models/SellTokenSource';

@@ -43,0 +43,0 @@ export type { Signature } from './models/Signature';

@@ -0,1 +1,2 @@

import type { PriceImprovement } from './PriceImprovement';
import type { Surplus } from './Surplus';

@@ -6,2 +7,2 @@ import type { Volume } from './Volume';

*/
export type FeePolicy = (Surplus | Volume);
export type FeePolicy = (Surplus | Volume | PriceImprovement);

@@ -16,3 +16,2 @@ export type OrderPostError = {

INVALID_SIGNATURE = "InvalidSignature",
INSUFFICIENT_FEE = "InsufficientFee",
SELL_AMOUNT_OVERFLOW = "SellAmountOverflow",

@@ -22,3 +21,5 @@ TRANSFER_SIMULATION_FAILED = "TransferSimulationFailed",

INCOMPATIBLE_SIGNING_SCHEME = "IncompatibleSigningScheme",
TOO_MANY_LIMIT_ORDERS_UNSUPPORTED_BUY_TOKEN_DESTINATION = "TooManyLimitOrders UnsupportedBuyTokenDestination",
TOO_MANY_LIMIT_ORDERS = "TooManyLimitOrders",
TOO_MUCH_GAS = "TooMuchGas",
UNSUPPORTED_BUY_TOKEN_DESTINATION = "UnsupportedBuyTokenDestination",
UNSUPPORTED_SELL_TOKEN_SOURCE = "UnsupportedSellTokenSource",

@@ -25,0 +26,0 @@ UNSUPPORTED_ORDER_TYPE = "UnsupportedOrderType",

@@ -6,3 +6,3 @@ /**

factor: number;
max_volume_factor: number;
maxVolumeFactor: number;
};
{
"name": "@cowprotocol/cow-sdk",
"version": "5.1.0",
"version": "5.2.0",
"license": "(MIT OR Apache-2.0)",

@@ -30,3 +30,3 @@ "files": [

"graphql:codegen": "graphql-codegen --config graphql-codegen.yml",
"swagger:codegen": " openapi --input https://raw.githubusercontent.com/cowprotocol/services/v2.245.1/crates/orderbook/openapi.yml --output src/order-book/generated --exportServices false --exportCore false",
"swagger:codegen": " openapi --input https://raw.githubusercontent.com/cowprotocol/services/v2.252.0/crates/orderbook/openapi.yml --output src/order-book/generated --exportServices false --exportCore false",
"typechain:codegen": "typechain --target ethers-v5 --out-dir ./src/composable/generated './abi/*.json'"

@@ -33,0 +33,0 @@ },

{
"name": "@cowprotocol/cow-sdk",
"version": "5.1.0",
"version": "5.2.0",
"license": "(MIT OR Apache-2.0)",

@@ -30,3 +30,3 @@ "files": [

"graphql:codegen": "graphql-codegen --config graphql-codegen.yml",
"swagger:codegen": " openapi --input https://raw.githubusercontent.com/cowprotocol/services/v2.245.1/crates/orderbook/openapi.yml --output src/order-book/generated --exportServices false --exportCore false",
"swagger:codegen": " openapi --input https://raw.githubusercontent.com/cowprotocol/services/v2.252.0/crates/orderbook/openapi.yml --output src/order-book/generated --exportServices false --exportCore false",
"typechain:codegen": "typechain --target ethers-v5 --out-dir ./src/composable/generated './abi/*.json'"

@@ -33,0 +33,0 @@ },

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is too big to display

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc