@cowprotocol/cow-sdk 5.3.1 → 5.3.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,4 +1,4 @@
1
- require("cross-fetch/polyfill");var e,t=require("limiter"),r=require("exponential-backoff"),n=require("graphql-request"),o=require("ethers"),a=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.ARBITRUM_ONE=42161]="ARBITRUM_ONE",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"),I=h(c),O=h(y),E=function(e,{path:t,query:n,method:o,body:a},s,i){try{const p={Accept:"application/json","Content-Type":"application/json"},u=`${e}${t}${n?"?"+n:""}`,d={method:o,body:(()=>{if(a)return"string"==typeof a?a:JSON.stringify(a)})(),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 S=[408,425,429,500,502,503,504],P={numOfAttempts:10,maxDelay:Infinity,jitter:"none",retry:e=>!(e instanceof A)||S.includes(e.response.status)},x={tokensPerInterval:5,interval:"second"},v=function(e){try{let t;const r=function(){if(204!==e.status)return function(r,n){try{var o=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 o&&o.then?o.then(void 0,n):o}(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)}};function g(e){return function(e){const{ethflowData:t}=e;if(!t)return e;const{userValidTo:r}=t,n=e.onchainUser||e.owner,o=l;return{...e,validTo:r,owner:n,sellToken:o}}(function(e){const{executedFeeAmount:t,executedSurplusFee:r}=e,n=BigInt(t||"0"),o=BigInt(r||"0"),a=String(n+o);return{...e,totalFee:a}}(e))}const _={[exports.SupportedChainId.MAINNET]:"https://api.cow.fi/mainnet",[exports.SupportedChainId.GNOSIS_CHAIN]:"https://api.cow.fi/xdai",[exports.SupportedChainId.ARBITRUM_ONE]:"https://api.cow.fi/arbitrum_one",[exports.SupportedChainId.SEPOLIA]:"https://api.cow.fi/sepolia"},N={[exports.SupportedChainId.MAINNET]:"https://barn.api.cow.fi/mainnet",[exports.SupportedChainId.GNOSIS_CHAIN]:"https://barn.api.cow.fi/xdai",[exports.SupportedChainId.ARBITRUM_ONE]:"https://barn.api.cow.fi/arbitrum_one",[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;function H(e,t){if("number"==typeof e){const r=e*10**t,n=r.toFixed();return{big:BigInt(n.includes("e")?r:n),num:e}}const r=BigInt(e);return{big:r,num:Number(r)/10**t}}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 K=n.gql`
1
+ require("cross-fetch/polyfill");var e,t=require("limiter"),r=require("exponential-backoff"),n=require("graphql-request"),o=require("ethers"),a=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.ARBITRUM_ONE=42161]="ARBITRUM_ONE",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"),I=h(c),O=h(y),E=function(e,{path:t,query:n,method:o,body:a},s,i){try{const p={Accept:"application/json","Content-Type":"application/json"},u=`${e}${t}${n?"?"+n:""}`,d={method:o,body:(()=>{if(a)return"string"==typeof a?a:JSON.stringify(a)})(),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 S=[408,425,429,500,502,503,504],P={numOfAttempts:10,maxDelay:Infinity,jitter:"none",retry:e=>!(e instanceof A)||S.includes(e.response.status)},x={tokensPerInterval:5,interval:"second"},v=function(e){try{let t;const r=function(){if(204!==e.status)return function(r,n){try{var o=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 o&&o.then?o.then(void 0,n):o}(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)}};function g(e){return function(e){const{ethflowData:t}=e;if(!t)return e;const{userValidTo:r}=t,n=e.onchainUser||e.owner,o=l;return{...e,validTo:r,owner:n,sellToken:o}}(function(e){const{executedFeeAmount:t,executedSurplusFee:r}=e,n=BigInt(t||"0"),o=BigInt(r||"0"),a=String(n+o);return{...e,totalFee:a}}(e))}const _={[exports.SupportedChainId.MAINNET]:"https://api.cow.fi/mainnet",[exports.SupportedChainId.GNOSIS_CHAIN]:"https://api.cow.fi/xdai",[exports.SupportedChainId.ARBITRUM_ONE]:"https://api.cow.fi/arbitrum_one",[exports.SupportedChainId.SEPOLIA]:"https://api.cow.fi/sepolia"},N={[exports.SupportedChainId.MAINNET]:"https://barn.api.cow.fi/mainnet",[exports.SupportedChainId.GNOSIS_CHAIN]:"https://barn.api.cow.fi/xdai",[exports.SupportedChainId.ARBITRUM_ONE]:"https://barn.api.cow.fi/arbitrum_one",[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=BigInt(1e4);function K(e,t){if("number"==typeof e){const r=e*10**t,n=r.toFixed();return{big:BigInt(n.includes("e")?r:n),num:e}}const r=BigInt(e);return{big:r,num:Number(r)/10**t}}const Y=n.gql`
2
2
  query Totals {
3
3
  totals {
4
4
  tokens
@@ -11,19 +11,19 @@ require("cross-fetch/polyfill");var e,t=require("limiter"),r=require("exponentia
11
11
  feesEth
12
12
  }
13
13
  }
14
- `,Y=n.gql`
14
+ `,q=n.gql`
15
15
  query LastDaysVolume($days: Int!) {
16
16
  dailyTotals(orderBy: timestamp, orderDirection: desc, first: $days) {
17
17
  timestamp
18
18
  volumeUsd
19
19
  }
20
20
  }
21
- `,q=n.gql`
21
+ `,Q=n.gql`
22
22
  query LastHoursVolume($hours: Int!) {
23
23
  hourlyTotals(orderBy: timestamp, orderDirection: desc, first: $hours) {
24
24
  timestamp
25
25
  volumeUsd
26
26
  }
27
27
  }
28
- `,Q="https://api.thegraph.com/subgraphs/name/cowprotocol",X={[exports.SupportedChainId.MAINNET]:Q+"/cow",[exports.SupportedChainId.GNOSIS_CHAIN]:Q+"/cow-gc",[exports.SupportedChainId.ARBITRUM_ONE]:null,[exports.SupportedChainId.SEPOLIA]:null},Z={[exports.SupportedChainId.MAINNET]:Q+"/cow-staging",[exports.SupportedChainId.GNOSIS_CHAIN]:Q+"/cow-gc-staging",[exports.SupportedChainId.ARBITRUM_ONE]:null,[exports.SupportedChainId.SEPOLIA]:null},z=()=>Promise.resolve().then(function(){return require("./utils-17f67bdd.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 o.utils.Interface(re)}static connect(e,t){return new o.Contract(e,re,t)}}ne.abi=re;const oe=[{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 o.utils.Interface(oe)}static connect(e,t){return new o.Contract(e,oe,t)}}ae.abi=oe;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 o.utils.defaultAbiCoder.encode(ce,[e])}function me(e){const{handler:t,salt:r,staticInput:n}=o.utils.defaultAbiCoder.decode(ce,e)[0];return{handler:t,salt:r,staticInput:n}}function Te(e,t){try{o.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 a.OrderBalance.ERC20;if(pe.includes(e))return a.OrderBalance.EXTERNAL;if(ue.includes(e))return a.OrderBalance.INTERNAL;throw new Error(`Unknown balance type: ${e}`)}function be(e){if(de.includes(e))return a.OrderKind.SELL;if(le.includes(e))return a.OrderKind.BUY;throw new Error(`Unknown kind: ${e}`)}function Ie(e){const{sellToken:t,sellAmount:r,buyToken:n,buyAmount:o,buyTokenBalance:a,sellTokenBalance:s,feeAmount:i,kind:p,receiver:u,validTo:d,partiallyFillable:l,appData:c}=e;return{sellToken:t,sellAmount:r,buyToken:n,buyAmount:o,feeAmount:i,receiver:u,partiallyFillable:l,appData:c,validTo:Number(d),kind:be(p.toString()),sellTokenBalance:fe(s.toString()),buyTokenBalance:fe(a.toString())}}let Oe,Ee;function Ae(){return Oe||(Oe=ne.createInterface()),Oe}function Se(e,t){return Ee||(Ee=ne.connect(O[e],t)),Ee}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=o.utils.keccak256(o.utils.randomBytes(32)),data:n,hasOffChainInput:a=!1}=e;if(!o.ethers.utils.isAddress(t))throw new Error(`Invalid handler: ${t}`);if(!o.ethers.utils.isHexString(r)||32!==o.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=a}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=Ae(),r={handler:this.handler,salt:this.salt,staticInput:this.encodeStaticInput()};if(e){const n=e.factoryArgs?o.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(),Ae().encodeFunctionData("remove",[this.id])}get id(){return o.utils.keccak256(this.serialize())}get ctx(){return this.isSingleOrder?this.id:o.constants.HashZero}get leaf(){return{handler:this.handler,salt:this.salt,staticInput:this.encodeStaticInput()}}static leafToId(e){return o.utils.keccak256(ye(e))}get offChainInput(){return"0x"}encodeStaticInputHelper(e,t){return o.utils.defaultAbiCoder.encode(e,[t])}poll(e){try{const t=this,{chainId:r,owner:n,provider:o,orderBookApi:a}=e,s=Se(r,o);return Promise.resolve(function(o,p){try{var u=function(){const o=t.isValid();return o.isValid?Promise.resolve(t.pollValidate(e)).then(function(o){return o||Promise.resolve(t.isAuthorized(e)).then(function(o){return o?Promise.resolve(s.getTradeableOrderWithSignature(n,t.leaf,t.offChainInput,[])).then(function([o,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,Ie(o))).then(function(r){return Promise.resolve(a.getOrder(r).then(()=>!0).catch(()=>!1)).then(function(n){let a;function i(e){return a?e:{result:exports.PollResultCode.SUCCESS,order:o,signature:s}}const p=function(){if(n)return Promise.resolve(t.handlePollFailedAlreadyPresent(r,o,e)).then(function(e){if(e)return a=1,e;const t={result:exports.PollResultCode.TRY_NEXT_BLOCK,reason:"Order already in orderbook"};return a=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: ${o.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:a,salt:s,staticInput:i}=me(e);if(a!=t)throw new Error("HandlerMismatch");const[p]=o.utils.defaultAbiCoder.decode(r,i);return n(p,s)}catch(e){throw"HandlerMismatch"===e.message?e:new Error("InvalidSerializedConditionalOrder")}}}const xe=["address","bytes32","bytes"],ve=["tuple(bytes32[] proof, tuple(address handler, bytes32 salt, bytes staticInput) params)[]"];class ge{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(!ge.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:a}=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,...o}=t[r];if(!ge.orderTypeRegistry.hasOwnProperty(n))throw new Error(`Unknown order type: ${n}`);e[r]=new(0,ge.orderTypeRegistry[n])(o)}return e}return"object"==typeof t&&null!==t&&t.hasOwnProperty("type")&&t.hasOwnProperty("hex")&&"BigNumber"===t.type?o.BigNumber.from(t):t}),s=new ge(t,r,n);return s.location=a,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 a=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,o){try{var a=Promise.resolve(r(n.encodeToJSON(t)))}catch(e){return o(e)}return a&&a.then?a.then(void 0,o):a}(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(a().then(t=>{try{return o.utils.hexlify(o.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,o){try{function a(r){return Promise.resolve(s.getTradeableOrderWithSignature(e,t.params,r,t.proof))}const s=Se(r,n);return Promise.resolve(o?Promise.resolve(o(e,t.params)).then(a):a("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 o.utils.defaultAbiCoder.encode(ve,[this.getProofs(e)])}encodeToJSON(e){return JSON.stringify(this.getProofs(e))}reset(){this.tree=void 0}static registerOrderType(e,t){ge.orderTypeRegistry[e]=t}static resetOrderTypeRegistry(){ge.orderTypeRegistry={}}}ge.orderTypeRegistry={};const _e="0x6cF1e9cA41f7611dEf408122793c358a3d11E5a5",Ne="0x52eD56Da04309Aca4c3FECC595298d80C2f16BAc",Ce=o.BigNumber.from(2).pow(32).sub(1),Re=o.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 ke extends Pe{constructor(e){const{handler:t,salt:r,data:n,hasOffChainInput:o}=e;if(t!==_e)throw new Error(`InvalidHandler: Expected: ${_e}, provided: ${t}`);super({handler:_e,salt:r,data:n,hasOffChainInput:o}),this.isSingleOrder=!0}static fromData(e,t){return new ke({handler:_e,data:e,salt:t})}static fromParams(e){return ke.deserialize(ye(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:a=Ue,numberOfParts:s,timeBetweenParts:i,durationOfPart:p=Me}=this.data;if(e==r)return"InvalidSameToken";if(e==o.constants.AddressZero||r==o.constants.AddressZero)return"InvalidToken";if(!t.gt(o.constants.Zero))return"InvalidSellAmount";if(!n.gt(o.constants.Zero))return"InvalidMinBuyAmount";if(a.startType===exports.StartTimeValue.AT_EPOCH){const e=a.epoch;if(!e.gte(o.constants.Zero)||!e.lt(Ce))return"InvalidStartTime"}return s.gt(o.constants.One)&&s.lte(Ce)?i.gt(o.constants.Zero)&&i.lte(Re)?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=o.utils.defaultAbiCoder.decode(["uint256"],e)[0];if(t.gt(Ce))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:o}=n;return function(r,n){try{var a=Promise.resolve(t.startTimestamp(e)).then(function(e){if(e>o)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 o>=r?{result:exports.PollResultCode.DONT_TRY_AGAIN,reason:`TWAP has expired. Expired at ${r} (${he(r)})`}:void 0})}catch(e){return n(e)}return a&&a.then?a.then(void 0,n):a}(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:o}=n,a=e.data.timeBetweenParts.toNumber(),{numberOfParts:s}=e.data;return Promise.resolve(e.startTimestamp(r)).then(function(e){if(o<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(a).add(e).toNumber();if(o>=t)return{result:exports.PollResultCode.UNEXPECTED_ERROR,reason:`TWAP is expired. Expired at ${t} (${he(t)})`,error:void 0};const r=Math.floor((o-e)/a);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)*a;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,_e,De,(e,t)=>new ke({handler:_e,salt:t,data:Fe(e)}))}toString(){const{sellAmount:e,sellToken:t,buyAmount:r,buyToken:n,numberOfParts:o,startTime:a=Ue,timeBetweenParts:s,durationOfPart:i=Me,receiver:p,appData:u}=this.data,d=a.startType===exports.StartTimeValue.AT_MINING_TIME?"AT_MINING_TIME":a.epoch.toNumber(),l=i.durationType===exports.DurationType.AUTO?"AUTO":i.duration.toNumber(),c={sellAmount:e.toString(),sellToken:t,buyAmount:r.toString(),buyToken:n,numberOfParts:o.toString(),startTime:d,timeBetweenParts:s.toNumber(),durationOfPart:l,receiver:p,appData:u};return`${this.orderType} (${this.id}): ${JSON.stringify(c)}`}transformDataToStruct(e){return Be(e)}transformStructToData(e){return Fe(e)}}function Be(e){const{sellAmount:t,buyAmount:r,numberOfParts:n,startTime:a=Ue,timeBetweenParts:s,durationOfPart:i=Me,...p}=e,{partSellAmount:u,minPartLimit:d}=n&&!n.isZero()?{partSellAmount:t.div(n),minPartLimit:r.div(n)}:{partSellAmount:o.constants.Zero,minPartLimit:o.constants.Zero},l=i.durationType===exports.DurationType.AUTO?o.constants.Zero:i.duration;return{partSellAmount:u,minPartLimit:d,t0:a.startType===exports.StartTimeValue.AT_MINING_TIME?o.constants.Zero:a.epoch,n:n,t:s,span:l,...p}}function Fe(e){const{n:t,partSellAmount:r,minPartLimit:n,t:o,t0:a,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:a};return{sellAmount:r.mul(t),buyAmount:n.mul(t),startTime:u,numberOfParts:t,timeBetweenParts:o,durationOfPart:p,...i}}const Ve={[_e]:e=>ke.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=Ne,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=P,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=x,exports.DEFAULT_TOKEN_FORMATTER=(e,t)=>`${t}@${e}`,exports.ENVS_LIST=p,exports.EXTENSIBLE_FALLBACK_HANDLER=c,exports.EXTENSIBLE_FALLBACK_HANDLER_CONTRACT_ADDRESS=I,exports.MAX_FREQUENCY=Re,exports.MAX_UINT32=Ce,exports.Multiplexer=ge,exports.ORDER_BOOK_PROD_CONFIG=_,exports.ORDER_BOOK_STAGING_CONFIG=N,exports.OrderBookApi=class{constructor(e={}){this.context=void 0,this.rateLimiter=void 0,this.context={...u,...e},this.rateLimiter=new t.RateLimiter(e.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 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 o=new URLSearchParams(C({offset:t.toString(),limit:r.toString()}));return this.fetch({path:`/api/v1/account/${e}/orders`,method:"GET",query:o},n).then(e=>e.map(g))}getTxOrders(e,t={}){return this.fetch({path:`/api/v1/transactions/${e}/orders`,method:"GET"},t).then(e=>e.map(g))}getOrder(e,t={}){return this.fetch({path:`/api/v1/orders/${e}`,method:"GET"},t).then(e=>g(e))}getOrderMultiEnv(e,t={}){const{env:r}=this.getContextWithOverride(t),n=p.filter(e=>e!==r);let o=0;const a=r=>{const s=n[o];return r instanceof A&&404===r.response.status&&s?(o++,this.getOrder(e,{...t,env:s}).catch(a)):Promise.reject(r)};return this.getOrder(e,{...t,env:r}).catch(a)}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}fetch(e,r={}){const{chainId:n,env:o,backoffOpts:a}=this.getContextWithOverride(r),s=this.getApiBaseUrls(o)[n],i=a||P,p=r.limiterOpts?new t.RateLimiter(r.limiterOpts):this.rateLimiter;return E(s,e,p,i)}},exports.OrderBookApiError=A,exports.OrderSigningUtils=J,exports.SUBGRAPH_PROD_CONFIG=X,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(K,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(Y,{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 o=this,{chainId:a,env:s}=o.getContextWithOverride(r),i=o.getEnvConfigs(s)[a];if(null===i)throw new Error("Unsupported Network. The subgraph API is not available in the Network "+a);return Promise.resolve(function(r,o){try{var a=Promise.resolve(n.request(i,e,t))}catch(e){return o(e)}return a&&a.then?a.then(void 0,o):a}(0,function(r){throw console.error(`[subgraph:${o.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?X:Z}},exports.TWAP_ADDRESS=_e,exports.Twap=ke,exports.createSetDomainVerifierTx=function(e,t){return ae.createInterface().encodeFunctionData("setDomainVerifier",[e,t])},exports.decodeParams=me,exports.encodeParams=ye,exports.formatEpoch=he,exports.fromStructToOrder=Ie,exports.getBlockInfo=se,exports.getDomainVerifier=function(e,t,r,n){try{const o=ae.connect(I[r],n);return Promise.resolve(o.callStatic.domainVerifiers(e,t))}catch(e){return Promise.reject(e)}},exports.getQuoteAmountsAndCosts=function(e){var t;const{orderParams:r,sellDecimals:n,buyDecimals:o,slippagePercentBps:a}=e,s=null!==(t=e.partnerFeeBps)&&void 0!==t?t:0,i=r.kind===exports.OrderKind.SELL,p=H(r.feeAmount,n),u=H(r.sellAmount,n),d=H(r.buyAmount,o),l=d.num/u.num,c=H(u.big+p.big,n),y=H(l*c.num,o),m=s>0?(i?y.big:u.big)/BigInt(s):BigInt(0),T=i?{sellAmount:c.big,buyAmount:d.big-m}:{sellAmount:c.big+m,buyAmount:d.big},h=e=>e*BigInt(a)/BigInt(1e4),f=i?{sellAmount:T.sellAmount,buyAmount:T.buyAmount-h(T.buyAmount)}:{sellAmount:T.sellAmount+h(T.sellAmount),buyAmount:T.buyAmount};return{isSell:i,costs:{networkFee:{amountInSellCurrency:p.big,amountInBuyCurrency:H(l*p.num,o).big},partnerFee:{amount:m,bps:s}},beforeNetworkCosts:{sellAmount:u.big,buyAmount:y.big},afterNetworkCosts:{sellAmount:c.big,buyAmount:d.big},afterPartnerFees:T,afterSlippage:f}},exports.isComposableCow=function(e,t){return e===O[t]},exports.isExtensibleFallbackHandler=function(e,t){return e===I[t]},exports.isValidAbi=Te,exports.logPrefix="cow-sdk:",exports.mapAddressToSupportedNetworks=h,exports.mapSupportedNetworks=T,exports.request=E,exports.transformDataToStruct=Be,exports.transformStructToData=Fe;
28
+ `,X="https://api.thegraph.com/subgraphs/name/cowprotocol",Z={[exports.SupportedChainId.MAINNET]:X+"/cow",[exports.SupportedChainId.GNOSIS_CHAIN]:X+"/cow-gc",[exports.SupportedChainId.ARBITRUM_ONE]:null,[exports.SupportedChainId.SEPOLIA]:null},z={[exports.SupportedChainId.MAINNET]:X+"/cow-staging",[exports.SupportedChainId.GNOSIS_CHAIN]:X+"/cow-gc-staging",[exports.SupportedChainId.ARBITRUM_ONE]:null,[exports.SupportedChainId.SEPOLIA]:null},J=()=>Promise.resolve().then(function(){return require("./utils-bf12253d.js")});class ee{static signOrder(e,t,r){try{return Promise.resolve(J()).then(function({signOrder:n}){return n(e,t,r)})}catch(e){return Promise.reject(e)}}static signOrderCancellation(e,t,r){try{return Promise.resolve(J()).then(function({signOrderCancellation:n}){return n(e,t,r)})}catch(e){return Promise.reject(e)}}static signOrderCancellations(e,t,r){try{return Promise.resolve(J()).then(function({signOrderCancellations:n}){return n(e,t,r)})}catch(e){return Promise.reject(e)}}static getDomain(e){try{return Promise.resolve(J()).then(function({getDomain:t}){return t(e)})}catch(e){return Promise.reject(e)}}static getDomainSeparator(e){try{return Promise.resolve(J()).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 te,re;exports.ProofLocation=void 0,(te=exports.ProofLocation||(exports.ProofLocation={}))[te.PRIVATE=0]="PRIVATE",te[te.EMITTED=1]="EMITTED",te[te.SWARM=2]="SWARM",te[te.WAKU=3]="WAKU",te[te.RESERVED=4]="RESERVED",te[te.IPFS=5]="IPFS",exports.PollResultCode=void 0,(re=exports.PollResultCode||(exports.PollResultCode={})).SUCCESS="SUCCESS",re.UNEXPECTED_ERROR="UNEXPECTED_ERROR",re.TRY_NEXT_BLOCK="TRY_NEXT_BLOCK",re.TRY_ON_BLOCK="TRY_ON_BLOCK",re.TRY_AT_EPOCH="TRY_AT_EPOCH",re.DONT_TRY_AGAIN="DONT_TRY_AGAIN";const ne=[{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 oe{static createInterface(){return new o.utils.Interface(ne)}static connect(e,t){return new o.Contract(e,ne,t)}}oe.abi=ne;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 se{static createInterface(){return new o.utils.Interface(ae)}static connect(e,t){return new o.Contract(e,ae,t)}}se.abi=ae;const ie=function(e){try{return Promise.resolve(e.getBlock("latest")).then(function(e){return{blockNumber:e.number,blockTimestamp:e.timestamp}})}catch(e){return Promise.reject(e)}},pe=["erc20","0x5a28e9363bb942b639270062aa6bb295f434bcdfc42c97267bf003f272060dc9"],ue=["external","0xabee3b73373acd583a130924aad6dc38cfdc44ba0555ba94ce2ff63980ea0632"],de=["internal","0x4ac99ace14ee0a5ef932dc609df0943ab7ac16b7583634612f8dc35a4289a6ce"],le=["sell","0xf3b277728b3fee749481eb3e0b3b48980dbbab78658fc419025cb16eee346775"],ce=["buy","0x6ed88e868af0a1983e3886d5f3e95a2fafbd6c3450bc229e27342283dc429ccc"],ye=["tuple(address handler, bytes32 salt, bytes staticInput)"];function me(e){return o.utils.defaultAbiCoder.encode(ye,[e])}function Te(e){const{handler:t,salt:r,staticInput:n}=o.utils.defaultAbiCoder.decode(ye,e)[0];return{handler:t,salt:r,staticInput:n}}function he(e,t){try{o.utils.defaultAbiCoder.encode(e,t)}catch(e){return!1}return!0}function fe(e){return new Date(1e3*e).toISOString()}function be(e){if(pe.includes(e))return a.OrderBalance.ERC20;if(ue.includes(e))return a.OrderBalance.EXTERNAL;if(de.includes(e))return a.OrderBalance.INTERNAL;throw new Error(`Unknown balance type: ${e}`)}function Ie(e){if(le.includes(e))return a.OrderKind.SELL;if(ce.includes(e))return a.OrderKind.BUY;throw new Error(`Unknown kind: ${e}`)}function Oe(e){const{sellToken:t,sellAmount:r,buyToken:n,buyAmount:o,buyTokenBalance:a,sellTokenBalance:s,feeAmount:i,kind:p,receiver:u,validTo:d,partiallyFillable:l,appData:c}=e;return{sellToken:t,sellAmount:r,buyToken:n,buyAmount:o,feeAmount:i,receiver:u,partiallyFillable:l,appData:c,validTo:Number(d),kind:Ie(p.toString()),sellTokenBalance:be(s.toString()),buyTokenBalance:be(a.toString())}}let Ee,Ae;function Se(){return Ee||(Ee=oe.createInterface()),Ee}function Pe(e,t){return Ae||(Ae=oe.connect(O[e],t)),Ae}class xe{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=o.utils.keccak256(o.utils.randomBytes(32)),data:n,hasOffChainInput:a=!1}=e;if(!o.ethers.utils.isAddress(t))throw new Error(`Invalid handler: ${t}`);if(!o.ethers.utils.isHexString(r)||32!==o.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=a}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?o.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 o.utils.keccak256(this.serialize())}get ctx(){return this.isSingleOrder?this.id:o.constants.HashZero}get leaf(){return{handler:this.handler,salt:this.salt,staticInput:this.encodeStaticInput()}}static leafToId(e){return o.utils.keccak256(me(e))}get offChainInput(){return"0x"}encodeStaticInputHelper(e,t){return o.utils.defaultAbiCoder.encode(e,[t])}poll(e){try{const t=this,{chainId:r,owner:n,provider:o,orderBookApi:a}=e,s=Pe(r,o);return Promise.resolve(function(o,p){try{var u=function(){const o=t.isValid();return o.isValid?Promise.resolve(t.pollValidate(e)).then(function(o){return o||Promise.resolve(t.isAuthorized(e)).then(function(o){return o?Promise.resolve(s.getTradeableOrderWithSignature(n,t.leaf,t.offChainInput,[])).then(function([o,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(ee.getDomain(e)).then(function(e){return n(e,r,t)})})}catch(e){return Promise.reject(e)}}(r,n,Oe(o))).then(function(r){return Promise.resolve(a.getOrder(r).then(()=>!0).catch(()=>!1)).then(function(n){let a;function i(e){return a?e:{result:exports.PollResultCode.SUCCESS,order:o,signature:s}}const p=function(){if(n)return Promise.resolve(t.handlePollFailedAlreadyPresent(r,o,e)).then(function(e){if(e)return a=1,e;const t={result:exports.PollResultCode.TRY_NEXT_BLOCK,reason:"Order already in orderbook"};return a=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: ${o.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 Pe(t,n).callStatic.singleOrders(r,this.id)}cabinet(e){const{chainId:t,owner:r,provider:n}=e;return Pe(t,n).callStatic.cabinet(r,this.ctx)}static deserializeHelper(e,t,r,n){try{const{handler:a,salt:s,staticInput:i}=Te(e);if(a!=t)throw new Error("HandlerMismatch");const[p]=o.utils.defaultAbiCoder.decode(r,i);return n(p,s)}catch(e){throw"HandlerMismatch"===e.message?e:new Error("InvalidSerializedConditionalOrder")}}}const ve=["address","bytes32","bytes"],ge=["tuple(bytes32[] proof, tuple(address handler, bytes32 salt, bytes staticInput) params)[]"];class _e{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(!_e.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:a}=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,...o}=t[r];if(!_e.orderTypeRegistry.hasOwnProperty(n))throw new Error(`Unknown order type: ${n}`);e[r]=new(0,_e.orderTypeRegistry[n])(o)}return e}return"object"==typeof t&&null!==t&&t.hasOwnProperty("type")&&t.hasOwnProperty("hex")&&"BigNumber"===t.type?o.BigNumber.from(t):t}),s=new _e(t,r,n);return s.location=a,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)]),ve)),this.tree}static decodeFromJSON(e){return JSON.parse(e)}prepareProofStruct(e,t,r){try{const n=this;void 0===e&&(e=n.location);const a=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,o){try{var a=Promise.resolve(r(n.encodeToJSON(t)))}catch(e){return o(e)}return a&&a.then?a.then(void 0,o):a}(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(a().then(t=>{try{return o.utils.hexlify(o.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,o){try{function a(r){return Promise.resolve(s.getTradeableOrderWithSignature(e,t.params,r,t.proof))}const s=Pe(r,n);return Promise.resolve(o?Promise.resolve(o(e,t.params)).then(a):a("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 o.utils.defaultAbiCoder.encode(ge,[this.getProofs(e)])}encodeToJSON(e){return JSON.stringify(this.getProofs(e))}reset(){this.tree=void 0}static registerOrderType(e,t){_e.orderTypeRegistry[e]=t}static resetOrderTypeRegistry(){_e.orderTypeRegistry={}}}_e.orderTypeRegistry={};const Ne="0x6cF1e9cA41f7611dEf408122793c358a3d11E5a5",Ce="0x52eD56Da04309Aca4c3FECC595298d80C2f16BAc",Re=o.BigNumber.from(2).pow(32).sub(1),De=o.BigNumber.from(31536e3),we=["tuple(address sellToken, address buyToken, address receiver, uint256 partSellAmount, uint256 minPartLimit, uint256 t0, uint256 n, uint256 t, uint256 span, bytes32 appData)"];var Le,Ue;exports.DurationType=void 0,(Le=exports.DurationType||(exports.DurationType={})).AUTO="AUTO",Le.LIMIT_DURATION="LIMIT_DURATION",exports.StartTimeValue=void 0,(Ue=exports.StartTimeValue||(exports.StartTimeValue={})).AT_MINING_TIME="AT_MINING_TIME",Ue.AT_EPOCH="AT_EPOCH";const Me={startType:exports.StartTimeValue.AT_MINING_TIME},ke={durationType:exports.DurationType.AUTO};class Be extends xe{constructor(e){const{handler:t,salt:r,data:n,hasOffChainInput:o}=e;if(t!==Ne)throw new Error(`InvalidHandler: Expected: ${Ne}, provided: ${t}`);super({handler:Ne,salt:r,data:n,hasOffChainInput:o}),this.isSingleOrder=!0}static fromData(e,t){return new Be({handler:Ne,data:e,salt:t})}static fromParams(e){return Be.deserialize(me(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:a=Me,numberOfParts:s,timeBetweenParts:i,durationOfPart:p=ke}=this.data;if(e==r)return"InvalidSameToken";if(e==o.constants.AddressZero||r==o.constants.AddressZero)return"InvalidToken";if(!t.gt(o.constants.Zero))return"InvalidSellAmount";if(!n.gt(o.constants.Zero))return"InvalidMinBuyAmount";if(a.startType===exports.StartTimeValue.AT_EPOCH){const e=a.epoch;if(!e.gte(o.constants.Zero)||!e.lt(Re))return"InvalidStartTime"}return s.gt(o.constants.One)&&s.lte(Re)?i.gt(o.constants.Zero)&&i.lte(De)?p.durationType!==exports.DurationType.LIMIT_DURATION||p.duration.lte(i)?he(we,[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=o.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(ie(e.provider)).then(function(r){const{blockInfo:n=r}=e,{blockTimestamp:o}=n;return function(r,n){try{var a=Promise.resolve(t.startTimestamp(e)).then(function(e){if(e>o)return{result:exports.PollResultCode.TRY_AT_EPOCH,epoch:e,reason:`TWAP hasn't started yet. Starts at ${e} (${fe(e)})`};const r=t.endTimestamp(e);return o>=r?{result:exports.PollResultCode.DONT_TRY_AGAIN,reason:`TWAP has expired. Expired at ${r} (${fe(r)})`}:void 0})}catch(e){return n(e)}return a&&a.then?a.then(void 0,n):a}(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(ie(r.provider)).then(function(t){const{blockInfo:n=t}=r,{blockTimestamp:o}=n,a=e.data.timeBetweenParts.toNumber(),{numberOfParts:s}=e.data;return Promise.resolve(e.startTimestamp(r)).then(function(e){if(o<e)return{result:exports.PollResultCode.UNEXPECTED_ERROR,reason:`TWAP part hash't started. First TWAP part start at ${e} (${fe(e)})`,error:void 0};const t=s.mul(a).add(e).toNumber();if(o>=t)return{result:exports.PollResultCode.UNEXPECTED_ERROR,reason:`TWAP is expired. Expired at ${t} (${fe(t)})`,error:void 0};const r=Math.floor((o-e)/a);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)*a;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} (${fe(n)})`}})})}catch(e){return Promise.reject(e)}}serialize(){return me(this.leaf)}encodeStaticInput(){return super.encodeStaticInputHelper(we,this.staticInput)}static deserialize(e){return super.deserializeHelper(e,Ne,we,(e,t)=>new Be({handler:Ne,salt:t,data:Ve(e)}))}toString(){const{sellAmount:e,sellToken:t,buyAmount:r,buyToken:n,numberOfParts:o,startTime:a=Me,timeBetweenParts:s,durationOfPart:i=ke,receiver:p,appData:u}=this.data,d=a.startType===exports.StartTimeValue.AT_MINING_TIME?"AT_MINING_TIME":a.epoch.toNumber(),l=i.durationType===exports.DurationType.AUTO?"AUTO":i.duration.toNumber(),c={sellAmount:e.toString(),sellToken:t,buyAmount:r.toString(),buyToken:n,numberOfParts:o.toString(),startTime:d,timeBetweenParts:s.toNumber(),durationOfPart:l,receiver:p,appData:u};return`${this.orderType} (${this.id}): ${JSON.stringify(c)}`}transformDataToStruct(e){return Fe(e)}transformStructToData(e){return Ve(e)}}function Fe(e){const{sellAmount:t,buyAmount:r,numberOfParts:n,startTime:a=Me,timeBetweenParts:s,durationOfPart:i=ke,...p}=e,{partSellAmount:u,minPartLimit:d}=n&&!n.isZero()?{partSellAmount:t.div(n),minPartLimit:r.div(n)}:{partSellAmount:o.constants.Zero,minPartLimit:o.constants.Zero},l=i.durationType===exports.DurationType.AUTO?o.constants.Zero:i.duration;return{partSellAmount:u,minPartLimit:d,t0:a.startType===exports.StartTimeValue.AT_MINING_TIME?o.constants.Zero:a.epoch,n:n,t:s,span:l,...p}}function Ve(e){const{n:t,partSellAmount:r,minPartLimit:n,t:o,t0:a,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:a};return{sellAmount:r.mul(t),buyAmount:n.mul(t),startTime:u,numberOfParts:t,timeBetweenParts:o,durationOfPart:p,...i}}const Ge={[Ne]:e=>Be.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=ye,exports.COW_PROTOCOL_SETTLEMENT_CONTRACT_ADDRESS=f,exports.COW_PROTOCOL_VAULT_RELAYER_ADDRESS=b,exports.CURRENT_BLOCK_TIMESTAMP_FACTORY_ADDRESS=Ce,exports.ConditionalOrder=xe,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=P,exports.DEFAULT_CONDITIONAL_ORDER_REGISTRY=Ge,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=x,exports.DEFAULT_TOKEN_FORMATTER=(e,t)=>`${t}@${e}`,exports.ENVS_LIST=p,exports.EXTENSIBLE_FALLBACK_HANDLER=c,exports.EXTENSIBLE_FALLBACK_HANDLER_CONTRACT_ADDRESS=I,exports.MAX_FREQUENCY=De,exports.MAX_UINT32=Re,exports.Multiplexer=_e,exports.ORDER_BOOK_PROD_CONFIG=_,exports.ORDER_BOOK_STAGING_CONFIG=N,exports.OrderBookApi=class{constructor(e={}){this.context=void 0,this.rateLimiter=void 0,this.context={...u,...e},this.rateLimiter=new t.RateLimiter(e.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 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 o=new URLSearchParams(C({offset:t.toString(),limit:r.toString()}));return this.fetch({path:`/api/v1/account/${e}/orders`,method:"GET",query:o},n).then(e=>e.map(g))}getTxOrders(e,t={}){return this.fetch({path:`/api/v1/transactions/${e}/orders`,method:"GET"},t).then(e=>e.map(g))}getOrder(e,t={}){return this.fetch({path:`/api/v1/orders/${e}`,method:"GET"},t).then(e=>g(e))}getOrderMultiEnv(e,t={}){const{env:r}=this.getContextWithOverride(t),n=p.filter(e=>e!==r);let o=0;const a=r=>{const s=n[o];return r instanceof A&&404===r.response.status&&s?(o++,this.getOrder(e,{...t,env:s}).catch(a)):Promise.reject(r)};return this.getOrder(e,{...t,env:r}).catch(a)}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}fetch(e,r={}){const{chainId:n,env:o,backoffOpts:a}=this.getContextWithOverride(r),s=this.getApiBaseUrls(o)[n],i=a||P,p=r.limiterOpts?new t.RateLimiter(r.limiterOpts):this.rateLimiter;return E(s,e,p,i)}},exports.OrderBookApiError=A,exports.OrderSigningUtils=ee,exports.SUBGRAPH_PROD_CONFIG=Z,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(q,{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 o=this,{chainId:a,env:s}=o.getContextWithOverride(r),i=o.getEnvConfigs(s)[a];if(null===i)throw new Error("Unsupported Network. The subgraph API is not available in the Network "+a);return Promise.resolve(function(r,o){try{var a=Promise.resolve(n.request(i,e,t))}catch(e){return o(e)}return a&&a.then?a.then(void 0,o):a}(0,function(r){throw console.error(`[subgraph:${o.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?Z:z}},exports.TWAP_ADDRESS=Ne,exports.Twap=Be,exports.createSetDomainVerifierTx=function(e,t){return se.createInterface().encodeFunctionData("setDomainVerifier",[e,t])},exports.decodeParams=Te,exports.encodeParams=me,exports.formatEpoch=fe,exports.fromStructToOrder=Oe,exports.getBlockInfo=ie,exports.getDomainVerifier=function(e,t,r,n){try{const o=se.connect(I[r],n);return Promise.resolve(o.callStatic.domainVerifiers(e,t))}catch(e){return Promise.reject(e)}},exports.getQuoteAmountsAndCosts=function(e){var t;const{orderParams:r,sellDecimals:n,buyDecimals:o,slippagePercentBps:a}=e,s=null!==(t=e.partnerFeeBps)&&void 0!==t?t:0,i=r.kind===exports.OrderKind.SELL,p=K(r.feeAmount,n),u=K(r.sellAmount,n),d=K(r.buyAmount,o),l=d.num/u.num,c=K(u.big+p.big,n),y=K(l*c.num,o),m=s>0?(i?y.big:u.big)*BigInt(s)/H:BigInt(0),T=i?{sellAmount:c.big,buyAmount:d.big-m}:{sellAmount:c.big+m,buyAmount:d.big},h=e=>e*BigInt(a)/H,f=i?{sellAmount:T.sellAmount,buyAmount:T.buyAmount-h(T.buyAmount)}:{sellAmount:T.sellAmount+h(T.sellAmount),buyAmount:T.buyAmount};return{isSell:i,costs:{networkFee:{amountInSellCurrency:p.big,amountInBuyCurrency:K(l*p.num,o).big},partnerFee:{amount:m,bps:s}},beforeNetworkCosts:{sellAmount:u.big,buyAmount:y.big},afterNetworkCosts:{sellAmount:c.big,buyAmount:d.big},afterPartnerFees:T,afterSlippage:f}},exports.isComposableCow=function(e,t){return e===O[t]},exports.isExtensibleFallbackHandler=function(e,t){return e===I[t]},exports.isValidAbi=he,exports.logPrefix="cow-sdk:",exports.mapAddressToSupportedNetworks=h,exports.mapSupportedNetworks=T,exports.request=E,exports.transformDataToStruct=Fe,exports.transformStructToData=Ve;
29
29
  //# sourceMappingURL=index.js.map