@cowprotocol/cow-sdk 5.4.1-RC.0 → 5.4.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- {"version":3,"file":"index-d84e3bdc.js","sources":["../src/common/chains.ts","../src/common/configs.ts","../src/common/cow-error.ts","../src/common/ipfs.ts","../src/common/consts.ts","../src/order-book/request.ts","../src/order-book/transformOrder.ts","../src/order-book/api.ts","../src/order-book/generated/models/BuyTokenDestination.ts","../src/order-book/generated/models/CompetitionOrderStatus.ts","../src/order-book/generated/models/EcdsaSigningScheme.ts","../src/order-book/generated/models/OnchainOrderData.ts","../src/order-book/generated/models/OrderCancellationError.ts","../src/order-book/generated/models/OrderClass.ts","../src/order-book/generated/models/OrderKind.ts","../src/order-book/generated/models/OrderPostError.ts","../src/order-book/generated/models/OrderQuoteSideKindBuy.ts","../src/order-book/generated/models/OrderQuoteSideKindSell.ts","../src/order-book/generated/models/OrderStatus.ts","../src/order-book/generated/models/PriceEstimationError.ts","../src/order-book/generated/models/PriceQuality.ts","../src/order-book/generated/models/SellTokenSource.ts","../src/order-book/generated/models/SigningScheme.ts","../src/order-book/quoteAmountsAndCostsUtils.ts","../src/subgraph/queries.ts","../src/subgraph/api.ts","../src/order-signing/orderSigningUtils.ts","../src/composable/types.ts","../src/composable/generated/factories/ComposableCoW__factory.ts","../src/composable/generated/factories/ExtensibleFallbackHandler__factory.ts","../src/composable/utils.ts","../src/composable/contracts.ts","../src/composable/ConditionalOrder.ts","../src/utils.ts","../src/composable/Multiplexer.ts","../src/composable/ConditionalOrderFactory.ts","../src/composable/orderTypes/Twap.ts","../src/composable/orderTypes/index.ts"],"sourcesContent":["/**\n * Supported chains and their `chainId` for the SDK.\n * @enum\n */\nexport enum SupportedChainId {\n MAINNET = 1,\n GNOSIS_CHAIN = 100,\n ARBITRUM_ONE = 42161,\n SEPOLIA = 11155111,\n}\n","import { SupportedChainId } from './chains'\nimport { BackoffOptions } from 'exponential-backoff'\nimport { RateLimiterOpts } from 'limiter/dist/esm'\n\n/**\n * IPFS configuration.\n *\n * For production use, consider using {@link Pinata: https://www.pinata.cloud/}\n * @property {string} [uri] The URI of the IPFS node to use.\n * @property {string} [writeUri] The URI of the IPFS node to use for writing.\n * @property {string} [readUri] The URI of the IPFS node to use for reading.\n * @property {string} [pinataApiKey] The API key to use for Pinata.\n * @property {string} [pinataApiSecret] The API secret to use for Pinata.\n */\nexport interface IpfsConfig {\n uri?: string\n writeUri?: string\n readUri?: string\n pinataApiKey?: string\n pinataApiSecret?: string\n}\n\n/**\n * @property {RateLimiterOpts} [limiterOpts] The options to use for the rate limiter.\n * @property {BackoffOptions} [backoffOpts] The options to use for the backoff.\n */\nexport interface RequestOptions {\n limiterOpts?: RateLimiterOpts\n backoffOpts?: BackoffOptions\n}\n\n/**\n * The environment to use for the Cow API.\n */\nexport type CowEnv = 'prod' | 'staging'\n\n/**\n * Override some properties of the {@link ApiContext}.\n */\nexport type PartialApiContext = Partial<ApiContext>\n\n/**\n * @property {string} [1] The base URL for the mainnet API.\n * @property {string} [100] The base URL for the Gnosis Chain API.\n * @property {string} [11155111] The base URL for the Sepolia testnet API.\n */\nexport type ApiBaseUrls = Record<SupportedChainId, string>\n\n/**\n * Define the context to use for the CoW Protocol API.\n *\n * CoW Protocol is a set of smart contracts and off-chain services, deployed on **multiple chains**.\n * {@link SupportedChainId Supported chains} are:\n * - Mainnet\n * - Gnosis Chain\n * - Sepolia\n *\n * Each chain has it's own API, and each API has it's own base URL.\n *\n * Options may be selectively overridden by passing a {@link PartialApiContext} to the constructor.\n * @see {@link https://api.cow.fi/docs/#/}\n * @property {SupportedChainId} chainId The `chainId`` corresponding to this CoW Protocol API instance.\n * @property {CowEnv} env The environment that this context corresponds to.\n * @property {ApiBaseUrls} [baseUrls] URls that may be used to connect to this context.\n */\nexport interface ApiContext {\n chainId: SupportedChainId\n env: CowEnv\n baseUrls?: ApiBaseUrls\n limiterOpts?: RateLimiterOpts\n backoffOpts?: BackoffOptions\n}\n\n/**\n * The list of available environments.\n */\nexport const ENVS_LIST: CowEnv[] = ['prod', 'staging']\n\n/**\n * The default CoW Protocol API context.\n */\nexport const DEFAULT_COW_API_CONTEXT: ApiContext = {\n env: 'prod',\n chainId: SupportedChainId.MAINNET,\n}\n","export class CowError extends Error {\n error_code?: string\n\n constructor(message: string, error_code?: string) {\n super(message)\n this.error_code = error_code\n }\n}\n\nexport const logPrefix = 'cow-sdk:'\n","export const DEFAULT_IPFS_READ_URI = 'https://gnosis.mypinata.cloud/ipfs'\nexport const DEFAULT_IPFS_WRITE_URI = 'https://api.pinata.cloud'\n","import { SupportedChainId } from './chains'\n\nexport const BUY_ETH_ADDRESS = '0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE'\nexport const EXTENSIBLE_FALLBACK_HANDLER = '0x2f55e8b20D0B9FEFA187AA7d00B6Cbe563605bF5'\nexport const COMPOSABLE_COW = '0xfdaFc9d1902f4e0b84f65F49f244b32b31013b74'\n\nconst VAULT_RELAYER = '0xC92E8bdf79f0507f65a392b0ab4667716BFE0110'\nconst SETTLEMENT_CONTRACT = '0x9008D19f58AAbD9eD0D60971565AA8510560ab41'\n\n/**\n * The list of supported chains.\n */\nexport const ALL_SUPPORTED_CHAIN_IDS: SupportedChainId[] = Object.values(SupportedChainId).filter(\n (chainId) => typeof chainId === 'number'\n) as SupportedChainId[]\n\nexport function mapSupportedNetworks<T>(value: (chainId: SupportedChainId) => T): Record<SupportedChainId, T>\nexport function mapSupportedNetworks<T>(value: T): Record<SupportedChainId, T>\nexport function mapSupportedNetworks<T>(value: T | ((chainId: SupportedChainId) => T)): Record<SupportedChainId, T> {\n return ALL_SUPPORTED_CHAIN_IDS.reduce<Record<number, T>>(\n (acc, chainId) => ({\n ...acc,\n [chainId]: typeof value === 'function' ? (value as (chainId: SupportedChainId) => T)(chainId) : value,\n }),\n {}\n )\n}\n\nexport function mapAddressToSupportedNetworks(address: string): Record<SupportedChainId, string> {\n return mapSupportedNetworks(address)\n}\n\n/**\n * An object containing the addresses of the CoW Protocol settlement contracts for each supported chain.\n */\nexport const COW_PROTOCOL_SETTLEMENT_CONTRACT_ADDRESS = mapAddressToSupportedNetworks(SETTLEMENT_CONTRACT)\n\n/**\n * An object containing the addresses of the CoW Protocol Vault realyer contracts for each supported chain.\n */\nexport const COW_PROTOCOL_VAULT_RELAYER_ADDRESS = mapAddressToSupportedNetworks(VAULT_RELAYER)\n\n/**\n * An object containing the addresses of the `ExtensibleFallbackHandler` contracts for each supported chain.\n */\nexport const EXTENSIBLE_FALLBACK_HANDLER_CONTRACT_ADDRESS = mapAddressToSupportedNetworks(EXTENSIBLE_FALLBACK_HANDLER)\n\n/**\n * An object containing the addresses of the `ComposableCow` contracts for each supported chain.\n */\nexport const COMPOSABLE_COW_CONTRACT_ADDRESS = mapAddressToSupportedNetworks(COMPOSABLE_COW)\n","import { backOff, BackoffOptions } from 'exponential-backoff'\nimport { RateLimiter, RateLimiterOpts } from 'limiter'\n\n/**\n * Error thrown when the CoW Protocol OrderBook API returns an error.\n */\nexport class OrderBookApiError<T = unknown> extends Error {\n /**\n * Error thrown when the CoW Protocol OrderBook API returns an error.\n * @param response The response from the CoW Protocol OrderBook API.\n * @param body The body of the response.\n * @constructor\n */\n constructor(public readonly response: Response, public readonly body: T) {\n super(typeof body === 'string' ? body : response.statusText)\n }\n}\n\nconst REQUEST_TIMEOUT = 408\nconst TOO_EARLY = 425\nconst TOO_MANY_REQUESTS = 429\nconst INTERNAL_SERVER_ERROR = 500\nconst BAD_GATEWAY = 502\nconst SERVICE_UNAVAILABLE = 503\nconst GATEWAY_TIMEOUT = 504\n\nconst STATUS_CODES_TO_RETRY = [\n REQUEST_TIMEOUT,\n TOO_EARLY,\n TOO_MANY_REQUESTS,\n INTERNAL_SERVER_ERROR,\n BAD_GATEWAY,\n SERVICE_UNAVAILABLE,\n GATEWAY_TIMEOUT,\n]\n\n/**\n * The default backoff options for CoW Protocol's API\n * @see {@link Backoff configuration: https://www.npmjs.com/package/@insertish/exponential-backoff}\n */\nexport const DEFAULT_BACKOFF_OPTIONS: BackoffOptions = {\n numOfAttempts: 10,\n maxDelay: Infinity,\n jitter: 'none',\n retry: (error: Error | OrderBookApiError) => {\n if (error instanceof OrderBookApiError) {\n return STATUS_CODES_TO_RETRY.includes(error.response.status)\n }\n\n return true\n },\n}\n\n/**\n * The default rate limiter options for CoW Protocol's API.\n *\n * **CAUTION**: The CoW Protocol OrderBook API is limited to 5 requests per second per IP.\n */\nexport const DEFAULT_LIMITER_OPTIONS: RateLimiterOpts = {\n tokensPerInterval: 5,\n interval: 'second',\n}\n\n/**\n * Describe the parameters for a fetch request.\n */\nexport interface FetchParams {\n path: string\n method: 'GET' | 'POST' | 'DELETE' | 'PUT'\n body?: unknown\n query?: URLSearchParams\n}\n\nconst getResponseBody = async (response: Response): Promise<unknown> => {\n if (response.status !== 204) {\n try {\n const contentType = response.headers.get('Content-Type')\n if (contentType) {\n if (contentType.toLowerCase().startsWith('application/json')) {\n return await response.json()\n } else {\n return await response.text()\n }\n }\n } catch (error) {\n console.error(error)\n }\n }\n return undefined\n}\n\n/**\n * Helper function to make a rate-limited request to an API.\n * @param baseUrl The base URL of the API.\n * @param path The path of the request.\n * @param query The query parameters of the request.\n * @param method The HTTP method of the request.\n * @param body The body of the request.\n * @param rateLimiter The rate limiter to use.\n * @param backoffOpts The backoff options to use.\n * @returns The response of the request.\n * @throws If the API returns an error or if the request fails.\n */\nexport async function request<T>(\n baseUrl: string,\n { path, query, method, body }: FetchParams,\n rateLimiter: RateLimiter,\n backoffOpts: BackoffOptions\n): Promise<T> {\n const queryString = query ? '?' + query : ''\n const headers = {\n Accept: 'application/json',\n 'Content-Type': 'application/json',\n }\n\n const url = `${baseUrl}${path}${queryString}`\n const bodyContent = (() => {\n if (!body) return undefined\n\n return typeof body === 'string' ? body : JSON.stringify(body)\n })()\n const init: RequestInit = {\n method,\n body: bodyContent,\n headers,\n }\n\n return backOff<T>(async () => {\n await rateLimiter.removeTokens(1)\n\n const response = await fetch(url, init)\n const responseBody = (await getResponseBody(response)) as T\n\n // Successful response\n if (response.status >= 200 && response.status < 300) {\n return responseBody\n }\n\n return Promise.reject(new OrderBookApiError(response, responseBody))\n }, backoffOpts)\n}\n","import { BUY_ETH_ADDRESS } from '../common/consts'\nimport { Order } from './generated'\nimport { EnrichedOrder } from './types'\n\n/**\n * Apply programmatic transformations to an order.\n *\n * For example, transformations may be applied to an order to recognise it as a Native EthFlow order.\n * @param order to apply transformations to\n * @returns An order with the total fee added.\n */\nexport function transformOrder(order: Order): EnrichedOrder {\n return transformEthFlowOrder(addTotalFeeToOrder(order))\n}\n\n/**\n * Add the total fee to the order.\n *\n * The total fee of the order will be represented by the `totalFee` field, which is the sum of `executedSurplusFee`\n * and `executedFeeAmount`.\n *\n * Note that either `executedSurplusFee` or `executedFeeAmount` may be `0`, or both might have a non `0` value.\n *\n * See https://cowservices.slack.com/archives/C036G0J90BU/p1705322037866779?thread_ts=1705083817.684659&cid=C036G0J90BU\n *\n * @param dto The order to add the total fee to.\n * @returns The order with the total fee added.\n */\nfunction addTotalFeeToOrder(dto: Order): EnrichedOrder {\n const { executedFeeAmount, executedSurplusFee } = dto\n\n const _executedFeeAmount = BigInt(executedFeeAmount || '0')\n const _executedSurplusFee = BigInt(executedSurplusFee || '0')\n\n const totalFee = String(_executedFeeAmount + _executedSurplusFee)\n\n return {\n ...dto,\n totalFee,\n }\n}\n\n/**\n * Transform order field for Native EthFlow orders\n *\n * A no-op for regular orders\n * For Native EthFlow, due to how the contract is setup:\n * - sellToken set to Native token address\n * - owner set to `onchainUser`\n * - validTo set to `ethflowData.userValidTo`\n */\nfunction transformEthFlowOrder(order: EnrichedOrder): EnrichedOrder {\n const { ethflowData } = order\n\n if (!ethflowData) {\n return order\n }\n\n const { userValidTo: validTo } = ethflowData\n const owner = order.onchainUser || order.owner\n const sellToken = BUY_ETH_ADDRESS\n\n return { ...order, validTo, owner, sellToken }\n}\n","import 'cross-fetch/polyfill'\nimport { RateLimiter } from 'limiter'\nimport { SupportedChainId } from '../common/chains'\nimport {\n ApiBaseUrls,\n ApiContext,\n CowEnv,\n DEFAULT_COW_API_CONTEXT,\n ENVS_LIST,\n PartialApiContext,\n} from '../common/configs'\nimport { CowError } from '../common/cow-error'\nimport {\n Address,\n AppDataHash,\n AppDataObject,\n CompetitionOrderStatus,\n NativePriceResponse,\n Order,\n OrderCancellations,\n OrderCreation,\n OrderQuoteRequest,\n OrderQuoteResponse,\n SolverCompetitionResponse,\n TotalSurplus,\n Trade,\n TransactionHash,\n UID,\n} from './generated'\nimport { DEFAULT_BACKOFF_OPTIONS, DEFAULT_LIMITER_OPTIONS, FetchParams, OrderBookApiError, request } from './request'\nimport { transformOrder } from './transformOrder'\nimport { EnrichedOrder } from './types'\n\n/**\n * An object containing *production* environment base URLs for each supported `chainId`.\n * @see {@link https://api.cow.fi/docs/#/}\n */\nexport const ORDER_BOOK_PROD_CONFIG: ApiBaseUrls = {\n [SupportedChainId.MAINNET]: 'https://api.cow.fi/mainnet',\n [SupportedChainId.GNOSIS_CHAIN]: 'https://api.cow.fi/xdai',\n [SupportedChainId.ARBITRUM_ONE]: 'https://api.cow.fi/arbitrum_one',\n [SupportedChainId.SEPOLIA]: 'https://api.cow.fi/sepolia',\n}\n\n/**\n * An object containing *staging* environment base URLs for each supported `chainId`.\n */\nexport const ORDER_BOOK_STAGING_CONFIG: ApiBaseUrls = {\n [SupportedChainId.MAINNET]: 'https://barn.api.cow.fi/mainnet',\n [SupportedChainId.GNOSIS_CHAIN]: 'https://barn.api.cow.fi/xdai',\n [SupportedChainId.ARBITRUM_ONE]: 'https://barn.api.cow.fi/arbitrum_one',\n [SupportedChainId.SEPOLIA]: 'https://barn.api.cow.fi/sepolia',\n}\n\nfunction cleanObjectFromUndefinedValues(obj: Record<string, string>): typeof obj {\n return Object.keys(obj).reduce((acc, key) => {\n const val = obj[key]\n if (typeof val !== 'undefined') acc[key] = val\n return acc\n }, {} as typeof obj)\n}\n\n/**\n * The parameters for the `getOrders` request.\n */\nexport type GetOrdersRequest = {\n owner: Address\n offset?: number\n limit?: number\n}\n\n/**\n * The CoW Protocol OrderBook API client.\n *\n * This is the main entry point for interacting with the CoW Protocol OrderBook API. The main advantage of using\n * this client is the batteries-included approach to interacting with the API. It handles:\n *\n * - Environment configuration (mainnet, staging, etc.)\n * - Rate limiting\n * - Retries\n * - Backoff\n * - Error handling\n * - Request signing\n * - Request validation\n *\n * @example\n *\n * ```typescript\n * import { OrderBookApi, OrderSigningUtils, SupportedChainId } from '@cowprotocol/cow-sdk'\n * import { Web3Provider } from '@ethersproject/providers'\n *\n * const account = 'YOUR_WALLET_ADDRESS'\n * const chainId = 100 // Gnosis chain\n * const provider = new Web3Provider(window.ethereum)\n * const signer = provider.getSigner()\n *\n * const quoteRequest = {\n * sellToken: '0x6a023ccd1ff6f2045c3309768ead9e68f978f6e1', // WETH gnosis chain\n * buyToken: '0x9c58bacc331c9aa871afd802db6379a98e80cedb', // GNO gnosis chain\n * from: account,\n * receiver: account,\n * sellAmountBeforeFee: (0.4 * 10 ** 18).toString(), // 0.4 WETH\n * kind: OrderQuoteSide.kind.SELL,\n * }\n *\n * const orderBookApi = new OrderBookApi({ chainId: SupportedChainId.GNOSIS_CHAIN })\n *\n * async function main() {\n * const { quote } = await orderBookApi.getQuote(quoteRequest)\n *\n * const orderSigningResult = await OrderSigningUtils.signOrder(quote, chainId, signer)\n *\n * const orderId = await orderBookApi.sendOrder({ ...quote, ...orderSigningResult })\n *\n * const order = await orderBookApi.getOrder(orderId)\n *\n * const trades = await orderBookApi.getTrades({ orderId })\n *\n * const orderCancellationSigningResult = await OrderSigningUtils.signOrderCancellations([orderId], chainId, signer)\n *\n * const cancellationResult = await orderBookApi.sendSignedOrderCancellations({...orderCancellationSigningResult, orderUids: [orderId] })\n *\n * console.log('Results: ', { orderId, order, trades, orderCancellationSigningResult, cancellationResult })\n * }\n * ```\n *\n * @see {@link Swagger documentation https://api.cow.fi/docs/#/}\n * @see {@link OrderBook API https://github.com/cowprotocol/services}\n */\nexport class OrderBookApi {\n public context: ApiContext\n\n private rateLimiter: RateLimiter\n\n /**\n * Creates a new instance of the CoW Protocol OrderBook API client.\n * @param context - The API context to use. If not provided, the default context will be used.\n */\n constructor(context: PartialApiContext = {}) {\n this.context = { ...DEFAULT_COW_API_CONTEXT, ...context }\n this.rateLimiter = new RateLimiter(context.limiterOpts || DEFAULT_LIMITER_OPTIONS)\n }\n\n /**\n * Get the version of the API.\n * @param contextOverride Optional context override for this request.\n * @returns The version of the API.\n * @see {@link https://api.cow.fi/docs/#/default/get_api_v1_version}\n */\n getVersion(contextOverride: PartialApiContext = {}): Promise<string> {\n return this.fetch({ path: '/api/v1/version', method: 'GET' }, contextOverride)\n }\n\n /**\n * Get all the trades for either an `owner` **OR** `orderUid`.\n *\n * Given that an order *may* be partially fillable, it is possible that a discrete order (`orderUid`)\n * may have *multiple* trades. Therefore, this method returns a list of trades, either for *all* the orders\n * of a given `owner`, or for a discrete order (`orderUid`).\n * @param request Either an `owner` or an `orderUid` **MUST** be specified.\n * @param contextOverride Optional context override for this request.\n * @returns A list of trades matching the request.\n */\n getTrades(\n request: { owner?: Address; orderUid?: UID },\n contextOverride: PartialApiContext = {}\n ): Promise<Array<Trade>> {\n if (request.owner && request.orderUid) {\n return Promise.reject(new CowError('Cannot specify both owner and orderId'))\n } else if (!request.owner && !request.orderUid) {\n return Promise.reject(new CowError('Must specify either owner or orderId'))\n }\n\n const query = new URLSearchParams(cleanObjectFromUndefinedValues(request))\n\n return this.fetch({ path: '/api/v1/trades', method: 'GET', query }, contextOverride)\n }\n\n /**\n * Get a list of orders for a given `owner`.\n * @param request The request parameters with `request.offset = 0` and `request.limit = 1000` by default.\n * @param contextOverride Optional context override for this request.\n * @returns A list of orders matching the request.\n * @see {@link GetOrdersRequest}\n * @see {@link EnrichedOrder}\n */\n getOrders(\n { owner, offset = 0, limit = 1000 }: GetOrdersRequest,\n contextOverride: PartialApiContext = {}\n ): Promise<Array<EnrichedOrder>> {\n const query = new URLSearchParams(\n cleanObjectFromUndefinedValues({ offset: offset.toString(), limit: limit.toString() })\n )\n\n return this.fetch<Array<EnrichedOrder>>(\n { path: `/api/v1/account/${owner}/orders`, method: 'GET', query },\n contextOverride\n ).then((orders) => {\n return orders.map(transformOrder)\n })\n }\n\n /**\n * Get a list of orders from a given settlement transaction hash.\n * @param txHash The transaction hash.\n * @param contextOverride Optional context override for this request.\n * @returns A list of orders matching the request.\n * @see {@link EnrichedOrder}\n */\n getTxOrders(txHash: TransactionHash, contextOverride: PartialApiContext = {}): Promise<Array<EnrichedOrder>> {\n return this.fetch<Array<EnrichedOrder>>(\n { path: `/api/v1/transactions/${txHash}/orders`, method: 'GET' },\n contextOverride\n ).then((orders) => {\n return orders.map(transformOrder)\n })\n }\n\n /**\n * Get an order by its unique identifier, `orderUid`.\n * @param orderUid The unique identifier of the order.\n * @param contextOverride Optional context override for this request.\n * @returns The order matching the request.\n */\n getOrder(orderUid: UID, contextOverride: PartialApiContext = {}): Promise<EnrichedOrder> {\n return this.fetch<Order>({ path: `/api/v1/orders/${orderUid}`, method: 'GET' }, contextOverride).then((order) => {\n return transformOrder(order)\n })\n }\n\n /**\n * Get the order status while open\n */\n getOrderCompetitionStatus(orderUid: UID, contextOverride: PartialApiContext = {}): Promise<CompetitionOrderStatus> {\n return this.fetch({ path: `/api/v1/orders/${orderUid}/status`, method: 'GET' }, contextOverride)\n }\n\n /**\n * Attempt to get an order by its unique identifier, `orderUid`, from multiple environments.\n *\n * **NOTE**: The environment refers to either `prod` or `staging`. This allows a conveience method to\n * attempt to get an order from both environments, in the event that the order is not found in the\n * environment specified in the context.\n * @param orderUid The unique identifier of the order.\n * @param contextOverride Optional context override for this request.\n * @returns The order matching the request.\n * @throws {OrderBookApiError} If the order is not found in any of the environments.\n */\n getOrderMultiEnv(orderUid: UID, contextOverride: PartialApiContext = {}): Promise<EnrichedOrder> {\n const { env } = this.getContextWithOverride(contextOverride)\n const otherEnvs = ENVS_LIST.filter((i) => i !== env)\n\n let attemptsCount = 0\n\n const fallback = (error: Error | OrderBookApiError): Promise<EnrichedOrder> => {\n const nextEnv = otherEnvs[attemptsCount]\n\n if (error instanceof OrderBookApiError && error.response.status === 404 && nextEnv) {\n attemptsCount++\n\n return this.getOrder(orderUid, { ...contextOverride, env: nextEnv }).catch(fallback)\n }\n\n return Promise.reject(error)\n }\n\n return this.getOrder(orderUid, { ...contextOverride, env }).catch(fallback)\n }\n\n /**\n * Get a quote for an order.\n * This allows for the calculation of the total cost of an order, including fees, before signing and submitting.\n * @param requestBody The parameters for the order quote request.\n * @param contextOverride Optional context override for this request.\n * @returns A hydrated order matching the request ready to be signed.\n */\n getQuote(requestBody: OrderQuoteRequest, contextOverride: PartialApiContext = {}): Promise<OrderQuoteResponse> {\n return this.fetch({ path: '/api/v1/quote', method: 'POST', body: requestBody }, contextOverride)\n }\n\n /**\n * Cancel one or more orders.\n *\n * **NOTE**: Cancellation is on a best-effort basis. Orders that are already in the process of being settled\n * (ie. transaction has been submitted to chain by the solver) cannot not be cancelled.\n * **CAUTION**: This method can only be used to cancel orders that were signed using `EIP-712` or `eth_sign (EIP-191)`.\n * @param requestBody Orders to be cancelled and signed instructions to cancel them.\n * @param contextOverride Optional context override for this request.\n * @returns A list of order unique identifiers that were successfully cancelled.\n */\n sendSignedOrderCancellations(\n requestBody: OrderCancellations,\n contextOverride: PartialApiContext = {}\n ): Promise<void> {\n return this.fetch({ path: '/api/v1/orders', method: 'DELETE', body: requestBody }, contextOverride)\n }\n\n /**\n * Submit an order to the order book.\n * @param requestBody The signed order to be submitted.\n * @param contextOverride Optional context override for this request.\n * @returns The unique identifier of the order.\n */\n sendOrder(requestBody: OrderCreation, contextOverride: PartialApiContext = {}): Promise<UID> {\n return this.fetch({ path: '/api/v1/orders', method: 'POST', body: requestBody }, contextOverride)\n }\n\n /**\n * Get the native price of a token.\n *\n * **NOTE**: The native price is the price of the token in the native currency of the chain. For example, on Ethereum\n * this would be the price of the token in ETH.\n * @param tokenAddress The address of the ERC-20 token.\n * @param contextOverride Optional context override for this request.\n * @returns The native price of the token.\n */\n getNativePrice(tokenAddress: Address, contextOverride: PartialApiContext = {}): Promise<NativePriceResponse> {\n return this.fetch({ path: `/api/v1/token/${tokenAddress}/native_price`, method: 'GET' }, contextOverride)\n }\n\n /**\n * Given a user's address, get the total surplus that they have earned.\n * @param address The user's address\n * @param contextOverride Optional context override for this request.\n * @returns Calculated user's surplus\n */\n getTotalSurplus(address: Address, contextOverride: PartialApiContext = {}): Promise<TotalSurplus> {\n return this.fetch({ path: `/api/v1/users/${address}/total_surplus`, method: 'GET' }, contextOverride)\n }\n\n /**\n * Retrieve the full app data for a given app data hash.\n * @param appDataHash `bytes32` hash of the app data\n * @param contextOverride Optional context override for this request.\n * @returns Full app data that was uploaded\n */\n getAppData(appDataHash: AppDataHash, contextOverride: PartialApiContext = {}): Promise<AppDataObject> {\n return this.fetch({ path: `/api/v1/app_data/${appDataHash}`, method: 'GET' }, contextOverride)\n }\n\n /**\n * Upload the full app data that corresponds to a given app data hash.\n * @param appDataHash `bytes32` hash of the app data\n * @param fullAppData Full app data to be uploaded\n * @param contextOverride Optional context override for this request.\n * @returns The string encoding of the full app data that was uploaded.\n */\n uploadAppData(\n appDataHash: AppDataHash,\n fullAppData: string,\n contextOverride: PartialApiContext = {}\n ): Promise<AppDataObject> {\n return this.fetch(\n { path: `/api/v1/app_data/${appDataHash}`, method: 'PUT', body: { fullAppData } },\n contextOverride\n )\n }\n\n getSolverCompetition(auctionId: number, contextOverride?: PartialApiContext): Promise<SolverCompetitionResponse>\n\n getSolverCompetition(txHash: string, contextOverride?: PartialApiContext): Promise<SolverCompetitionResponse>\n\n /**\n * Given an auction id or tx hash, get the details of the solver competition for that auction.\n * @param auctionIdorTx auction id or tx hash corresponding to the auction\n * @param contextOverride Optional context override for this request.\n * @returns An object containing the solver competition details\n */\n getSolverCompetition(\n auctionIdorTx: number | string,\n contextOverride: PartialApiContext = {}\n ): Promise<SolverCompetitionResponse> {\n return this.fetch(\n {\n path: `/api/v1/solver_competition${typeof auctionIdorTx === 'string' ? '/by_tx_hash' : ''}/${auctionIdorTx}`,\n method: 'GET',\n },\n contextOverride\n )\n }\n\n /**\n * Generate an API endpoint for an order by its unique identifier, `orderUid`.\n * @param orderUid The unique identifier of the order.\n * @param contextOverride Optional context override for this request.\n * @returns The API endpoint to get the order.\n */\n getOrderLink(orderUid: UID, contextOverride?: PartialApiContext): string {\n const { chainId, env } = this.getContextWithOverride(contextOverride)\n return this.getApiBaseUrls(env)[chainId] + `/api/v1/orders/${orderUid}`\n }\n\n /**\n * Apply an override to the context for a request.\n * @param contextOverride Optional context override for this request.\n * @returns New context with the override applied.\n */\n private getContextWithOverride(contextOverride: PartialApiContext = {}): ApiContext {\n return { ...this.context, ...contextOverride }\n }\n\n /**\n * Get the base URLs for the API endpoints given the environment.\n * @param env The environment to get the base URLs for.\n * @returns The base URLs for the API endpoints.\n */\n private getApiBaseUrls(env: CowEnv): ApiBaseUrls {\n if (this.context.baseUrls) return this.context.baseUrls\n\n return env === 'prod' ? ORDER_BOOK_PROD_CONFIG : ORDER_BOOK_STAGING_CONFIG\n }\n\n /**\n * Make a request to the API.\n * @param params The parameters for the request.\n * @param contextOverride Optional context override for this request.\n * @returns The response from the API.\n */\n private fetch<T>(params: FetchParams, contextOverride: PartialApiContext = {}): Promise<T> {\n const { chainId, env, backoffOpts: _backoffOpts } = this.getContextWithOverride(contextOverride)\n const baseUrl = this.getApiBaseUrls(env)[chainId]\n const backoffOpts = _backoffOpts || DEFAULT_BACKOFF_OPTIONS\n const rateLimiter = contextOverride.limiterOpts ? new RateLimiter(contextOverride.limiterOpts) : this.rateLimiter\n\n return request(baseUrl, params, rateLimiter, backoffOpts)\n }\n}\n","/* istanbul ignore file */\n/* tslint:disable */\n/* eslint-disable */\n\n/**\n * Where should the `buyToken` be transferred to?\n */\nexport enum BuyTokenDestination {\n ERC20 = 'erc20',\n INTERNAL = 'internal',\n}\n","/* istanbul ignore file */\n/* tslint:disable */\n/* eslint-disable */\n\nimport type { ExecutedAmounts } from './ExecutedAmounts';\n\nexport type CompetitionOrderStatus = {\n type: CompetitionOrderStatus.type;\n /**\n * A list of solvers who participated in the latest competition. The presence of executed amounts defines whether the solver provided a solution for the desired order.\n *\n */\n value?: Array<{\n /**\n * Name of the solver.\n */\n solver: string;\n executedAmounts?: ExecutedAmounts;\n }>;\n};\n\nexport namespace CompetitionOrderStatus {\n\n export enum type {\n OPEN = 'open',\n SCHEDULED = 'scheduled',\n ACTIVE = 'active',\n SOLVED = 'solved',\n EXECUTING = 'executing',\n TRADED = 'traded',\n CANCELLED = 'cancelled',\n }\n\n\n}\n\n","/* istanbul ignore file */\n/* tslint:disable */\n/* eslint-disable */\n\n/**\n * How was the order signed?\n */\nexport enum EcdsaSigningScheme {\n EIP712 = 'eip712',\n ETHSIGN = 'ethsign',\n}\n","/* istanbul ignore file */\n/* tslint:disable */\n/* eslint-disable */\n\nimport type { Address } from './Address';\n\nexport type OnchainOrderData = {\n /**\n * If orders are placed as on-chain orders, the owner of the order might\n * be a smart contract, but not the user placing the order. The\n * actual user will be provided in this field.\n *\n */\n sender: Address;\n /**\n * Describes the error, if the order placement was not successful. This could\n * happen, for example, if the `validTo` is too high, or no valid quote was\n * found or generated.\n *\n */\n placementError?: OnchainOrderData.placementError;\n};\n\nexport namespace OnchainOrderData {\n\n /**\n * Describes the error, if the order placement was not successful. This could\n * happen, for example, if the `validTo` is too high, or no valid quote was\n * found or generated.\n *\n */\n export enum placementError {\n QUOTE_NOT_FOUND = 'QuoteNotFound',\n VALID_TO_TOO_FAR_IN_FUTURE = 'ValidToTooFarInFuture',\n PRE_VALIDATION_ERROR = 'PreValidationError',\n }\n\n\n}\n\n","/* istanbul ignore file */\n/* tslint:disable */\n/* eslint-disable */\n\nexport type OrderCancellationError = {\n errorType: OrderCancellationError.errorType;\n description: string;\n};\n\nexport namespace OrderCancellationError {\n\n export enum errorType {\n INVALID_SIGNATURE = 'InvalidSignature',\n WRONG_OWNER = 'WrongOwner',\n ORDER_NOT_FOUND = 'OrderNotFound',\n ALREADY_CANCELLED = 'AlreadyCancelled',\n ORDER_FULLY_EXECUTED = 'OrderFullyExecuted',\n ORDER_EXPIRED = 'OrderExpired',\n ON_CHAIN_ORDER = 'OnChainOrder',\n }\n\n\n}\n\n","/* istanbul ignore file */\n/* tslint:disable */\n/* eslint-disable */\n\n/**\n * Order class.\n */\nexport enum OrderClass {\n MARKET = 'market',\n LIMIT = 'limit',\n LIQUIDITY = 'liquidity',\n}\n","/* istanbul ignore file */\n/* tslint:disable */\n/* eslint-disable */\n\n/**\n * Is this order a buy or sell?\n */\nexport enum OrderKind {\n BUY = 'buy',\n SELL = 'sell',\n}\n","/* istanbul ignore file */\n/* tslint:disable */\n/* eslint-disable */\n\nexport type OrderPostError = {\n errorType: OrderPostError.errorType;\n description: string;\n};\n\nexport namespace OrderPostError {\n\n export enum errorType {\n DUPLICATED_ORDER = 'DuplicatedOrder',\n QUOTE_NOT_FOUND = 'QuoteNotFound',\n QUOTE_NOT_VERIFIED = 'QuoteNotVerified',\n INVALID_QUOTE = 'InvalidQuote',\n MISSING_FROM = 'MissingFrom',\n WRONG_OWNER = 'WrongOwner',\n INVALID_EIP1271SIGNATURE = 'InvalidEip1271Signature',\n INSUFFICIENT_BALANCE = 'InsufficientBalance',\n INSUFFICIENT_ALLOWANCE = 'InsufficientAllowance',\n INVALID_SIGNATURE = 'InvalidSignature',\n SELL_AMOUNT_OVERFLOW = 'SellAmountOverflow',\n TRANSFER_SIMULATION_FAILED = 'TransferSimulationFailed',\n ZERO_AMOUNT = 'ZeroAmount',\n INCOMPATIBLE_SIGNING_SCHEME = 'IncompatibleSigningScheme',\n TOO_MANY_LIMIT_ORDERS = 'TooManyLimitOrders',\n TOO_MUCH_GAS = 'TooMuchGas',\n UNSUPPORTED_BUY_TOKEN_DESTINATION = 'UnsupportedBuyTokenDestination',\n UNSUPPORTED_SELL_TOKEN_SOURCE = 'UnsupportedSellTokenSource',\n UNSUPPORTED_ORDER_TYPE = 'UnsupportedOrderType',\n INSUFFICIENT_VALID_TO = 'InsufficientValidTo',\n EXCESSIVE_VALID_TO = 'ExcessiveValidTo',\n INVALID_NATIVE_SELL_TOKEN = 'InvalidNativeSellToken',\n SAME_BUY_AND_SELL_TOKEN = 'SameBuyAndSellToken',\n UNSUPPORTED_TOKEN = 'UnsupportedToken',\n INVALID_APP_DATA = 'InvalidAppData',\n APP_DATA_HASH_MISMATCH = 'AppDataHashMismatch',\n APPDATA_FROM_MISMATCH = 'AppdataFromMismatch',\n }\n\n\n}\n\n","/* istanbul ignore file */\n/* tslint:disable */\n/* eslint-disable */\n\nexport enum OrderQuoteSideKindBuy {\n BUY = 'buy',\n}\n","/* istanbul ignore file */\n/* tslint:disable */\n/* eslint-disable */\n\nexport enum OrderQuoteSideKindSell {\n SELL = 'sell',\n}\n","/* istanbul ignore file */\n/* tslint:disable */\n/* eslint-disable */\n\n/**\n * The current order status.\n */\nexport enum OrderStatus {\n PRESIGNATURE_PENDING = 'presignaturePending',\n OPEN = 'open',\n FULFILLED = 'fulfilled',\n CANCELLED = 'cancelled',\n EXPIRED = 'expired',\n}\n","/* istanbul ignore file */\n/* tslint:disable */\n/* eslint-disable */\n\nexport type PriceEstimationError = {\n errorType: PriceEstimationError.errorType;\n description: string;\n};\n\nexport namespace PriceEstimationError {\n\n export enum errorType {\n QUOTE_NOT_VERIFIED = 'QuoteNotVerified',\n UNSUPPORTED_TOKEN = 'UnsupportedToken',\n ZERO_AMOUNT = 'ZeroAmount',\n UNSUPPORTED_ORDER_TYPE = 'UnsupportedOrderType',\n }\n\n\n}\n\n","/* istanbul ignore file */\n/* tslint:disable */\n/* eslint-disable */\n\n/**\n * How good should the price estimate be?\n *\n * Fast: The price estimate is chosen among the fastest N price estimates.\n * Optimal: The price estimate is chosen among all price estimates.\n * Verified: The price estimate is chosen among all verified/simulated price estimates.\n *\n * **NOTE**: Orders are supposed to be created from `verified` or `optimal` price estimates.\n *\n */\nexport enum PriceQuality {\n FAST = 'fast',\n OPTIMAL = 'optimal',\n VERIFIED = 'verified',\n}\n","/* istanbul ignore file */\n/* tslint:disable */\n/* eslint-disable */\n\n/**\n * Where should the `sellToken` be drawn from?\n */\nexport enum SellTokenSource {\n ERC20 = 'erc20',\n INTERNAL = 'internal',\n EXTERNAL = 'external',\n}\n","/* istanbul ignore file */\n/* tslint:disable */\n/* eslint-disable */\n\n/**\n * How was the order signed?\n */\nexport enum SigningScheme {\n EIP712 = 'eip712',\n ETHSIGN = 'ethsign',\n PRESIGN = 'presign',\n EIP1271 = 'eip1271',\n}\n","import { QuoteAmountsAndCosts } from './types'\nimport { OrderKind, type OrderParameters } from './generated'\n\ninterface Params {\n orderParams: OrderParameters\n sellDecimals: number\n buyDecimals: number\n slippagePercentBps: number\n partnerFeeBps: number | undefined\n}\n\nconst ONE_HUNDRED_BPS = BigInt(100 * 100)\n\nexport function getQuoteAmountsAndCosts(params: Params): QuoteAmountsAndCosts {\n const { orderParams, sellDecimals, buyDecimals, slippagePercentBps } = params\n const partnerFeeBps = params.partnerFeeBps ?? 0\n const isSell = orderParams.kind === OrderKind.SELL\n /**\n * Wrap raw values into CurrencyAmount objects\n * We also make amounts names more specific with \"beforeNetworkCosts\" and \"afterNetworkCosts\" suffixes\n */\n const networkCostAmount = getBigNumber(orderParams.feeAmount, sellDecimals)\n const sellAmountBeforeNetworkCosts = getBigNumber(orderParams.sellAmount, sellDecimals)\n const buyAmountAfterNetworkCosts = getBigNumber(orderParams.buyAmount, buyDecimals)\n\n /**\n * This is an actual price of the quote since it's derrived only from the quote sell and buy amounts\n */\n const quotePrice = buyAmountAfterNetworkCosts.num / sellAmountBeforeNetworkCosts.num\n\n /**\n * Before networkCosts + networkCosts = After networkCosts :)\n */\n const sellAmountAfterNetworkCosts = getBigNumber(\n sellAmountBeforeNetworkCosts.big + networkCostAmount.big,\n sellDecimals\n )\n\n /**\n * Since the quote contains only buy amount after network costs\n * we have to calculate the buy amount before network costs from the quote price\n */\n const buyAmountBeforeNetworkCosts = getBigNumber(quotePrice * sellAmountAfterNetworkCosts.num, buyDecimals)\n\n /**\n * Partner fee is always added on the surplus amount, for sell-orders it's buy amount, for buy-orders it's sell amount\n */\n const surplusAmount = isSell ? buyAmountBeforeNetworkCosts.big : sellAmountBeforeNetworkCosts.big\n const partnerFeeAmount = partnerFeeBps > 0 ? (surplusAmount * BigInt(partnerFeeBps)) / ONE_HUNDRED_BPS : BigInt(0)\n\n /**\n * Partner fee is always added on the surplus token, for sell-orders it's buy token, for buy-orders it's sell token\n */\n const afterPartnerFees = isSell\n ? {\n sellAmount: sellAmountAfterNetworkCosts.big,\n buyAmount: buyAmountAfterNetworkCosts.big - partnerFeeAmount,\n }\n : {\n sellAmount: sellAmountAfterNetworkCosts.big + partnerFeeAmount,\n buyAmount: buyAmountAfterNetworkCosts.big,\n }\n\n const getSlippageAmount = (amount: bigint) => (amount * BigInt(slippagePercentBps)) / ONE_HUNDRED_BPS\n\n /**\n * Same rules apply for slippage as for partner fees\n */\n const afterSlippage = isSell\n ? {\n sellAmount: afterPartnerFees.sellAmount,\n buyAmount: afterPartnerFees.buyAmount - getSlippageAmount(afterPartnerFees.buyAmount),\n }\n : {\n sellAmount: afterPartnerFees.sellAmount + getSlippageAmount(afterPartnerFees.sellAmount),\n buyAmount: afterPartnerFees.buyAmount,\n }\n\n return {\n isSell,\n costs: {\n networkFee: {\n amountInSellCurrency: networkCostAmount.big,\n amountInBuyCurrency: getBigNumber(quotePrice * networkCostAmount.num, buyDecimals).big,\n },\n partnerFee: {\n amount: partnerFeeAmount,\n bps: partnerFeeBps,\n },\n },\n beforeNetworkCosts: {\n sellAmount: sellAmountBeforeNetworkCosts.big,\n buyAmount: buyAmountBeforeNetworkCosts.big,\n },\n afterNetworkCosts: {\n sellAmount: sellAmountAfterNetworkCosts.big,\n buyAmount: buyAmountAfterNetworkCosts.big,\n },\n afterPartnerFees,\n afterSlippage,\n }\n}\n\ntype BigNumber = {\n big: bigint\n num: number\n}\n\n/**\n * BigInt works well with subtraction and addition, but it's not very good with multiplication and division\n * To multiply/divide token amounts we have to convert them to numbers, but we have to be careful with precision\n * @param value\n * @param decimals\n */\nfunction getBigNumber(value: string | bigint | number, decimals: number): BigNumber {\n if (typeof value === 'number') {\n const bigAsNumber = value * 10 ** decimals\n const bigAsNumberString = bigAsNumber.toFixed()\n const big = BigInt(bigAsNumberString.includes('e') ? bigAsNumber : bigAsNumberString)\n\n return { big, num: value }\n }\n\n const big = BigInt(value)\n const num = Number(big) / 10 ** decimals\n\n return { big, num }\n}\n","import { gql } from 'graphql-request'\n\n/**\n * GraphQL query for the total number of tokens, orders, traders, settlements, volume, and fees.\n */\nexport const TOTALS_QUERY = gql`\n query Totals {\n totals {\n tokens\n orders\n traders\n settlements\n volumeUsd\n volumeEth\n feesUsd\n feesEth\n }\n }\n`\n\n/**\n * GraphQL query for the total volume over the last N days.\n * @param days The number of days to query.\n */\nexport const LAST_DAYS_VOLUME_QUERY = gql`\n query LastDaysVolume($days: Int!) {\n dailyTotals(orderBy: timestamp, orderDirection: desc, first: $days) {\n timestamp\n volumeUsd\n }\n }\n`\n\n/**\n * GraphQL query for the total volume over the last N hours.\n * @param hours The number of hours to query.\n */\nexport const LAST_HOURS_VOLUME_QUERY = gql`\n query LastHoursVolume($hours: Int!) {\n hourlyTotals(orderBy: timestamp, orderDirection: desc, first: $hours) {\n timestamp\n volumeUsd\n }\n }\n`\n","import { Variables, request } from 'graphql-request'\nimport { DocumentNode } from 'graphql/index'\nimport { SupportedChainId } from '../common/chains'\nimport { ApiContext, CowEnv, DEFAULT_COW_API_CONTEXT } from '../common/configs'\nimport { CowError } from '../common/cow-error'\nimport { LastDaysVolumeQuery, LastHoursVolumeQuery, TotalsQuery } from './graphql'\nimport { LAST_DAYS_VOLUME_QUERY, LAST_HOURS_VOLUME_QUERY, TOTALS_QUERY } from './queries'\n\nconst SUBGRAPH_BASE_URL = 'https://api.thegraph.com/subgraphs/name/cowprotocol'\n\ntype SubgraphApiBaseUrls = Record<SupportedChainId, string | null>\n\ninterface SubgraphApiContext extends Omit<ApiContext, 'baseUrls'> {\n baseUrls?: SubgraphApiBaseUrls\n}\n\ntype PartialSubgraphApiContext = Partial<SubgraphApiContext>\n\n/**\n * CoW Protocol Production Subgraph API configuration.\n * @see {@link https://api.thegraph.com/subgraphs/name/cowprotocol/cow}\n * @see {@link https://api.thegraph.com/subgraphs/name/cowprotocol/cow-gc}\n */\nexport const SUBGRAPH_PROD_CONFIG: SubgraphApiBaseUrls = {\n [SupportedChainId.MAINNET]: SUBGRAPH_BASE_URL + '/cow',\n [SupportedChainId.GNOSIS_CHAIN]: SUBGRAPH_BASE_URL + '/cow-gc',\n [SupportedChainId.ARBITRUM_ONE]: null,\n [SupportedChainId.SEPOLIA]: null,\n}\n\n/**\n * CoW Protocol Staging Subgraph API configuration.\n * @deprecated\n * @see {@link https://api.thegraph.com/subgraphs/name/cowprotocol/cow-staging}\n * @see {@link https://api.thegraph.com/subgraphs/name/cowprotocol/cow-gc-staging}\n */\nexport const SUBGRAPH_STAGING_CONFIG: SubgraphApiBaseUrls = {\n [SupportedChainId.MAINNET]: SUBGRAPH_BASE_URL + '/cow-staging',\n [SupportedChainId.GNOSIS_CHAIN]: SUBGRAPH_BASE_URL + '/cow-gc-staging',\n [SupportedChainId.ARBITRUM_ONE]: null,\n [SupportedChainId.SEPOLIA]: null,\n}\n\n/**\n * TheGraph API client for CoW Protocol.\n */\nexport class SubgraphApi {\n API_NAME = 'CoW Protocol Subgraph'\n\n public context: SubgraphApiContext\n\n /**\n * Create a new CoW Protocol API instance.\n * @param context Any properties of the {@link SubgraphApiContext} may be overridden by passing a {@link PartialSubgraphApiContext}.\n */\n constructor(context: PartialSubgraphApiContext = {}) {\n this.context = {\n ...DEFAULT_COW_API_CONTEXT,\n ...context,\n }\n }\n\n /**\n * Query the totals from TheGraph for the CoW Protocol.\n * @param contextOverride Override the context for this call only.\n * @returns The totals for the CoW Protocol.\n */\n async getTotals(contextOverride: PartialSubgraphApiContext = {}): Promise<TotalsQuery['totals'][0]> {\n const response = await this.runQuery<TotalsQuery>(TOTALS_QUERY, undefined, contextOverride)\n return response.totals[0]\n }\n\n /**\n * Query the volume over the last N days from TheGraph for the CoW Protocol.\n * @param {number} days The number of days to query.\n * @param {PartialSubgraphApiContext} contextOverride Override the context for this call only.\n * @returns The volume for the last N days.\n */\n async getLastDaysVolume(days: number, contextOverride: PartialSubgraphApiContext = {}): Promise<LastDaysVolumeQuery> {\n return this.runQuery<LastDaysVolumeQuery>(LAST_DAYS_VOLUME_QUERY, { days }, contextOverride)\n }\n\n /**\n * Query the volume over the last N hours from TheGraph for the CoW Protocol.\n * @param {number} hours The number of hours to query.\n * @param {PartialSubgraphApiContext} contextOverride Override the context for this call only.\n * @returns The volume for the last N hours.\n */\n async getLastHoursVolume(\n hours: number,\n contextOverride: PartialSubgraphApiContext = {}\n ): Promise<LastHoursVolumeQuery> {\n return this.runQuery<LastHoursVolumeQuery>(LAST_HOURS_VOLUME_QUERY, { hours }, contextOverride)\n }\n\n /**\n * Run a query against the CoW Protocol Subgraph.\n * @param {string | DocumentNode} query GQL query string or DocumentNode.\n * @param {Variables | undefined} variables To be passed to the query.\n * @param {PartialSubgraphApiContext} contextOverride Override the context for this call only.\n * @returns Results of the query.\n * @throws {@link CowError} if the query fails.\n */\n async runQuery<T>(\n query: string | DocumentNode,\n variables: Variables | undefined = undefined,\n contextOverride: PartialSubgraphApiContext = {}\n ): Promise<T> {\n const { chainId, env } = this.getContextWithOverride(contextOverride)\n const baseUrl = this.getEnvConfigs(env)[chainId]\n\n if (baseUrl === null) {\n throw new Error('Unsupported Network. The subgraph API is not available in the Network ' + chainId)\n }\n\n try {\n return await request(baseUrl, query, variables)\n } catch (error) {\n console.error(`[subgraph:${this.API_NAME}]`, error)\n throw new CowError(\n `Error running query: ${query}. Variables: ${JSON.stringify(variables)}. API: ${baseUrl}. Inner Error: ${error}`\n )\n }\n }\n\n /**\n * Override parts of the context for a specific call.\n * @param {PartialSubgraphApiContext} contextOverride Override the context for this call only.\n * @returns {SubgraphApiContext} The context with the override applied.\n */\n private getContextWithOverride(contextOverride: PartialSubgraphApiContext = {}): SubgraphApiContext {\n return { ...this.context, ...contextOverride }\n }\n\n /**\n * Get the base URLs for the given environment.\n * @param {CowEnv} env The environment to get the base URLs for.\n * @returns {ApiBaseUrls} The base URLs for the given environment.\n */\n private getEnvConfigs(env: CowEnv): SubgraphApiBaseUrls {\n if (this.context.baseUrls) return this.context.baseUrls\n\n return env === 'prod' ? SUBGRAPH_PROD_CONFIG : SUBGRAPH_STAGING_CONFIG\n }\n}\n","import type { SupportedChainId } from '../common'\nimport type { Signer } from '@ethersproject/abstract-signer'\nimport type { TypedDataDomain } from '@cowprotocol/contracts'\nimport type { SigningResult, UnsignedOrder } from './types'\n\nconst getSignUtils = () => import('./utils')\nconst ethersUtils = () => import('ethers/lib/utils')\n\n/**\n * Utility class for signing order intents and cancellations.\n *\n * @remarks This class only supports `eth_sign` and wallet-native EIP-712 signing. For use of\n * `presign` and `eip1271` {@link https://docs.cow.fi/ | see the docs}.\n * @example\n *\n * ```typescript\n * import { OrderSigningUtils, SupportedChainId } from '@cowprotocol/cow-sdk'\n * import { Web3Provider } from '@ethersproject/providers'\n *\n * const account = 'YOUR_WALLET_ADDRESS'\n * const chainId = 100 // Gnosis chain\n * const provider = new Web3Provider(window.ethereum)\n * const signer = provider.getSigner()\n *\n * async function main() {\n * const { order: Order } = { ... }\n * const orderSigningResult = await OrderSigningUtils.signOrder(quote, chainId, signer)\n *\n * const orderId = await orderBookApi.sendOrder({ ...quote, ...orderSigningResult })\n *\n * const order = await orderBookApi.getOrder(orderId)\n *\n * const trades = await orderBookApi.getTrades({ orderId })\n *\n * const orderCancellationSigningResult = await OrderSigningUtils.signOrderCancellations([orderId], chainId, signer)\n *\n * const cancellationResult = await orderBookApi.sendSignedOrderCancellations({...orderCancellationSigningResult, orderUids: [orderId] })\n *\n * console.log('Results: ', { orderId, order, trades, orderCancellationSigningResult, cancellationResult })\n * }\n * ```\n */\nexport class OrderSigningUtils {\n /**\n * Sign the order intent with the specified signer.\n *\n * @remarks If the API reports an error with the signature, it is likely to be due to an incorrectly\n * specified `chainId`. Please ensure that the `chainId` is correct for the network you are\n * using.\n * @param {UnsignedOrder} order The unsigned order intent to be placed.\n * @param {SupportedChainId} chainId The CoW Protocol `chainId` context that's being used.\n * @param {Signer} signer The signer who is placing the order intent.\n * @returns {Promise<SigningResult>} Encoded signature including signing scheme for the order.\n */\n static async signOrder(order: UnsignedOrder, chainId: SupportedChainId, signer: Signer): Promise<SigningResult> {\n const { signOrder } = await getSignUtils()\n return signOrder(order, chainId, signer)\n }\n\n /**\n * Sign a cancellation message of an order intent with the specified signer.\n * @param {string} orderUid The unique identifier of the order to cancel.\n * @param {SupportedChainId} chainId The CoW Protocol `chainid` context that's being used.\n * @param {Signer} signer The signer who initially placed the order intent.\n * @returns {Promise<SigningResult>} Encoded signature including signing scheme for the cancellation.\n */\n static async signOrderCancellation(\n orderUid: string,\n chainId: SupportedChainId,\n signer: Signer\n ): Promise<SigningResult> {\n const { signOrderCancellation } = await getSignUtils()\n return signOrderCancellation(orderUid, chainId, signer)\n }\n\n /**\n * Sign a cancellation message of multiple order intents with the specified signer.\n * @param {string[]} orderUids An array of `orderUid` to cancel.\n * @param {SupportedChainId} chainId The CoW Protocol protocol `chainId` context that's being used.\n * @param {Signer} signer The signer who initially placed the order intents.\n * @returns {Promise<SigningResult>} Encoded signature including signing scheme for the cancellation.\n */\n static async signOrderCancellations(\n orderUids: string[],\n chainId: SupportedChainId,\n signer: Signer\n ): Promise<SigningResult> {\n const { signOrderCancellations } = await getSignUtils()\n return signOrderCancellations(orderUids, chainId, signer)\n }\n\n /**\n * Get the EIP-712 typed domain data being used for signing.\n * @param {SupportedChainId} chainId The CoW Protocol protocol `chainId` context that's being used.\n * @return The EIP-712 typed domain data.\n * @see https://eips.ethereum.org/EIPS/eip-712\n */\n static async getDomain(chainId: SupportedChainId): Promise<TypedDataDomain> {\n const { getDomain } = await getSignUtils()\n return getDomain(chainId)\n }\n\n /**\n * Get the domain separator hash for the EIP-712 typed domain data being used for signing.\n * @param chainId {SupportedChainId} chainId The CoW Protocol protocol `chainId` context that's being used.\n * @returns A string representation of the EIP-712 typed domain data hash.\n */\n static async getDomainSeparator(chainId: SupportedChainId): Promise<string> {\n const { getDomain } = await getSignUtils()\n const { _TypedDataEncoder } = await ethersUtils()\n return _TypedDataEncoder.hashDomain(getDomain(chainId))\n }\n\n /**\n * Get the EIP-712 types used for signing a GPv2Order.Data struct. This is useful for when\n * signing orders using smart contracts, whereby this SDK cannot do the EIP-1271 signing for you.\n * @returns The EIP-712 types used for signing.\n */\n static getEIP712Types(): Record<string, any> {\n return {\n Order: [\n { name: 'sellToken', type: 'address' },\n { name: 'buyToken', type: 'address' },\n { name: 'receiver', type: 'address' },\n { name: 'sellAmount', type: 'uint256' },\n { name: 'buyAmount', type: 'uint256' },\n { name: 'validTo', type: 'uint32' },\n { name: 'appData', type: 'bytes32' },\n { name: 'feeAmount', type: 'uint256' },\n { name: 'kind', type: 'string' },\n { name: 'partiallyFillable', type: 'bool' },\n { name: 'sellTokenBalance', type: 'string' },\n { name: 'buyTokenBalance', type: 'string' },\n ],\n }\n }\n}\n","import { OrderBookApi } from '../order-book'\nimport { SupportedChainId } from '../common'\nimport { GPv2Order } from './generated/ComposableCoW'\nimport { providers } from 'ethers'\n\nexport interface ConditionalOrderArguments<T> {\n handler: string\n data: T\n salt?: string\n hasOffChainInput?: boolean\n}\n\nexport type ConditionalOrderParams = {\n readonly handler: string\n readonly salt: string\n readonly staticInput: string\n}\n\nexport enum ProofLocation {\n // The location of the proofs is private to the caller.\n PRIVATE = 0,\n // The `data` field of the emitted `Proof` struct contains proofs + conditional order parameters.\n EMITTED = 1,\n // The `data` field of the emitted `Proof` struct contains the Swarm address (`bytes32`) of the proofs + conditional order parameters.\n SWARM = 2,\n // The `data` field is set to TBD.\n WAKU = 3,\n // The `data` field is set to TBD\n RESERVED = 4,\n // The `data` field of the emitted `Proof` struct contains the IPFS address (`bytes32`) of the proofs + conditional order parameters.\n IPFS = 5,\n}\n\n/**\n * A factory and it's arguments that are called at transaction mining time to generate the context\n * for a conditional order(s).\n *\n * This allows to support the case where conditional orders may want to *commence* validity at the\n * time of transaction mining, like in the case of a `TWAP` executed by a DAO or `Safe` that takes\n * a reasonable amount of time to aggregate signatures or collect votes.\n *\n * @remarks This is used in conjunction with `setRootWithContext` or `createWithContext`.\n */\nexport type ContextFactory = {\n // The address of the `IValueFactory` that will be used to resolve the context.\n address: string\n // Any arguments that will be passed to the `IValueFactory` to resolve the context.\n factoryArgs?: {\n args: unknown[]\n argsType: string[]\n }\n}\n\n/**\n * A struct for a proof that can be used with `setRoot` and `setRootWithContext` on a\n * ComposableCoW-enabled Safe.\n */\nexport type ProofStruct = {\n // The location of the proof.\n location: ProofLocation\n // The data for the proof.\n data: string | '0x'\n}\n\n/**\n * Payload for emitting a merkle root to a ComposableCoW-enabled Safe.\n *\n * If setting `ProofLocation.EMITTED`, this type should be used as the `data` in the `Proof` struct.\n */\nexport type PayloadLocationEmitted = {\n // An array of conditional orders and their proofs.\n proofs: ProofWithParams[]\n}\n\n/**\n * A proof for a conditional order and it's parameters.\n */\nexport type ProofWithParams = {\n // The proof for the Merkle tree that contains the conditional order.\n proof: string[]\n // The parameters as expected by ABI encoding.\n params: ConditionalOrderParams\n}\n\nexport type OwnerContext = {\n owner: string\n chainId: SupportedChainId\n provider: providers.Provider\n}\n\nexport type PollParams = OwnerContext & {\n orderBookApi: OrderBookApi\n offchainInput?: string\n proof?: string[]\n\n /**\n * If present, it can be used for custom conditional order validations. If not present, the orders will need to get the block info themselves\n */\n blockInfo?: BlockInfo\n}\n\nexport type BlockInfo = {\n blockNumber: number\n blockTimestamp: number\n}\n\nexport type PollResult = PollResultSuccess | PollResultErrors\n\nexport type PollResultErrors =\n | PollResultTryNextBlock\n | PollResultTryOnBlock\n | PollResultTryAtEpoch\n | PollResultUnexpectedError\n | PollResultDontTryAgain\n\nexport enum PollResultCode {\n SUCCESS = 'SUCCESS',\n UNEXPECTED_ERROR = 'UNEXPECTED_ERROR',\n TRY_NEXT_BLOCK = 'TRY_NEXT_BLOCK',\n TRY_ON_BLOCK = 'TRY_ON_BLOCK',\n TRY_AT_EPOCH = 'TRY_AT_EPOCH',\n DONT_TRY_AGAIN = 'DONT_TRY_AGAIN',\n}\nexport interface PollResultSuccess {\n readonly result: PollResultCode.SUCCESS\n readonly order: GPv2Order.DataStruct\n readonly signature: string\n}\n\nexport interface PollResultUnexpectedError {\n readonly result: PollResultCode.UNEXPECTED_ERROR\n readonly error: unknown\n reason?: string\n}\n\nexport interface PollResultTryNextBlock {\n readonly result: PollResultCode.TRY_NEXT_BLOCK\n reason?: string\n}\n\nexport interface PollResultTryOnBlock {\n readonly result: PollResultCode.TRY_ON_BLOCK\n readonly blockNumber: number\n reason?: string\n}\n\nexport interface PollResultTryAtEpoch {\n readonly result: PollResultCode.TRY_AT_EPOCH\n /**\n * The epoch after which it is ok to retry to to poll this order.\n * The value is expressed as a Unix timestamp (in seconds).\n *\n * This epoch will be inclusive, meaning that it is ok to retry at the block mined precisely at this epoch or later.\n */\n readonly epoch: number\n reason?: string\n}\n\nexport interface PollResultDontTryAgain {\n readonly result: PollResultCode.DONT_TRY_AGAIN\n reason?: string\n}\n\nexport type IsValidResult = IsValid | IsNotValid\nexport interface IsValid {\n isValid: true\n}\nexport interface IsNotValid {\n isValid: false\n reason: string\n}\n","/* Autogenerated file. Do not edit manually. */\n/* tslint:disable */\n/* eslint-disable */\n\nimport { Contract, Signer, utils } from \"ethers\";\nimport type { Provider } from \"@ethersproject/providers\";\nimport type { ComposableCoW, ComposableCoWInterface } from \"../ComposableCoW\";\n\nconst _abi = [\n {\n inputs: [\n {\n internalType: \"address\",\n name: \"_settlement\",\n type: \"address\",\n },\n ],\n stateMutability: \"nonpayable\",\n type: \"constructor\",\n },\n {\n inputs: [],\n name: \"InterfaceNotSupported\",\n type: \"error\",\n },\n {\n inputs: [],\n name: \"InvalidHandler\",\n type: \"error\",\n },\n {\n inputs: [],\n name: \"ProofNotAuthed\",\n type: \"error\",\n },\n {\n inputs: [],\n name: \"SingleOrderNotAuthed\",\n type: \"error\",\n },\n {\n inputs: [],\n name: \"SwapGuardRestricted\",\n type: \"error\",\n },\n {\n anonymous: false,\n inputs: [\n {\n indexed: true,\n internalType: \"address\",\n name: \"owner\",\n type: \"address\",\n },\n {\n components: [\n {\n internalType: \"contract IConditionalOrder\",\n name: \"handler\",\n type: \"address\",\n },\n {\n internalType: \"bytes32\",\n name: \"salt\",\n type: \"bytes32\",\n },\n {\n internalType: \"bytes\",\n name: \"staticInput\",\n type: \"bytes\",\n },\n ],\n indexed: false,\n internalType: \"struct IConditionalOrder.ConditionalOrderParams\",\n name: \"params\",\n type: \"tuple\",\n },\n ],\n name: \"ConditionalOrderCreated\",\n type: \"event\",\n },\n {\n anonymous: false,\n inputs: [\n {\n indexed: true,\n internalType: \"address\",\n name: \"owner\",\n type: \"address\",\n },\n {\n indexed: false,\n internalType: \"bytes32\",\n name: \"root\",\n type: \"bytes32\",\n },\n {\n components: [\n {\n internalType: \"uint256\",\n name: \"location\",\n type: \"uint256\",\n },\n {\n internalType: \"bytes\",\n name: \"data\",\n type: \"bytes\",\n },\n ],\n indexed: false,\n internalType: \"struct ComposableCoW.Proof\",\n name: \"proof\",\n type: \"tuple\",\n },\n ],\n name: \"MerkleRootSet\",\n type: \"event\",\n },\n {\n anonymous: false,\n inputs: [\n {\n indexed: true,\n internalType: \"address\",\n name: \"owner\",\n type: \"address\",\n },\n {\n indexed: false,\n internalType: \"contract ISwapGuard\",\n name: \"swapGuard\",\n type: \"address\",\n },\n ],\n name: \"SwapGuardSet\",\n type: \"event\",\n },\n {\n inputs: [\n {\n internalType: \"address\",\n name: \"\",\n type: \"address\",\n },\n {\n internalType: \"bytes32\",\n name: \"\",\n type: \"bytes32\",\n },\n ],\n name: \"cabinet\",\n outputs: [\n {\n internalType: \"bytes32\",\n name: \"\",\n type: \"bytes32\",\n },\n ],\n stateMutability: \"view\",\n type: \"function\",\n },\n {\n inputs: [\n {\n components: [\n {\n internalType: \"contract IConditionalOrder\",\n name: \"handler\",\n type: \"address\",\n },\n {\n internalType: \"bytes32\",\n name: \"salt\",\n type: \"bytes32\",\n },\n {\n internalType: \"bytes\",\n name: \"staticInput\",\n type: \"bytes\",\n },\n ],\n internalType: \"struct IConditionalOrder.ConditionalOrderParams\",\n name: \"params\",\n type: \"tuple\",\n },\n {\n internalType: \"bool\",\n name: \"dispatch\",\n type: \"bool\",\n },\n ],\n name: \"create\",\n outputs: [],\n stateMutability: \"nonpayable\",\n type: \"function\",\n },\n {\n inputs: [\n {\n components: [\n {\n internalType: \"contract IConditionalOrder\",\n name: \"handler\",\n type: \"address\",\n },\n {\n internalType: \"bytes32\",\n name: \"salt\",\n type: \"bytes32\",\n },\n {\n internalType: \"bytes\",\n name: \"staticInput\",\n type: \"bytes\",\n },\n ],\n internalType: \"struct IConditionalOrder.ConditionalOrderParams\",\n name: \"params\",\n type: \"tuple\",\n },\n {\n internalType: \"contract IValueFactory\",\n name: \"factory\",\n type: \"address\",\n },\n {\n internalType: \"bytes\",\n name: \"data\",\n type: \"bytes\",\n },\n {\n internalType: \"bool\",\n name: \"dispatch\",\n type: \"bool\",\n },\n ],\n name: \"createWithContext\",\n outputs: [],\n stateMutability: \"nonpayable\",\n type: \"function\",\n },\n {\n inputs: [],\n name: \"domainSeparator\",\n outputs: [\n {\n internalType: \"bytes32\",\n name: \"\",\n type: \"bytes32\",\n },\n ],\n stateMutability: \"view\",\n type: \"function\",\n },\n {\n inputs: [\n {\n internalType: \"address\",\n name: \"owner\",\n type: \"address\",\n },\n {\n components: [\n {\n internalType: \"contract IConditionalOrder\",\n name: \"handler\",\n type: \"address\",\n },\n {\n internalType: \"bytes32\",\n name: \"salt\",\n type: \"bytes32\",\n },\n {\n internalType: \"bytes\",\n name: \"staticInput\",\n type: \"bytes\",\n },\n ],\n internalType: \"struct IConditionalOrder.ConditionalOrderParams\",\n name: \"params\",\n type: \"tuple\",\n },\n {\n internalType: \"bytes\",\n name: \"offchainInput\",\n type: \"bytes\",\n },\n {\n internalType: \"bytes32[]\",\n name: \"proof\",\n type: \"bytes32[]\",\n },\n ],\n name: \"getTradeableOrderWithSignature\",\n outputs: [\n {\n components: [\n {\n internalType: \"contract IERC20\",\n name: \"sellToken\",\n type: \"address\",\n },\n {\n internalType: \"contract IERC20\",\n name: \"buyToken\",\n type: \"address\",\n },\n {\n internalType: \"address\",\n name: \"receiver\",\n type: \"address\",\n },\n {\n internalType: \"uint256\",\n name: \"sellAmount\",\n type: \"uint256\",\n },\n {\n internalType: \"uint256\",\n name: \"buyAmount\",\n type: \"uint256\",\n },\n {\n internalType: \"uint32\",\n name: \"validTo\",\n type: \"uint32\",\n },\n {\n internalType: \"bytes32\",\n name: \"appData\",\n type: \"bytes32\",\n },\n {\n internalType: \"uint256\",\n name: \"feeAmount\",\n type: \"uint256\",\n },\n {\n internalType: \"bytes32\",\n name: \"kind\",\n type: \"bytes32\",\n },\n {\n internalType: \"bool\",\n name: \"partiallyFillable\",\n type: \"bool\",\n },\n {\n internalType: \"bytes32\",\n name: \"sellTokenBalance\",\n type: \"bytes32\",\n },\n {\n internalType: \"bytes32\",\n name: \"buyTokenBalance\",\n type: \"bytes32\",\n },\n ],\n internalType: \"struct GPv2Order.Data\",\n name: \"order\",\n type: \"tuple\",\n },\n {\n internalType: \"bytes\",\n name: \"signature\",\n type: \"bytes\",\n },\n ],\n stateMutability: \"view\",\n type: \"function\",\n },\n {\n inputs: [\n {\n components: [\n {\n internalType: \"contract IConditionalOrder\",\n name: \"handler\",\n type: \"address\",\n },\n {\n internalType: \"bytes32\",\n name: \"salt\",\n type: \"bytes32\",\n },\n {\n internalType: \"bytes\",\n name: \"staticInput\",\n type: \"bytes\",\n },\n ],\n internalType: \"struct IConditionalOrder.ConditionalOrderParams\",\n name: \"params\",\n type: \"tuple\",\n },\n ],\n name: \"hash\",\n outputs: [\n {\n internalType: \"bytes32\",\n name: \"\",\n type: \"bytes32\",\n },\n ],\n stateMutability: \"pure\",\n type: \"function\",\n },\n {\n inputs: [\n {\n internalType: \"contract Safe\",\n name: \"safe\",\n type: \"address\",\n },\n {\n internalType: \"address\",\n name: \"sender\",\n type: \"address\",\n },\n {\n internalType: \"bytes32\",\n name: \"_hash\",\n type: \"bytes32\",\n },\n {\n internalType: \"bytes32\",\n name: \"_domainSeparator\",\n type: \"bytes32\",\n },\n {\n internalType: \"bytes32\",\n name: \"\",\n type: \"bytes32\",\n },\n {\n internalType: \"bytes\",\n name: \"encodeData\",\n type: \"bytes\",\n },\n {\n internalType: \"bytes\",\n name: \"payload\",\n type: \"bytes\",\n },\n ],\n name: \"isValidSafeSignature\",\n outputs: [\n {\n internalType: \"bytes4\",\n name: \"magic\",\n type: \"bytes4\",\n },\n ],\n stateMutability: \"view\",\n type: \"function\",\n },\n {\n inputs: [\n {\n internalType: \"bytes32\",\n name: \"singleOrderHash\",\n type: \"bytes32\",\n },\n ],\n name: \"remove\",\n outputs: [],\n stateMutability: \"nonpayable\",\n type: \"function\",\n },\n {\n inputs: [\n {\n internalType: \"address\",\n name: \"\",\n type: \"address\",\n },\n ],\n name: \"roots\",\n outputs: [\n {\n internalType: \"bytes32\",\n name: \"\",\n type: \"bytes32\",\n },\n ],\n stateMutability: \"view\",\n type: \"function\",\n },\n {\n inputs: [\n {\n internalType: \"bytes32\",\n name: \"root\",\n type: \"bytes32\",\n },\n {\n components: [\n {\n internalType: \"uint256\",\n name: \"location\",\n type: \"uint256\",\n },\n {\n internalType: \"bytes\",\n name: \"data\",\n type: \"bytes\",\n },\n ],\n internalType: \"struct ComposableCoW.Proof\",\n name: \"proof\",\n type: \"tuple\",\n },\n ],\n name: \"setRoot\",\n outputs: [],\n stateMutability: \"nonpayable\",\n type: \"function\",\n },\n {\n inputs: [\n {\n internalType: \"bytes32\",\n name: \"root\",\n type: \"bytes32\",\n },\n {\n components: [\n {\n internalType: \"uint256\",\n name: \"location\",\n type: \"uint256\",\n },\n {\n internalType: \"bytes\",\n name: \"data\",\n type: \"bytes\",\n },\n ],\n internalType: \"struct ComposableCoW.Proof\",\n name: \"proof\",\n type: \"tuple\",\n },\n {\n internalType: \"contract IValueFactory\",\n name: \"factory\",\n type: \"address\",\n },\n {\n internalType: \"bytes\",\n name: \"data\",\n type: \"bytes\",\n },\n ],\n name: \"setRootWithContext\",\n outputs: [],\n stateMutability: \"nonpayable\",\n type: \"function\",\n },\n {\n inputs: [\n {\n internalType: \"contract ISwapGuard\",\n name: \"swapGuard\",\n type: \"address\",\n },\n ],\n name: \"setSwapGuard\",\n outputs: [],\n stateMutability: \"nonpayable\",\n type: \"function\",\n },\n {\n inputs: [\n {\n internalType: \"address\",\n name: \"\",\n type: \"address\",\n },\n {\n internalType: \"bytes32\",\n name: \"\",\n type: \"bytes32\",\n },\n ],\n name: \"singleOrders\",\n outputs: [\n {\n internalType: \"bool\",\n name: \"\",\n type: \"bool\",\n },\n ],\n stateMutability: \"view\",\n type: \"function\",\n },\n {\n inputs: [\n {\n internalType: \"address\",\n name: \"\",\n type: \"address\",\n },\n ],\n name: \"swapGuards\",\n outputs: [\n {\n internalType: \"contract ISwapGuard\",\n name: \"\",\n type: \"address\",\n },\n ],\n stateMutability: \"view\",\n type: \"function\",\n },\n] as const;\n\nexport class ComposableCoW__factory {\n static readonly abi = _abi;\n static createInterface(): ComposableCoWInterface {\n return new utils.Interface(_abi) as ComposableCoWInterface;\n }\n static connect(\n address: string,\n signerOrProvider: Signer | Provider\n ): ComposableCoW {\n return new Contract(address, _abi, signerOrProvider) as ComposableCoW;\n }\n}\n","/* Autogenerated file. Do not edit manually. */\n/* tslint:disable */\n/* eslint-disable */\n\nimport { Contract, Signer, utils } from \"ethers\";\nimport type { Provider } from \"@ethersproject/providers\";\nimport type {\n ExtensibleFallbackHandler,\n ExtensibleFallbackHandlerInterface,\n} from \"../ExtensibleFallbackHandler\";\n\nconst _abi = [\n {\n anonymous: false,\n inputs: [\n {\n indexed: true,\n internalType: \"contract Safe\",\n name: \"safe\",\n type: \"address\",\n },\n {\n indexed: false,\n internalType: \"bytes32\",\n name: \"domainSeparator\",\n type: \"bytes32\",\n },\n {\n indexed: false,\n internalType: \"contract ISafeSignatureVerifier\",\n name: \"verifier\",\n type: \"address\",\n },\n ],\n name: \"AddedDomainVerifier\",\n type: \"event\",\n },\n {\n anonymous: false,\n inputs: [\n {\n indexed: true,\n internalType: \"contract Safe\",\n name: \"safe\",\n type: \"address\",\n },\n {\n indexed: false,\n internalType: \"bytes4\",\n name: \"interfaceId\",\n type: \"bytes4\",\n },\n ],\n name: \"AddedInterface\",\n type: \"event\",\n },\n {\n anonymous: false,\n inputs: [\n {\n indexed: true,\n internalType: \"contract Safe\",\n name: \"safe\",\n type: \"address\",\n },\n {\n indexed: false,\n internalType: \"bytes4\",\n name: \"selector\",\n type: \"bytes4\",\n },\n {\n indexed: false,\n internalType: \"bytes32\",\n name: \"method\",\n type: \"bytes32\",\n },\n ],\n name: \"AddedSafeMethod\",\n type: \"event\",\n },\n {\n anonymous: false,\n inputs: [\n {\n indexed: true,\n internalType: \"contract Safe\",\n name: \"safe\",\n type: \"address\",\n },\n {\n indexed: false,\n internalType: \"bytes32\",\n name: \"domainSeparator\",\n type: \"bytes32\",\n },\n {\n indexed: false,\n internalType: \"contract ISafeSignatureVerifier\",\n name: \"oldVerifier\",\n type: \"address\",\n },\n {\n indexed: false,\n internalType: \"contract ISafeSignatureVerifier\",\n name: \"newVerifier\",\n type: \"address\",\n },\n ],\n name: \"ChangedDomainVerifier\",\n type: \"event\",\n },\n {\n anonymous: false,\n inputs: [\n {\n indexed: true,\n internalType: \"contract Safe\",\n name: \"safe\",\n type: \"address\",\n },\n {\n indexed: false,\n internalType: \"bytes4\",\n name: \"selector\",\n type: \"bytes4\",\n },\n {\n indexed: false,\n internalType: \"bytes32\",\n name: \"oldMethod\",\n type: \"bytes32\",\n },\n {\n indexed: false,\n internalType: \"bytes32\",\n name: \"newMethod\",\n type: \"bytes32\",\n },\n ],\n name: \"ChangedSafeMethod\",\n type: \"event\",\n },\n {\n anonymous: false,\n inputs: [\n {\n indexed: true,\n internalType: \"contract Safe\",\n name: \"safe\",\n type: \"address\",\n },\n {\n indexed: false,\n internalType: \"bytes32\",\n name: \"domainSeparator\",\n type: \"bytes32\",\n },\n ],\n name: \"RemovedDomainVerifier\",\n type: \"event\",\n },\n {\n anonymous: false,\n inputs: [\n {\n indexed: true,\n internalType: \"contract Safe\",\n name: \"safe\",\n type: \"address\",\n },\n {\n indexed: false,\n internalType: \"bytes4\",\n name: \"interfaceId\",\n type: \"bytes4\",\n },\n ],\n name: \"RemovedInterface\",\n type: \"event\",\n },\n {\n anonymous: false,\n inputs: [\n {\n indexed: true,\n internalType: \"contract Safe\",\n name: \"safe\",\n type: \"address\",\n },\n {\n indexed: false,\n internalType: \"bytes4\",\n name: \"selector\",\n type: \"bytes4\",\n },\n ],\n name: \"RemovedSafeMethod\",\n type: \"event\",\n },\n {\n stateMutability: \"nonpayable\",\n type: \"fallback\",\n },\n {\n inputs: [\n {\n internalType: \"contract Safe\",\n name: \"\",\n type: \"address\",\n },\n {\n internalType: \"bytes32\",\n name: \"\",\n type: \"bytes32\",\n },\n ],\n name: \"domainVerifiers\",\n outputs: [\n {\n internalType: \"contract ISafeSignatureVerifier\",\n name: \"\",\n type: \"address\",\n },\n ],\n stateMutability: \"view\",\n type: \"function\",\n },\n {\n inputs: [\n {\n internalType: \"bytes32\",\n name: \"_hash\",\n type: \"bytes32\",\n },\n {\n internalType: \"bytes\",\n name: \"signature\",\n type: \"bytes\",\n },\n ],\n name: \"isValidSignature\",\n outputs: [\n {\n internalType: \"bytes4\",\n name: \"magic\",\n type: \"bytes4\",\n },\n ],\n stateMutability: \"view\",\n type: \"function\",\n },\n {\n inputs: [\n {\n internalType: \"address\",\n name: \"\",\n type: \"address\",\n },\n {\n internalType: \"address\",\n name: \"\",\n type: \"address\",\n },\n {\n internalType: \"uint256[]\",\n name: \"\",\n type: \"uint256[]\",\n },\n {\n internalType: \"uint256[]\",\n name: \"\",\n type: \"uint256[]\",\n },\n {\n internalType: \"bytes\",\n name: \"\",\n type: \"bytes\",\n },\n ],\n name: \"onERC1155BatchReceived\",\n outputs: [\n {\n internalType: \"bytes4\",\n name: \"\",\n type: \"bytes4\",\n },\n ],\n stateMutability: \"pure\",\n type: \"function\",\n },\n {\n inputs: [\n {\n internalType: \"address\",\n name: \"\",\n type: \"address\",\n },\n {\n internalType: \"address\",\n name: \"\",\n type: \"address\",\n },\n {\n internalType: \"uint256\",\n name: \"\",\n type: \"uint256\",\n },\n {\n internalType: \"uint256\",\n name: \"\",\n type: \"uint256\",\n },\n {\n internalType: \"bytes\",\n name: \"\",\n type: \"bytes\",\n },\n ],\n name: \"onERC1155Received\",\n outputs: [\n {\n internalType: \"bytes4\",\n name: \"\",\n type: \"bytes4\",\n },\n ],\n stateMutability: \"pure\",\n type: \"function\",\n },\n {\n inputs: [\n {\n internalType: \"address\",\n name: \"\",\n type: \"address\",\n },\n {\n internalType: \"address\",\n name: \"\",\n type: \"address\",\n },\n {\n internalType: \"uint256\",\n name: \"\",\n type: \"uint256\",\n },\n {\n internalType: \"bytes\",\n name: \"\",\n type: \"bytes\",\n },\n ],\n name: \"onERC721Received\",\n outputs: [\n {\n internalType: \"bytes4\",\n name: \"\",\n type: \"bytes4\",\n },\n ],\n stateMutability: \"pure\",\n type: \"function\",\n },\n {\n inputs: [\n {\n internalType: \"contract Safe\",\n name: \"\",\n type: \"address\",\n },\n {\n internalType: \"bytes4\",\n name: \"\",\n type: \"bytes4\",\n },\n ],\n name: \"safeInterfaces\",\n outputs: [\n {\n internalType: \"bool\",\n name: \"\",\n type: \"bool\",\n },\n ],\n stateMutability: \"view\",\n type: \"function\",\n },\n {\n inputs: [\n {\n internalType: \"contract Safe\",\n name: \"\",\n type: \"address\",\n },\n {\n internalType: \"bytes4\",\n name: \"\",\n type: \"bytes4\",\n },\n ],\n name: \"safeMethods\",\n outputs: [\n {\n internalType: \"bytes32\",\n name: \"\",\n type: \"bytes32\",\n },\n ],\n stateMutability: \"view\",\n type: \"function\",\n },\n {\n inputs: [\n {\n internalType: \"bytes32\",\n name: \"domainSeparator\",\n type: \"bytes32\",\n },\n {\n internalType: \"contract ISafeSignatureVerifier\",\n name: \"newVerifier\",\n type: \"address\",\n },\n ],\n name: \"setDomainVerifier\",\n outputs: [],\n stateMutability: \"nonpayable\",\n type: \"function\",\n },\n {\n inputs: [\n {\n internalType: \"bytes4\",\n name: \"selector\",\n type: \"bytes4\",\n },\n {\n internalType: \"bytes32\",\n name: \"newMethod\",\n type: \"bytes32\",\n },\n ],\n name: \"setSafeMethod\",\n outputs: [],\n stateMutability: \"nonpayable\",\n type: \"function\",\n },\n {\n inputs: [\n {\n internalType: \"bytes4\",\n name: \"interfaceId\",\n type: \"bytes4\",\n },\n {\n internalType: \"bool\",\n name: \"supported\",\n type: \"bool\",\n },\n ],\n name: \"setSupportedInterface\",\n outputs: [],\n stateMutability: \"nonpayable\",\n type: \"function\",\n },\n {\n inputs: [\n {\n internalType: \"bytes4\",\n name: \"_interfaceId\",\n type: \"bytes4\",\n },\n {\n internalType: \"bytes32[]\",\n name: \"handlerWithSelectors\",\n type: \"bytes32[]\",\n },\n ],\n name: \"setSupportedInterfaceBatch\",\n outputs: [],\n stateMutability: \"nonpayable\",\n type: \"function\",\n },\n {\n inputs: [\n {\n internalType: \"bytes4\",\n name: \"interfaceId\",\n type: \"bytes4\",\n },\n ],\n name: \"supportsInterface\",\n outputs: [\n {\n internalType: \"bool\",\n name: \"\",\n type: \"bool\",\n },\n ],\n stateMutability: \"view\",\n type: \"function\",\n },\n] as const;\n\nexport class ExtensibleFallbackHandler__factory {\n static readonly abi = _abi;\n static createInterface(): ExtensibleFallbackHandlerInterface {\n return new utils.Interface(_abi) as ExtensibleFallbackHandlerInterface;\n }\n static connect(\n address: string,\n signerOrProvider: Signer | Provider\n ): ExtensibleFallbackHandler {\n return new Contract(\n address,\n _abi,\n signerOrProvider\n ) as ExtensibleFallbackHandler;\n }\n}\n","import { utils, providers, BigNumber } from 'ethers'\nimport {\n COMPOSABLE_COW_CONTRACT_ADDRESS,\n EXTENSIBLE_FALLBACK_HANDLER_CONTRACT_ADDRESS,\n SupportedChainId,\n} from '../common'\nimport { ExtensibleFallbackHandler__factory } from './generated'\nimport { BlockInfo, ConditionalOrderParams } from './types'\nimport { Order, OrderBalance, OrderKind } from '@cowprotocol/contracts'\nimport { GPv2Order } from './generated/ComposableCoW'\n\nconst ERC20_BALANCE_VALUES = ['erc20', '0x5a28e9363bb942b639270062aa6bb295f434bcdfc42c97267bf003f272060dc9']\nconst EXTERNAL_BALANCE_VALUES = ['external', '0xabee3b73373acd583a130924aad6dc38cfdc44ba0555ba94ce2ff63980ea0632']\nconst INTERNAL_BALANCE_VALUES = ['internal', '0x4ac99ace14ee0a5ef932dc609df0943ab7ac16b7583634612f8dc35a4289a6ce']\nconst SELL_KIND_VALUES = ['sell', '0xf3b277728b3fee749481eb3e0b3b48980dbbab78658fc419025cb16eee346775']\nconst BUY_KIND_VALUES = ['buy', '0x6ed88e868af0a1983e3886d5f3e95a2fafbd6c3450bc229e27342283dc429ccc']\n\n// Define the ABI tuple for the ConditionalOrderParams struct\nexport const CONDITIONAL_ORDER_PARAMS_ABI = ['tuple(address handler, bytes32 salt, bytes staticInput)']\n\nexport const DEFAULT_TOKEN_FORMATTER = (address: string, amount: BigNumber) => `${amount}@${address}`\n\nexport function isExtensibleFallbackHandler(handler: string, chainId: SupportedChainId): boolean {\n return handler === EXTENSIBLE_FALLBACK_HANDLER_CONTRACT_ADDRESS[chainId]\n}\n\nexport function isComposableCow(handler: string, chainId: SupportedChainId): boolean {\n return handler === COMPOSABLE_COW_CONTRACT_ADDRESS[chainId]\n}\n\nexport async function getDomainVerifier(\n safe: string,\n domain: string,\n chainId: SupportedChainId,\n provider: providers.Provider\n): Promise<string> {\n const contract = ExtensibleFallbackHandler__factory.connect(\n EXTENSIBLE_FALLBACK_HANDLER_CONTRACT_ADDRESS[chainId],\n provider\n )\n return await contract.callStatic.domainVerifiers(safe, domain)\n}\n\nexport function createSetDomainVerifierTx(domain: string, verifier: string): string {\n return ExtensibleFallbackHandler__factory.createInterface().encodeFunctionData('setDomainVerifier', [\n domain,\n verifier,\n ])\n}\n\n/**\n * Encode the `ConditionalOrderParams` for the conditional order.\n *\n * @param params The `ConditionalOrderParams` struct representing the conditional order as taken from a merkle tree.\n * @returns The ABI-encoded conditional order.\n * @see ConditionalOrderParams\n */\nexport function encodeParams(params: ConditionalOrderParams): string {\n return utils.defaultAbiCoder.encode(CONDITIONAL_ORDER_PARAMS_ABI, [params])\n}\n\n/**\n * Decode the `ConditionalOrderParams` for the conditional order.\n *\n * @param encoded The encoded conditional order.\n * @returns The decoded conditional order.\n */\nexport function decodeParams(encoded: string): ConditionalOrderParams {\n const { handler, salt, staticInput } = utils.defaultAbiCoder.decode(CONDITIONAL_ORDER_PARAMS_ABI, encoded)[0]\n return { handler, salt, staticInput }\n}\n\n/**\n * Helper method for validating ABI types.\n * @param types ABI types to validate against.\n * @param values The values to validate.\n * @returns {boolean} Whether the values are valid ABI for the given types.\n */\nexport function isValidAbi(types: readonly (string | utils.ParamType)[], values: any[]): boolean {\n try {\n utils.defaultAbiCoder.encode(types, values)\n } catch (e) {\n return false\n }\n return true\n}\n\nexport async function getBlockInfo(provider: providers.Provider): Promise<BlockInfo> {\n const block = await provider.getBlock('latest')\n\n return {\n blockNumber: block.number,\n blockTimestamp: block.timestamp,\n }\n}\n\nexport function formatEpoch(epoch: number): string {\n return new Date(epoch * 1000).toISOString()\n}\n\n/**\n * Convert a balance source/destination hash to a string\n *\n * @param balance balance source/destination hash\n * @returns string representation of the balance\n * @throws if the balance is not recognized\n */\nfunction balanceToString(balance: string) {\n if (ERC20_BALANCE_VALUES.includes(balance)) {\n return OrderBalance.ERC20\n } else if (EXTERNAL_BALANCE_VALUES.includes(balance)) {\n return OrderBalance.EXTERNAL\n } else if (INTERNAL_BALANCE_VALUES.includes(balance)) {\n return OrderBalance.INTERNAL\n } else {\n throw new Error(`Unknown balance type: ${balance}`)\n }\n}\n\n/**\n * Convert an order kind hash to a string\n * @param kind of order in hash format\n * @returns string representation of the order kind\n */\nfunction kindToString(kind: string) {\n if (SELL_KIND_VALUES.includes(kind)) {\n return OrderKind.SELL\n } else if (BUY_KIND_VALUES.includes(kind)) {\n return OrderKind.BUY\n } else {\n throw new Error(`Unknown kind: ${kind}`)\n }\n}\n\nexport function fromStructToOrder(order: GPv2Order.DataStruct): Order {\n const {\n sellToken,\n sellAmount,\n buyToken,\n buyAmount,\n buyTokenBalance,\n sellTokenBalance,\n feeAmount,\n kind,\n receiver,\n validTo,\n partiallyFillable,\n appData,\n } = order\n\n return {\n sellToken,\n sellAmount,\n buyToken,\n buyAmount,\n feeAmount,\n receiver,\n partiallyFillable,\n appData,\n validTo: Number(validTo),\n kind: kindToString(kind.toString()),\n sellTokenBalance: balanceToString(sellTokenBalance.toString()),\n buyTokenBalance: balanceToString(buyTokenBalance.toString()),\n }\n}\n","import { providers } from 'ethers'\nimport { COMPOSABLE_COW_CONTRACT_ADDRESS, SupportedChainId } from '../common'\nimport { ComposableCoW, ComposableCoW__factory } from './generated'\nimport { ComposableCoWInterface } from './generated/ComposableCoW'\n\nlet composableCowInterfaceCache: ComposableCoWInterface | undefined\nlet composableCowContractCache: ComposableCoW | undefined\n\nexport function getComposableCowInterface(): ComposableCoWInterface {\n if (!composableCowInterfaceCache) {\n composableCowInterfaceCache = ComposableCoW__factory.createInterface()\n }\n\n return composableCowInterfaceCache\n}\n\nexport function getComposableCow(chain: SupportedChainId, provider: providers.Provider): ComposableCoW {\n if (!composableCowContractCache) {\n composableCowContractCache = ComposableCoW__factory.connect(COMPOSABLE_COW_CONTRACT_ADDRESS[chain], provider)\n }\n\n return composableCowContractCache\n}\n","import { BigNumber, constants, ethers, utils } from 'ethers'\nimport { GPv2Order, IConditionalOrder } from './generated/ComposableCoW'\n\nimport { decodeParams, encodeParams, fromStructToOrder } from './utils'\nimport {\n ConditionalOrderArguments,\n ConditionalOrderParams,\n ContextFactory,\n IsValidResult,\n OwnerContext,\n PollParams,\n PollResult,\n PollResultCode,\n PollResultErrors,\n} from './types'\nimport { getComposableCow, getComposableCowInterface } from './contracts'\nimport { UID } from '../order-book'\nimport { computeOrderUid } from '../utils'\n\n/**\n * An abstract base class from which all conditional orders should inherit.\n *\n * This class provides some basic functionality to help with handling conditional orders,\n * such as:\n * - Validating the conditional order\n * - Creating a human-readable string representation of the conditional order\n * - Serializing the conditional order for use with the `IConditionalOrder` struct\n * - Getting any dependencies for the conditional order\n * - Getting the off-chain input for the conditional order\n *\n * **NOTE**: Instances of conditional orders have an `id` property that is a `keccak256` hash of\n * the serialized conditional order.\n */\nexport abstract class ConditionalOrder<D, S> {\n public readonly handler: string\n public readonly salt: string\n public readonly data: D\n public readonly staticInput: S\n public readonly hasOffChainInput: boolean\n\n /**\n * A constructor that provides some basic validation for the conditional order.\n *\n * This constructor **MUST** be called by any class that inherits from `ConditionalOrder`.\n *\n * **NOTE**: The salt is optional and will be randomly generated if not provided.\n * @param handler The address of the handler for the conditional order.\n * @param salt A 32-byte string used to salt the conditional order.\n * @param data The data of the order\n * @param hasOffChainInput Whether the conditional order has off-chain input.\n * @throws If the handler is not a valid ethereum address.\n * @throws If the salt is not a valid 32-byte string.\n */\n constructor(params: ConditionalOrderArguments<D>) {\n const { handler, salt = utils.keccak256(utils.randomBytes(32)), data, hasOffChainInput = false } = params\n // Verify input to the constructor\n // 1. Verify that the handler is a valid ethereum address\n if (!ethers.utils.isAddress(handler)) {\n throw new Error(`Invalid handler: ${handler}`)\n }\n\n // 2. Verify that the salt is a valid 32-byte string usable with ethers\n if (!ethers.utils.isHexString(salt) || ethers.utils.hexDataLength(salt) !== 32) {\n throw new Error(`Invalid salt: ${salt}`)\n }\n\n this.handler = handler\n this.salt = salt\n this.data = data\n this.staticInput = this.transformDataToStruct(data)\n\n this.hasOffChainInput = hasOffChainInput\n }\n\n // TODO: https://github.com/cowprotocol/cow-sdk/issues/155\n abstract get isSingleOrder(): boolean\n\n /**\n * Get a descriptive name for the type of the conditional order (i.e twap, dca, etc).\n *\n * @returns {string} The concrete type of the conditional order.\n */\n abstract get orderType(): string\n\n /**\n * Get the context dependency for the conditional order.\n *\n * This is used when calling `createWithContext` or `setRootWithContext` on a ComposableCoW-enabled Safe.\n * @returns The context dependency.\n */\n get context(): ContextFactory | undefined {\n return undefined\n }\n\n assertIsValid(): void {\n const isValidResult = this.isValid()\n if (!isValidResult.isValid) {\n throw new Error(`Invalid order: ${isValidResult.reason}`)\n }\n }\n\n abstract isValid(): IsValidResult\n\n /**\n * Get the calldata for creating the conditional order.\n *\n * This will automatically determine whether or not to use `create` or `createWithContext` based on the\n * order type's context dependency.\n *\n * **NOTE**: By default, this will cause the create to emit the `ConditionalOrderCreated` event.\n * @returns The calldata for creating the conditional order.\n */\n get createCalldata(): string {\n this.assertIsValid()\n\n const context = this.context\n const composableCow = getComposableCowInterface()\n const paramsStruct: IConditionalOrder.ConditionalOrderParamsStruct = {\n handler: this.handler,\n salt: this.salt,\n staticInput: this.encodeStaticInput(),\n }\n\n if (context) {\n // Create (with context)\n const contextArgsAbi = context.factoryArgs\n ? utils.defaultAbiCoder.encode(context.factoryArgs.argsType, context.factoryArgs.args)\n : '0x'\n return composableCow.encodeFunctionData('createWithContext', [\n paramsStruct,\n context.address,\n contextArgsAbi,\n true,\n ])\n } else {\n // Create\n return composableCow.encodeFunctionData('create', [paramsStruct, true])\n }\n }\n\n /**\n * Get the calldata for removing a conditional order that was created as a single order.\n * @returns The calldata for removing the conditional order.\n */\n get removeCalldata(): string {\n this.assertIsValid()\n\n return getComposableCowInterface().encodeFunctionData('remove', [this.id])\n }\n\n /**\n * Calculate the id of the conditional order (which also happens to be the key used for `ctx` in the ComposableCoW contract).\n *\n * This is a `keccak256` hash of the serialized conditional order.\n * @returns The id of the conditional order.\n */\n get id(): string {\n return utils.keccak256(this.serialize())\n }\n\n /**\n * The context key of the order (bytes32(0) if a merkle tree is used, otherwise H(params)) with which to lookup the cabinet\n *\n * The context, relates to the 'ctx' in the contract: https://github.com/cowprotocol/composable-cow/blob/c7fb85ab10c05e28a1632ba97a1749fb261fcdfb/src/interfaces/IConditionalOrder.sol#L38\n */\n protected get ctx(): string {\n return this.isSingleOrder ? this.id : constants.HashZero\n }\n\n /**\n * Get the `leaf` of the conditional order. This is the data that is used to create the merkle tree.\n *\n * For the purposes of this library, the `leaf` is the `ConditionalOrderParams` struct.\n * @returns The `leaf` of the conditional order.\n * @see ConditionalOrderParams\n */\n get leaf(): ConditionalOrderParams {\n return {\n handler: this.handler,\n salt: this.salt,\n staticInput: this.encodeStaticInput(),\n }\n }\n\n /**\n * Calculate the id of the conditional order.\n * @param leaf The `leaf` representing the conditional order.\n * @returns The id of the conditional order.\n * @see ConditionalOrderParams\n */\n static leafToId(leaf: ConditionalOrderParams): string {\n return utils.keccak256(encodeParams(leaf))\n }\n\n /**\n * If the conditional order has off-chain input, return it!\n *\n * **NOTE**: This should be overridden by any conditional order that has off-chain input.\n * @returns The off-chain input.\n */\n get offChainInput(): string {\n return '0x'\n }\n\n /**\n * Create a human-readable string representation of the conditional order.\n *\n * @param tokenFormatter An optional function that takes an address and an amount and returns a human-readable string.\n */\n abstract toString(tokenFormatter?: (address: string, amount: BigNumber) => string): string\n\n /**\n * Serializes the conditional order into it's ABI-encoded form.\n *\n * @returns The equivalent of `IConditionalOrder.Params` for the conditional order.\n */\n abstract serialize(): string\n\n /**\n * Encode the `staticInput` for the conditional order.\n *\n * @returns The ABI-encoded `staticInput` for the conditional order.\n * @see ConditionalOrderParams\n */\n abstract encodeStaticInput(): string\n\n /**\n * A helper function for generically serializing a conditional order's static input.\n *\n * @param orderDataTypes ABI types for the order's data struct.\n * @param data The order's data struct.\n * @returns An ABI-encoded representation of the order's data struct.\n */\n protected encodeStaticInputHelper(orderDataTypes: string[], staticInput: S): string {\n return utils.defaultAbiCoder.encode(orderDataTypes, [staticInput])\n }\n\n /**\n * Poll a conditional order to see if it is tradeable.\n *\n * @param owner The owner of the conditional order.\n * @param p The proof and parameters.\n * @param chain Which chain to use for the ComposableCoW contract.\n * @param provider An RPC provider for the chain.\n * @param offChainInputFn A function, if provided, that will return the off-chain input for the conditional order.\n * @throws If the conditional order is not tradeable.\n * @returns The tradeable `GPv2Order.Data` struct and the `signature` for the conditional order.\n */\n async poll(params: PollParams): Promise<PollResult> {\n const { chainId, owner, provider, orderBookApi } = params\n const composableCow = getComposableCow(chainId, provider)\n\n try {\n const isValid = this.isValid()\n // Do a validation first\n if (!isValid.isValid) {\n return {\n result: PollResultCode.DONT_TRY_AGAIN,\n reason: `InvalidConditionalOrder. Reason: ${isValid.reason}`,\n }\n }\n\n // Let the concrete Conditional Order decide about the poll result\n const pollResult = await this.pollValidate(params)\n if (pollResult) {\n return pollResult\n }\n\n // Check if the owner authorized the order\n const isAuthorized = await this.isAuthorized(params)\n if (!isAuthorized) {\n return {\n result: PollResultCode.DONT_TRY_AGAIN,\n reason: `NotAuthorized: Order ${this.id} is not authorized for ${owner} on chain ${chainId}`,\n }\n }\n\n // Lastly, try to get the tradeable order and signature\n const [order, signature] = await composableCow.getTradeableOrderWithSignature(\n owner,\n this.leaf,\n this.offChainInput,\n []\n )\n\n const orderUid = await computeOrderUid(chainId, owner, fromStructToOrder(order))\n\n // Check if the order is already in the order book\n const isOrderInOrderbook = await orderBookApi\n .getOrder(orderUid)\n .then(() => true)\n .catch(() => false)\n\n // Let the concrete Conditional Order decide about the poll result (in the case the order is already in the orderbook)\n if (isOrderInOrderbook) {\n const pollResult = await this.handlePollFailedAlreadyPresent(orderUid, order, params)\n if (pollResult) {\n return pollResult\n }\n\n return {\n result: PollResultCode.TRY_NEXT_BLOCK,\n reason: 'Order already in orderbook',\n }\n }\n\n return {\n result: PollResultCode.SUCCESS,\n order,\n signature,\n }\n } catch (error) {\n return {\n result: PollResultCode.UNEXPECTED_ERROR,\n error: error,\n }\n }\n }\n\n /**\n * Checks if the owner authorized the conditional order.\n *\n * @param params owner context, to be able to check if the order is authorized\n * @returns true if the owner authorized the order, false otherwise.\n */\n public isAuthorized(params: OwnerContext): Promise<boolean> {\n const { chainId, owner, provider } = params\n const composableCow = getComposableCow(chainId, provider)\n return composableCow.callStatic.singleOrders(owner, this.id)\n }\n\n /**\n * Checks the value in the cabinet for a given owner and chain\n *\n * @param params owner context, to be able to check the cabinet\n */\n public cabinet(params: OwnerContext): Promise<string> {\n const { chainId, owner, provider } = params\n\n const composableCow = getComposableCow(chainId, provider)\n return composableCow.callStatic.cabinet(owner, this.ctx)\n }\n\n /**\n * Allow concrete conditional orders to perform additional validation for the poll method.\n *\n * This will allow the concrete orders to decide when an order shouldn't be polled again. For example, if the orders is expired.\n * It also allows to signal when should the next check be done. For example, an order could signal that the validations will fail until a certain time or block.\n *\n * @param params The poll parameters\n *\n * @returns undefined if the concrete order can't make a decision. Otherwise, it returns a PollResultErrors object.\n */\n protected abstract pollValidate(params: PollParams): Promise<PollResultErrors | undefined>\n\n /**\n * This method lets the concrete conditional order decide what to do if the order yielded in the polling is already present in the Orderbook API.\n *\n * The concrete conditional order will have a chance to schedule the next poll.\n * For example, a TWAP order that has the current part already in the orderbook, can signal that the next poll should be done at the start time of the next part.\n *\n * @param params\n */\n protected abstract handlePollFailedAlreadyPresent(\n orderUid: UID,\n order: GPv2Order.DataStruct,\n params: PollParams\n ): Promise<PollResultErrors | undefined>\n\n /**\n * Convert the struct that the contract expect as an encoded `staticInput` into a friendly data object modelling the smart order.\n *\n * **NOTE**: This should be overridden by any conditional order that requires transformations.\n * This implementation is a no-op if you use the same type for both.\n *\n * @param params {S} Parameters that are passed in to the constructor.\n * @returns {D} The static input for the conditional order.\n */\n abstract transformStructToData(params: S): D\n\n /**\n * Converts a friendly data object modelling the smart order into the struct that the contract expect as an encoded `staticInput`.\n *\n * **NOTE**: This should be overridden by any conditional order that requires transformations.\n * This implementation is a no-op if you use the same type for both.\n *\n * @param params {S} Parameters that are passed in to the constructor.\n * @returns {D} The static input for the conditional order.\n */\n abstract transformDataToStruct(params: D): S\n\n /**\n * A helper function for generically deserializing a conditional order.\n * @param s The ABI-encoded `IConditionalOrder.Params` struct to deserialize.\n * @param handler Address of the handler for the conditional order.\n * @param orderDataTypes ABI types for the order's data struct.\n * @param callback A callback function that takes the deserialized data struct and the salt and returns an instance of the class.\n * @returns An instance of the conditional order class.\n */\n protected static deserializeHelper<T>(\n s: string,\n handler: string,\n orderDataTypes: string[],\n callback: (d: any, salt: string) => T\n ): T {\n try {\n // First, decode the `IConditionalOrder.Params` struct\n const { handler: recoveredHandler, salt, staticInput } = decodeParams(s)\n\n // Second, verify that the recovered handler is the correct handler\n if (!(recoveredHandler == handler)) throw new Error('HandlerMismatch')\n\n // Third, decode the data struct\n const [d] = utils.defaultAbiCoder.decode(orderDataTypes, staticInput)\n\n // Create a new instance of the class\n return callback(d, salt)\n } catch (e: any) {\n if (e.message === 'HandlerMismatch') {\n throw e\n } else {\n throw new Error('InvalidSerializedConditionalOrder')\n }\n }\n }\n}\n","import type { Order } from '@cowprotocol/contracts'\nimport type { SupportedChainId } from './common'\nimport { OrderSigningUtils } from './order-signing'\n\nexport async function computeOrderUid(chainId: SupportedChainId, owner: string, order: Order): Promise<string> {\n const { computeOrderUid: _computeOrderUid } = await import('@cowprotocol/contracts')\n const domain = await OrderSigningUtils.getDomain(chainId)\n\n return _computeOrderUid(domain, order, owner)\n}\n","import { StandardMerkleTree } from '@openzeppelin/merkle-tree'\nimport { BigNumber, providers, utils } from 'ethers'\n\nimport { SupportedChainId } from '../common'\n\nimport { ComposableCoW, GPv2Order } from './generated/ComposableCoW'\nimport { ProofLocation, ProofWithParams, ConditionalOrderParams } from './types'\nimport { ConditionalOrder } from './ConditionalOrder'\nimport { getComposableCow } from './contracts'\n\nconst CONDITIONAL_ORDER_LEAF_ABI = ['address', 'bytes32', 'bytes']\n\nconst PAYLOAD_EMITTED_ABI = ['tuple(bytes32[] proof, tuple(address handler, bytes32 salt, bytes staticInput) params)[]']\n\nexport type Orders = Record<string, ConditionalOrder<unknown, unknown>>\n\n/**\n * Multiplexer for conditional orders - using `ComposableCoW`!\n *\n * This class provides functionality to:\n * - Generate a merkle tree of conditional orders\n * - Generate proofs for all orders in the merkle tree\n * - Save proofs, with the ability to omit / skip specific conditional orders\n * - Support for passing an optional upload function to upload the proofs to a decentralized storage network\n */\nexport class Multiplexer {\n static orderTypeRegistry: Record<string, new (...args: unknown[]) => ConditionalOrder<unknown, unknown>> = {}\n\n public chain: SupportedChainId\n public location: ProofLocation\n\n private orders: Orders = {}\n private tree?: StandardMerkleTree<string[]>\n private ctx?: string\n\n /**\n * @param chain The `chainId` for where we're using `ComposableCoW`.\n * @param orders An optional array of conditional orders to initialize the merkle tree with.\n * @param root An optional root to verify against.\n * @param location The location of the proofs for the conditional orders.\n */\n constructor(\n chain: SupportedChainId,\n orders?: Orders,\n root?: string,\n location: ProofLocation = ProofLocation.PRIVATE\n ) {\n this.chain = chain\n this.location = location\n\n // If orders are provided, the length must be > 0\n if (orders && Object.keys(orders).length === 0) {\n throw new Error('orders must have non-zero length')\n }\n\n // If orders are provided, so must a root, and vice versa\n if ((orders && !root) || (!orders && root)) {\n throw new Error('orders cannot have undefined root')\n }\n\n // can only proceed past here if both orders and root are provided, or neither are\n\n // validate that no unknown order types are provided\n for (const orderKey in orders) {\n if (orders.hasOwnProperty(orderKey)) {\n const order = orders[orderKey]\n if (!Multiplexer.orderTypeRegistry.hasOwnProperty(order.orderType)) {\n throw new Error(`Unknown order type: ${order.orderType}`)\n }\n }\n }\n\n // If orders (and therefore the root) are provided, generate the merkle tree\n if (orders) {\n this.orders = orders\n\n // if generate was successful, we can verify the root\n if (this.getOrGenerateTree().root !== root) {\n throw new Error('root mismatch')\n }\n }\n }\n\n // --- user facing serialization methods ---\n\n /**\n * Given a serialized multiplexer, create the multiplexer and rehydrate all conditional orders.\n * Integrity of the multiplexer will be verified by generating the merkle tree and verifying\n * the root.\n *\n * **NOTE**: Before using this method, you must register all conditional order types using `Multiplexer.registerOrderType`.\n * @param s The serialized multiplexer.\n * @returns The multiplexer with all conditional orders rehydrated.\n * @throws If the multiplexer cannot be deserialized.\n * @throws If the merkle tree cannot be generated.\n * @throws If the merkle tree cannot be verified against the root.\n */\n static fromJSON(s: string): Multiplexer {\n // reviver function to deserialize the orders\n const reviver = (k: string, v: any) => {\n if (k === 'orders' && typeof v === 'object' && v !== null) {\n const orders: Orders = {}\n\n for (const orderKey in v) {\n if (v.hasOwnProperty(orderKey)) {\n const { orderType, ...orderData } = v[orderKey]\n\n if (Multiplexer.orderTypeRegistry.hasOwnProperty(orderType)) {\n const OrderConstructor = Multiplexer.orderTypeRegistry[orderType]\n orders[orderKey] = new OrderConstructor(orderData)\n } else {\n throw new Error(`Unknown order type: ${orderType}`)\n }\n }\n }\n\n return orders\n }\n\n // Make sure we deserialize `BigNumber` correctly\n if (typeof v === 'object' && v !== null && v.hasOwnProperty('type') && v.hasOwnProperty('hex')) {\n if (v.type === 'BigNumber') {\n return BigNumber.from(v)\n }\n }\n\n return v\n }\n\n const { chain, orders, root, location } = JSON.parse(s, reviver)\n const m = new Multiplexer(chain, orders, root)\n m.location = location\n return m\n }\n\n /**\n * Serialize the multiplexer to JSON.\n *\n * This will include all state necessary to reconstruct the multiplexer, including the root.\n * @remarks This will **NOT** include the merkle tree.\n * @returns The JSON representation of the multiplexer, including the root but excluding the merkle tree.\n */\n toJSON(): string {\n const root = this.getOrGenerateTree().root\n\n // serialize the multiplexer, including the root but excluding the merkle tree.\n return JSON.stringify({ ...this, root }, (k, v) => {\n // filter out the merkle tree\n if (k === 'tree') return undefined\n if (typeof v === 'object' && v !== null && 'orderType' in v) {\n const conditionalOrder = v as ConditionalOrder<unknown, unknown>\n return {\n ...conditionalOrder,\n orderType: conditionalOrder.orderType,\n }\n }\n // We do not do any custom serialization of `BigNumber` in order to preserve it's type.\n return v\n })\n }\n\n // --- crud methods ---\n\n /**\n * Add a conditional order to the merkle tree.\n * @param order The order to add to the merkle tree.\n */\n add<T, P>(order: ConditionalOrder<T, P>): void {\n order.assertIsValid()\n\n this.orders[order.id] = order\n this.reset()\n }\n\n /**\n * Remove a conditional order from the merkle tree.\n * @param id The id of the `ConditionalOrder` to remove from the merkle tree.\n */\n remove(id: string): void {\n delete this.orders[id]\n this.reset()\n }\n\n /**\n * Update a given conditional order in the merkle tree.\n * @param id The id of the `ConditionalOrder` to update.\n * @param updater A function that takes the existing `ConditionalOrder` and context, returning an updated `ConditionalOrder`.\n */\n update(\n id: string,\n updater: (order: ConditionalOrder<unknown, unknown>, ctx?: string) => ConditionalOrder<unknown, unknown>\n ): void {\n // copy the existing order and update it, given the existing context (if any)\n const order = updater(this.orders[id], this.ctx)\n // delete the existing order\n delete this.orders[id]\n\n // add the updated order\n this.orders[order.id] = order\n this.reset()\n }\n\n // --- accessors ---\n\n /**\n * Accessor for a given conditional order in the multiplexer.\n * @param id The `id` of the `ConditionalOrder` to retrieve.\n * @returns A `ConditionalOrder` with the given `id`.\n */\n getById(id: string): ConditionalOrder<unknown, unknown> {\n return this.orders[id]\n }\n\n /**\n * Accessor for a given conditional order in the multiplexer.\n * @param i The index of the `ConditionalOrder` to retrieve.\n * @returns A `ConditionalOrder` at the given index.\n */\n getByIndex(i: number): ConditionalOrder<unknown, unknown> {\n return this.orders[this.orderIds[i]]\n }\n\n /**\n * Get all the conditional order ids in the multiplexer.\n */\n get orderIds(): string[] {\n return Object.keys(this.orders)\n }\n\n get root(): string {\n return this.getOrGenerateTree().root\n }\n\n /**\n * Retrieve the merkle tree of orders, or generate it if it doesn't exist.\n *\n * **CAUTION**: Developers of the SDK should prefer to use this method instead of generating the\n * merkle tree themselves. This method makes use of caching to avoid generating the\n * merkle tree needlessly.\n * @throws If the merkle tree cannot be generated.\n * @returns The merkle tree for the current set of conditional orders.\n */\n private getOrGenerateTree(): StandardMerkleTree<string[]> {\n if (!this.tree) {\n this.tree = StandardMerkleTree.of(\n Object.values(this.orders).map((order) => [...Object.values(order.leaf)]),\n CONDITIONAL_ORDER_LEAF_ABI\n )\n }\n\n return this.tree\n }\n\n // --- serialization for watchtowers / indexers ---\n\n /**\n * The primary method for watch towers to use when deserializing the proofs and parameters for the conditional orders.\n * @param s The serialized proofs with parameters for consumption by watchtowers / indexers.\n * @returns The `ProofWithParams` array.\n * @throws If the `ProofWithParams` array cannot be deserialized.\n */\n static decodeFromJSON(s: string): ProofWithParams[] {\n // no need to rehydrate `BigNumber` as this is fully ABI encoded\n return JSON.parse(s)\n }\n\n /**\n * The primary entry point for dapps integrating with `ComposableCoW` to generate the proofs and\n * parameters for the conditional orders.\n *\n * After populating the multiplexer with conditional orders, this method can be used to generate\n * the proofs and parameters for the conditional orders. The returned `ProofStruct` can then be\n * used with `setRoot` or `setRootWithContext` on a `ComposableCoW`-enabled Safe.\n *\n * @param filter {@link getProofs}\n * @parma locFn A function that takes the off-chain encoded input, and returns the `location`\n * for the `ProofStruct`, and the `data` for the `ProofStruct`.\n * @returns The ABI-encoded `ProofStruct` for `setRoot` and `setRootWithContext`.\n */\n async prepareProofStruct(\n location: ProofLocation = this.location,\n filter?: (v: string[]) => boolean,\n uploader?: (offChainEncoded: string) => Promise<string>\n ): Promise<ComposableCoW.ProofStruct> {\n const data = async (): Promise<string> => {\n switch (location) {\n case ProofLocation.PRIVATE:\n return '0x'\n case ProofLocation.EMITTED:\n return this.encodeToABI(filter)\n case ProofLocation.SWARM:\n case ProofLocation.WAKU:\n case ProofLocation.IPFS:\n if (!uploader) throw new Error('Must provide an uploader function')\n try {\n return await uploader(this.encodeToJSON(filter))\n } catch (e) {\n throw new Error(`Error uploading to decentralized storage ${location}: ${e}`)\n }\n default:\n throw new Error('Unsupported location')\n }\n }\n\n return await data()\n .then((d) => {\n try {\n // validate that `d` is a valid `bytes` ready to be abi-encoded\n utils.hexlify(utils.arrayify(d))\n\n // if we get here, we have a valid `data` field for the `ProofStruct`\n // This means that if there was an upload function, it was called and the upload was successful\n // note: we don't check if the location has changed because we don't care\n this.location = location\n\n return {\n location,\n data: d,\n }\n } catch (e) {\n throw new Error(`data returned by uploader is invalid`)\n }\n })\n .catch((e) => {\n throw new Error(`Error preparing proof struct: ${e}`)\n })\n }\n\n /**\n * Poll a conditional order to see if it is tradeable.\n * @param owner The owner of the conditional order.\n * @param p The proof and parameters.\n * @param chain Which chain to use for the ComposableCoW contract.\n * @param provider An RPC provider for the chain.\n * @param offChainInputFn A function, if provided, that will return the off-chain input for the conditional order.\n * @throws If the conditional order is not tradeable.\n * @returns The tradeable `GPv2Order.Data` struct and the `signature` for the conditional order.\n */\n static async poll(\n owner: string,\n p: ProofWithParams,\n chain: SupportedChainId,\n provider: providers.Provider,\n offChainInputFn?: (owner: string, params: ConditionalOrderParams) => Promise<string>\n ): Promise<[GPv2Order.DataStruct, string]> {\n const composableCow = getComposableCow(chain, provider)\n\n const offChainInput = offChainInputFn ? await offChainInputFn(owner, p.params) : '0x'\n return await composableCow.getTradeableOrderWithSignature(owner, p.params, offChainInput, p.proof)\n }\n\n /**\n * The primary entry point for dumping the proofs and parameters for the conditional orders.\n *\n * This is to be used by watchtowers / indexers to store the proofs and parameters for the\n * conditional orders off-chain. The encoding returned by this method may **NOT** contain all\n * proofs and parameters, depending on the `filter` provided, and therefore should not be used\n * to rehydrate the multiplexer from a user's perspective.\n * @param filter {@link getProofs}\n * @returns A JSON-encoded string of the proofs and parameters for the conditional orders.\n */\n dumpProofs(filter?: (v: string[]) => boolean): string {\n return this.encodeToJSON(filter)\n }\n\n dumpProofsAndParams(filter?: (v: string[]) => boolean): ProofWithParams[] {\n return this.getProofs(filter)\n }\n\n /**\n * Get the proofs with parameters for the conditional orders in the merkle tree.\n * @param filter A function that takes a conditional order and returns a boolean indicating\n * whether the order should be included in the proof.\n * @returns An array of proofs and their order's parameters for the conditional orders in the\n * merkle tree.\n */\n private getProofs(filter?: (v: string[]) => boolean): ProofWithParams[] {\n // Get a list of all entry indices in the tree, excluding any that don't match the filter\n return [...this.getOrGenerateTree().entries()]\n .map(([i, v]) => {\n if ((filter && filter(v)) || filter === undefined) {\n return { idx: i, value: v }\n } else {\n return undefined\n }\n })\n .reduce((acc: ProofWithParams[], x) => {\n if (x) {\n const p: ConditionalOrderParams = {\n handler: x.value[0],\n salt: x.value[1],\n staticInput: x.value[2],\n }\n acc.push({\n proof: this.getOrGenerateTree().getProof(x.idx),\n params: p,\n })\n }\n return acc\n }, [])\n }\n\n /**\n * ABI-encode the proofs and parameters for the conditional orders in the merkle tree.\n * @param filter {@link getProofs}\n * @returns ABI-encoded `data` for the `ProofStruct`.\n */\n private encodeToABI(filter?: (v: string[]) => boolean): string {\n return utils.defaultAbiCoder.encode(PAYLOAD_EMITTED_ABI, [this.getProofs(filter)])\n }\n\n /**\n * JSON-encode the proofs and parameters for the conditional orders in the merkle tree.\n * @param filter {@link getProofs}\n * @returns The JSON-encoded data for storage off-chain.\n */\n private encodeToJSON(filter?: (v: string[]) => boolean): string {\n return JSON.stringify(this.getProofs(filter))\n }\n\n /**\n * A helper to reset the merkle tree.\n */\n private reset(): void {\n this.tree = undefined\n }\n\n /**\n * Register a conditional order type with the multiplexer.\n *\n * **CAUTION**: This is required for using `Multiplexer.fromJSON` and `Multiplexer.toJSON`.\n * @param orderType The order type to register.\n * @param conditionalOrderClass The class to use for the given order type.\n */\n public static registerOrderType(\n orderType: string,\n conditionalOrderClass: new (...args: any[]) => ConditionalOrder<unknown, unknown>\n ) {\n Multiplexer.orderTypeRegistry[orderType] = conditionalOrderClass\n }\n\n /**\n * Reset the order type registry.\n */\n public static resetOrderTypeRegistry() {\n Multiplexer.orderTypeRegistry = {}\n }\n}\n","import { type ConditionalOrder } from './ConditionalOrder'\nimport { ConditionalOrderParams } from './types'\n\nexport type FromParams<D, S> = (params: ConditionalOrderParams) => ConditionalOrder<D, S>\nexport type ConditionalOrderRegistry = Record<string, FromParams<unknown, unknown>>\n\nexport class ConditionalOrderFactory {\n public knownOrderTypes\n\n constructor(registry: ConditionalOrderRegistry) {\n this.knownOrderTypes = registry\n }\n\n public fromParams(params: ConditionalOrderParams): ConditionalOrder<unknown, unknown> | undefined {\n const { handler } = params\n\n const factory = this.knownOrderTypes[handler]\n if (!factory) {\n return undefined\n }\n\n return factory(params)\n }\n}\n","import { BigNumber, constants, utils } from 'ethers'\n\nimport { ConditionalOrder } from '../ConditionalOrder'\nimport {\n ConditionalOrderArguments,\n ConditionalOrderParams,\n ContextFactory,\n OwnerContext,\n IsValidResult,\n PollParams,\n PollResultCode,\n PollResultErrors,\n} from '../types'\nimport { encodeParams, formatEpoch, getBlockInfo, isValidAbi } from '../utils'\nimport { GPv2Order } from '../generated/ComposableCoW'\n\n// The type of Conditional Order\nconst TWAP_ORDER_TYPE = 'twap'\n// The address of the TWAP handler contract\nexport const TWAP_ADDRESS = '0x6cF1e9cA41f7611dEf408122793c358a3d11E5a5'\n/**\n * The address of the `CurrentBlockTimestampFactory` contract\n *\n * **NOTE**: This is used in the event that TWAP's have a `t0` of `0`.\n */\nexport const CURRENT_BLOCK_TIMESTAMP_FACTORY_ADDRESS = '0x52eD56Da04309Aca4c3FECC595298d80C2f16BAc'\n\nexport const MAX_UINT32 = BigNumber.from(2).pow(32).sub(1) // 2^32 - 1\nexport const MAX_FREQUENCY = BigNumber.from(365 * 24 * 60 * 60) // 1 year\n\n// Define the ABI tuple for the TWAPData struct\nconst TWAP_STRUCT_ABI = [\n 'tuple(address sellToken, address buyToken, address receiver, uint256 partSellAmount, uint256 minPartLimit, uint256 t0, uint256 n, uint256 t, uint256 span, bytes32 appData)',\n]\n\n/**\n * Base parameters for a TWAP order. Shared by:\n * - TwapStruct (modelling the contract's struct used for `staticInput`).\n * - TwapData (modelling the friendly SDK interface).\n */\nexport type TwapDataBase = {\n /**\n * which token to sell\n */\n readonly sellToken: string\n\n /**\n * which token to buy\n */\n readonly buyToken: string\n\n /**\n * who to send the tokens to\n */\n readonly receiver: string\n\n /**\n * Meta-data associated with the order. Normally would be the keccak256 hash of the document generated in http://github.com/cowprotocol/app-data\n *\n * This hash should have been uploaded to the API https://api.cow.fi/docs/#/default/put_api_v1_app_data__app_data_hash_ and potentially to other data availability protocols like IPFS.\n *\n */\n readonly appData: string\n}\n\n/**\n * Parameters for a TWAP order, as expected by the contract's `staticInput`.\n */\nexport interface TwapStruct extends TwapDataBase {\n /**\n * amount of sellToken to sell in each part\n */\n readonly partSellAmount: BigNumber\n\n /**\n * minimum amount of buyToken that must be bought in each part\n */\n readonly minPartLimit: BigNumber\n\n /**\n * start time of the TWAP\n */\n readonly t0: BigNumber\n\n /**\n * number of parts\n */\n readonly n: BigNumber\n\n /**\n * duration of the TWAP interval\n */\n readonly t: BigNumber\n\n /**\n * whether the TWAP is valid for the entire interval or not\n */\n readonly span: BigNumber\n}\n\n/**\n * Parameters for a TWAP order, made a little more user-friendly for SDK users.\n *\n * @see {@link TwapStruct} for the native struct.\n */\nexport interface TwapData extends TwapDataBase {\n /**\n * total amount of sellToken to sell across the entire TWAP\n */\n readonly sellAmount: BigNumber\n\n /**\n * minimum amount of buyToken that must be bought across the entire TWAP\n */\n readonly buyAmount: BigNumber\n\n /**\n * start time of the TWAP\n */\n readonly startTime?: StartTime\n\n /**\n * number of parts\n */\n readonly numberOfParts: BigNumber\n\n /**\n * duration of the TWAP interval\n */\n readonly timeBetweenParts: BigNumber\n\n /**\n * whether the TWAP is valid for the entire interval or not\n */\n readonly durationOfPart?: DurationOfPart\n}\n\nexport type DurationOfPart =\n | { durationType: DurationType.AUTO }\n | { durationType: DurationType.LIMIT_DURATION; duration: BigNumber }\n\nexport enum DurationType {\n AUTO = 'AUTO',\n LIMIT_DURATION = 'LIMIT_DURATION',\n}\n\nexport type StartTime =\n | { startType: StartTimeValue.AT_MINING_TIME }\n | { startType: StartTimeValue.AT_EPOCH; epoch: BigNumber }\n\nexport enum StartTimeValue {\n AT_MINING_TIME = 'AT_MINING_TIME',\n AT_EPOCH = 'AT_EPOCH',\n}\n\nconst DEFAULT_START_TIME: StartTime = { startType: StartTimeValue.AT_MINING_TIME }\nconst DEFAULT_DURATION_OF_PART: DurationOfPart = { durationType: DurationType.AUTO }\n\n/**\n * `ComposableCoW` implementation of a TWAP order.\n * @author mfw78 <mfw78@rndlabs.xyz>\n */\nexport class Twap extends ConditionalOrder<TwapData, TwapStruct> {\n isSingleOrder = true\n\n /**\n * @see {@link ConditionalOrder.constructor}\n * @throws If the TWAP order is invalid.\n * @throws If the TWAP order is not ABI-encodable.\n * @throws If the handler is not the TWAP address.\n */\n constructor(params: ConditionalOrderArguments<TwapData>) {\n const { handler, salt, data: staticInput, hasOffChainInput } = params\n\n // First, verify that the handler is the TWAP address\n if (handler !== TWAP_ADDRESS) throw new Error(`InvalidHandler: Expected: ${TWAP_ADDRESS}, provided: ${handler}`)\n\n // Third, construct the base class using transformed parameters\n super({ handler: TWAP_ADDRESS, salt, data: staticInput, hasOffChainInput })\n }\n\n /**\n * Create a TWAP order with sound defaults.\n * @param data The TWAP order parameters in a more user-friendly format.\n * @returns An instance of the TWAP order.\n */\n static fromData(data: TwapData, salt?: string): Twap {\n return new Twap({ handler: TWAP_ADDRESS, data, salt })\n }\n\n /**\n * Create a TWAP order with sound defaults.\n * @param data The TWAP order parameters in a more user-friendly format.\n * @returns An instance of the TWAP order.\n */\n static fromParams(params: ConditionalOrderParams): Twap {\n return Twap.deserialize(encodeParams(params))\n }\n\n /**\n * Enforces that TWAPs will commence at the beginning of a block by use of the\n * `CurrentBlockTimestampFactory` contract to provide the current block timestamp\n * as the start time of the TWAP.\n */\n get context(): ContextFactory | undefined {\n if (this.staticInput.t0.gt(0)) {\n return super.context\n } else {\n return {\n address: CURRENT_BLOCK_TIMESTAMP_FACTORY_ADDRESS,\n factoryArgs: undefined,\n }\n }\n }\n\n /**\n * @inheritdoc {@link ConditionalOrder.orderType}\n */\n get orderType(): string {\n return TWAP_ORDER_TYPE\n }\n\n /**\n * Validate the TWAP order.\n * @param data The TWAP order to validate.\n * @returns Whether the TWAP order is valid.\n * @throws If the TWAP order is invalid.\n * @see {@link TwapStruct} for the native struct.\n */\n isValid(): IsValidResult {\n const error = (() => {\n const {\n sellToken,\n sellAmount,\n buyToken,\n buyAmount,\n startTime = DEFAULT_START_TIME,\n numberOfParts,\n timeBetweenParts,\n durationOfPart = DEFAULT_DURATION_OF_PART,\n } = this.data\n\n // Verify that the order params are logically valid\n if (!(sellToken != buyToken)) return 'InvalidSameToken'\n if (!(sellToken != constants.AddressZero && buyToken != constants.AddressZero)) return 'InvalidToken'\n if (!sellAmount.gt(constants.Zero)) return 'InvalidSellAmount'\n if (!buyAmount.gt(constants.Zero)) return 'InvalidMinBuyAmount'\n if (startTime.startType === StartTimeValue.AT_EPOCH) {\n const t0 = startTime.epoch\n if (!(t0.gte(constants.Zero) && t0.lt(MAX_UINT32))) return 'InvalidStartTime'\n }\n if (!(numberOfParts.gt(constants.One) && numberOfParts.lte(MAX_UINT32))) return 'InvalidNumParts'\n if (!(timeBetweenParts.gt(constants.Zero) && timeBetweenParts.lte(MAX_FREQUENCY))) return 'InvalidFrequency'\n if (durationOfPart.durationType === DurationType.LIMIT_DURATION) {\n if (!durationOfPart.duration.lte(timeBetweenParts)) return 'InvalidSpan'\n }\n\n // Verify that the staticInput derived from the data is ABI-encodable\n if (!isValidAbi(TWAP_STRUCT_ABI, [this.staticInput])) return 'InvalidData'\n\n // No errors\n return undefined\n })()\n\n return error ? { isValid: false, reason: error } : { isValid: true }\n }\n\n protected async startTimestamp(params: OwnerContext): Promise<number> {\n const { startTime } = this.data\n\n if (startTime?.startType === StartTimeValue.AT_EPOCH) {\n return startTime.epoch.toNumber()\n }\n\n const cabinet = await this.cabinet(params)\n const rawCabinetEpoch = utils.defaultAbiCoder.decode(['uint256'], cabinet)[0] as BigNumber\n\n // Guard against out-of-range cabinet epoch\n if (rawCabinetEpoch.gt(MAX_UINT32)) {\n throw new Error(`Cabinet epoch out of range: ${rawCabinetEpoch.toString()}`)\n }\n\n // Convert the cabinet epoch (bignumber) to a number.\n const cabinetEpoch = rawCabinetEpoch.toNumber()\n\n if (cabinetEpoch === 0) {\n throw new Error('Cabinet is not set. Required for TWAP orders that start at mining time.')\n }\n\n return cabinetEpoch\n }\n\n /**\n * Given the start timestamp of the TWAP, calculate the end timestamp.\n * @dev As usually the `endTimestamp` is used when determining a TWAP's validity, we don't\n * do any lookup to the blockchain to determine the start timestamp, as this has likely\n * already been done during the verification flow.\n * @dev Beware to handle the case of `span != 0` ie. `durationOfPart.durationType !== DurationType.AUTO`.\n * @param startTimestamp The start timestamp of the TWAP.\n * @returns The timestamp at which the TWAP will end.\n */\n protected endTimestamp(startTimestamp: number): number {\n const { numberOfParts, timeBetweenParts, durationOfPart } = this.data\n\n if (durationOfPart && durationOfPart.durationType === DurationType.LIMIT_DURATION) {\n return startTimestamp + numberOfParts.sub(1).mul(timeBetweenParts).add(durationOfPart.duration).toNumber()\n }\n\n return startTimestamp + numberOfParts.mul(timeBetweenParts).toNumber()\n }\n\n /**\n * Checks if the owner authorized the conditional order.\n *\n * @param owner The owner of the conditional order.\n * @param chain Which chain to use for the ComposableCoW contract.\n * @param provider An RPC provider for the chain.\n * @returns true if the owner authorized the order, false otherwise.\n */\n protected async pollValidate(params: PollParams): Promise<PollResultErrors | undefined> {\n const { blockInfo = await getBlockInfo(params.provider) } = params\n const { blockTimestamp } = blockInfo\n\n try {\n const startTimestamp = await this.startTimestamp(params)\n\n if (startTimestamp > blockTimestamp) {\n // The start time hasn't started\n return {\n result: PollResultCode.TRY_AT_EPOCH,\n epoch: startTimestamp,\n reason: `TWAP hasn't started yet. Starts at ${startTimestamp} (${formatEpoch(startTimestamp)})`,\n }\n }\n\n const expirationTimestamp = this.endTimestamp(startTimestamp)\n if (blockTimestamp >= expirationTimestamp) {\n // The order has expired\n return {\n result: PollResultCode.DONT_TRY_AGAIN,\n reason: `TWAP has expired. Expired at ${expirationTimestamp} (${formatEpoch(expirationTimestamp)})`,\n }\n }\n\n return undefined\n } catch (err: any) {\n if (err?.message?.includes('Cabinet is not set')) {\n // in this case we have a firm reason to not monitor this order as the cabinet is not set\n return {\n result: PollResultCode.DONT_TRY_AGAIN,\n reason: `${err?.message}. User likely removed the order.`,\n }\n } else if (err?.message?.includes('Cabinet epoch out of range')) {\n // in this case we have a firm reason to not monitor this order as the cabinet is not set correctly\n return {\n result: PollResultCode.DONT_TRY_AGAIN,\n reason: `${err?.message}`,\n }\n }\n\n return {\n result: PollResultCode.UNEXPECTED_ERROR,\n reason: `Unexpected error: ${err.message}`,\n error: err,\n }\n }\n }\n\n /**\n * Handles the error when the order is already present in the orderbook.\n *\n * Given the current part is in the book, it will signal to Watch Tower what to do:\n * - Wait until the next part starts\n * - Don't try again if current part is the last one\n *\n * NOTE: The error messages will refer to the parts 1-indexed, so first part is 1, second part is 2, etc.\n */\n protected async handlePollFailedAlreadyPresent(\n _orderUid: string,\n _order: GPv2Order.DataStruct,\n params: PollParams\n ): Promise<PollResultErrors | undefined> {\n const { blockInfo = await getBlockInfo(params.provider) } = params\n const { blockTimestamp } = blockInfo\n\n const timeBetweenParts = this.data.timeBetweenParts.toNumber()\n const { numberOfParts } = this.data\n const startTimestamp = await this.startTimestamp(params)\n\n if (blockTimestamp < startTimestamp) {\n return {\n result: PollResultCode.UNEXPECTED_ERROR,\n reason: `TWAP part hash't started. First TWAP part start at ${startTimestamp} (${formatEpoch(startTimestamp)})`,\n error: undefined,\n }\n }\n const expireTime = numberOfParts.mul(timeBetweenParts).add(startTimestamp).toNumber()\n if (blockTimestamp >= expireTime) {\n return {\n result: PollResultCode.UNEXPECTED_ERROR,\n reason: `TWAP is expired. Expired at ${expireTime} (${formatEpoch(expireTime)})`,\n error: undefined,\n }\n }\n\n // Get current part number\n const currentPartNumber = Math.floor((blockTimestamp - startTimestamp) / timeBetweenParts)\n\n // If current part is the last one\n if (currentPartNumber === numberOfParts.toNumber() - 1) {\n return {\n result: PollResultCode.DONT_TRY_AGAIN,\n reason: `Current active TWAP part (${\n currentPartNumber + 1\n }/${numberOfParts}) is already in the Order Book. This was the last TWAP part, no more orders need to be placed`,\n }\n }\n\n // Next part start time\n const nextPartStartTime = startTimestamp + (currentPartNumber + 1) * timeBetweenParts\n\n /**\n * Given we know, that TWAP part that is due in the current block is already in the Orderbook,\n * Then, we can safely instruct that we should wait until the next TWAP part starts\n */\n return {\n result: PollResultCode.TRY_AT_EPOCH,\n epoch: nextPartStartTime,\n reason: `Current active TWAP part (${\n currentPartNumber + 1\n }/${numberOfParts}) is already in the Order Book. TWAP part ${\n currentPartNumber + 2\n } doesn't start until ${nextPartStartTime} (${formatEpoch(nextPartStartTime)})`,\n }\n }\n\n /**\n * Serialize the TWAP order into it's ABI-encoded form.\n * @returns {string} The ABI-encoded TWAP order.\n */\n serialize(): string {\n return encodeParams(this.leaf)\n }\n\n /**\n * Get the encoded static input for the TWAP order.\n * @returns {string} The ABI-encoded TWAP order.\n */\n encodeStaticInput(): string {\n return super.encodeStaticInputHelper(TWAP_STRUCT_ABI, this.staticInput)\n }\n\n /**\n * Deserialize a TWAP order from it's ABI-encoded form.\n * @param {string} twapSerialized ABI-encoded TWAP order to deserialize.\n * @returns A deserialized TWAP order.\n */\n static deserialize(twapSerialized: string): Twap {\n return super.deserializeHelper(\n twapSerialized,\n TWAP_ADDRESS,\n TWAP_STRUCT_ABI,\n (struct: TwapStruct, salt: string) =>\n new Twap({\n handler: TWAP_ADDRESS,\n salt,\n data: transformStructToData(struct),\n })\n )\n }\n\n /**\n * Create a human-readable string representation of the TWAP order.\n * @returns {string} A human-readable string representation of the TWAP order.\n */\n toString(): string {\n const {\n sellAmount,\n sellToken,\n buyAmount,\n buyToken,\n numberOfParts,\n startTime = DEFAULT_START_TIME,\n timeBetweenParts,\n durationOfPart = DEFAULT_DURATION_OF_PART,\n receiver,\n appData,\n } = this.data\n\n const startTimeFormatted =\n startTime.startType === StartTimeValue.AT_MINING_TIME ? 'AT_MINING_TIME' : startTime.epoch.toNumber()\n const durationOfPartFormatted =\n durationOfPart.durationType === DurationType.AUTO ? 'AUTO' : durationOfPart.duration.toNumber()\n\n const details = {\n sellAmount: sellAmount.toString(),\n sellToken,\n buyAmount: buyAmount.toString(),\n buyToken,\n numberOfParts: numberOfParts.toString(),\n startTime: startTimeFormatted,\n timeBetweenParts: timeBetweenParts.toNumber(),\n durationOfPart: durationOfPartFormatted,\n receiver,\n appData,\n }\n\n return `${this.orderType} (${this.id}): ${JSON.stringify(details)}`\n }\n\n /**\n * Transform parameters into a native struct.\n *\n * @param {TwapData} data As passed by the consumer of the API.\n * @returns {TwapStruct} A formatted struct as expected by the smart contract.\n */\n transformDataToStruct(data: TwapData): TwapStruct {\n return transformDataToStruct(data)\n }\n\n /**\n * Transform parameters into a TWAP order struct.\n *\n * @param {TwapData} params As passed by the consumer of the API.\n * @returns {TwapStruct} A formatted struct as expected by the smart contract.\n */\n transformStructToData(struct: TwapStruct): TwapData {\n return transformStructToData(struct)\n }\n}\n\n/**\n * Transform parameters into a native struct.\n *\n * @param {TwapData} data As passed by the consumer of the API.\n * @returns {TwapStruct} A formatted struct as expected by the smart contract.\n */\nexport function transformDataToStruct(data: TwapData): TwapStruct {\n const {\n sellAmount,\n buyAmount,\n numberOfParts,\n startTime: startTime = DEFAULT_START_TIME,\n timeBetweenParts,\n durationOfPart = DEFAULT_DURATION_OF_PART,\n ...rest\n } = data\n\n const { partSellAmount, minPartLimit } =\n numberOfParts && !numberOfParts.isZero()\n ? {\n partSellAmount: sellAmount.div(numberOfParts),\n minPartLimit: buyAmount.div(numberOfParts),\n }\n : {\n partSellAmount: constants.Zero,\n minPartLimit: constants.Zero,\n }\n\n const span = durationOfPart.durationType === DurationType.AUTO ? constants.Zero : durationOfPart.duration\n const t0 = startTime.startType === StartTimeValue.AT_MINING_TIME ? constants.Zero : startTime.epoch\n\n return {\n partSellAmount,\n minPartLimit,\n t0,\n n: numberOfParts,\n t: timeBetweenParts,\n span,\n ...rest,\n }\n}\n\n/**\n * Transform parameters into a TWAP order struct.\n *\n * @param {TwapData} params As passed by the consumer of the API.\n * @returns {TwapStruct} A formatted struct as expected by the smart contract.\n */\nexport function transformStructToData(struct: TwapStruct): TwapData {\n const { n: numberOfParts, partSellAmount, minPartLimit, t: timeBetweenParts, t0: startEpoch, span, ...rest } = struct\n\n const durationOfPart: DurationOfPart = span.isZero()\n ? { durationType: DurationType.AUTO }\n : { durationType: DurationType.LIMIT_DURATION, duration: span }\n\n const startTime: StartTime = span.isZero()\n ? { startType: StartTimeValue.AT_MINING_TIME }\n : { startType: StartTimeValue.AT_EPOCH, epoch: startEpoch }\n\n return {\n sellAmount: partSellAmount.mul(numberOfParts),\n buyAmount: minPartLimit.mul(numberOfParts),\n startTime,\n numberOfParts,\n timeBetweenParts,\n durationOfPart,\n ...rest,\n }\n}\n","import { ConditionalOrderRegistry } from '../ConditionalOrderFactory'\nimport { TWAP_ADDRESS, Twap } from './Twap'\nexport * from './Twap'\n\nexport const DEFAULT_CONDITIONAL_ORDER_REGISTRY: ConditionalOrderRegistry = {\n // Registry of all known order types\n [TWAP_ADDRESS]: (params) => Twap.fromParams(params),\n}\n"],"names":["SupportedChainId","ENVS_LIST","DEFAULT_COW_API_CONTEXT","env","chainId","MAINNET","CowError","Error","constructor","message","error_code","super","this","logPrefix","DEFAULT_IPFS_READ_URI","DEFAULT_IPFS_WRITE_URI","BUY_ETH_ADDRESS","EXTENSIBLE_FALLBACK_HANDLER","COMPOSABLE_COW","ALL_SUPPORTED_CHAIN_IDS","Object","values","filter","mapSupportedNetworks","value","reduce","acc","_extends","mapAddressToSupportedNetworks","address","COW_PROTOCOL_SETTLEMENT_CONTRACT_ADDRESS","COW_PROTOCOL_VAULT_RELAYER_ADDRESS","EXTENSIBLE_FALLBACK_HANDLER_CONTRACT_ADDRESS","COMPOSABLE_COW_CONTRACT_ADDRESS","OrderBookApiError","response","body","statusText","STATUS_CODES_TO_RETRY","DEFAULT_BACKOFF_OPTIONS","numOfAttempts","maxDelay","Infinity","jitter","retry","error","includes","status","DEFAULT_LIMITER_OPTIONS","tokensPerInterval","interval","getResponseBody","async","contentType","headers","get","toLowerCase","startsWith","json","text","console","undefined","request","baseUrl","path","query","method","rateLimiter","backoffOpts","url","init","JSON","stringify","Accept","backOff","removeTokens","fetch","responseBody","Promise","reject","transformOrder","order","ethflowData","userValidTo","validTo","owner","onchainUser","sellToken","transformEthFlowOrder","dto","executedFeeAmount","executedSurplusFee","_executedFeeAmount","BigInt","_executedSurplusFee","totalFee","String","addTotalFeeToOrder","ORDER_BOOK_PROD_CONFIG","GNOSIS_CHAIN","ARBITRUM_ONE","SEPOLIA","ORDER_BOOK_STAGING_CONFIG","cleanObjectFromUndefinedValues","obj","keys","key","val","OrderBookApi","context","RateLimiter","limiterOpts","getVersion","contextOverride","getTrades","orderUid","URLSearchParams","getOrders","offset","limit","toString","then","orders","map","getTxOrders","txHash","getOrder","getOrderCompetitionStatus","getOrderMultiEnv","getContextWithOverride","otherEnvs","i","attemptsCount","fallback","nextEnv","catch","getQuote","requestBody","sendSignedOrderCancellations","sendOrder","getNativePrice","tokenAddress","getTotalSurplus","getAppData","appDataHash","uploadAppData","fullAppData","getSolverCompetition","auctionIdorTx","getOrderLink","getApiBaseUrls","baseUrls","params","_backoffOpts","BuyTokenDestination","CompetitionOrderStatus","EcdsaSigningScheme","OnchainOrderData","OrderCancellationError","OrderClass","OrderKind","OrderPostError","OrderQuoteSideKindBuy","OrderQuoteSideKindSell","OrderStatus","PriceEstimationError","PriceQuality","SellTokenSource","SigningScheme","type","placementError","errorType","ONE_HUNDRED_BPS","getQuoteAmountsAndCosts","_params$partnerFeeBps","orderParams","sellDecimals","buyDecimals","slippagePercentBps","partnerFeeBps","isSell","kind","SELL","networkCostAmount","getBigNumber","feeAmount","sellAmountBeforeNetworkCosts","sellAmount","buyAmountAfterNetworkCosts","buyAmount","quotePrice","num","sellAmountAfterNetworkCosts","big","buyAmountBeforeNetworkCosts","partnerFeeAmount","afterPartnerFees","getSlippageAmount","amount","afterSlippage","costs","networkFee","amountInSellCurrency","amountInBuyCurrency","partnerFee","bps","beforeNetworkCosts","afterNetworkCosts","decimals","bigAsNumber","bigAsNumberString","toFixed","Number","_t","_t2","_t3","_","t","TOTALS_QUERY","gql","LAST_DAYS_VOLUME_QUERY","LAST_HOURS_VOLUME_QUERY","SUBGRAPH_BASE_URL","SUBGRAPH_PROD_CONFIG","SUBGRAPH_STAGING_CONFIG","SubgraphApi","API_NAME","runQuery","totals","days","hours","variables","getEnvConfigs","getSignUtils","import","OrderSigningUtils","static","signer","signOrder","signOrderCancellation","orderUids","signOrderCancellations","getDomain","_TypedDataEncoder","hashDomain","Order","name","ProofLocation","PollResultCode","_abi","inputs","internalType","stateMutability","anonymous","indexed","components","outputs","ComposableCoW__factory","utils","Interface","signerOrProvider","Contract","abi","ExtensibleFallbackHandler__factory","ERC20_BALANCE_VALUES","EXTERNAL_BALANCE_VALUES","INTERNAL_BALANCE_VALUES","SELL_KIND_VALUES","BUY_KIND_VALUES","CONDITIONAL_ORDER_PARAMS_ABI","DEFAULT_TOKEN_FORMATTER","isExtensibleFallbackHandler","handler","isComposableCow","getDomainVerifier","safe","domain","provider","contract","connect","callStatic","domainVerifiers","createSetDomainVerifierTx","verifier","createInterface","encodeFunctionData","encodeParams","defaultAbiCoder","encode","decodeParams","encoded","salt","staticInput","decode","isValidAbi","types","e","getBlockInfo","block","getBlock","blockNumber","number","blockTimestamp","timestamp","formatEpoch","epoch","Date","toISOString","balanceToString","balance","OrderBalance","ERC20","EXTERNAL","INTERNAL","kindToString","BUY","fromStructToOrder","buyToken","buyTokenBalance","sellTokenBalance","receiver","partiallyFillable","appData","composableCowInterfaceCache","composableCowContractCache","getComposableCowInterface","getComposableCow","chain","ConditionalOrder","data","hasOffChainInput","keccak256","randomBytes","ethers","isAddress","isHexString","hexDataLength","transformDataToStruct","assertIsValid","isValidResult","isValid","reason","createCalldata","composableCow","paramsStruct","encodeStaticInput","contextArgsAbi","factoryArgs","argsType","args","removeCalldata","id","serialize","ctx","isSingleOrder","constants","HashZero","leaf","offChainInput","encodeStaticInputHelper","orderDataTypes","orderBookApi","result","DONT_TRY_AGAIN","pollResult","pollValidate","isAuthorized","signature","getTradeableOrderWithSignature","computeOrderUid","_computeOrderUid","handlePollFailedAlreadyPresent","TRY_NEXT_BLOCK","SUCCESS","UNEXPECTED_ERROR","singleOrders","cabinet","s","callback","recoveredHandler","d","_excluded","CONDITIONAL_ORDER_LEAF_ABI","PAYLOAD_EMITTED_ABI","Multiplexer","root","location","PRIVATE","tree","length","orderKey","hasOwnProperty","orderTypeRegistry","orderType","getOrGenerateTree","parse","reviver","k","v","_v$orderKey","orderData","_objectWithoutPropertiesLoose","OrderConstructor","BigNumber","from","m","toJSON","conditionalOrder","add","reset","remove","update","updater","getById","getByIndex","orderIds","StandardMerkleTree","of","uploader","_this","EMITTED","encodeToABI","SWARM","WAKU","IPFS","encodeToJSON","hexlify","arrayify","p","offChainInputFn","proof","dumpProofs","dumpProofsAndParams","getProofs","entries","idx","x","push","getProof","conditionalOrderClass","ConditionalOrderFactory","registry","knownOrderTypes","fromParams","factory","TWAP_ADDRESS","CURRENT_BLOCK_TIMESTAMP_FACTORY_ADDRESS","MAX_UINT32","pow","sub","MAX_FREQUENCY","TWAP_STRUCT_ABI","DurationType","StartTimeValue","DEFAULT_START_TIME","startType","AT_MINING_TIME","DEFAULT_DURATION_OF_PART","durationType","AUTO","Twap","deserialize","t0","gt","startTime","numberOfParts","timeBetweenParts","durationOfPart","AddressZero","Zero","AT_EPOCH","gte","lt","One","lte","LIMIT_DURATION","duration","toNumber","rawCabinetEpoch","cabinetEpoch","endTimestamp","startTimestamp","mul","blockInfo","TRY_AT_EPOCH","expirationTimestamp","err","_err$message","_err$message2","_orderUid","_order","expireTime","currentPartNumber","Math","floor","nextPartStartTime","twapSerialized","deserializeHelper","struct","transformStructToData","startTimeFormatted","durationOfPartFormatted","details","rest","partSellAmount","minPartLimit","is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1C,GAC/BwC,aAAc5T,EAAU8T,IAAI1C,IAE9B,CACEuC,eAAgBrJ,EAAUkH,KAC1BoC,aAActJ,EAAUkH,MAMhC,OAAA1b,EAAA,CACE6d,iBACAC,eACA3C,GALSE,EAAUT,YAAcF,GAAeG,eAAiBrG,EAAUkH,KAAOL,EAAU/J,MAM5F2M,EAAG3C,EACHxP,EAAGyP,EACH2C,KATW1C,EAAeT,eAAiBN,GAAaO,KAAOxG,EAAUkH,KAAOF,EAAeS,UAU5F2B,EAEP,CAQM,SAAUJ,GAAsBD,GACpC,MAAQU,EAAG3C,EAAauC,eAAEA,EAAcC,aAAEA,EAAchS,EAAGyP,EAAkBJ,GAAIgD,EAAUD,KAAEA,GAAkBX,EAATK,EAAItG,EAAKiG,EAAMa,IAE/G5C,EAAiC0C,EAAKH,SACxC,CAAEhD,aAAcN,GAAaO,MAC7B,CAAED,aAAcN,GAAauB,eAAgBC,SAAUiC,GAErD7C,EAAuB6C,EAAKH,SAC9B,CAAEnD,UAAWF,GAAeG,gBAC5B,CAAED,UAAWF,GAAeiB,SAAUrK,MAAO6M,GAEjD,OAAAne,EACEgK,CAAAA,WAAY6T,EAAetB,IAAIjB,GAC/BpR,UAAW4T,EAAavB,IAAIjB,GAC5BD,YACAC,gBACAC,mBACAC,kBACGoC,EAEP,CCnlBa,MAAAS,GAA+D,CAE1EnE,CAACA,IAAgBrS,GAAWoT,GAAKjB,WAAWnS"}
1
+ {"version":3,"file":"index-d84e3bdc.js","sources":["../src/common/chains.ts","../src/common/configs.ts","../src/common/cow-error.ts","../src/common/ipfs.ts","../src/common/consts.ts","../src/order-book/request.ts","../src/order-book/transformOrder.ts","../src/order-book/api.ts","../src/order-book/generated/models/BuyTokenDestination.ts","../src/order-book/generated/models/CompetitionOrderStatus.ts","../src/order-book/generated/models/EcdsaSigningScheme.ts","../src/order-book/generated/models/OnchainOrderData.ts","../src/order-book/generated/models/OrderCancellationError.ts","../src/order-book/generated/models/OrderClass.ts","../src/order-book/generated/models/OrderKind.ts","../src/order-book/generated/models/OrderPostError.ts","../src/order-book/generated/models/OrderQuoteSideKindBuy.ts","../src/order-book/generated/models/OrderQuoteSideKindSell.ts","../src/order-book/generated/models/OrderStatus.ts","../src/order-book/generated/models/PriceEstimationError.ts","../src/order-book/generated/models/PriceQuality.ts","../src/order-book/generated/models/SellTokenSource.ts","../src/order-book/generated/models/SigningScheme.ts","../src/order-book/quoteAmountsAndCostsUtils.ts","../src/subgraph/queries.ts","../src/subgraph/api.ts","../src/order-signing/orderSigningUtils.ts","../src/composable/types.ts","../src/composable/generated/factories/ComposableCoW__factory.ts","../src/composable/generated/factories/ExtensibleFallbackHandler__factory.ts","../src/composable/utils.ts","../src/composable/contracts.ts","../src/composable/ConditionalOrder.ts","../src/utils.ts","../src/composable/Multiplexer.ts","../src/composable/ConditionalOrderFactory.ts","../src/composable/orderTypes/Twap.ts","../src/composable/orderTypes/index.ts"],"sourcesContent":["/**\n * Supported chains and their `chainId` for the SDK.\n * @enum\n */\nexport enum SupportedChainId {\n MAINNET = 1,\n GNOSIS_CHAIN = 100,\n ARBITRUM_ONE = 42161,\n SEPOLIA = 11155111,\n}\n","import { SupportedChainId } from './chains'\nimport { BackoffOptions } from 'exponential-backoff'\nimport { RateLimiterOpts } from 'limiter/dist/esm'\n\n/**\n * IPFS configuration.\n *\n * For production use, consider using {@link Pinata: https://www.pinata.cloud/}\n * @property {string} [uri] The URI of the IPFS node to use.\n * @property {string} [writeUri] The URI of the IPFS node to use for writing.\n * @property {string} [readUri] The URI of the IPFS node to use for reading.\n * @property {string} [pinataApiKey] The API key to use for Pinata.\n * @property {string} [pinataApiSecret] The API secret to use for Pinata.\n */\nexport interface IpfsConfig {\n uri?: string\n writeUri?: string\n readUri?: string\n pinataApiKey?: string\n pinataApiSecret?: string\n}\n\n/**\n * @property {RateLimiterOpts} [limiterOpts] The options to use for the rate limiter.\n * @property {BackoffOptions} [backoffOpts] The options to use for the backoff.\n */\nexport interface RequestOptions {\n limiterOpts?: RateLimiterOpts\n backoffOpts?: BackoffOptions\n}\n\n/**\n * The environment to use for the Cow API.\n */\nexport type CowEnv = 'prod' | 'staging'\n\n/**\n * Override some properties of the {@link ApiContext}.\n */\nexport type PartialApiContext = Partial<ApiContext>\n\n/**\n * @property {string} [1] The base URL for the mainnet API.\n * @property {string} [100] The base URL for the Gnosis Chain API.\n * @property {string} [11155111] The base URL for the Sepolia testnet API.\n */\nexport type ApiBaseUrls = Record<SupportedChainId, string>\n\n/**\n * Define the context to use for the CoW Protocol API.\n *\n * CoW Protocol is a set of smart contracts and off-chain services, deployed on **multiple chains**.\n * {@link SupportedChainId Supported chains} are:\n * - Mainnet\n * - Gnosis Chain\n * - Sepolia\n *\n * Each chain has it's own API, and each API has it's own base URL.\n *\n * Options may be selectively overridden by passing a {@link PartialApiContext} to the constructor.\n * @see {@link https://api.cow.fi/docs/#/}\n * @property {SupportedChainId} chainId The `chainId`` corresponding to this CoW Protocol API instance.\n * @property {CowEnv} env The environment that this context corresponds to.\n * @property {ApiBaseUrls} [baseUrls] URls that may be used to connect to this context.\n */\nexport interface ApiContext {\n chainId: SupportedChainId\n env: CowEnv\n baseUrls?: ApiBaseUrls\n limiterOpts?: RateLimiterOpts\n backoffOpts?: BackoffOptions\n}\n\n/**\n * The list of available environments.\n */\nexport const ENVS_LIST: CowEnv[] = ['prod', 'staging']\n\n/**\n * The default CoW Protocol API context.\n */\nexport const DEFAULT_COW_API_CONTEXT: ApiContext = {\n env: 'prod',\n chainId: SupportedChainId.MAINNET,\n}\n","export class CowError extends Error {\n error_code?: string\n\n constructor(message: string, error_code?: string) {\n super(message)\n this.error_code = error_code\n }\n}\n\nexport const logPrefix = 'cow-sdk:'\n","export const DEFAULT_IPFS_READ_URI = 'https://gnosis.mypinata.cloud/ipfs'\nexport const DEFAULT_IPFS_WRITE_URI = 'https://api.pinata.cloud'\n","import { SupportedChainId } from './chains'\n\nexport const BUY_ETH_ADDRESS = '0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE'\nexport const EXTENSIBLE_FALLBACK_HANDLER = '0x2f55e8b20D0B9FEFA187AA7d00B6Cbe563605bF5'\nexport const COMPOSABLE_COW = '0xfdaFc9d1902f4e0b84f65F49f244b32b31013b74'\n\nconst VAULT_RELAYER = '0xC92E8bdf79f0507f65a392b0ab4667716BFE0110'\nconst SETTLEMENT_CONTRACT = '0x9008D19f58AAbD9eD0D60971565AA8510560ab41'\n\n/**\n * The list of supported chains.\n */\nexport const ALL_SUPPORTED_CHAIN_IDS: SupportedChainId[] = Object.values(SupportedChainId).filter(\n (chainId) => typeof chainId === 'number'\n) as SupportedChainId[]\n\nexport function mapSupportedNetworks<T>(value: (chainId: SupportedChainId) => T): Record<SupportedChainId, T>\nexport function mapSupportedNetworks<T>(value: T): Record<SupportedChainId, T>\nexport function mapSupportedNetworks<T>(value: T | ((chainId: SupportedChainId) => T)): Record<SupportedChainId, T> {\n return ALL_SUPPORTED_CHAIN_IDS.reduce<Record<number, T>>(\n (acc, chainId) => ({\n ...acc,\n [chainId]: typeof value === 'function' ? (value as (chainId: SupportedChainId) => T)(chainId) : value,\n }),\n {}\n )\n}\n\nexport function mapAddressToSupportedNetworks(address: string): Record<SupportedChainId, string> {\n return mapSupportedNetworks(address)\n}\n\n/**\n * An object containing the addresses of the CoW Protocol settlement contracts for each supported chain.\n */\nexport const COW_PROTOCOL_SETTLEMENT_CONTRACT_ADDRESS = mapAddressToSupportedNetworks(SETTLEMENT_CONTRACT)\n\n/**\n * An object containing the addresses of the CoW Protocol Vault realyer contracts for each supported chain.\n */\nexport const COW_PROTOCOL_VAULT_RELAYER_ADDRESS = mapAddressToSupportedNetworks(VAULT_RELAYER)\n\n/**\n * An object containing the addresses of the `ExtensibleFallbackHandler` contracts for each supported chain.\n */\nexport const EXTENSIBLE_FALLBACK_HANDLER_CONTRACT_ADDRESS = mapAddressToSupportedNetworks(EXTENSIBLE_FALLBACK_HANDLER)\n\n/**\n * An object containing the addresses of the `ComposableCow` contracts for each supported chain.\n */\nexport const COMPOSABLE_COW_CONTRACT_ADDRESS = mapAddressToSupportedNetworks(COMPOSABLE_COW)\n","import { backOff, BackoffOptions } from 'exponential-backoff'\nimport { RateLimiter, RateLimiterOpts } from 'limiter'\n\n/**\n * Error thrown when the CoW Protocol OrderBook API returns an error.\n */\nexport class OrderBookApiError<T = unknown> extends Error {\n /**\n * Error thrown when the CoW Protocol OrderBook API returns an error.\n * @param response The response from the CoW Protocol OrderBook API.\n * @param body The body of the response.\n * @constructor\n */\n constructor(public readonly response: Response, public readonly body: T) {\n super(typeof body === 'string' ? body : response.statusText)\n }\n}\n\nconst REQUEST_TIMEOUT = 408\nconst TOO_EARLY = 425\nconst TOO_MANY_REQUESTS = 429\nconst INTERNAL_SERVER_ERROR = 500\nconst BAD_GATEWAY = 502\nconst SERVICE_UNAVAILABLE = 503\nconst GATEWAY_TIMEOUT = 504\n\nconst STATUS_CODES_TO_RETRY = [\n REQUEST_TIMEOUT,\n TOO_EARLY,\n TOO_MANY_REQUESTS,\n INTERNAL_SERVER_ERROR,\n BAD_GATEWAY,\n SERVICE_UNAVAILABLE,\n GATEWAY_TIMEOUT,\n]\n\n/**\n * The default backoff options for CoW Protocol's API\n * @see {@link Backoff configuration: https://www.npmjs.com/package/@insertish/exponential-backoff}\n */\nexport const DEFAULT_BACKOFF_OPTIONS: BackoffOptions = {\n numOfAttempts: 10,\n maxDelay: Infinity,\n jitter: 'none',\n retry: (error: Error | OrderBookApiError) => {\n if (error instanceof OrderBookApiError) {\n return STATUS_CODES_TO_RETRY.includes(error.response.status)\n }\n\n return true\n },\n}\n\n/**\n * The default rate limiter options for CoW Protocol's API.\n *\n * **CAUTION**: The CoW Protocol OrderBook API is limited to 5 requests per second per IP.\n */\nexport const DEFAULT_LIMITER_OPTIONS: RateLimiterOpts = {\n tokensPerInterval: 5,\n interval: 'second',\n}\n\n/**\n * Describe the parameters for a fetch request.\n */\nexport interface FetchParams {\n path: string\n method: 'GET' | 'POST' | 'DELETE' | 'PUT'\n body?: unknown\n query?: URLSearchParams\n}\n\nconst getResponseBody = async (response: Response): Promise<unknown> => {\n if (response.status !== 204) {\n try {\n const contentType = response.headers.get('Content-Type')\n if (contentType) {\n if (contentType.toLowerCase().startsWith('application/json')) {\n return await response.json()\n } else {\n return await response.text()\n }\n }\n } catch (error) {\n console.error(error)\n }\n }\n return undefined\n}\n\n/**\n * Helper function to make a rate-limited request to an API.\n * @param baseUrl The base URL of the API.\n * @param path The path of the request.\n * @param query The query parameters of the request.\n * @param method The HTTP method of the request.\n * @param body The body of the request.\n * @param rateLimiter The rate limiter to use.\n * @param backoffOpts The backoff options to use.\n * @returns The response of the request.\n * @throws If the API returns an error or if the request fails.\n */\nexport async function request<T>(\n baseUrl: string,\n { path, query, method, body }: FetchParams,\n rateLimiter: RateLimiter,\n backoffOpts: BackoffOptions\n): Promise<T> {\n const queryString = query ? '?' + query : ''\n const headers = {\n Accept: 'application/json',\n 'Content-Type': 'application/json',\n }\n\n const url = `${baseUrl}${path}${queryString}`\n const bodyContent = (() => {\n if (!body) return undefined\n\n return typeof body === 'string' ? body : JSON.stringify(body)\n })()\n const init: RequestInit = {\n method,\n body: bodyContent,\n headers,\n }\n\n return backOff<T>(async () => {\n await rateLimiter.removeTokens(1)\n\n const response = await fetch(url, init)\n const responseBody = (await getResponseBody(response)) as T\n\n // Successful response\n if (response.status >= 200 && response.status < 300) {\n return responseBody\n }\n\n return Promise.reject(new OrderBookApiError(response, responseBody))\n }, backoffOpts)\n}\n","import { BUY_ETH_ADDRESS } from '../common/consts'\nimport { Order } from './generated'\nimport { EnrichedOrder } from './types'\n\n/**\n * Apply programmatic transformations to an order.\n *\n * For example, transformations may be applied to an order to recognise it as a Native EthFlow order.\n * @param order to apply transformations to\n * @returns An order with the total fee added.\n */\nexport function transformOrder(order: Order): EnrichedOrder {\n return transformEthFlowOrder(addTotalFeeToOrder(order))\n}\n\n/**\n * Add the total fee to the order.\n *\n * The total fee of the order will be represented by the `totalFee` field, which is the sum of `executedSurplusFee`\n * and `executedFeeAmount`.\n *\n * Note that either `executedSurplusFee` or `executedFeeAmount` may be `0`, or both might have a non `0` value.\n *\n * See https://cowservices.slack.com/archives/C036G0J90BU/p1705322037866779?thread_ts=1705083817.684659&cid=C036G0J90BU\n *\n * @param dto The order to add the total fee to.\n * @returns The order with the total fee added.\n */\nfunction addTotalFeeToOrder(dto: Order): EnrichedOrder {\n const { executedFeeAmount, executedSurplusFee } = dto\n\n const _executedFeeAmount = BigInt(executedFeeAmount || '0')\n const _executedSurplusFee = BigInt(executedSurplusFee || '0')\n\n const totalFee = String(_executedFeeAmount + _executedSurplusFee)\n\n return {\n ...dto,\n totalFee,\n }\n}\n\n/**\n * Transform order field for Native EthFlow orders\n *\n * A no-op for regular orders\n * For Native EthFlow, due to how the contract is setup:\n * - sellToken set to Native token address\n * - owner set to `onchainUser`\n * - validTo set to `ethflowData.userValidTo`\n */\nfunction transformEthFlowOrder(order: EnrichedOrder): EnrichedOrder {\n const { ethflowData } = order\n\n if (!ethflowData) {\n return order\n }\n\n const { userValidTo: validTo } = ethflowData\n const owner = order.onchainUser || order.owner\n const sellToken = BUY_ETH_ADDRESS\n\n return { ...order, validTo, owner, sellToken }\n}\n","import 'cross-fetch/polyfill'\nimport { RateLimiter } from 'limiter'\nimport { SupportedChainId } from '../common/chains'\nimport {\n ApiBaseUrls,\n ApiContext,\n CowEnv,\n DEFAULT_COW_API_CONTEXT,\n ENVS_LIST,\n PartialApiContext,\n} from '../common/configs'\nimport { CowError } from '../common/cow-error'\nimport {\n Address,\n AppDataHash,\n AppDataObject,\n CompetitionOrderStatus,\n NativePriceResponse,\n Order,\n OrderCancellations,\n OrderCreation,\n OrderQuoteRequest,\n OrderQuoteResponse,\n SolverCompetitionResponse,\n TotalSurplus,\n Trade,\n TransactionHash,\n UID,\n} from './generated'\nimport { DEFAULT_BACKOFF_OPTIONS, DEFAULT_LIMITER_OPTIONS, FetchParams, OrderBookApiError, request } from './request'\nimport { transformOrder } from './transformOrder'\nimport { EnrichedOrder } from './types'\n\n/**\n * An object containing *production* environment base URLs for each supported `chainId`.\n * @see {@link https://api.cow.fi/docs/#/}\n */\nexport const ORDER_BOOK_PROD_CONFIG: ApiBaseUrls = {\n [SupportedChainId.MAINNET]: 'https://api.cow.fi/mainnet',\n [SupportedChainId.GNOSIS_CHAIN]: 'https://api.cow.fi/xdai',\n [SupportedChainId.ARBITRUM_ONE]: 'https://api.cow.fi/arbitrum_one',\n [SupportedChainId.SEPOLIA]: 'https://api.cow.fi/sepolia',\n}\n\n/**\n * An object containing *staging* environment base URLs for each supported `chainId`.\n */\nexport const ORDER_BOOK_STAGING_CONFIG: ApiBaseUrls = {\n [SupportedChainId.MAINNET]: 'https://barn.api.cow.fi/mainnet',\n [SupportedChainId.GNOSIS_CHAIN]: 'https://barn.api.cow.fi/xdai',\n [SupportedChainId.ARBITRUM_ONE]: 'https://barn.api.cow.fi/arbitrum_one',\n [SupportedChainId.SEPOLIA]: 'https://barn.api.cow.fi/sepolia',\n}\n\nfunction cleanObjectFromUndefinedValues(obj: Record<string, string>): typeof obj {\n return Object.keys(obj).reduce((acc, key) => {\n const val = obj[key]\n if (typeof val !== 'undefined') acc[key] = val\n return acc\n }, {} as typeof obj)\n}\n\n/**\n * The parameters for the `getOrders` request.\n */\nexport type GetOrdersRequest = {\n owner: Address\n offset?: number\n limit?: number\n}\n\n/**\n * The CoW Protocol OrderBook API client.\n *\n * This is the main entry point for interacting with the CoW Protocol OrderBook API. The main advantage of using\n * this client is the batteries-included approach to interacting with the API. It handles:\n *\n * - Environment configuration (mainnet, staging, etc.)\n * - Rate limiting\n * - Retries\n * - Backoff\n * - Error handling\n * - Request signing\n * - Request validation\n *\n * @example\n *\n * ```typescript\n * import { OrderBookApi, OrderSigningUtils, SupportedChainId } from '@cowprotocol/cow-sdk'\n * import { Web3Provider } from '@ethersproject/providers'\n *\n * const account = 'YOUR_WALLET_ADDRESS'\n * const chainId = 100 // Gnosis chain\n * const provider = new Web3Provider(window.ethereum)\n * const signer = provider.getSigner()\n *\n * const quoteRequest = {\n * sellToken: '0x6a023ccd1ff6f2045c3309768ead9e68f978f6e1', // WETH gnosis chain\n * buyToken: '0x9c58bacc331c9aa871afd802db6379a98e80cedb', // GNO gnosis chain\n * from: account,\n * receiver: account,\n * sellAmountBeforeFee: (0.4 * 10 ** 18).toString(), // 0.4 WETH\n * kind: OrderQuoteSide.kind.SELL,\n * }\n *\n * const orderBookApi = new OrderBookApi({ chainId: SupportedChainId.GNOSIS_CHAIN })\n *\n * async function main() {\n * const { quote } = await orderBookApi.getQuote(quoteRequest)\n *\n * const orderSigningResult = await OrderSigningUtils.signOrder(quote, chainId, signer)\n *\n * const orderId = await orderBookApi.sendOrder({ ...quote, ...orderSigningResult })\n *\n * const order = await orderBookApi.getOrder(orderId)\n *\n * const trades = await orderBookApi.getTrades({ orderId })\n *\n * const orderCancellationSigningResult = await OrderSigningUtils.signOrderCancellations([orderId], chainId, signer)\n *\n * const cancellationResult = await orderBookApi.sendSignedOrderCancellations({...orderCancellationSigningResult, orderUids: [orderId] })\n *\n * console.log('Results: ', { orderId, order, trades, orderCancellationSigningResult, cancellationResult })\n * }\n * ```\n *\n * @see {@link Swagger documentation https://api.cow.fi/docs/#/}\n * @see {@link OrderBook API https://github.com/cowprotocol/services}\n */\nexport class OrderBookApi {\n public context: ApiContext\n\n private rateLimiter: RateLimiter\n\n /**\n * Creates a new instance of the CoW Protocol OrderBook API client.\n * @param context - The API context to use. If not provided, the default context will be used.\n */\n constructor(context: PartialApiContext = {}) {\n this.context = { ...DEFAULT_COW_API_CONTEXT, ...context }\n this.rateLimiter = new RateLimiter(context.limiterOpts || DEFAULT_LIMITER_OPTIONS)\n }\n\n /**\n * Get the version of the API.\n * @param contextOverride Optional context override for this request.\n * @returns The version of the API.\n * @see {@link https://api.cow.fi/docs/#/default/get_api_v1_version}\n */\n getVersion(contextOverride: PartialApiContext = {}): Promise<string> {\n return this.fetch({ path: '/api/v1/version', method: 'GET' }, contextOverride)\n }\n\n /**\n * Get all the trades for either an `owner` **OR** `orderUid`.\n *\n * Given that an order *may* be partially fillable, it is possible that a discrete order (`orderUid`)\n * may have *multiple* trades. Therefore, this method returns a list of trades, either for *all* the orders\n * of a given `owner`, or for a discrete order (`orderUid`).\n * @param request Either an `owner` or an `orderUid` **MUST** be specified.\n * @param contextOverride Optional context override for this request.\n * @returns A list of trades matching the request.\n */\n getTrades(\n request: { owner?: Address; orderUid?: UID },\n contextOverride: PartialApiContext = {}\n ): Promise<Array<Trade>> {\n if (request.owner && request.orderUid) {\n return Promise.reject(new CowError('Cannot specify both owner and orderId'))\n } else if (!request.owner && !request.orderUid) {\n return Promise.reject(new CowError('Must specify either owner or orderId'))\n }\n\n const query = new URLSearchParams(cleanObjectFromUndefinedValues(request))\n\n return this.fetch({ path: '/api/v1/trades', method: 'GET', query }, contextOverride)\n }\n\n /**\n * Get a list of orders for a given `owner`.\n * @param request The request parameters with `request.offset = 0` and `request.limit = 1000` by default.\n * @param contextOverride Optional context override for this request.\n * @returns A list of orders matching the request.\n * @see {@link GetOrdersRequest}\n * @see {@link EnrichedOrder}\n */\n getOrders(\n { owner, offset = 0, limit = 1000 }: GetOrdersRequest,\n contextOverride: PartialApiContext = {}\n ): Promise<Array<EnrichedOrder>> {\n const query = new URLSearchParams(\n cleanObjectFromUndefinedValues({ offset: offset.toString(), limit: limit.toString() })\n )\n\n return this.fetch<Array<EnrichedOrder>>(\n { path: `/api/v1/account/${owner}/orders`, method: 'GET', query },\n contextOverride\n ).then((orders) => {\n return orders.map(transformOrder)\n })\n }\n\n /**\n * Get a list of orders from a given settlement transaction hash.\n * @param txHash The transaction hash.\n * @param contextOverride Optional context override for this request.\n * @returns A list of orders matching the request.\n * @see {@link EnrichedOrder}\n */\n getTxOrders(txHash: TransactionHash, contextOverride: PartialApiContext = {}): Promise<Array<EnrichedOrder>> {\n return this.fetch<Array<EnrichedOrder>>(\n { path: `/api/v1/transactions/${txHash}/orders`, method: 'GET' },\n contextOverride\n ).then((orders) => {\n return orders.map(transformOrder)\n })\n }\n\n /**\n * Get an order by its unique identifier, `orderUid`.\n * @param orderUid The unique identifier of the order.\n * @param contextOverride Optional context override for this request.\n * @returns The order matching the request.\n */\n getOrder(orderUid: UID, contextOverride: PartialApiContext = {}): Promise<EnrichedOrder> {\n return this.fetch<Order>({ path: `/api/v1/orders/${orderUid}`, method: 'GET' }, contextOverride).then((order) => {\n return transformOrder(order)\n })\n }\n\n /**\n * Get the order status while open\n */\n getOrderCompetitionStatus(orderUid: UID, contextOverride: PartialApiContext = {}): Promise<CompetitionOrderStatus> {\n return this.fetch({ path: `/api/v1/orders/${orderUid}/status`, method: 'GET' }, contextOverride)\n }\n\n /**\n * Attempt to get an order by its unique identifier, `orderUid`, from multiple environments.\n *\n * **NOTE**: The environment refers to either `prod` or `staging`. This allows a conveience method to\n * attempt to get an order from both environments, in the event that the order is not found in the\n * environment specified in the context.\n * @param orderUid The unique identifier of the order.\n * @param contextOverride Optional context override for this request.\n * @returns The order matching the request.\n * @throws {OrderBookApiError} If the order is not found in any of the environments.\n */\n getOrderMultiEnv(orderUid: UID, contextOverride: PartialApiContext = {}): Promise<EnrichedOrder> {\n const { env } = this.getContextWithOverride(contextOverride)\n const otherEnvs = ENVS_LIST.filter((i) => i !== env)\n\n let attemptsCount = 0\n\n const fallback = (error: Error | OrderBookApiError): Promise<EnrichedOrder> => {\n const nextEnv = otherEnvs[attemptsCount]\n\n if (error instanceof OrderBookApiError && error.response.status === 404 && nextEnv) {\n attemptsCount++\n\n return this.getOrder(orderUid, { ...contextOverride, env: nextEnv }).catch(fallback)\n }\n\n return Promise.reject(error)\n }\n\n return this.getOrder(orderUid, { ...contextOverride, env }).catch(fallback)\n }\n\n /**\n * Get a quote for an order.\n * This allows for the calculation of the total cost of an order, including fees, before signing and submitting.\n * @param requestBody The parameters for the order quote request.\n * @param contextOverride Optional context override for this request.\n * @returns A hydrated order matching the request ready to be signed.\n */\n getQuote(requestBody: OrderQuoteRequest, contextOverride: PartialApiContext = {}): Promise<OrderQuoteResponse> {\n return this.fetch({ path: '/api/v1/quote', method: 'POST', body: requestBody }, contextOverride)\n }\n\n /**\n * Cancel one or more orders.\n *\n * **NOTE**: Cancellation is on a best-effort basis. Orders that are already in the process of being settled\n * (ie. transaction has been submitted to chain by the solver) cannot not be cancelled.\n * **CAUTION**: This method can only be used to cancel orders that were signed using `EIP-712` or `eth_sign (EIP-191)`.\n * @param requestBody Orders to be cancelled and signed instructions to cancel them.\n * @param contextOverride Optional context override for this request.\n * @returns A list of order unique identifiers that were successfully cancelled.\n */\n sendSignedOrderCancellations(\n requestBody: OrderCancellations,\n contextOverride: PartialApiContext = {}\n ): Promise<void> {\n return this.fetch({ path: '/api/v1/orders', method: 'DELETE', body: requestBody }, contextOverride)\n }\n\n /**\n * Submit an order to the order book.\n * @param requestBody The signed order to be submitted.\n * @param contextOverride Optional context override for this request.\n * @returns The unique identifier of the order.\n */\n sendOrder(requestBody: OrderCreation, contextOverride: PartialApiContext = {}): Promise<UID> {\n return this.fetch({ path: '/api/v1/orders', method: 'POST', body: requestBody }, contextOverride)\n }\n\n /**\n * Get the native price of a token.\n *\n * **NOTE**: The native price is the price of the token in the native currency of the chain. For example, on Ethereum\n * this would be the price of the token in ETH.\n * @param tokenAddress The address of the ERC-20 token.\n * @param contextOverride Optional context override for this request.\n * @returns The native price of the token.\n */\n getNativePrice(tokenAddress: Address, contextOverride: PartialApiContext = {}): Promise<NativePriceResponse> {\n return this.fetch({ path: `/api/v1/token/${tokenAddress}/native_price`, method: 'GET' }, contextOverride)\n }\n\n /**\n * Given a user's address, get the total surplus that they have earned.\n * @param address The user's address\n * @param contextOverride Optional context override for this request.\n * @returns Calculated user's surplus\n */\n getTotalSurplus(address: Address, contextOverride: PartialApiContext = {}): Promise<TotalSurplus> {\n return this.fetch({ path: `/api/v1/users/${address}/total_surplus`, method: 'GET' }, contextOverride)\n }\n\n /**\n * Retrieve the full app data for a given app data hash.\n * @param appDataHash `bytes32` hash of the app data\n * @param contextOverride Optional context override for this request.\n * @returns Full app data that was uploaded\n */\n getAppData(appDataHash: AppDataHash, contextOverride: PartialApiContext = {}): Promise<AppDataObject> {\n return this.fetch({ path: `/api/v1/app_data/${appDataHash}`, method: 'GET' }, contextOverride)\n }\n\n /**\n * Upload the full app data that corresponds to a given app data hash.\n * @param appDataHash `bytes32` hash of the app data\n * @param fullAppData Full app data to be uploaded\n * @param contextOverride Optional context override for this request.\n * @returns The string encoding of the full app data that was uploaded.\n */\n uploadAppData(\n appDataHash: AppDataHash,\n fullAppData: string,\n contextOverride: PartialApiContext = {}\n ): Promise<AppDataObject> {\n return this.fetch(\n { path: `/api/v1/app_data/${appDataHash}`, method: 'PUT', body: { fullAppData } },\n contextOverride\n )\n }\n\n getSolverCompetition(auctionId: number, contextOverride?: PartialApiContext): Promise<SolverCompetitionResponse>\n\n getSolverCompetition(txHash: string, contextOverride?: PartialApiContext): Promise<SolverCompetitionResponse>\n\n /**\n * Given an auction id or tx hash, get the details of the solver competition for that auction.\n * @param auctionIdorTx auction id or tx hash corresponding to the auction\n * @param contextOverride Optional context override for this request.\n * @returns An object containing the solver competition details\n */\n getSolverCompetition(\n auctionIdorTx: number | string,\n contextOverride: PartialApiContext = {}\n ): Promise<SolverCompetitionResponse> {\n return this.fetch(\n {\n path: `/api/v1/solver_competition${typeof auctionIdorTx === 'string' ? '/by_tx_hash' : ''}/${auctionIdorTx}`,\n method: 'GET',\n },\n contextOverride\n )\n }\n\n /**\n * Generate an API endpoint for an order by its unique identifier, `orderUid`.\n * @param orderUid The unique identifier of the order.\n * @param contextOverride Optional context override for this request.\n * @returns The API endpoint to get the order.\n */\n getOrderLink(orderUid: UID, contextOverride?: PartialApiContext): string {\n const { chainId, env } = this.getContextWithOverride(contextOverride)\n return this.getApiBaseUrls(env)[chainId] + `/api/v1/orders/${orderUid}`\n }\n\n /**\n * Apply an override to the context for a request.\n * @param contextOverride Optional context override for this request.\n * @returns New context with the override applied.\n */\n private getContextWithOverride(contextOverride: PartialApiContext = {}): ApiContext {\n return { ...this.context, ...contextOverride }\n }\n\n /**\n * Get the base URLs for the API endpoints given the environment.\n * @param env The environment to get the base URLs for.\n * @returns The base URLs for the API endpoints.\n */\n private getApiBaseUrls(env: CowEnv): ApiBaseUrls {\n if (this.context.baseUrls) return this.context.baseUrls\n\n return env === 'prod' ? ORDER_BOOK_PROD_CONFIG : ORDER_BOOK_STAGING_CONFIG\n }\n\n /**\n * Make a request to the API.\n * @param params The parameters for the request.\n * @param contextOverride Optional context override for this request.\n * @returns The response from the API.\n */\n private fetch<T>(params: FetchParams, contextOverride: PartialApiContext = {}): Promise<T> {\n const { chainId, env, backoffOpts: _backoffOpts } = this.getContextWithOverride(contextOverride)\n const baseUrl = this.getApiBaseUrls(env)[chainId]\n const backoffOpts = _backoffOpts || DEFAULT_BACKOFF_OPTIONS\n const rateLimiter = contextOverride.limiterOpts ? new RateLimiter(contextOverride.limiterOpts) : this.rateLimiter\n\n return request(baseUrl, params, rateLimiter, backoffOpts)\n }\n}\n","/* istanbul ignore file */\n/* tslint:disable */\n/* eslint-disable */\n\n/**\n * Where should the `buyToken` be transferred to?\n */\nexport enum BuyTokenDestination {\n ERC20 = 'erc20',\n INTERNAL = 'internal',\n}\n","/* istanbul ignore file */\n/* tslint:disable */\n/* eslint-disable */\n\nimport type { ExecutedAmounts } from './ExecutedAmounts';\n\nexport type CompetitionOrderStatus = {\n type: CompetitionOrderStatus.type;\n /**\n * A list of solvers who participated in the latest competition, sorted by score in ascending order, where the last element is the winner.\n * The presence of executed amounts defines whether the solver provided a solution for the desired order.\n *\n */\n value?: Array<{\n /**\n * Name of the solver.\n */\n solver: string;\n executedAmounts?: ExecutedAmounts;\n }>;\n};\n\nexport namespace CompetitionOrderStatus {\n\n export enum type {\n OPEN = 'open',\n SCHEDULED = 'scheduled',\n ACTIVE = 'active',\n SOLVED = 'solved',\n EXECUTING = 'executing',\n TRADED = 'traded',\n CANCELLED = 'cancelled',\n }\n\n\n}\n\n","/* istanbul ignore file */\n/* tslint:disable */\n/* eslint-disable */\n\n/**\n * How was the order signed?\n */\nexport enum EcdsaSigningScheme {\n EIP712 = 'eip712',\n ETHSIGN = 'ethsign',\n}\n","/* istanbul ignore file */\n/* tslint:disable */\n/* eslint-disable */\n\nimport type { Address } from './Address';\n\nexport type OnchainOrderData = {\n /**\n * If orders are placed as on-chain orders, the owner of the order might\n * be a smart contract, but not the user placing the order. The\n * actual user will be provided in this field.\n *\n */\n sender: Address;\n /**\n * Describes the error, if the order placement was not successful. This could\n * happen, for example, if the `validTo` is too high, or no valid quote was\n * found or generated.\n *\n */\n placementError?: OnchainOrderData.placementError;\n};\n\nexport namespace OnchainOrderData {\n\n /**\n * Describes the error, if the order placement was not successful. This could\n * happen, for example, if the `validTo` is too high, or no valid quote was\n * found or generated.\n *\n */\n export enum placementError {\n QUOTE_NOT_FOUND = 'QuoteNotFound',\n VALID_TO_TOO_FAR_IN_FUTURE = 'ValidToTooFarInFuture',\n PRE_VALIDATION_ERROR = 'PreValidationError',\n }\n\n\n}\n\n","/* istanbul ignore file */\n/* tslint:disable */\n/* eslint-disable */\n\nexport type OrderCancellationError = {\n errorType: OrderCancellationError.errorType;\n description: string;\n};\n\nexport namespace OrderCancellationError {\n\n export enum errorType {\n INVALID_SIGNATURE = 'InvalidSignature',\n WRONG_OWNER = 'WrongOwner',\n ORDER_NOT_FOUND = 'OrderNotFound',\n ALREADY_CANCELLED = 'AlreadyCancelled',\n ORDER_FULLY_EXECUTED = 'OrderFullyExecuted',\n ORDER_EXPIRED = 'OrderExpired',\n ON_CHAIN_ORDER = 'OnChainOrder',\n }\n\n\n}\n\n","/* istanbul ignore file */\n/* tslint:disable */\n/* eslint-disable */\n\n/**\n * Order class.\n */\nexport enum OrderClass {\n MARKET = 'market',\n LIMIT = 'limit',\n LIQUIDITY = 'liquidity',\n}\n","/* istanbul ignore file */\n/* tslint:disable */\n/* eslint-disable */\n\n/**\n * Is this order a buy or sell?\n */\nexport enum OrderKind {\n BUY = 'buy',\n SELL = 'sell',\n}\n","/* istanbul ignore file */\n/* tslint:disable */\n/* eslint-disable */\n\nexport type OrderPostError = {\n errorType: OrderPostError.errorType;\n description: string;\n};\n\nexport namespace OrderPostError {\n\n export enum errorType {\n DUPLICATED_ORDER = 'DuplicatedOrder',\n QUOTE_NOT_FOUND = 'QuoteNotFound',\n QUOTE_NOT_VERIFIED = 'QuoteNotVerified',\n INVALID_QUOTE = 'InvalidQuote',\n MISSING_FROM = 'MissingFrom',\n WRONG_OWNER = 'WrongOwner',\n INVALID_EIP1271SIGNATURE = 'InvalidEip1271Signature',\n INSUFFICIENT_BALANCE = 'InsufficientBalance',\n INSUFFICIENT_ALLOWANCE = 'InsufficientAllowance',\n INVALID_SIGNATURE = 'InvalidSignature',\n SELL_AMOUNT_OVERFLOW = 'SellAmountOverflow',\n TRANSFER_SIMULATION_FAILED = 'TransferSimulationFailed',\n ZERO_AMOUNT = 'ZeroAmount',\n INCOMPATIBLE_SIGNING_SCHEME = 'IncompatibleSigningScheme',\n TOO_MANY_LIMIT_ORDERS = 'TooManyLimitOrders',\n TOO_MUCH_GAS = 'TooMuchGas',\n UNSUPPORTED_BUY_TOKEN_DESTINATION = 'UnsupportedBuyTokenDestination',\n UNSUPPORTED_SELL_TOKEN_SOURCE = 'UnsupportedSellTokenSource',\n UNSUPPORTED_ORDER_TYPE = 'UnsupportedOrderType',\n INSUFFICIENT_VALID_TO = 'InsufficientValidTo',\n EXCESSIVE_VALID_TO = 'ExcessiveValidTo',\n INVALID_NATIVE_SELL_TOKEN = 'InvalidNativeSellToken',\n SAME_BUY_AND_SELL_TOKEN = 'SameBuyAndSellToken',\n UNSUPPORTED_TOKEN = 'UnsupportedToken',\n INVALID_APP_DATA = 'InvalidAppData',\n APP_DATA_HASH_MISMATCH = 'AppDataHashMismatch',\n APPDATA_FROM_MISMATCH = 'AppdataFromMismatch',\n }\n\n\n}\n\n","/* istanbul ignore file */\n/* tslint:disable */\n/* eslint-disable */\n\nexport enum OrderQuoteSideKindBuy {\n BUY = 'buy',\n}\n","/* istanbul ignore file */\n/* tslint:disable */\n/* eslint-disable */\n\nexport enum OrderQuoteSideKindSell {\n SELL = 'sell',\n}\n","/* istanbul ignore file */\n/* tslint:disable */\n/* eslint-disable */\n\n/**\n * The current order status.\n */\nexport enum OrderStatus {\n PRESIGNATURE_PENDING = 'presignaturePending',\n OPEN = 'open',\n FULFILLED = 'fulfilled',\n CANCELLED = 'cancelled',\n EXPIRED = 'expired',\n}\n","/* istanbul ignore file */\n/* tslint:disable */\n/* eslint-disable */\n\nexport type PriceEstimationError = {\n errorType: PriceEstimationError.errorType;\n description: string;\n};\n\nexport namespace PriceEstimationError {\n\n export enum errorType {\n QUOTE_NOT_VERIFIED = 'QuoteNotVerified',\n UNSUPPORTED_TOKEN = 'UnsupportedToken',\n ZERO_AMOUNT = 'ZeroAmount',\n UNSUPPORTED_ORDER_TYPE = 'UnsupportedOrderType',\n }\n\n\n}\n\n","/* istanbul ignore file */\n/* tslint:disable */\n/* eslint-disable */\n\n/**\n * How good should the price estimate be?\n *\n * Fast: The price estimate is chosen among the fastest N price estimates.\n * Optimal: The price estimate is chosen among all price estimates.\n * Verified: The price estimate is chosen among all verified/simulated price estimates.\n *\n * **NOTE**: Orders are supposed to be created from `verified` or `optimal` price estimates.\n *\n */\nexport enum PriceQuality {\n FAST = 'fast',\n OPTIMAL = 'optimal',\n VERIFIED = 'verified',\n}\n","/* istanbul ignore file */\n/* tslint:disable */\n/* eslint-disable */\n\n/**\n * Where should the `sellToken` be drawn from?\n */\nexport enum SellTokenSource {\n ERC20 = 'erc20',\n INTERNAL = 'internal',\n EXTERNAL = 'external',\n}\n","/* istanbul ignore file */\n/* tslint:disable */\n/* eslint-disable */\n\n/**\n * How was the order signed?\n */\nexport enum SigningScheme {\n EIP712 = 'eip712',\n ETHSIGN = 'ethsign',\n PRESIGN = 'presign',\n EIP1271 = 'eip1271',\n}\n","import { QuoteAmountsAndCosts } from './types'\nimport { OrderKind, type OrderParameters } from './generated'\n\ninterface Params {\n orderParams: OrderParameters\n sellDecimals: number\n buyDecimals: number\n slippagePercentBps: number\n partnerFeeBps: number | undefined\n}\n\nconst ONE_HUNDRED_BPS = BigInt(100 * 100)\n\nexport function getQuoteAmountsAndCosts(params: Params): QuoteAmountsAndCosts {\n const { orderParams, sellDecimals, buyDecimals, slippagePercentBps } = params\n const partnerFeeBps = params.partnerFeeBps ?? 0\n const isSell = orderParams.kind === OrderKind.SELL\n /**\n * Wrap raw values into CurrencyAmount objects\n * We also make amounts names more specific with \"beforeNetworkCosts\" and \"afterNetworkCosts\" suffixes\n */\n const networkCostAmount = getBigNumber(orderParams.feeAmount, sellDecimals)\n const sellAmountBeforeNetworkCosts = getBigNumber(orderParams.sellAmount, sellDecimals)\n const buyAmountAfterNetworkCosts = getBigNumber(orderParams.buyAmount, buyDecimals)\n\n /**\n * This is an actual price of the quote since it's derrived only from the quote sell and buy amounts\n */\n const quotePrice = buyAmountAfterNetworkCosts.num / sellAmountBeforeNetworkCosts.num\n\n /**\n * Before networkCosts + networkCosts = After networkCosts :)\n */\n const sellAmountAfterNetworkCosts = getBigNumber(\n sellAmountBeforeNetworkCosts.big + networkCostAmount.big,\n sellDecimals\n )\n\n /**\n * Since the quote contains only buy amount after network costs\n * we have to calculate the buy amount before network costs from the quote price\n */\n const buyAmountBeforeNetworkCosts = getBigNumber(quotePrice * sellAmountAfterNetworkCosts.num, buyDecimals)\n\n /**\n * Partner fee is always added on the surplus amount, for sell-orders it's buy amount, for buy-orders it's sell amount\n */\n const surplusAmount = isSell ? buyAmountBeforeNetworkCosts.big : sellAmountBeforeNetworkCosts.big\n const partnerFeeAmount = partnerFeeBps > 0 ? (surplusAmount * BigInt(partnerFeeBps)) / ONE_HUNDRED_BPS : BigInt(0)\n\n /**\n * Partner fee is always added on the surplus token, for sell-orders it's buy token, for buy-orders it's sell token\n */\n const afterPartnerFees = isSell\n ? {\n sellAmount: sellAmountAfterNetworkCosts.big,\n buyAmount: buyAmountAfterNetworkCosts.big - partnerFeeAmount,\n }\n : {\n sellAmount: sellAmountAfterNetworkCosts.big + partnerFeeAmount,\n buyAmount: buyAmountAfterNetworkCosts.big,\n }\n\n const getSlippageAmount = (amount: bigint) => (amount * BigInt(slippagePercentBps)) / ONE_HUNDRED_BPS\n\n /**\n * Same rules apply for slippage as for partner fees\n */\n const afterSlippage = isSell\n ? {\n sellAmount: afterPartnerFees.sellAmount,\n buyAmount: afterPartnerFees.buyAmount - getSlippageAmount(afterPartnerFees.buyAmount),\n }\n : {\n sellAmount: afterPartnerFees.sellAmount + getSlippageAmount(afterPartnerFees.sellAmount),\n buyAmount: afterPartnerFees.buyAmount,\n }\n\n return {\n isSell,\n costs: {\n networkFee: {\n amountInSellCurrency: networkCostAmount.big,\n amountInBuyCurrency: getBigNumber(quotePrice * networkCostAmount.num, buyDecimals).big,\n },\n partnerFee: {\n amount: partnerFeeAmount,\n bps: partnerFeeBps,\n },\n },\n beforeNetworkCosts: {\n sellAmount: sellAmountBeforeNetworkCosts.big,\n buyAmount: buyAmountBeforeNetworkCosts.big,\n },\n afterNetworkCosts: {\n sellAmount: sellAmountAfterNetworkCosts.big,\n buyAmount: buyAmountAfterNetworkCosts.big,\n },\n afterPartnerFees,\n afterSlippage,\n }\n}\n\ntype BigNumber = {\n big: bigint\n num: number\n}\n\n/**\n * BigInt works well with subtraction and addition, but it's not very good with multiplication and division\n * To multiply/divide token amounts we have to convert them to numbers, but we have to be careful with precision\n * @param value\n * @param decimals\n */\nfunction getBigNumber(value: string | bigint | number, decimals: number): BigNumber {\n if (typeof value === 'number') {\n const bigAsNumber = value * 10 ** decimals\n const bigAsNumberString = bigAsNumber.toFixed()\n const big = BigInt(bigAsNumberString.includes('e') ? bigAsNumber : bigAsNumberString)\n\n return { big, num: value }\n }\n\n const big = BigInt(value)\n const num = Number(big) / 10 ** decimals\n\n return { big, num }\n}\n","import { gql } from 'graphql-request'\n\n/**\n * GraphQL query for the total number of tokens, orders, traders, settlements, volume, and fees.\n */\nexport const TOTALS_QUERY = gql`\n query Totals {\n totals {\n tokens\n orders\n traders\n settlements\n volumeUsd\n volumeEth\n feesUsd\n feesEth\n }\n }\n`\n\n/**\n * GraphQL query for the total volume over the last N days.\n * @param days The number of days to query.\n */\nexport const LAST_DAYS_VOLUME_QUERY = gql`\n query LastDaysVolume($days: Int!) {\n dailyTotals(orderBy: timestamp, orderDirection: desc, first: $days) {\n timestamp\n volumeUsd\n }\n }\n`\n\n/**\n * GraphQL query for the total volume over the last N hours.\n * @param hours The number of hours to query.\n */\nexport const LAST_HOURS_VOLUME_QUERY = gql`\n query LastHoursVolume($hours: Int!) {\n hourlyTotals(orderBy: timestamp, orderDirection: desc, first: $hours) {\n timestamp\n volumeUsd\n }\n }\n`\n","import { Variables, request } from 'graphql-request'\nimport { DocumentNode } from 'graphql/index'\nimport { SupportedChainId } from '../common/chains'\nimport { ApiContext, CowEnv, DEFAULT_COW_API_CONTEXT } from '../common/configs'\nimport { CowError } from '../common/cow-error'\nimport { LastDaysVolumeQuery, LastHoursVolumeQuery, TotalsQuery } from './graphql'\nimport { LAST_DAYS_VOLUME_QUERY, LAST_HOURS_VOLUME_QUERY, TOTALS_QUERY } from './queries'\n\nconst SUBGRAPH_BASE_URL = 'https://api.thegraph.com/subgraphs/name/cowprotocol'\n\ntype SubgraphApiBaseUrls = Record<SupportedChainId, string | null>\n\ninterface SubgraphApiContext extends Omit<ApiContext, 'baseUrls'> {\n baseUrls?: SubgraphApiBaseUrls\n}\n\ntype PartialSubgraphApiContext = Partial<SubgraphApiContext>\n\n/**\n * CoW Protocol Production Subgraph API configuration.\n * @see {@link https://api.thegraph.com/subgraphs/name/cowprotocol/cow}\n * @see {@link https://api.thegraph.com/subgraphs/name/cowprotocol/cow-gc}\n */\nexport const SUBGRAPH_PROD_CONFIG: SubgraphApiBaseUrls = {\n [SupportedChainId.MAINNET]: SUBGRAPH_BASE_URL + '/cow',\n [SupportedChainId.GNOSIS_CHAIN]: SUBGRAPH_BASE_URL + '/cow-gc',\n [SupportedChainId.ARBITRUM_ONE]: null,\n [SupportedChainId.SEPOLIA]: null,\n}\n\n/**\n * CoW Protocol Staging Subgraph API configuration.\n * @deprecated\n * @see {@link https://api.thegraph.com/subgraphs/name/cowprotocol/cow-staging}\n * @see {@link https://api.thegraph.com/subgraphs/name/cowprotocol/cow-gc-staging}\n */\nexport const SUBGRAPH_STAGING_CONFIG: SubgraphApiBaseUrls = {\n [SupportedChainId.MAINNET]: SUBGRAPH_BASE_URL + '/cow-staging',\n [SupportedChainId.GNOSIS_CHAIN]: SUBGRAPH_BASE_URL + '/cow-gc-staging',\n [SupportedChainId.ARBITRUM_ONE]: null,\n [SupportedChainId.SEPOLIA]: null,\n}\n\n/**\n * TheGraph API client for CoW Protocol.\n */\nexport class SubgraphApi {\n API_NAME = 'CoW Protocol Subgraph'\n\n public context: SubgraphApiContext\n\n /**\n * Create a new CoW Protocol API instance.\n * @param context Any properties of the {@link SubgraphApiContext} may be overridden by passing a {@link PartialSubgraphApiContext}.\n */\n constructor(context: PartialSubgraphApiContext = {}) {\n this.context = {\n ...DEFAULT_COW_API_CONTEXT,\n ...context,\n }\n }\n\n /**\n * Query the totals from TheGraph for the CoW Protocol.\n * @param contextOverride Override the context for this call only.\n * @returns The totals for the CoW Protocol.\n */\n async getTotals(contextOverride: PartialSubgraphApiContext = {}): Promise<TotalsQuery['totals'][0]> {\n const response = await this.runQuery<TotalsQuery>(TOTALS_QUERY, undefined, contextOverride)\n return response.totals[0]\n }\n\n /**\n * Query the volume over the last N days from TheGraph for the CoW Protocol.\n * @param {number} days The number of days to query.\n * @param {PartialSubgraphApiContext} contextOverride Override the context for this call only.\n * @returns The volume for the last N days.\n */\n async getLastDaysVolume(days: number, contextOverride: PartialSubgraphApiContext = {}): Promise<LastDaysVolumeQuery> {\n return this.runQuery<LastDaysVolumeQuery>(LAST_DAYS_VOLUME_QUERY, { days }, contextOverride)\n }\n\n /**\n * Query the volume over the last N hours from TheGraph for the CoW Protocol.\n * @param {number} hours The number of hours to query.\n * @param {PartialSubgraphApiContext} contextOverride Override the context for this call only.\n * @returns The volume for the last N hours.\n */\n async getLastHoursVolume(\n hours: number,\n contextOverride: PartialSubgraphApiContext = {}\n ): Promise<LastHoursVolumeQuery> {\n return this.runQuery<LastHoursVolumeQuery>(LAST_HOURS_VOLUME_QUERY, { hours }, contextOverride)\n }\n\n /**\n * Run a query against the CoW Protocol Subgraph.\n * @param {string | DocumentNode} query GQL query string or DocumentNode.\n * @param {Variables | undefined} variables To be passed to the query.\n * @param {PartialSubgraphApiContext} contextOverride Override the context for this call only.\n * @returns Results of the query.\n * @throws {@link CowError} if the query fails.\n */\n async runQuery<T>(\n query: string | DocumentNode,\n variables: Variables | undefined = undefined,\n contextOverride: PartialSubgraphApiContext = {}\n ): Promise<T> {\n const { chainId, env } = this.getContextWithOverride(contextOverride)\n const baseUrl = this.getEnvConfigs(env)[chainId]\n\n if (baseUrl === null) {\n throw new Error('Unsupported Network. The subgraph API is not available in the Network ' + chainId)\n }\n\n try {\n return await request(baseUrl, query, variables)\n } catch (error) {\n console.error(`[subgraph:${this.API_NAME}]`, error)\n throw new CowError(\n `Error running query: ${query}. Variables: ${JSON.stringify(variables)}. API: ${baseUrl}. Inner Error: ${error}`\n )\n }\n }\n\n /**\n * Override parts of the context for a specific call.\n * @param {PartialSubgraphApiContext} contextOverride Override the context for this call only.\n * @returns {SubgraphApiContext} The context with the override applied.\n */\n private getContextWithOverride(contextOverride: PartialSubgraphApiContext = {}): SubgraphApiContext {\n return { ...this.context, ...contextOverride }\n }\n\n /**\n * Get the base URLs for the given environment.\n * @param {CowEnv} env The environment to get the base URLs for.\n * @returns {ApiBaseUrls} The base URLs for the given environment.\n */\n private getEnvConfigs(env: CowEnv): SubgraphApiBaseUrls {\n if (this.context.baseUrls) return this.context.baseUrls\n\n return env === 'prod' ? SUBGRAPH_PROD_CONFIG : SUBGRAPH_STAGING_CONFIG\n }\n}\n","import type { SupportedChainId } from '../common'\nimport type { Signer } from '@ethersproject/abstract-signer'\nimport type { TypedDataDomain } from '@cowprotocol/contracts'\nimport type { SigningResult, UnsignedOrder } from './types'\n\nconst getSignUtils = () => import('./utils')\nconst ethersUtils = () => import('ethers/lib/utils')\n\n/**\n * Utility class for signing order intents and cancellations.\n *\n * @remarks This class only supports `eth_sign` and wallet-native EIP-712 signing. For use of\n * `presign` and `eip1271` {@link https://docs.cow.fi/ | see the docs}.\n * @example\n *\n * ```typescript\n * import { OrderSigningUtils, SupportedChainId } from '@cowprotocol/cow-sdk'\n * import { Web3Provider } from '@ethersproject/providers'\n *\n * const account = 'YOUR_WALLET_ADDRESS'\n * const chainId = 100 // Gnosis chain\n * const provider = new Web3Provider(window.ethereum)\n * const signer = provider.getSigner()\n *\n * async function main() {\n * const { order: Order } = { ... }\n * const orderSigningResult = await OrderSigningUtils.signOrder(quote, chainId, signer)\n *\n * const orderId = await orderBookApi.sendOrder({ ...quote, ...orderSigningResult })\n *\n * const order = await orderBookApi.getOrder(orderId)\n *\n * const trades = await orderBookApi.getTrades({ orderId })\n *\n * const orderCancellationSigningResult = await OrderSigningUtils.signOrderCancellations([orderId], chainId, signer)\n *\n * const cancellationResult = await orderBookApi.sendSignedOrderCancellations({...orderCancellationSigningResult, orderUids: [orderId] })\n *\n * console.log('Results: ', { orderId, order, trades, orderCancellationSigningResult, cancellationResult })\n * }\n * ```\n */\nexport class OrderSigningUtils {\n /**\n * Sign the order intent with the specified signer.\n *\n * @remarks If the API reports an error with the signature, it is likely to be due to an incorrectly\n * specified `chainId`. Please ensure that the `chainId` is correct for the network you are\n * using.\n * @param {UnsignedOrder} order The unsigned order intent to be placed.\n * @param {SupportedChainId} chainId The CoW Protocol `chainId` context that's being used.\n * @param {Signer} signer The signer who is placing the order intent.\n * @returns {Promise<SigningResult>} Encoded signature including signing scheme for the order.\n */\n static async signOrder(order: UnsignedOrder, chainId: SupportedChainId, signer: Signer): Promise<SigningResult> {\n const { signOrder } = await getSignUtils()\n return signOrder(order, chainId, signer)\n }\n\n /**\n * Sign a cancellation message of an order intent with the specified signer.\n * @param {string} orderUid The unique identifier of the order to cancel.\n * @param {SupportedChainId} chainId The CoW Protocol `chainid` context that's being used.\n * @param {Signer} signer The signer who initially placed the order intent.\n * @returns {Promise<SigningResult>} Encoded signature including signing scheme for the cancellation.\n */\n static async signOrderCancellation(\n orderUid: string,\n chainId: SupportedChainId,\n signer: Signer\n ): Promise<SigningResult> {\n const { signOrderCancellation } = await getSignUtils()\n return signOrderCancellation(orderUid, chainId, signer)\n }\n\n /**\n * Sign a cancellation message of multiple order intents with the specified signer.\n * @param {string[]} orderUids An array of `orderUid` to cancel.\n * @param {SupportedChainId} chainId The CoW Protocol protocol `chainId` context that's being used.\n * @param {Signer} signer The signer who initially placed the order intents.\n * @returns {Promise<SigningResult>} Encoded signature including signing scheme for the cancellation.\n */\n static async signOrderCancellations(\n orderUids: string[],\n chainId: SupportedChainId,\n signer: Signer\n ): Promise<SigningResult> {\n const { signOrderCancellations } = await getSignUtils()\n return signOrderCancellations(orderUids, chainId, signer)\n }\n\n /**\n * Get the EIP-712 typed domain data being used for signing.\n * @param {SupportedChainId} chainId The CoW Protocol protocol `chainId` context that's being used.\n * @return The EIP-712 typed domain data.\n * @see https://eips.ethereum.org/EIPS/eip-712\n */\n static async getDomain(chainId: SupportedChainId): Promise<TypedDataDomain> {\n const { getDomain } = await getSignUtils()\n return getDomain(chainId)\n }\n\n /**\n * Get the domain separator hash for the EIP-712 typed domain data being used for signing.\n * @param chainId {SupportedChainId} chainId The CoW Protocol protocol `chainId` context that's being used.\n * @returns A string representation of the EIP-712 typed domain data hash.\n */\n static async getDomainSeparator(chainId: SupportedChainId): Promise<string> {\n const { getDomain } = await getSignUtils()\n const { _TypedDataEncoder } = await ethersUtils()\n return _TypedDataEncoder.hashDomain(getDomain(chainId))\n }\n\n /**\n * Get the EIP-712 types used for signing a GPv2Order.Data struct. This is useful for when\n * signing orders using smart contracts, whereby this SDK cannot do the EIP-1271 signing for you.\n * @returns The EIP-712 types used for signing.\n */\n static getEIP712Types(): Record<string, any> {\n return {\n Order: [\n { name: 'sellToken', type: 'address' },\n { name: 'buyToken', type: 'address' },\n { name: 'receiver', type: 'address' },\n { name: 'sellAmount', type: 'uint256' },\n { name: 'buyAmount', type: 'uint256' },\n { name: 'validTo', type: 'uint32' },\n { name: 'appData', type: 'bytes32' },\n { name: 'feeAmount', type: 'uint256' },\n { name: 'kind', type: 'string' },\n { name: 'partiallyFillable', type: 'bool' },\n { name: 'sellTokenBalance', type: 'string' },\n { name: 'buyTokenBalance', type: 'string' },\n ],\n }\n }\n}\n","import { OrderBookApi } from '../order-book'\nimport { SupportedChainId } from '../common'\nimport { GPv2Order } from './generated/ComposableCoW'\nimport { providers } from 'ethers'\n\nexport interface ConditionalOrderArguments<T> {\n handler: string\n data: T\n salt?: string\n hasOffChainInput?: boolean\n}\n\nexport type ConditionalOrderParams = {\n readonly handler: string\n readonly salt: string\n readonly staticInput: string\n}\n\nexport enum ProofLocation {\n // The location of the proofs is private to the caller.\n PRIVATE = 0,\n // The `data` field of the emitted `Proof` struct contains proofs + conditional order parameters.\n EMITTED = 1,\n // The `data` field of the emitted `Proof` struct contains the Swarm address (`bytes32`) of the proofs + conditional order parameters.\n SWARM = 2,\n // The `data` field is set to TBD.\n WAKU = 3,\n // The `data` field is set to TBD\n RESERVED = 4,\n // The `data` field of the emitted `Proof` struct contains the IPFS address (`bytes32`) of the proofs + conditional order parameters.\n IPFS = 5,\n}\n\n/**\n * A factory and it's arguments that are called at transaction mining time to generate the context\n * for a conditional order(s).\n *\n * This allows to support the case where conditional orders may want to *commence* validity at the\n * time of transaction mining, like in the case of a `TWAP` executed by a DAO or `Safe` that takes\n * a reasonable amount of time to aggregate signatures or collect votes.\n *\n * @remarks This is used in conjunction with `setRootWithContext` or `createWithContext`.\n */\nexport type ContextFactory = {\n // The address of the `IValueFactory` that will be used to resolve the context.\n address: string\n // Any arguments that will be passed to the `IValueFactory` to resolve the context.\n factoryArgs?: {\n args: unknown[]\n argsType: string[]\n }\n}\n\n/**\n * A struct for a proof that can be used with `setRoot` and `setRootWithContext` on a\n * ComposableCoW-enabled Safe.\n */\nexport type ProofStruct = {\n // The location of the proof.\n location: ProofLocation\n // The data for the proof.\n data: string | '0x'\n}\n\n/**\n * Payload for emitting a merkle root to a ComposableCoW-enabled Safe.\n *\n * If setting `ProofLocation.EMITTED`, this type should be used as the `data` in the `Proof` struct.\n */\nexport type PayloadLocationEmitted = {\n // An array of conditional orders and their proofs.\n proofs: ProofWithParams[]\n}\n\n/**\n * A proof for a conditional order and it's parameters.\n */\nexport type ProofWithParams = {\n // The proof for the Merkle tree that contains the conditional order.\n proof: string[]\n // The parameters as expected by ABI encoding.\n params: ConditionalOrderParams\n}\n\nexport type OwnerContext = {\n owner: string\n chainId: SupportedChainId\n provider: providers.Provider\n}\n\nexport type PollParams = OwnerContext & {\n orderBookApi: OrderBookApi\n offchainInput?: string\n proof?: string[]\n\n /**\n * If present, it can be used for custom conditional order validations. If not present, the orders will need to get the block info themselves\n */\n blockInfo?: BlockInfo\n}\n\nexport type BlockInfo = {\n blockNumber: number\n blockTimestamp: number\n}\n\nexport type PollResult = PollResultSuccess | PollResultErrors\n\nexport type PollResultErrors =\n | PollResultTryNextBlock\n | PollResultTryOnBlock\n | PollResultTryAtEpoch\n | PollResultUnexpectedError\n | PollResultDontTryAgain\n\nexport enum PollResultCode {\n SUCCESS = 'SUCCESS',\n UNEXPECTED_ERROR = 'UNEXPECTED_ERROR',\n TRY_NEXT_BLOCK = 'TRY_NEXT_BLOCK',\n TRY_ON_BLOCK = 'TRY_ON_BLOCK',\n TRY_AT_EPOCH = 'TRY_AT_EPOCH',\n DONT_TRY_AGAIN = 'DONT_TRY_AGAIN',\n}\nexport interface PollResultSuccess {\n readonly result: PollResultCode.SUCCESS\n readonly order: GPv2Order.DataStruct\n readonly signature: string\n}\n\nexport interface PollResultUnexpectedError {\n readonly result: PollResultCode.UNEXPECTED_ERROR\n readonly error: unknown\n reason?: string\n}\n\nexport interface PollResultTryNextBlock {\n readonly result: PollResultCode.TRY_NEXT_BLOCK\n reason?: string\n}\n\nexport interface PollResultTryOnBlock {\n readonly result: PollResultCode.TRY_ON_BLOCK\n readonly blockNumber: number\n reason?: string\n}\n\nexport interface PollResultTryAtEpoch {\n readonly result: PollResultCode.TRY_AT_EPOCH\n /**\n * The epoch after which it is ok to retry to to poll this order.\n * The value is expressed as a Unix timestamp (in seconds).\n *\n * This epoch will be inclusive, meaning that it is ok to retry at the block mined precisely at this epoch or later.\n */\n readonly epoch: number\n reason?: string\n}\n\nexport interface PollResultDontTryAgain {\n readonly result: PollResultCode.DONT_TRY_AGAIN\n reason?: string\n}\n\nexport type IsValidResult = IsValid | IsNotValid\nexport interface IsValid {\n isValid: true\n}\nexport interface IsNotValid {\n isValid: false\n reason: string\n}\n","/* Autogenerated file. Do not edit manually. */\n/* tslint:disable */\n/* eslint-disable */\n\nimport { Contract, Signer, utils } from \"ethers\";\nimport type { Provider } from \"@ethersproject/providers\";\nimport type { ComposableCoW, ComposableCoWInterface } from \"../ComposableCoW\";\n\nconst _abi = [\n {\n inputs: [\n {\n internalType: \"address\",\n name: \"_settlement\",\n type: \"address\",\n },\n ],\n stateMutability: \"nonpayable\",\n type: \"constructor\",\n },\n {\n inputs: [],\n name: \"InterfaceNotSupported\",\n type: \"error\",\n },\n {\n inputs: [],\n name: \"InvalidHandler\",\n type: \"error\",\n },\n {\n inputs: [],\n name: \"ProofNotAuthed\",\n type: \"error\",\n },\n {\n inputs: [],\n name: \"SingleOrderNotAuthed\",\n type: \"error\",\n },\n {\n inputs: [],\n name: \"SwapGuardRestricted\",\n type: \"error\",\n },\n {\n anonymous: false,\n inputs: [\n {\n indexed: true,\n internalType: \"address\",\n name: \"owner\",\n type: \"address\",\n },\n {\n components: [\n {\n internalType: \"contract IConditionalOrder\",\n name: \"handler\",\n type: \"address\",\n },\n {\n internalType: \"bytes32\",\n name: \"salt\",\n type: \"bytes32\",\n },\n {\n internalType: \"bytes\",\n name: \"staticInput\",\n type: \"bytes\",\n },\n ],\n indexed: false,\n internalType: \"struct IConditionalOrder.ConditionalOrderParams\",\n name: \"params\",\n type: \"tuple\",\n },\n ],\n name: \"ConditionalOrderCreated\",\n type: \"event\",\n },\n {\n anonymous: false,\n inputs: [\n {\n indexed: true,\n internalType: \"address\",\n name: \"owner\",\n type: \"address\",\n },\n {\n indexed: false,\n internalType: \"bytes32\",\n name: \"root\",\n type: \"bytes32\",\n },\n {\n components: [\n {\n internalType: \"uint256\",\n name: \"location\",\n type: \"uint256\",\n },\n {\n internalType: \"bytes\",\n name: \"data\",\n type: \"bytes\",\n },\n ],\n indexed: false,\n internalType: \"struct ComposableCoW.Proof\",\n name: \"proof\",\n type: \"tuple\",\n },\n ],\n name: \"MerkleRootSet\",\n type: \"event\",\n },\n {\n anonymous: false,\n inputs: [\n {\n indexed: true,\n internalType: \"address\",\n name: \"owner\",\n type: \"address\",\n },\n {\n indexed: false,\n internalType: \"contract ISwapGuard\",\n name: \"swapGuard\",\n type: \"address\",\n },\n ],\n name: \"SwapGuardSet\",\n type: \"event\",\n },\n {\n inputs: [\n {\n internalType: \"address\",\n name: \"\",\n type: \"address\",\n },\n {\n internalType: \"bytes32\",\n name: \"\",\n type: \"bytes32\",\n },\n ],\n name: \"cabinet\",\n outputs: [\n {\n internalType: \"bytes32\",\n name: \"\",\n type: \"bytes32\",\n },\n ],\n stateMutability: \"view\",\n type: \"function\",\n },\n {\n inputs: [\n {\n components: [\n {\n internalType: \"contract IConditionalOrder\",\n name: \"handler\",\n type: \"address\",\n },\n {\n internalType: \"bytes32\",\n name: \"salt\",\n type: \"bytes32\",\n },\n {\n internalType: \"bytes\",\n name: \"staticInput\",\n type: \"bytes\",\n },\n ],\n internalType: \"struct IConditionalOrder.ConditionalOrderParams\",\n name: \"params\",\n type: \"tuple\",\n },\n {\n internalType: \"bool\",\n name: \"dispatch\",\n type: \"bool\",\n },\n ],\n name: \"create\",\n outputs: [],\n stateMutability: \"nonpayable\",\n type: \"function\",\n },\n {\n inputs: [\n {\n components: [\n {\n internalType: \"contract IConditionalOrder\",\n name: \"handler\",\n type: \"address\",\n },\n {\n internalType: \"bytes32\",\n name: \"salt\",\n type: \"bytes32\",\n },\n {\n internalType: \"bytes\",\n name: \"staticInput\",\n type: \"bytes\",\n },\n ],\n internalType: \"struct IConditionalOrder.ConditionalOrderParams\",\n name: \"params\",\n type: \"tuple\",\n },\n {\n internalType: \"contract IValueFactory\",\n name: \"factory\",\n type: \"address\",\n },\n {\n internalType: \"bytes\",\n name: \"data\",\n type: \"bytes\",\n },\n {\n internalType: \"bool\",\n name: \"dispatch\",\n type: \"bool\",\n },\n ],\n name: \"createWithContext\",\n outputs: [],\n stateMutability: \"nonpayable\",\n type: \"function\",\n },\n {\n inputs: [],\n name: \"domainSeparator\",\n outputs: [\n {\n internalType: \"bytes32\",\n name: \"\",\n type: \"bytes32\",\n },\n ],\n stateMutability: \"view\",\n type: \"function\",\n },\n {\n inputs: [\n {\n internalType: \"address\",\n name: \"owner\",\n type: \"address\",\n },\n {\n components: [\n {\n internalType: \"contract IConditionalOrder\",\n name: \"handler\",\n type: \"address\",\n },\n {\n internalType: \"bytes32\",\n name: \"salt\",\n type: \"bytes32\",\n },\n {\n internalType: \"bytes\",\n name: \"staticInput\",\n type: \"bytes\",\n },\n ],\n internalType: \"struct IConditionalOrder.ConditionalOrderParams\",\n name: \"params\",\n type: \"tuple\",\n },\n {\n internalType: \"bytes\",\n name: \"offchainInput\",\n type: \"bytes\",\n },\n {\n internalType: \"bytes32[]\",\n name: \"proof\",\n type: \"bytes32[]\",\n },\n ],\n name: \"getTradeableOrderWithSignature\",\n outputs: [\n {\n components: [\n {\n internalType: \"contract IERC20\",\n name: \"sellToken\",\n type: \"address\",\n },\n {\n internalType: \"contract IERC20\",\n name: \"buyToken\",\n type: \"address\",\n },\n {\n internalType: \"address\",\n name: \"receiver\",\n type: \"address\",\n },\n {\n internalType: \"uint256\",\n name: \"sellAmount\",\n type: \"uint256\",\n },\n {\n internalType: \"uint256\",\n name: \"buyAmount\",\n type: \"uint256\",\n },\n {\n internalType: \"uint32\",\n name: \"validTo\",\n type: \"uint32\",\n },\n {\n internalType: \"bytes32\",\n name: \"appData\",\n type: \"bytes32\",\n },\n {\n internalType: \"uint256\",\n name: \"feeAmount\",\n type: \"uint256\",\n },\n {\n internalType: \"bytes32\",\n name: \"kind\",\n type: \"bytes32\",\n },\n {\n internalType: \"bool\",\n name: \"partiallyFillable\",\n type: \"bool\",\n },\n {\n internalType: \"bytes32\",\n name: \"sellTokenBalance\",\n type: \"bytes32\",\n },\n {\n internalType: \"bytes32\",\n name: \"buyTokenBalance\",\n type: \"bytes32\",\n },\n ],\n internalType: \"struct GPv2Order.Data\",\n name: \"order\",\n type: \"tuple\",\n },\n {\n internalType: \"bytes\",\n name: \"signature\",\n type: \"bytes\",\n },\n ],\n stateMutability: \"view\",\n type: \"function\",\n },\n {\n inputs: [\n {\n components: [\n {\n internalType: \"contract IConditionalOrder\",\n name: \"handler\",\n type: \"address\",\n },\n {\n internalType: \"bytes32\",\n name: \"salt\",\n type: \"bytes32\",\n },\n {\n internalType: \"bytes\",\n name: \"staticInput\",\n type: \"bytes\",\n },\n ],\n internalType: \"struct IConditionalOrder.ConditionalOrderParams\",\n name: \"params\",\n type: \"tuple\",\n },\n ],\n name: \"hash\",\n outputs: [\n {\n internalType: \"bytes32\",\n name: \"\",\n type: \"bytes32\",\n },\n ],\n stateMutability: \"pure\",\n type: \"function\",\n },\n {\n inputs: [\n {\n internalType: \"contract Safe\",\n name: \"safe\",\n type: \"address\",\n },\n {\n internalType: \"address\",\n name: \"sender\",\n type: \"address\",\n },\n {\n internalType: \"bytes32\",\n name: \"_hash\",\n type: \"bytes32\",\n },\n {\n internalType: \"bytes32\",\n name: \"_domainSeparator\",\n type: \"bytes32\",\n },\n {\n internalType: \"bytes32\",\n name: \"\",\n type: \"bytes32\",\n },\n {\n internalType: \"bytes\",\n name: \"encodeData\",\n type: \"bytes\",\n },\n {\n internalType: \"bytes\",\n name: \"payload\",\n type: \"bytes\",\n },\n ],\n name: \"isValidSafeSignature\",\n outputs: [\n {\n internalType: \"bytes4\",\n name: \"magic\",\n type: \"bytes4\",\n },\n ],\n stateMutability: \"view\",\n type: \"function\",\n },\n {\n inputs: [\n {\n internalType: \"bytes32\",\n name: \"singleOrderHash\",\n type: \"bytes32\",\n },\n ],\n name: \"remove\",\n outputs: [],\n stateMutability: \"nonpayable\",\n type: \"function\",\n },\n {\n inputs: [\n {\n internalType: \"address\",\n name: \"\",\n type: \"address\",\n },\n ],\n name: \"roots\",\n outputs: [\n {\n internalType: \"bytes32\",\n name: \"\",\n type: \"bytes32\",\n },\n ],\n stateMutability: \"view\",\n type: \"function\",\n },\n {\n inputs: [\n {\n internalType: \"bytes32\",\n name: \"root\",\n type: \"bytes32\",\n },\n {\n components: [\n {\n internalType: \"uint256\",\n name: \"location\",\n type: \"uint256\",\n },\n {\n internalType: \"bytes\",\n name: \"data\",\n type: \"bytes\",\n },\n ],\n internalType: \"struct ComposableCoW.Proof\",\n name: \"proof\",\n type: \"tuple\",\n },\n ],\n name: \"setRoot\",\n outputs: [],\n stateMutability: \"nonpayable\",\n type: \"function\",\n },\n {\n inputs: [\n {\n internalType: \"bytes32\",\n name: \"root\",\n type: \"bytes32\",\n },\n {\n components: [\n {\n internalType: \"uint256\",\n name: \"location\",\n type: \"uint256\",\n },\n {\n internalType: \"bytes\",\n name: \"data\",\n type: \"bytes\",\n },\n ],\n internalType: \"struct ComposableCoW.Proof\",\n name: \"proof\",\n type: \"tuple\",\n },\n {\n internalType: \"contract IValueFactory\",\n name: \"factory\",\n type: \"address\",\n },\n {\n internalType: \"bytes\",\n name: \"data\",\n type: \"bytes\",\n },\n ],\n name: \"setRootWithContext\",\n outputs: [],\n stateMutability: \"nonpayable\",\n type: \"function\",\n },\n {\n inputs: [\n {\n internalType: \"contract ISwapGuard\",\n name: \"swapGuard\",\n type: \"address\",\n },\n ],\n name: \"setSwapGuard\",\n outputs: [],\n stateMutability: \"nonpayable\",\n type: \"function\",\n },\n {\n inputs: [\n {\n internalType: \"address\",\n name: \"\",\n type: \"address\",\n },\n {\n internalType: \"bytes32\",\n name: \"\",\n type: \"bytes32\",\n },\n ],\n name: \"singleOrders\",\n outputs: [\n {\n internalType: \"bool\",\n name: \"\",\n type: \"bool\",\n },\n ],\n stateMutability: \"view\",\n type: \"function\",\n },\n {\n inputs: [\n {\n internalType: \"address\",\n name: \"\",\n type: \"address\",\n },\n ],\n name: \"swapGuards\",\n outputs: [\n {\n internalType: \"contract ISwapGuard\",\n name: \"\",\n type: \"address\",\n },\n ],\n stateMutability: \"view\",\n type: \"function\",\n },\n] as const;\n\nexport class ComposableCoW__factory {\n static readonly abi = _abi;\n static createInterface(): ComposableCoWInterface {\n return new utils.Interface(_abi) as ComposableCoWInterface;\n }\n static connect(\n address: string,\n signerOrProvider: Signer | Provider\n ): ComposableCoW {\n return new Contract(address, _abi, signerOrProvider) as ComposableCoW;\n }\n}\n","/* Autogenerated file. Do not edit manually. */\n/* tslint:disable */\n/* eslint-disable */\n\nimport { Contract, Signer, utils } from \"ethers\";\nimport type { Provider } from \"@ethersproject/providers\";\nimport type {\n ExtensibleFallbackHandler,\n ExtensibleFallbackHandlerInterface,\n} from \"../ExtensibleFallbackHandler\";\n\nconst _abi = [\n {\n anonymous: false,\n inputs: [\n {\n indexed: true,\n internalType: \"contract Safe\",\n name: \"safe\",\n type: \"address\",\n },\n {\n indexed: false,\n internalType: \"bytes32\",\n name: \"domainSeparator\",\n type: \"bytes32\",\n },\n {\n indexed: false,\n internalType: \"contract ISafeSignatureVerifier\",\n name: \"verifier\",\n type: \"address\",\n },\n ],\n name: \"AddedDomainVerifier\",\n type: \"event\",\n },\n {\n anonymous: false,\n inputs: [\n {\n indexed: true,\n internalType: \"contract Safe\",\n name: \"safe\",\n type: \"address\",\n },\n {\n indexed: false,\n internalType: \"bytes4\",\n name: \"interfaceId\",\n type: \"bytes4\",\n },\n ],\n name: \"AddedInterface\",\n type: \"event\",\n },\n {\n anonymous: false,\n inputs: [\n {\n indexed: true,\n internalType: \"contract Safe\",\n name: \"safe\",\n type: \"address\",\n },\n {\n indexed: false,\n internalType: \"bytes4\",\n name: \"selector\",\n type: \"bytes4\",\n },\n {\n indexed: false,\n internalType: \"bytes32\",\n name: \"method\",\n type: \"bytes32\",\n },\n ],\n name: \"AddedSafeMethod\",\n type: \"event\",\n },\n {\n anonymous: false,\n inputs: [\n {\n indexed: true,\n internalType: \"contract Safe\",\n name: \"safe\",\n type: \"address\",\n },\n {\n indexed: false,\n internalType: \"bytes32\",\n name: \"domainSeparator\",\n type: \"bytes32\",\n },\n {\n indexed: false,\n internalType: \"contract ISafeSignatureVerifier\",\n name: \"oldVerifier\",\n type: \"address\",\n },\n {\n indexed: false,\n internalType: \"contract ISafeSignatureVerifier\",\n name: \"newVerifier\",\n type: \"address\",\n },\n ],\n name: \"ChangedDomainVerifier\",\n type: \"event\",\n },\n {\n anonymous: false,\n inputs: [\n {\n indexed: true,\n internalType: \"contract Safe\",\n name: \"safe\",\n type: \"address\",\n },\n {\n indexed: false,\n internalType: \"bytes4\",\n name: \"selector\",\n type: \"bytes4\",\n },\n {\n indexed: false,\n internalType: \"bytes32\",\n name: \"oldMethod\",\n type: \"bytes32\",\n },\n {\n indexed: false,\n internalType: \"bytes32\",\n name: \"newMethod\",\n type: \"bytes32\",\n },\n ],\n name: \"ChangedSafeMethod\",\n type: \"event\",\n },\n {\n anonymous: false,\n inputs: [\n {\n indexed: true,\n internalType: \"contract Safe\",\n name: \"safe\",\n type: \"address\",\n },\n {\n indexed: false,\n internalType: \"bytes32\",\n name: \"domainSeparator\",\n type: \"bytes32\",\n },\n ],\n name: \"RemovedDomainVerifier\",\n type: \"event\",\n },\n {\n anonymous: false,\n inputs: [\n {\n indexed: true,\n internalType: \"contract Safe\",\n name: \"safe\",\n type: \"address\",\n },\n {\n indexed: false,\n internalType: \"bytes4\",\n name: \"interfaceId\",\n type: \"bytes4\",\n },\n ],\n name: \"RemovedInterface\",\n type: \"event\",\n },\n {\n anonymous: false,\n inputs: [\n {\n indexed: true,\n internalType: \"contract Safe\",\n name: \"safe\",\n type: \"address\",\n },\n {\n indexed: false,\n internalType: \"bytes4\",\n name: \"selector\",\n type: \"bytes4\",\n },\n ],\n name: \"RemovedSafeMethod\",\n type: \"event\",\n },\n {\n stateMutability: \"nonpayable\",\n type: \"fallback\",\n },\n {\n inputs: [\n {\n internalType: \"contract Safe\",\n name: \"\",\n type: \"address\",\n },\n {\n internalType: \"bytes32\",\n name: \"\",\n type: \"bytes32\",\n },\n ],\n name: \"domainVerifiers\",\n outputs: [\n {\n internalType: \"contract ISafeSignatureVerifier\",\n name: \"\",\n type: \"address\",\n },\n ],\n stateMutability: \"view\",\n type: \"function\",\n },\n {\n inputs: [\n {\n internalType: \"bytes32\",\n name: \"_hash\",\n type: \"bytes32\",\n },\n {\n internalType: \"bytes\",\n name: \"signature\",\n type: \"bytes\",\n },\n ],\n name: \"isValidSignature\",\n outputs: [\n {\n internalType: \"bytes4\",\n name: \"magic\",\n type: \"bytes4\",\n },\n ],\n stateMutability: \"view\",\n type: \"function\",\n },\n {\n inputs: [\n {\n internalType: \"address\",\n name: \"\",\n type: \"address\",\n },\n {\n internalType: \"address\",\n name: \"\",\n type: \"address\",\n },\n {\n internalType: \"uint256[]\",\n name: \"\",\n type: \"uint256[]\",\n },\n {\n internalType: \"uint256[]\",\n name: \"\",\n type: \"uint256[]\",\n },\n {\n internalType: \"bytes\",\n name: \"\",\n type: \"bytes\",\n },\n ],\n name: \"onERC1155BatchReceived\",\n outputs: [\n {\n internalType: \"bytes4\",\n name: \"\",\n type: \"bytes4\",\n },\n ],\n stateMutability: \"pure\",\n type: \"function\",\n },\n {\n inputs: [\n {\n internalType: \"address\",\n name: \"\",\n type: \"address\",\n },\n {\n internalType: \"address\",\n name: \"\",\n type: \"address\",\n },\n {\n internalType: \"uint256\",\n name: \"\",\n type: \"uint256\",\n },\n {\n internalType: \"uint256\",\n name: \"\",\n type: \"uint256\",\n },\n {\n internalType: \"bytes\",\n name: \"\",\n type: \"bytes\",\n },\n ],\n name: \"onERC1155Received\",\n outputs: [\n {\n internalType: \"bytes4\",\n name: \"\",\n type: \"bytes4\",\n },\n ],\n stateMutability: \"pure\",\n type: \"function\",\n },\n {\n inputs: [\n {\n internalType: \"address\",\n name: \"\",\n type: \"address\",\n },\n {\n internalType: \"address\",\n name: \"\",\n type: \"address\",\n },\n {\n internalType: \"uint256\",\n name: \"\",\n type: \"uint256\",\n },\n {\n internalType: \"bytes\",\n name: \"\",\n type: \"bytes\",\n },\n ],\n name: \"onERC721Received\",\n outputs: [\n {\n internalType: \"bytes4\",\n name: \"\",\n type: \"bytes4\",\n },\n ],\n stateMutability: \"pure\",\n type: \"function\",\n },\n {\n inputs: [\n {\n internalType: \"contract Safe\",\n name: \"\",\n type: \"address\",\n },\n {\n internalType: \"bytes4\",\n name: \"\",\n type: \"bytes4\",\n },\n ],\n name: \"safeInterfaces\",\n outputs: [\n {\n internalType: \"bool\",\n name: \"\",\n type: \"bool\",\n },\n ],\n stateMutability: \"view\",\n type: \"function\",\n },\n {\n inputs: [\n {\n internalType: \"contract Safe\",\n name: \"\",\n type: \"address\",\n },\n {\n internalType: \"bytes4\",\n name: \"\",\n type: \"bytes4\",\n },\n ],\n name: \"safeMethods\",\n outputs: [\n {\n internalType: \"bytes32\",\n name: \"\",\n type: \"bytes32\",\n },\n ],\n stateMutability: \"view\",\n type: \"function\",\n },\n {\n inputs: [\n {\n internalType: \"bytes32\",\n name: \"domainSeparator\",\n type: \"bytes32\",\n },\n {\n internalType: \"contract ISafeSignatureVerifier\",\n name: \"newVerifier\",\n type: \"address\",\n },\n ],\n name: \"setDomainVerifier\",\n outputs: [],\n stateMutability: \"nonpayable\",\n type: \"function\",\n },\n {\n inputs: [\n {\n internalType: \"bytes4\",\n name: \"selector\",\n type: \"bytes4\",\n },\n {\n internalType: \"bytes32\",\n name: \"newMethod\",\n type: \"bytes32\",\n },\n ],\n name: \"setSafeMethod\",\n outputs: [],\n stateMutability: \"nonpayable\",\n type: \"function\",\n },\n {\n inputs: [\n {\n internalType: \"bytes4\",\n name: \"interfaceId\",\n type: \"bytes4\",\n },\n {\n internalType: \"bool\",\n name: \"supported\",\n type: \"bool\",\n },\n ],\n name: \"setSupportedInterface\",\n outputs: [],\n stateMutability: \"nonpayable\",\n type: \"function\",\n },\n {\n inputs: [\n {\n internalType: \"bytes4\",\n name: \"_interfaceId\",\n type: \"bytes4\",\n },\n {\n internalType: \"bytes32[]\",\n name: \"handlerWithSelectors\",\n type: \"bytes32[]\",\n },\n ],\n name: \"setSupportedInterfaceBatch\",\n outputs: [],\n stateMutability: \"nonpayable\",\n type: \"function\",\n },\n {\n inputs: [\n {\n internalType: \"bytes4\",\n name: \"interfaceId\",\n type: \"bytes4\",\n },\n ],\n name: \"supportsInterface\",\n outputs: [\n {\n internalType: \"bool\",\n name: \"\",\n type: \"bool\",\n },\n ],\n stateMutability: \"view\",\n type: \"function\",\n },\n] as const;\n\nexport class ExtensibleFallbackHandler__factory {\n static readonly abi = _abi;\n static createInterface(): ExtensibleFallbackHandlerInterface {\n return new utils.Interface(_abi) as ExtensibleFallbackHandlerInterface;\n }\n static connect(\n address: string,\n signerOrProvider: Signer | Provider\n ): ExtensibleFallbackHandler {\n return new Contract(\n address,\n _abi,\n signerOrProvider\n ) as ExtensibleFallbackHandler;\n }\n}\n","import { utils, providers, BigNumber } from 'ethers'\nimport {\n COMPOSABLE_COW_CONTRACT_ADDRESS,\n EXTENSIBLE_FALLBACK_HANDLER_CONTRACT_ADDRESS,\n SupportedChainId,\n} from '../common'\nimport { ExtensibleFallbackHandler__factory } from './generated'\nimport { BlockInfo, ConditionalOrderParams } from './types'\nimport { Order, OrderBalance, OrderKind } from '@cowprotocol/contracts'\nimport { GPv2Order } from './generated/ComposableCoW'\n\nconst ERC20_BALANCE_VALUES = ['erc20', '0x5a28e9363bb942b639270062aa6bb295f434bcdfc42c97267bf003f272060dc9']\nconst EXTERNAL_BALANCE_VALUES = ['external', '0xabee3b73373acd583a130924aad6dc38cfdc44ba0555ba94ce2ff63980ea0632']\nconst INTERNAL_BALANCE_VALUES = ['internal', '0x4ac99ace14ee0a5ef932dc609df0943ab7ac16b7583634612f8dc35a4289a6ce']\nconst SELL_KIND_VALUES = ['sell', '0xf3b277728b3fee749481eb3e0b3b48980dbbab78658fc419025cb16eee346775']\nconst BUY_KIND_VALUES = ['buy', '0x6ed88e868af0a1983e3886d5f3e95a2fafbd6c3450bc229e27342283dc429ccc']\n\n// Define the ABI tuple for the ConditionalOrderParams struct\nexport const CONDITIONAL_ORDER_PARAMS_ABI = ['tuple(address handler, bytes32 salt, bytes staticInput)']\n\nexport const DEFAULT_TOKEN_FORMATTER = (address: string, amount: BigNumber) => `${amount}@${address}`\n\nexport function isExtensibleFallbackHandler(handler: string, chainId: SupportedChainId): boolean {\n return handler === EXTENSIBLE_FALLBACK_HANDLER_CONTRACT_ADDRESS[chainId]\n}\n\nexport function isComposableCow(handler: string, chainId: SupportedChainId): boolean {\n return handler === COMPOSABLE_COW_CONTRACT_ADDRESS[chainId]\n}\n\nexport async function getDomainVerifier(\n safe: string,\n domain: string,\n chainId: SupportedChainId,\n provider: providers.Provider\n): Promise<string> {\n const contract = ExtensibleFallbackHandler__factory.connect(\n EXTENSIBLE_FALLBACK_HANDLER_CONTRACT_ADDRESS[chainId],\n provider\n )\n return await contract.callStatic.domainVerifiers(safe, domain)\n}\n\nexport function createSetDomainVerifierTx(domain: string, verifier: string): string {\n return ExtensibleFallbackHandler__factory.createInterface().encodeFunctionData('setDomainVerifier', [\n domain,\n verifier,\n ])\n}\n\n/**\n * Encode the `ConditionalOrderParams` for the conditional order.\n *\n * @param params The `ConditionalOrderParams` struct representing the conditional order as taken from a merkle tree.\n * @returns The ABI-encoded conditional order.\n * @see ConditionalOrderParams\n */\nexport function encodeParams(params: ConditionalOrderParams): string {\n return utils.defaultAbiCoder.encode(CONDITIONAL_ORDER_PARAMS_ABI, [params])\n}\n\n/**\n * Decode the `ConditionalOrderParams` for the conditional order.\n *\n * @param encoded The encoded conditional order.\n * @returns The decoded conditional order.\n */\nexport function decodeParams(encoded: string): ConditionalOrderParams {\n const { handler, salt, staticInput } = utils.defaultAbiCoder.decode(CONDITIONAL_ORDER_PARAMS_ABI, encoded)[0]\n return { handler, salt, staticInput }\n}\n\n/**\n * Helper method for validating ABI types.\n * @param types ABI types to validate against.\n * @param values The values to validate.\n * @returns {boolean} Whether the values are valid ABI for the given types.\n */\nexport function isValidAbi(types: readonly (string | utils.ParamType)[], values: any[]): boolean {\n try {\n utils.defaultAbiCoder.encode(types, values)\n } catch (e) {\n return false\n }\n return true\n}\n\nexport async function getBlockInfo(provider: providers.Provider): Promise<BlockInfo> {\n const block = await provider.getBlock('latest')\n\n return {\n blockNumber: block.number,\n blockTimestamp: block.timestamp,\n }\n}\n\nexport function formatEpoch(epoch: number): string {\n return new Date(epoch * 1000).toISOString()\n}\n\n/**\n * Convert a balance source/destination hash to a string\n *\n * @param balance balance source/destination hash\n * @returns string representation of the balance\n * @throws if the balance is not recognized\n */\nfunction balanceToString(balance: string) {\n if (ERC20_BALANCE_VALUES.includes(balance)) {\n return OrderBalance.ERC20\n } else if (EXTERNAL_BALANCE_VALUES.includes(balance)) {\n return OrderBalance.EXTERNAL\n } else if (INTERNAL_BALANCE_VALUES.includes(balance)) {\n return OrderBalance.INTERNAL\n } else {\n throw new Error(`Unknown balance type: ${balance}`)\n }\n}\n\n/**\n * Convert an order kind hash to a string\n * @param kind of order in hash format\n * @returns string representation of the order kind\n */\nfunction kindToString(kind: string) {\n if (SELL_KIND_VALUES.includes(kind)) {\n return OrderKind.SELL\n } else if (BUY_KIND_VALUES.includes(kind)) {\n return OrderKind.BUY\n } else {\n throw new Error(`Unknown kind: ${kind}`)\n }\n}\n\nexport function fromStructToOrder(order: GPv2Order.DataStruct): Order {\n const {\n sellToken,\n sellAmount,\n buyToken,\n buyAmount,\n buyTokenBalance,\n sellTokenBalance,\n feeAmount,\n kind,\n receiver,\n validTo,\n partiallyFillable,\n appData,\n } = order\n\n return {\n sellToken,\n sellAmount,\n buyToken,\n buyAmount,\n feeAmount,\n receiver,\n partiallyFillable,\n appData,\n validTo: Number(validTo),\n kind: kindToString(kind.toString()),\n sellTokenBalance: balanceToString(sellTokenBalance.toString()),\n buyTokenBalance: balanceToString(buyTokenBalance.toString()),\n }\n}\n","import { providers } from 'ethers'\nimport { COMPOSABLE_COW_CONTRACT_ADDRESS, SupportedChainId } from '../common'\nimport { ComposableCoW, ComposableCoW__factory } from './generated'\nimport { ComposableCoWInterface } from './generated/ComposableCoW'\n\nlet composableCowInterfaceCache: ComposableCoWInterface | undefined\nlet composableCowContractCache: ComposableCoW | undefined\n\nexport function getComposableCowInterface(): ComposableCoWInterface {\n if (!composableCowInterfaceCache) {\n composableCowInterfaceCache = ComposableCoW__factory.createInterface()\n }\n\n return composableCowInterfaceCache\n}\n\nexport function getComposableCow(chain: SupportedChainId, provider: providers.Provider): ComposableCoW {\n if (!composableCowContractCache) {\n composableCowContractCache = ComposableCoW__factory.connect(COMPOSABLE_COW_CONTRACT_ADDRESS[chain], provider)\n }\n\n return composableCowContractCache\n}\n","import { BigNumber, constants, ethers, utils } from 'ethers'\nimport { GPv2Order, IConditionalOrder } from './generated/ComposableCoW'\n\nimport { decodeParams, encodeParams, fromStructToOrder } from './utils'\nimport {\n ConditionalOrderArguments,\n ConditionalOrderParams,\n ContextFactory,\n IsValidResult,\n OwnerContext,\n PollParams,\n PollResult,\n PollResultCode,\n PollResultErrors,\n} from './types'\nimport { getComposableCow, getComposableCowInterface } from './contracts'\nimport { UID } from '../order-book'\nimport { computeOrderUid } from '../utils'\n\n/**\n * An abstract base class from which all conditional orders should inherit.\n *\n * This class provides some basic functionality to help with handling conditional orders,\n * such as:\n * - Validating the conditional order\n * - Creating a human-readable string representation of the conditional order\n * - Serializing the conditional order for use with the `IConditionalOrder` struct\n * - Getting any dependencies for the conditional order\n * - Getting the off-chain input for the conditional order\n *\n * **NOTE**: Instances of conditional orders have an `id` property that is a `keccak256` hash of\n * the serialized conditional order.\n */\nexport abstract class ConditionalOrder<D, S> {\n public readonly handler: string\n public readonly salt: string\n public readonly data: D\n public readonly staticInput: S\n public readonly hasOffChainInput: boolean\n\n /**\n * A constructor that provides some basic validation for the conditional order.\n *\n * This constructor **MUST** be called by any class that inherits from `ConditionalOrder`.\n *\n * **NOTE**: The salt is optional and will be randomly generated if not provided.\n * @param handler The address of the handler for the conditional order.\n * @param salt A 32-byte string used to salt the conditional order.\n * @param data The data of the order\n * @param hasOffChainInput Whether the conditional order has off-chain input.\n * @throws If the handler is not a valid ethereum address.\n * @throws If the salt is not a valid 32-byte string.\n */\n constructor(params: ConditionalOrderArguments<D>) {\n const { handler, salt = utils.keccak256(utils.randomBytes(32)), data, hasOffChainInput = false } = params\n // Verify input to the constructor\n // 1. Verify that the handler is a valid ethereum address\n if (!ethers.utils.isAddress(handler)) {\n throw new Error(`Invalid handler: ${handler}`)\n }\n\n // 2. Verify that the salt is a valid 32-byte string usable with ethers\n if (!ethers.utils.isHexString(salt) || ethers.utils.hexDataLength(salt) !== 32) {\n throw new Error(`Invalid salt: ${salt}`)\n }\n\n this.handler = handler\n this.salt = salt\n this.data = data\n this.staticInput = this.transformDataToStruct(data)\n\n this.hasOffChainInput = hasOffChainInput\n }\n\n // TODO: https://github.com/cowprotocol/cow-sdk/issues/155\n abstract get isSingleOrder(): boolean\n\n /**\n * Get a descriptive name for the type of the conditional order (i.e twap, dca, etc).\n *\n * @returns {string} The concrete type of the conditional order.\n */\n abstract get orderType(): string\n\n /**\n * Get the context dependency for the conditional order.\n *\n * This is used when calling `createWithContext` or `setRootWithContext` on a ComposableCoW-enabled Safe.\n * @returns The context dependency.\n */\n get context(): ContextFactory | undefined {\n return undefined\n }\n\n assertIsValid(): void {\n const isValidResult = this.isValid()\n if (!isValidResult.isValid) {\n throw new Error(`Invalid order: ${isValidResult.reason}`)\n }\n }\n\n abstract isValid(): IsValidResult\n\n /**\n * Get the calldata for creating the conditional order.\n *\n * This will automatically determine whether or not to use `create` or `createWithContext` based on the\n * order type's context dependency.\n *\n * **NOTE**: By default, this will cause the create to emit the `ConditionalOrderCreated` event.\n * @returns The calldata for creating the conditional order.\n */\n get createCalldata(): string {\n this.assertIsValid()\n\n const context = this.context\n const composableCow = getComposableCowInterface()\n const paramsStruct: IConditionalOrder.ConditionalOrderParamsStruct = {\n handler: this.handler,\n salt: this.salt,\n staticInput: this.encodeStaticInput(),\n }\n\n if (context) {\n // Create (with context)\n const contextArgsAbi = context.factoryArgs\n ? utils.defaultAbiCoder.encode(context.factoryArgs.argsType, context.factoryArgs.args)\n : '0x'\n return composableCow.encodeFunctionData('createWithContext', [\n paramsStruct,\n context.address,\n contextArgsAbi,\n true,\n ])\n } else {\n // Create\n return composableCow.encodeFunctionData('create', [paramsStruct, true])\n }\n }\n\n /**\n * Get the calldata for removing a conditional order that was created as a single order.\n * @returns The calldata for removing the conditional order.\n */\n get removeCalldata(): string {\n this.assertIsValid()\n\n return getComposableCowInterface().encodeFunctionData('remove', [this.id])\n }\n\n /**\n * Calculate the id of the conditional order (which also happens to be the key used for `ctx` in the ComposableCoW contract).\n *\n * This is a `keccak256` hash of the serialized conditional order.\n * @returns The id of the conditional order.\n */\n get id(): string {\n return utils.keccak256(this.serialize())\n }\n\n /**\n * The context key of the order (bytes32(0) if a merkle tree is used, otherwise H(params)) with which to lookup the cabinet\n *\n * The context, relates to the 'ctx' in the contract: https://github.com/cowprotocol/composable-cow/blob/c7fb85ab10c05e28a1632ba97a1749fb261fcdfb/src/interfaces/IConditionalOrder.sol#L38\n */\n protected get ctx(): string {\n return this.isSingleOrder ? this.id : constants.HashZero\n }\n\n /**\n * Get the `leaf` of the conditional order. This is the data that is used to create the merkle tree.\n *\n * For the purposes of this library, the `leaf` is the `ConditionalOrderParams` struct.\n * @returns The `leaf` of the conditional order.\n * @see ConditionalOrderParams\n */\n get leaf(): ConditionalOrderParams {\n return {\n handler: this.handler,\n salt: this.salt,\n staticInput: this.encodeStaticInput(),\n }\n }\n\n /**\n * Calculate the id of the conditional order.\n * @param leaf The `leaf` representing the conditional order.\n * @returns The id of the conditional order.\n * @see ConditionalOrderParams\n */\n static leafToId(leaf: ConditionalOrderParams): string {\n return utils.keccak256(encodeParams(leaf))\n }\n\n /**\n * If the conditional order has off-chain input, return it!\n *\n * **NOTE**: This should be overridden by any conditional order that has off-chain input.\n * @returns The off-chain input.\n */\n get offChainInput(): string {\n return '0x'\n }\n\n /**\n * Create a human-readable string representation of the conditional order.\n *\n * @param tokenFormatter An optional function that takes an address and an amount and returns a human-readable string.\n */\n abstract toString(tokenFormatter?: (address: string, amount: BigNumber) => string): string\n\n /**\n * Serializes the conditional order into it's ABI-encoded form.\n *\n * @returns The equivalent of `IConditionalOrder.Params` for the conditional order.\n */\n abstract serialize(): string\n\n /**\n * Encode the `staticInput` for the conditional order.\n *\n * @returns The ABI-encoded `staticInput` for the conditional order.\n * @see ConditionalOrderParams\n */\n abstract encodeStaticInput(): string\n\n /**\n * A helper function for generically serializing a conditional order's static input.\n *\n * @param orderDataTypes ABI types for the order's data struct.\n * @param data The order's data struct.\n * @returns An ABI-encoded representation of the order's data struct.\n */\n protected encodeStaticInputHelper(orderDataTypes: string[], staticInput: S): string {\n return utils.defaultAbiCoder.encode(orderDataTypes, [staticInput])\n }\n\n /**\n * Poll a conditional order to see if it is tradeable.\n *\n * @param owner The owner of the conditional order.\n * @param p The proof and parameters.\n * @param chain Which chain to use for the ComposableCoW contract.\n * @param provider An RPC provider for the chain.\n * @param offChainInputFn A function, if provided, that will return the off-chain input for the conditional order.\n * @throws If the conditional order is not tradeable.\n * @returns The tradeable `GPv2Order.Data` struct and the `signature` for the conditional order.\n */\n async poll(params: PollParams): Promise<PollResult> {\n const { chainId, owner, provider, orderBookApi } = params\n const composableCow = getComposableCow(chainId, provider)\n\n try {\n const isValid = this.isValid()\n // Do a validation first\n if (!isValid.isValid) {\n return {\n result: PollResultCode.DONT_TRY_AGAIN,\n reason: `InvalidConditionalOrder. Reason: ${isValid.reason}`,\n }\n }\n\n // Let the concrete Conditional Order decide about the poll result\n const pollResult = await this.pollValidate(params)\n if (pollResult) {\n return pollResult\n }\n\n // Check if the owner authorized the order\n const isAuthorized = await this.isAuthorized(params)\n if (!isAuthorized) {\n return {\n result: PollResultCode.DONT_TRY_AGAIN,\n reason: `NotAuthorized: Order ${this.id} is not authorized for ${owner} on chain ${chainId}`,\n }\n }\n\n // Lastly, try to get the tradeable order and signature\n const [order, signature] = await composableCow.getTradeableOrderWithSignature(\n owner,\n this.leaf,\n this.offChainInput,\n []\n )\n\n const orderUid = await computeOrderUid(chainId, owner, fromStructToOrder(order))\n\n // Check if the order is already in the order book\n const isOrderInOrderbook = await orderBookApi\n .getOrder(orderUid)\n .then(() => true)\n .catch(() => false)\n\n // Let the concrete Conditional Order decide about the poll result (in the case the order is already in the orderbook)\n if (isOrderInOrderbook) {\n const pollResult = await this.handlePollFailedAlreadyPresent(orderUid, order, params)\n if (pollResult) {\n return pollResult\n }\n\n return {\n result: PollResultCode.TRY_NEXT_BLOCK,\n reason: 'Order already in orderbook',\n }\n }\n\n return {\n result: PollResultCode.SUCCESS,\n order,\n signature,\n }\n } catch (error) {\n return {\n result: PollResultCode.UNEXPECTED_ERROR,\n error: error,\n }\n }\n }\n\n /**\n * Checks if the owner authorized the conditional order.\n *\n * @param params owner context, to be able to check if the order is authorized\n * @returns true if the owner authorized the order, false otherwise.\n */\n public isAuthorized(params: OwnerContext): Promise<boolean> {\n const { chainId, owner, provider } = params\n const composableCow = getComposableCow(chainId, provider)\n return composableCow.callStatic.singleOrders(owner, this.id)\n }\n\n /**\n * Checks the value in the cabinet for a given owner and chain\n *\n * @param params owner context, to be able to check the cabinet\n */\n public cabinet(params: OwnerContext): Promise<string> {\n const { chainId, owner, provider } = params\n\n const composableCow = getComposableCow(chainId, provider)\n return composableCow.callStatic.cabinet(owner, this.ctx)\n }\n\n /**\n * Allow concrete conditional orders to perform additional validation for the poll method.\n *\n * This will allow the concrete orders to decide when an order shouldn't be polled again. For example, if the orders is expired.\n * It also allows to signal when should the next check be done. For example, an order could signal that the validations will fail until a certain time or block.\n *\n * @param params The poll parameters\n *\n * @returns undefined if the concrete order can't make a decision. Otherwise, it returns a PollResultErrors object.\n */\n protected abstract pollValidate(params: PollParams): Promise<PollResultErrors | undefined>\n\n /**\n * This method lets the concrete conditional order decide what to do if the order yielded in the polling is already present in the Orderbook API.\n *\n * The concrete conditional order will have a chance to schedule the next poll.\n * For example, a TWAP order that has the current part already in the orderbook, can signal that the next poll should be done at the start time of the next part.\n *\n * @param params\n */\n protected abstract handlePollFailedAlreadyPresent(\n orderUid: UID,\n order: GPv2Order.DataStruct,\n params: PollParams\n ): Promise<PollResultErrors | undefined>\n\n /**\n * Convert the struct that the contract expect as an encoded `staticInput` into a friendly data object modelling the smart order.\n *\n * **NOTE**: This should be overridden by any conditional order that requires transformations.\n * This implementation is a no-op if you use the same type for both.\n *\n * @param params {S} Parameters that are passed in to the constructor.\n * @returns {D} The static input for the conditional order.\n */\n abstract transformStructToData(params: S): D\n\n /**\n * Converts a friendly data object modelling the smart order into the struct that the contract expect as an encoded `staticInput`.\n *\n * **NOTE**: This should be overridden by any conditional order that requires transformations.\n * This implementation is a no-op if you use the same type for both.\n *\n * @param params {S} Parameters that are passed in to the constructor.\n * @returns {D} The static input for the conditional order.\n */\n abstract transformDataToStruct(params: D): S\n\n /**\n * A helper function for generically deserializing a conditional order.\n * @param s The ABI-encoded `IConditionalOrder.Params` struct to deserialize.\n * @param handler Address of the handler for the conditional order.\n * @param orderDataTypes ABI types for the order's data struct.\n * @param callback A callback function that takes the deserialized data struct and the salt and returns an instance of the class.\n * @returns An instance of the conditional order class.\n */\n protected static deserializeHelper<T>(\n s: string,\n handler: string,\n orderDataTypes: string[],\n callback: (d: any, salt: string) => T\n ): T {\n try {\n // First, decode the `IConditionalOrder.Params` struct\n const { handler: recoveredHandler, salt, staticInput } = decodeParams(s)\n\n // Second, verify that the recovered handler is the correct handler\n if (!(recoveredHandler == handler)) throw new Error('HandlerMismatch')\n\n // Third, decode the data struct\n const [d] = utils.defaultAbiCoder.decode(orderDataTypes, staticInput)\n\n // Create a new instance of the class\n return callback(d, salt)\n } catch (e: any) {\n if (e.message === 'HandlerMismatch') {\n throw e\n } else {\n throw new Error('InvalidSerializedConditionalOrder')\n }\n }\n }\n}\n","import type { Order } from '@cowprotocol/contracts'\nimport type { SupportedChainId } from './common'\nimport { OrderSigningUtils } from './order-signing'\n\nexport async function computeOrderUid(chainId: SupportedChainId, owner: string, order: Order): Promise<string> {\n const { computeOrderUid: _computeOrderUid } = await import('@cowprotocol/contracts')\n const domain = await OrderSigningUtils.getDomain(chainId)\n\n return _computeOrderUid(domain, order, owner)\n}\n","import { StandardMerkleTree } from '@openzeppelin/merkle-tree'\nimport { BigNumber, providers, utils } from 'ethers'\n\nimport { SupportedChainId } from '../common'\n\nimport { ComposableCoW, GPv2Order } from './generated/ComposableCoW'\nimport { ProofLocation, ProofWithParams, ConditionalOrderParams } from './types'\nimport { ConditionalOrder } from './ConditionalOrder'\nimport { getComposableCow } from './contracts'\n\nconst CONDITIONAL_ORDER_LEAF_ABI = ['address', 'bytes32', 'bytes']\n\nconst PAYLOAD_EMITTED_ABI = ['tuple(bytes32[] proof, tuple(address handler, bytes32 salt, bytes staticInput) params)[]']\n\nexport type Orders = Record<string, ConditionalOrder<unknown, unknown>>\n\n/**\n * Multiplexer for conditional orders - using `ComposableCoW`!\n *\n * This class provides functionality to:\n * - Generate a merkle tree of conditional orders\n * - Generate proofs for all orders in the merkle tree\n * - Save proofs, with the ability to omit / skip specific conditional orders\n * - Support for passing an optional upload function to upload the proofs to a decentralized storage network\n */\nexport class Multiplexer {\n static orderTypeRegistry: Record<string, new (...args: unknown[]) => ConditionalOrder<unknown, unknown>> = {}\n\n public chain: SupportedChainId\n public location: ProofLocation\n\n private orders: Orders = {}\n private tree?: StandardMerkleTree<string[]>\n private ctx?: string\n\n /**\n * @param chain The `chainId` for where we're using `ComposableCoW`.\n * @param orders An optional array of conditional orders to initialize the merkle tree with.\n * @param root An optional root to verify against.\n * @param location The location of the proofs for the conditional orders.\n */\n constructor(\n chain: SupportedChainId,\n orders?: Orders,\n root?: string,\n location: ProofLocation = ProofLocation.PRIVATE\n ) {\n this.chain = chain\n this.location = location\n\n // If orders are provided, the length must be > 0\n if (orders && Object.keys(orders).length === 0) {\n throw new Error('orders must have non-zero length')\n }\n\n // If orders are provided, so must a root, and vice versa\n if ((orders && !root) || (!orders && root)) {\n throw new Error('orders cannot have undefined root')\n }\n\n // can only proceed past here if both orders and root are provided, or neither are\n\n // validate that no unknown order types are provided\n for (const orderKey in orders) {\n if (orders.hasOwnProperty(orderKey)) {\n const order = orders[orderKey]\n if (!Multiplexer.orderTypeRegistry.hasOwnProperty(order.orderType)) {\n throw new Error(`Unknown order type: ${order.orderType}`)\n }\n }\n }\n\n // If orders (and therefore the root) are provided, generate the merkle tree\n if (orders) {\n this.orders = orders\n\n // if generate was successful, we can verify the root\n if (this.getOrGenerateTree().root !== root) {\n throw new Error('root mismatch')\n }\n }\n }\n\n // --- user facing serialization methods ---\n\n /**\n * Given a serialized multiplexer, create the multiplexer and rehydrate all conditional orders.\n * Integrity of the multiplexer will be verified by generating the merkle tree and verifying\n * the root.\n *\n * **NOTE**: Before using this method, you must register all conditional order types using `Multiplexer.registerOrderType`.\n * @param s The serialized multiplexer.\n * @returns The multiplexer with all conditional orders rehydrated.\n * @throws If the multiplexer cannot be deserialized.\n * @throws If the merkle tree cannot be generated.\n * @throws If the merkle tree cannot be verified against the root.\n */\n static fromJSON(s: string): Multiplexer {\n // reviver function to deserialize the orders\n const reviver = (k: string, v: any) => {\n if (k === 'orders' && typeof v === 'object' && v !== null) {\n const orders: Orders = {}\n\n for (const orderKey in v) {\n if (v.hasOwnProperty(orderKey)) {\n const { orderType, ...orderData } = v[orderKey]\n\n if (Multiplexer.orderTypeRegistry.hasOwnProperty(orderType)) {\n const OrderConstructor = Multiplexer.orderTypeRegistry[orderType]\n orders[orderKey] = new OrderConstructor(orderData)\n } else {\n throw new Error(`Unknown order type: ${orderType}`)\n }\n }\n }\n\n return orders\n }\n\n // Make sure we deserialize `BigNumber` correctly\n if (typeof v === 'object' && v !== null && v.hasOwnProperty('type') && v.hasOwnProperty('hex')) {\n if (v.type === 'BigNumber') {\n return BigNumber.from(v)\n }\n }\n\n return v\n }\n\n const { chain, orders, root, location } = JSON.parse(s, reviver)\n const m = new Multiplexer(chain, orders, root)\n m.location = location\n return m\n }\n\n /**\n * Serialize the multiplexer to JSON.\n *\n * This will include all state necessary to reconstruct the multiplexer, including the root.\n * @remarks This will **NOT** include the merkle tree.\n * @returns The JSON representation of the multiplexer, including the root but excluding the merkle tree.\n */\n toJSON(): string {\n const root = this.getOrGenerateTree().root\n\n // serialize the multiplexer, including the root but excluding the merkle tree.\n return JSON.stringify({ ...this, root }, (k, v) => {\n // filter out the merkle tree\n if (k === 'tree') return undefined\n if (typeof v === 'object' && v !== null && 'orderType' in v) {\n const conditionalOrder = v as ConditionalOrder<unknown, unknown>\n return {\n ...conditionalOrder,\n orderType: conditionalOrder.orderType,\n }\n }\n // We do not do any custom serialization of `BigNumber` in order to preserve it's type.\n return v\n })\n }\n\n // --- crud methods ---\n\n /**\n * Add a conditional order to the merkle tree.\n * @param order The order to add to the merkle tree.\n */\n add<T, P>(order: ConditionalOrder<T, P>): void {\n order.assertIsValid()\n\n this.orders[order.id] = order\n this.reset()\n }\n\n /**\n * Remove a conditional order from the merkle tree.\n * @param id The id of the `ConditionalOrder` to remove from the merkle tree.\n */\n remove(id: string): void {\n delete this.orders[id]\n this.reset()\n }\n\n /**\n * Update a given conditional order in the merkle tree.\n * @param id The id of the `ConditionalOrder` to update.\n * @param updater A function that takes the existing `ConditionalOrder` and context, returning an updated `ConditionalOrder`.\n */\n update(\n id: string,\n updater: (order: ConditionalOrder<unknown, unknown>, ctx?: string) => ConditionalOrder<unknown, unknown>\n ): void {\n // copy the existing order and update it, given the existing context (if any)\n const order = updater(this.orders[id], this.ctx)\n // delete the existing order\n delete this.orders[id]\n\n // add the updated order\n this.orders[order.id] = order\n this.reset()\n }\n\n // --- accessors ---\n\n /**\n * Accessor for a given conditional order in the multiplexer.\n * @param id The `id` of the `ConditionalOrder` to retrieve.\n * @returns A `ConditionalOrder` with the given `id`.\n */\n getById(id: string): ConditionalOrder<unknown, unknown> {\n return this.orders[id]\n }\n\n /**\n * Accessor for a given conditional order in the multiplexer.\n * @param i The index of the `ConditionalOrder` to retrieve.\n * @returns A `ConditionalOrder` at the given index.\n */\n getByIndex(i: number): ConditionalOrder<unknown, unknown> {\n return this.orders[this.orderIds[i]]\n }\n\n /**\n * Get all the conditional order ids in the multiplexer.\n */\n get orderIds(): string[] {\n return Object.keys(this.orders)\n }\n\n get root(): string {\n return this.getOrGenerateTree().root\n }\n\n /**\n * Retrieve the merkle tree of orders, or generate it if it doesn't exist.\n *\n * **CAUTION**: Developers of the SDK should prefer to use this method instead of generating the\n * merkle tree themselves. This method makes use of caching to avoid generating the\n * merkle tree needlessly.\n * @throws If the merkle tree cannot be generated.\n * @returns The merkle tree for the current set of conditional orders.\n */\n private getOrGenerateTree(): StandardMerkleTree<string[]> {\n if (!this.tree) {\n this.tree = StandardMerkleTree.of(\n Object.values(this.orders).map((order) => [...Object.values(order.leaf)]),\n CONDITIONAL_ORDER_LEAF_ABI\n )\n }\n\n return this.tree\n }\n\n // --- serialization for watchtowers / indexers ---\n\n /**\n * The primary method for watch towers to use when deserializing the proofs and parameters for the conditional orders.\n * @param s The serialized proofs with parameters for consumption by watchtowers / indexers.\n * @returns The `ProofWithParams` array.\n * @throws If the `ProofWithParams` array cannot be deserialized.\n */\n static decodeFromJSON(s: string): ProofWithParams[] {\n // no need to rehydrate `BigNumber` as this is fully ABI encoded\n return JSON.parse(s)\n }\n\n /**\n * The primary entry point for dapps integrating with `ComposableCoW` to generate the proofs and\n * parameters for the conditional orders.\n *\n * After populating the multiplexer with conditional orders, this method can be used to generate\n * the proofs and parameters for the conditional orders. The returned `ProofStruct` can then be\n * used with `setRoot` or `setRootWithContext` on a `ComposableCoW`-enabled Safe.\n *\n * @param filter {@link getProofs}\n * @parma locFn A function that takes the off-chain encoded input, and returns the `location`\n * for the `ProofStruct`, and the `data` for the `ProofStruct`.\n * @returns The ABI-encoded `ProofStruct` for `setRoot` and `setRootWithContext`.\n */\n async prepareProofStruct(\n location: ProofLocation = this.location,\n filter?: (v: string[]) => boolean,\n uploader?: (offChainEncoded: string) => Promise<string>\n ): Promise<ComposableCoW.ProofStruct> {\n const data = async (): Promise<string> => {\n switch (location) {\n case ProofLocation.PRIVATE:\n return '0x'\n case ProofLocation.EMITTED:\n return this.encodeToABI(filter)\n case ProofLocation.SWARM:\n case ProofLocation.WAKU:\n case ProofLocation.IPFS:\n if (!uploader) throw new Error('Must provide an uploader function')\n try {\n return await uploader(this.encodeToJSON(filter))\n } catch (e) {\n throw new Error(`Error uploading to decentralized storage ${location}: ${e}`)\n }\n default:\n throw new Error('Unsupported location')\n }\n }\n\n return await data()\n .then((d) => {\n try {\n // validate that `d` is a valid `bytes` ready to be abi-encoded\n utils.hexlify(utils.arrayify(d))\n\n // if we get here, we have a valid `data` field for the `ProofStruct`\n // This means that if there was an upload function, it was called and the upload was successful\n // note: we don't check if the location has changed because we don't care\n this.location = location\n\n return {\n location,\n data: d,\n }\n } catch (e) {\n throw new Error(`data returned by uploader is invalid`)\n }\n })\n .catch((e) => {\n throw new Error(`Error preparing proof struct: ${e}`)\n })\n }\n\n /**\n * Poll a conditional order to see if it is tradeable.\n * @param owner The owner of the conditional order.\n * @param p The proof and parameters.\n * @param chain Which chain to use for the ComposableCoW contract.\n * @param provider An RPC provider for the chain.\n * @param offChainInputFn A function, if provided, that will return the off-chain input for the conditional order.\n * @throws If the conditional order is not tradeable.\n * @returns The tradeable `GPv2Order.Data` struct and the `signature` for the conditional order.\n */\n static async poll(\n owner: string,\n p: ProofWithParams,\n chain: SupportedChainId,\n provider: providers.Provider,\n offChainInputFn?: (owner: string, params: ConditionalOrderParams) => Promise<string>\n ): Promise<[GPv2Order.DataStruct, string]> {\n const composableCow = getComposableCow(chain, provider)\n\n const offChainInput = offChainInputFn ? await offChainInputFn(owner, p.params) : '0x'\n return await composableCow.getTradeableOrderWithSignature(owner, p.params, offChainInput, p.proof)\n }\n\n /**\n * The primary entry point for dumping the proofs and parameters for the conditional orders.\n *\n * This is to be used by watchtowers / indexers to store the proofs and parameters for the\n * conditional orders off-chain. The encoding returned by this method may **NOT** contain all\n * proofs and parameters, depending on the `filter` provided, and therefore should not be used\n * to rehydrate the multiplexer from a user's perspective.\n * @param filter {@link getProofs}\n * @returns A JSON-encoded string of the proofs and parameters for the conditional orders.\n */\n dumpProofs(filter?: (v: string[]) => boolean): string {\n return this.encodeToJSON(filter)\n }\n\n dumpProofsAndParams(filter?: (v: string[]) => boolean): ProofWithParams[] {\n return this.getProofs(filter)\n }\n\n /**\n * Get the proofs with parameters for the conditional orders in the merkle tree.\n * @param filter A function that takes a conditional order and returns a boolean indicating\n * whether the order should be included in the proof.\n * @returns An array of proofs and their order's parameters for the conditional orders in the\n * merkle tree.\n */\n private getProofs(filter?: (v: string[]) => boolean): ProofWithParams[] {\n // Get a list of all entry indices in the tree, excluding any that don't match the filter\n return [...this.getOrGenerateTree().entries()]\n .map(([i, v]) => {\n if ((filter && filter(v)) || filter === undefined) {\n return { idx: i, value: v }\n } else {\n return undefined\n }\n })\n .reduce((acc: ProofWithParams[], x) => {\n if (x) {\n const p: ConditionalOrderParams = {\n handler: x.value[0],\n salt: x.value[1],\n staticInput: x.value[2],\n }\n acc.push({\n proof: this.getOrGenerateTree().getProof(x.idx),\n params: p,\n })\n }\n return acc\n }, [])\n }\n\n /**\n * ABI-encode the proofs and parameters for the conditional orders in the merkle tree.\n * @param filter {@link getProofs}\n * @returns ABI-encoded `data` for the `ProofStruct`.\n */\n private encodeToABI(filter?: (v: string[]) => boolean): string {\n return utils.defaultAbiCoder.encode(PAYLOAD_EMITTED_ABI, [this.getProofs(filter)])\n }\n\n /**\n * JSON-encode the proofs and parameters for the conditional orders in the merkle tree.\n * @param filter {@link getProofs}\n * @returns The JSON-encoded data for storage off-chain.\n */\n private encodeToJSON(filter?: (v: string[]) => boolean): string {\n return JSON.stringify(this.getProofs(filter))\n }\n\n /**\n * A helper to reset the merkle tree.\n */\n private reset(): void {\n this.tree = undefined\n }\n\n /**\n * Register a conditional order type with the multiplexer.\n *\n * **CAUTION**: This is required for using `Multiplexer.fromJSON` and `Multiplexer.toJSON`.\n * @param orderType The order type to register.\n * @param conditionalOrderClass The class to use for the given order type.\n */\n public static registerOrderType(\n orderType: string,\n conditionalOrderClass: new (...args: any[]) => ConditionalOrder<unknown, unknown>\n ) {\n Multiplexer.orderTypeRegistry[orderType] = conditionalOrderClass\n }\n\n /**\n * Reset the order type registry.\n */\n public static resetOrderTypeRegistry() {\n Multiplexer.orderTypeRegistry = {}\n }\n}\n","import { type ConditionalOrder } from './ConditionalOrder'\nimport { ConditionalOrderParams } from './types'\n\nexport type FromParams<D, S> = (params: ConditionalOrderParams) => ConditionalOrder<D, S>\nexport type ConditionalOrderRegistry = Record<string, FromParams<unknown, unknown>>\n\nexport class ConditionalOrderFactory {\n public knownOrderTypes\n\n constructor(registry: ConditionalOrderRegistry) {\n this.knownOrderTypes = registry\n }\n\n public fromParams(params: ConditionalOrderParams): ConditionalOrder<unknown, unknown> | undefined {\n const { handler } = params\n\n const factory = this.knownOrderTypes[handler]\n if (!factory) {\n return undefined\n }\n\n return factory(params)\n }\n}\n","import { BigNumber, constants, utils } from 'ethers'\n\nimport { ConditionalOrder } from '../ConditionalOrder'\nimport {\n ConditionalOrderArguments,\n ConditionalOrderParams,\n ContextFactory,\n OwnerContext,\n IsValidResult,\n PollParams,\n PollResultCode,\n PollResultErrors,\n} from '../types'\nimport { encodeParams, formatEpoch, getBlockInfo, isValidAbi } from '../utils'\nimport { GPv2Order } from '../generated/ComposableCoW'\n\n// The type of Conditional Order\nconst TWAP_ORDER_TYPE = 'twap'\n// The address of the TWAP handler contract\nexport const TWAP_ADDRESS = '0x6cF1e9cA41f7611dEf408122793c358a3d11E5a5'\n/**\n * The address of the `CurrentBlockTimestampFactory` contract\n *\n * **NOTE**: This is used in the event that TWAP's have a `t0` of `0`.\n */\nexport const CURRENT_BLOCK_TIMESTAMP_FACTORY_ADDRESS = '0x52eD56Da04309Aca4c3FECC595298d80C2f16BAc'\n\nexport const MAX_UINT32 = BigNumber.from(2).pow(32).sub(1) // 2^32 - 1\nexport const MAX_FREQUENCY = BigNumber.from(365 * 24 * 60 * 60) // 1 year\n\n// Define the ABI tuple for the TWAPData struct\nconst TWAP_STRUCT_ABI = [\n 'tuple(address sellToken, address buyToken, address receiver, uint256 partSellAmount, uint256 minPartLimit, uint256 t0, uint256 n, uint256 t, uint256 span, bytes32 appData)',\n]\n\n/**\n * Base parameters for a TWAP order. Shared by:\n * - TwapStruct (modelling the contract's struct used for `staticInput`).\n * - TwapData (modelling the friendly SDK interface).\n */\nexport type TwapDataBase = {\n /**\n * which token to sell\n */\n readonly sellToken: string\n\n /**\n * which token to buy\n */\n readonly buyToken: string\n\n /**\n * who to send the tokens to\n */\n readonly receiver: string\n\n /**\n * Meta-data associated with the order. Normally would be the keccak256 hash of the document generated in http://github.com/cowprotocol/app-data\n *\n * This hash should have been uploaded to the API https://api.cow.fi/docs/#/default/put_api_v1_app_data__app_data_hash_ and potentially to other data availability protocols like IPFS.\n *\n */\n readonly appData: string\n}\n\n/**\n * Parameters for a TWAP order, as expected by the contract's `staticInput`.\n */\nexport interface TwapStruct extends TwapDataBase {\n /**\n * amount of sellToken to sell in each part\n */\n readonly partSellAmount: BigNumber\n\n /**\n * minimum amount of buyToken that must be bought in each part\n */\n readonly minPartLimit: BigNumber\n\n /**\n * start time of the TWAP\n */\n readonly t0: BigNumber\n\n /**\n * number of parts\n */\n readonly n: BigNumber\n\n /**\n * duration of the TWAP interval\n */\n readonly t: BigNumber\n\n /**\n * whether the TWAP is valid for the entire interval or not\n */\n readonly span: BigNumber\n}\n\n/**\n * Parameters for a TWAP order, made a little more user-friendly for SDK users.\n *\n * @see {@link TwapStruct} for the native struct.\n */\nexport interface TwapData extends TwapDataBase {\n /**\n * total amount of sellToken to sell across the entire TWAP\n */\n readonly sellAmount: BigNumber\n\n /**\n * minimum amount of buyToken that must be bought across the entire TWAP\n */\n readonly buyAmount: BigNumber\n\n /**\n * start time of the TWAP\n */\n readonly startTime?: StartTime\n\n /**\n * number of parts\n */\n readonly numberOfParts: BigNumber\n\n /**\n * duration of the TWAP interval\n */\n readonly timeBetweenParts: BigNumber\n\n /**\n * whether the TWAP is valid for the entire interval or not\n */\n readonly durationOfPart?: DurationOfPart\n}\n\nexport type DurationOfPart =\n | { durationType: DurationType.AUTO }\n | { durationType: DurationType.LIMIT_DURATION; duration: BigNumber }\n\nexport enum DurationType {\n AUTO = 'AUTO',\n LIMIT_DURATION = 'LIMIT_DURATION',\n}\n\nexport type StartTime =\n | { startType: StartTimeValue.AT_MINING_TIME }\n | { startType: StartTimeValue.AT_EPOCH; epoch: BigNumber }\n\nexport enum StartTimeValue {\n AT_MINING_TIME = 'AT_MINING_TIME',\n AT_EPOCH = 'AT_EPOCH',\n}\n\nconst DEFAULT_START_TIME: StartTime = { startType: StartTimeValue.AT_MINING_TIME }\nconst DEFAULT_DURATION_OF_PART: DurationOfPart = { durationType: DurationType.AUTO }\n\n/**\n * `ComposableCoW` implementation of a TWAP order.\n * @author mfw78 <mfw78@rndlabs.xyz>\n */\nexport class Twap extends ConditionalOrder<TwapData, TwapStruct> {\n isSingleOrder = true\n\n /**\n * @see {@link ConditionalOrder.constructor}\n * @throws If the TWAP order is invalid.\n * @throws If the TWAP order is not ABI-encodable.\n * @throws If the handler is not the TWAP address.\n */\n constructor(params: ConditionalOrderArguments<TwapData>) {\n const { handler, salt, data: staticInput, hasOffChainInput } = params\n\n // First, verify that the handler is the TWAP address\n if (handler !== TWAP_ADDRESS) throw new Error(`InvalidHandler: Expected: ${TWAP_ADDRESS}, provided: ${handler}`)\n\n // Third, construct the base class using transformed parameters\n super({ handler: TWAP_ADDRESS, salt, data: staticInput, hasOffChainInput })\n }\n\n /**\n * Create a TWAP order with sound defaults.\n * @param data The TWAP order parameters in a more user-friendly format.\n * @returns An instance of the TWAP order.\n */\n static fromData(data: TwapData, salt?: string): Twap {\n return new Twap({ handler: TWAP_ADDRESS, data, salt })\n }\n\n /**\n * Create a TWAP order with sound defaults.\n * @param data The TWAP order parameters in a more user-friendly format.\n * @returns An instance of the TWAP order.\n */\n static fromParams(params: ConditionalOrderParams): Twap {\n return Twap.deserialize(encodeParams(params))\n }\n\n /**\n * Enforces that TWAPs will commence at the beginning of a block by use of the\n * `CurrentBlockTimestampFactory` contract to provide the current block timestamp\n * as the start time of the TWAP.\n */\n get context(): ContextFactory | undefined {\n if (this.staticInput.t0.gt(0)) {\n return super.context\n } else {\n return {\n address: CURRENT_BLOCK_TIMESTAMP_FACTORY_ADDRESS,\n factoryArgs: undefined,\n }\n }\n }\n\n /**\n * @inheritdoc {@link ConditionalOrder.orderType}\n */\n get orderType(): string {\n return TWAP_ORDER_TYPE\n }\n\n /**\n * Validate the TWAP order.\n * @param data The TWAP order to validate.\n * @returns Whether the TWAP order is valid.\n * @throws If the TWAP order is invalid.\n * @see {@link TwapStruct} for the native struct.\n */\n isValid(): IsValidResult {\n const error = (() => {\n const {\n sellToken,\n sellAmount,\n buyToken,\n buyAmount,\n startTime = DEFAULT_START_TIME,\n numberOfParts,\n timeBetweenParts,\n durationOfPart = DEFAULT_DURATION_OF_PART,\n } = this.data\n\n // Verify that the order params are logically valid\n if (!(sellToken != buyToken)) return 'InvalidSameToken'\n if (!(sellToken != constants.AddressZero && buyToken != constants.AddressZero)) return 'InvalidToken'\n if (!sellAmount.gt(constants.Zero)) return 'InvalidSellAmount'\n if (!buyAmount.gt(constants.Zero)) return 'InvalidMinBuyAmount'\n if (startTime.startType === StartTimeValue.AT_EPOCH) {\n const t0 = startTime.epoch\n if (!(t0.gte(constants.Zero) && t0.lt(MAX_UINT32))) return 'InvalidStartTime'\n }\n if (!(numberOfParts.gt(constants.One) && numberOfParts.lte(MAX_UINT32))) return 'InvalidNumParts'\n if (!(timeBetweenParts.gt(constants.Zero) && timeBetweenParts.lte(MAX_FREQUENCY))) return 'InvalidFrequency'\n if (durationOfPart.durationType === DurationType.LIMIT_DURATION) {\n if (!durationOfPart.duration.lte(timeBetweenParts)) return 'InvalidSpan'\n }\n\n // Verify that the staticInput derived from the data is ABI-encodable\n if (!isValidAbi(TWAP_STRUCT_ABI, [this.staticInput])) return 'InvalidData'\n\n // No errors\n return undefined\n })()\n\n return error ? { isValid: false, reason: error } : { isValid: true }\n }\n\n protected async startTimestamp(params: OwnerContext): Promise<number> {\n const { startTime } = this.data\n\n if (startTime?.startType === StartTimeValue.AT_EPOCH) {\n return startTime.epoch.toNumber()\n }\n\n const cabinet = await this.cabinet(params)\n const rawCabinetEpoch = utils.defaultAbiCoder.decode(['uint256'], cabinet)[0] as BigNumber\n\n // Guard against out-of-range cabinet epoch\n if (rawCabinetEpoch.gt(MAX_UINT32)) {\n throw new Error(`Cabinet epoch out of range: ${rawCabinetEpoch.toString()}`)\n }\n\n // Convert the cabinet epoch (bignumber) to a number.\n const cabinetEpoch = rawCabinetEpoch.toNumber()\n\n if (cabinetEpoch === 0) {\n throw new Error('Cabinet is not set. Required for TWAP orders that start at mining time.')\n }\n\n return cabinetEpoch\n }\n\n /**\n * Given the start timestamp of the TWAP, calculate the end timestamp.\n * @dev As usually the `endTimestamp` is used when determining a TWAP's validity, we don't\n * do any lookup to the blockchain to determine the start timestamp, as this has likely\n * already been done during the verification flow.\n * @dev Beware to handle the case of `span != 0` ie. `durationOfPart.durationType !== DurationType.AUTO`.\n * @param startTimestamp The start timestamp of the TWAP.\n * @returns The timestamp at which the TWAP will end.\n */\n protected endTimestamp(startTimestamp: number): number {\n const { numberOfParts, timeBetweenParts, durationOfPart } = this.data\n\n if (durationOfPart && durationOfPart.durationType === DurationType.LIMIT_DURATION) {\n return startTimestamp + numberOfParts.sub(1).mul(timeBetweenParts).add(durationOfPart.duration).toNumber()\n }\n\n return startTimestamp + numberOfParts.mul(timeBetweenParts).toNumber()\n }\n\n /**\n * Checks if the owner authorized the conditional order.\n *\n * @param owner The owner of the conditional order.\n * @param chain Which chain to use for the ComposableCoW contract.\n * @param provider An RPC provider for the chain.\n * @returns true if the owner authorized the order, false otherwise.\n */\n protected async pollValidate(params: PollParams): Promise<PollResultErrors | undefined> {\n const { blockInfo = await getBlockInfo(params.provider) } = params\n const { blockTimestamp } = blockInfo\n\n try {\n const startTimestamp = await this.startTimestamp(params)\n\n if (startTimestamp > blockTimestamp) {\n // The start time hasn't started\n return {\n result: PollResultCode.TRY_AT_EPOCH,\n epoch: startTimestamp,\n reason: `TWAP hasn't started yet. Starts at ${startTimestamp} (${formatEpoch(startTimestamp)})`,\n }\n }\n\n const expirationTimestamp = this.endTimestamp(startTimestamp)\n if (blockTimestamp >= expirationTimestamp) {\n // The order has expired\n return {\n result: PollResultCode.DONT_TRY_AGAIN,\n reason: `TWAP has expired. Expired at ${expirationTimestamp} (${formatEpoch(expirationTimestamp)})`,\n }\n }\n\n return undefined\n } catch (err: any) {\n if (err?.message?.includes('Cabinet is not set')) {\n // in this case we have a firm reason to not monitor this order as the cabinet is not set\n return {\n result: PollResultCode.DONT_TRY_AGAIN,\n reason: `${err?.message}. User likely removed the order.`,\n }\n } else if (err?.message?.includes('Cabinet epoch out of range')) {\n // in this case we have a firm reason to not monitor this order as the cabinet is not set correctly\n return {\n result: PollResultCode.DONT_TRY_AGAIN,\n reason: `${err?.message}`,\n }\n }\n\n return {\n result: PollResultCode.UNEXPECTED_ERROR,\n reason: `Unexpected error: ${err.message}`,\n error: err,\n }\n }\n }\n\n /**\n * Handles the error when the order is already present in the orderbook.\n *\n * Given the current part is in the book, it will signal to Watch Tower what to do:\n * - Wait until the next part starts\n * - Don't try again if current part is the last one\n *\n * NOTE: The error messages will refer to the parts 1-indexed, so first part is 1, second part is 2, etc.\n */\n protected async handlePollFailedAlreadyPresent(\n _orderUid: string,\n _order: GPv2Order.DataStruct,\n params: PollParams\n ): Promise<PollResultErrors | undefined> {\n const { blockInfo = await getBlockInfo(params.provider) } = params\n const { blockTimestamp } = blockInfo\n\n const timeBetweenParts = this.data.timeBetweenParts.toNumber()\n const { numberOfParts } = this.data\n const startTimestamp = await this.startTimestamp(params)\n\n if (blockTimestamp < startTimestamp) {\n return {\n result: PollResultCode.UNEXPECTED_ERROR,\n reason: `TWAP part hash't started. First TWAP part start at ${startTimestamp} (${formatEpoch(startTimestamp)})`,\n error: undefined,\n }\n }\n const expireTime = numberOfParts.mul(timeBetweenParts).add(startTimestamp).toNumber()\n if (blockTimestamp >= expireTime) {\n return {\n result: PollResultCode.UNEXPECTED_ERROR,\n reason: `TWAP is expired. Expired at ${expireTime} (${formatEpoch(expireTime)})`,\n error: undefined,\n }\n }\n\n // Get current part number\n const currentPartNumber = Math.floor((blockTimestamp - startTimestamp) / timeBetweenParts)\n\n // If current part is the last one\n if (currentPartNumber === numberOfParts.toNumber() - 1) {\n return {\n result: PollResultCode.DONT_TRY_AGAIN,\n reason: `Current active TWAP part (${\n currentPartNumber + 1\n }/${numberOfParts}) is already in the Order Book. This was the last TWAP part, no more orders need to be placed`,\n }\n }\n\n // Next part start time\n const nextPartStartTime = startTimestamp + (currentPartNumber + 1) * timeBetweenParts\n\n /**\n * Given we know, that TWAP part that is due in the current block is already in the Orderbook,\n * Then, we can safely instruct that we should wait until the next TWAP part starts\n */\n return {\n result: PollResultCode.TRY_AT_EPOCH,\n epoch: nextPartStartTime,\n reason: `Current active TWAP part (${\n currentPartNumber + 1\n }/${numberOfParts}) is already in the Order Book. TWAP part ${\n currentPartNumber + 2\n } doesn't start until ${nextPartStartTime} (${formatEpoch(nextPartStartTime)})`,\n }\n }\n\n /**\n * Serialize the TWAP order into it's ABI-encoded form.\n * @returns {string} The ABI-encoded TWAP order.\n */\n serialize(): string {\n return encodeParams(this.leaf)\n }\n\n /**\n * Get the encoded static input for the TWAP order.\n * @returns {string} The ABI-encoded TWAP order.\n */\n encodeStaticInput(): string {\n return super.encodeStaticInputHelper(TWAP_STRUCT_ABI, this.staticInput)\n }\n\n /**\n * Deserialize a TWAP order from it's ABI-encoded form.\n * @param {string} twapSerialized ABI-encoded TWAP order to deserialize.\n * @returns A deserialized TWAP order.\n */\n static deserialize(twapSerialized: string): Twap {\n return super.deserializeHelper(\n twapSerialized,\n TWAP_ADDRESS,\n TWAP_STRUCT_ABI,\n (struct: TwapStruct, salt: string) =>\n new Twap({\n handler: TWAP_ADDRESS,\n salt,\n data: transformStructToData(struct),\n })\n )\n }\n\n /**\n * Create a human-readable string representation of the TWAP order.\n * @returns {string} A human-readable string representation of the TWAP order.\n */\n toString(): string {\n const {\n sellAmount,\n sellToken,\n buyAmount,\n buyToken,\n numberOfParts,\n startTime = DEFAULT_START_TIME,\n timeBetweenParts,\n durationOfPart = DEFAULT_DURATION_OF_PART,\n receiver,\n appData,\n } = this.data\n\n const startTimeFormatted =\n startTime.startType === StartTimeValue.AT_MINING_TIME ? 'AT_MINING_TIME' : startTime.epoch.toNumber()\n const durationOfPartFormatted =\n durationOfPart.durationType === DurationType.AUTO ? 'AUTO' : durationOfPart.duration.toNumber()\n\n const details = {\n sellAmount: sellAmount.toString(),\n sellToken,\n buyAmount: buyAmount.toString(),\n buyToken,\n numberOfParts: numberOfParts.toString(),\n startTime: startTimeFormatted,\n timeBetweenParts: timeBetweenParts.toNumber(),\n durationOfPart: durationOfPartFormatted,\n receiver,\n appData,\n }\n\n return `${this.orderType} (${this.id}): ${JSON.stringify(details)}`\n }\n\n /**\n * Transform parameters into a native struct.\n *\n * @param {TwapData} data As passed by the consumer of the API.\n * @returns {TwapStruct} A formatted struct as expected by the smart contract.\n */\n transformDataToStruct(data: TwapData): TwapStruct {\n return transformDataToStruct(data)\n }\n\n /**\n * Transform parameters into a TWAP order struct.\n *\n * @param {TwapData} params As passed by the consumer of the API.\n * @returns {TwapStruct} A formatted struct as expected by the smart contract.\n */\n transformStructToData(struct: TwapStruct): TwapData {\n return transformStructToData(struct)\n }\n}\n\n/**\n * Transform parameters into a native struct.\n *\n * @param {TwapData} data As passed by the consumer of the API.\n * @returns {TwapStruct} A formatted struct as expected by the smart contract.\n */\nexport function transformDataToStruct(data: TwapData): TwapStruct {\n const {\n sellAmount,\n buyAmount,\n numberOfParts,\n startTime: startTime = DEFAULT_START_TIME,\n timeBetweenParts,\n durationOfPart = DEFAULT_DURATION_OF_PART,\n ...rest\n } = data\n\n const { partSellAmount, minPartLimit } =\n numberOfParts && !numberOfParts.isZero()\n ? {\n partSellAmount: sellAmount.div(numberOfParts),\n minPartLimit: buyAmount.div(numberOfParts),\n }\n : {\n partSellAmount: constants.Zero,\n minPartLimit: constants.Zero,\n }\n\n const span = durationOfPart.durationType === DurationType.AUTO ? constants.Zero : durationOfPart.duration\n const t0 = startTime.startType === StartTimeValue.AT_MINING_TIME ? constants.Zero : startTime.epoch\n\n return {\n partSellAmount,\n minPartLimit,\n t0,\n n: numberOfParts,\n t: timeBetweenParts,\n span,\n ...rest,\n }\n}\n\n/**\n * Transform parameters into a TWAP order struct.\n *\n * @param {TwapData} params As passed by the consumer of the API.\n * @returns {TwapStruct} A formatted struct as expected by the smart contract.\n */\nexport function transformStructToData(struct: TwapStruct): TwapData {\n const { n: numberOfParts, partSellAmount, minPartLimit, t: timeBetweenParts, t0: startEpoch, span, ...rest } = struct\n\n const durationOfPart: DurationOfPart = span.isZero()\n ? { durationType: DurationType.AUTO }\n : { durationType: DurationType.LIMIT_DURATION, duration: span }\n\n const startTime: StartTime = span.isZero()\n ? { startType: StartTimeValue.AT_MINING_TIME }\n : { startType: StartTimeValue.AT_EPOCH, epoch: startEpoch }\n\n return {\n sellAmount: partSellAmount.mul(numberOfParts),\n buyAmount: minPartLimit.mul(numberOfParts),\n startTime,\n numberOfParts,\n timeBetweenParts,\n durationOfPart,\n ...rest,\n }\n}\n","import { ConditionalOrderRegistry } from '../ConditionalOrderFactory'\nimport { TWAP_ADDRESS, Twap } from './Twap'\nexport * from './Twap'\n\nexport const DEFAULT_CONDITIONAL_ORDER_REGISTRY: ConditionalOrderRegistry = {\n // Registry of all known order types\n [TWAP_ADDRESS]: (params) => Twap.fromParams(params),\n}\n"],"names":["SupportedChainId","ENVS_LIST","DEFAULT_COW_API_CONTEXT","env","chainId","MAINNET","CowError","Error","constructor","message","error_code","super","this","logPrefix","DEFAULT_IPFS_READ_URI","DEFAULT_IPFS_WRITE_URI","BUY_ETH_ADDRESS","EXTENSIBLE_FALLBACK_HANDLER","COMPOSABLE_COW","ALL_SUPPORTED_CHAIN_IDS","Object","values","filter","mapSupportedNetworks","value","reduce","acc","_extends","mapAddressToSupportedNetworks","address","COW_PROTOCOL_SETTLEMENT_CONTRACT_ADDRESS","COW_PROTOCOL_VAULT_RELAYER_ADDRESS","EXTENSIBLE_FALLBACK_HANDLER_CONTRACT_ADDRESS","COMPOSABLE_COW_CONTRACT_ADDRESS","OrderBookApiError","response","body","statusText","STATUS_CODES_TO_RETRY","DEFAULT_BACKOFF_OPTIONS","numOfAttempts","maxDelay","Infinity","jitter","retry","error","includes","status","DEFAULT_LIMITER_OPTIONS","tokensPerInterval","interval","getResponseBody","async","contentType","headers","get","toLowerCase","startsWith","json","text","console","undefined","request","baseUrl","path","query","method","rateLimiter","backoffOpts","url","init","JSON","stringify","Accept","backOff","removeTokens","fetch","responseBody","Promise","reject","transformOrder","order","ethflowData","userValidTo","validTo","owner","onchainUser","sellToken","transformEthFlowOrder","dto","executedFeeAmount","executedSurplusFee","_executedFeeAmount","BigInt","_executedSurplusFee","totalFee","String","addTotalFeeToOrder","ORDER_BOOK_PROD_CONFIG","GNOSIS_CHAIN","ARBITRUM_ONE","SEPOLIA","ORDER_BOOK_STAGING_CONFIG","cleanObjectFromUndefinedValues","obj","keys","key","val","OrderBookApi","context","RateLimiter","limiterOpts","getVersion","contextOverride","getTrades","orderUid","URLSearchParams","getOrders","offset","limit","toString","then","orders","map","getTxOrders","txHash","getOrder","getOrderCompetitionStatus","getOrderMultiEnv","getContextWithOverride","otherEnvs","i","attemptsCount","fallback","nextEnv","catch","getQuote","requestBody","sendSignedOrderCancellations","sendOrder","getNativePrice","tokenAddress","getTotalSurplus","getAppData","appDataHash","uploadAppData","fullAppData","getSolverCompetition","auctionIdorTx","getOrderLink","getApiBaseUrls","baseUrls","params","_backoffOpts","BuyTokenDestination","CompetitionOrderStatus","EcdsaSigningScheme","OnchainOrderData","OrderCancellationError","OrderClass","OrderKind","OrderPostError","OrderQuoteSideKindBuy","OrderQuoteSideKindSell","OrderStatus","PriceEstimationError","PriceQuality","SellTokenSource","SigningScheme","type","placementError","errorType","ONE_HUNDRED_BPS","getQuoteAmountsAndCosts","_params$partnerFeeBps","orderParams","sellDecimals","buyDecimals","slippagePercentBps","partnerFeeBps","isSell","kind","SELL","networkCostAmount","getBigNumber","feeAmount","sellAmountBeforeNetworkCosts","sellAmount","buyAmountAfterNetworkCosts","buyAmount","quotePrice","num","sellAmountAfterNetworkCosts","big","buyAmountBeforeNetworkCosts","partnerFeeAmount","afterPartnerFees","getSlippageAmount","amount","afterSlippage","costs","networkFee","amountInSellCurrency","amountInBuyCurrency","partnerFee","bps","beforeNetworkCosts","afterNetworkCosts","decimals","bigAsNumber","bigAsNumberString","toFixed","Number","_t","_t2","_t3","_","t","TOTALS_QUERY","gql","LAST_DAYS_VOLUME_QUERY","LAST_HOURS_VOLUME_QUERY","SUBGRAPH_BASE_URL","SUBGRAPH_PROD_CONFIG","SUBGRAPH_STAGING_CONFIG","SubgraphApi","API_NAME","runQuery","totals","days","hours","variables","getEnvConfigs","getSignUtils","import","OrderSigningUtils","static","signer","signOrder","signOrderCancellation","orderUids","signOrderCancellations","getDomain","_TypedDataEncoder","hashDomain","Order","name","ProofLocation","PollResultCode","_abi","inputs","internalType","stateMutability","anonymous","indexed","components","outputs","ComposableCoW__factory","utils","Interface","signerOrProvider","Contract","abi","ExtensibleFallbackHandler__factory","ERC20_BALANCE_VALUES","EXTERNAL_BALANCE_VALUES","INTERNAL_BALANCE_VALUES","SELL_KIND_VALUES","BUY_KIND_VALUES","CONDITIONAL_ORDER_PARAMS_ABI","DEFAULT_TOKEN_FORMATTER","isExtensibleFallbackHandler","handler","isComposableCow","getDomainVerifier","safe","domain","provider","contract","connect","callStatic","domainVerifiers","createSetDomainVerifierTx","verifier","createInterface","encodeFunctionData","encodeParams","defaultAbiCoder","encode","decodeParams","encoded","salt","staticInput","decode","isValidAbi","types","e","getBlockInfo","block","getBlock","blockNumber","number","blockTimestamp","timestamp","formatEpoch","epoch","Date","toISOString","balanceToString","balance","OrderBalance","ERC20","EXTERNAL","INTERNAL","kindToString","BUY","fromStructToOrder","buyToken","buyTokenBalance","sellTokenBalance","receiver","partiallyFillable","appData","composableCowInterfaceCache","composableCowContractCache","getComposableCowInterface","getComposableCow","chain","ConditionalOrder","data","hasOffChainInput","keccak256","randomBytes","ethers","isAddress","isHexString","hexDataLength","transformDataToStruct","assertIsValid","isValidResult","isValid","reason","createCalldata","composableCow","paramsStruct","encodeStaticInput","contextArgsAbi","factoryArgs","argsType","args","removeCalldata","id","serialize","ctx","isSingleOrder","constants","HashZero","leaf","offChainInput","encodeStaticInputHelper","orderDataTypes","orderBookApi","result","DONT_TRY_AGAIN","pollResult","pollValidate","isAuthorized","signature","getTradeableOrderWithSignature","computeOrderUid","_computeOrderUid","handlePollFailedAlreadyPresent","TRY_NEXT_BLOCK","SUCCESS","UNEXPECTED_ERROR","singleOrders","cabinet","s","callback","recoveredHandler","d","_excluded","CONDITIONAL_ORDER_LEAF_ABI","PAYLOAD_EMITTED_ABI","Multiplexer","root","location","PRIVATE","tree","length","orderKey","hasOwnProperty","orderTypeRegistry","orderType","getOrGenerateTree","parse","reviver","k","v","_v$orderKey","orderData","_objectWithoutPropertiesLoose","OrderConstructor","BigNumber","from","m","toJSON","conditionalOrder","add","reset","remove","update","updater","getById","getByIndex","orderIds","StandardMerkleTree","of","uploader","_this","EMITTED","encodeToABI","SWARM","WAKU","IPFS","encodeToJSON","hexlify","arrayify","p","offChainInputFn","proof","dumpProofs","dumpProofsAndParams","getProofs","entries","idx","x","push","getProof","conditionalOrderClass","ConditionalOrderFactory","registry","knownOrderTypes","fromParams","factory","TWAP_ADDRESS","CURRENT_BLOCK_TIMESTAMP_FACTORY_ADDRESS","MAX_UINT32","pow","sub","MAX_FREQUENCY","TWAP_STRUCT_ABI","DurationType","StartTimeValue","DEFAULT_START_TIME","startType","AT_MINING_TIME","DEFAULT_DURATION_OF_PART","durationType","AUTO","Twap","deserialize","t0","gt","startTime","numberOfParts","timeBetweenParts","durationOfPart","AddressZero","Zero","AT_EPOCH","gte","lt","One","lte","LIMIT_DURATION","duration","toNumber","rawCabinetEpoch","cabinetEpoch","endTimestamp","startTimestamp","mul","blockInfo","TRY_AT_EPOCH","expirationTimestamp","err","_err$message","_err$message2","_orderUid","_order","expireTime","currentPartNumber","Math","floor","nextPartStartTime","twapSerialized","deserializeHelper","struct","transformStructToData","startTimeFormatted","durationOfPartFormatted","details","rest","partSellAmount","minPartLimit","isZero","div","n","span","startEpoch","_excluded2","DEFAULT_CONDITIONAL_ORDER_REGISTRY"],"mappings":"+XAIY,IAAAA,GAAZ,SAAYA,GACVA,EAAAA,EAAA,QAAA,GAAA,UACAA,EAAAA,EAAA,aAAA,KAAA,eACAA,EAAAA,EAAA,aAAA,OAAA,eACAA,EAAAA,EAAA,QAAA,UAAA,SACD,CALD,CAAYA,IAAAA,EAKX,CAAA,ICmEY,MAAAC,EAAsB,CAAC,OAAQ,WAK/BC,EAAsC,CACjDC,IAAK,OACLC,QAASJ,EAAiBK,SCnFf,MAAAC,UAAiBC,MAG5BC,YAAYC,EAAiBC,GAC3BC,MAAMF,GAAQG,KAHhBF,gBAIE,EAAAE,KAAKF,WAAaA,CACpB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