@cowprotocol/cow-sdk 2.4.0-rc.0 → 3.0.0-rc.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index-856e1ad2.js.map +1 -1
- package/dist/index.js.map +1 -1
- package/dist/index.module.js.map +1 -1
- package/dist/order-book/api.d.ts +4 -4
- package/dist/order-book/generated/index.d.ts +2 -1
- package/dist/order-book/generated/models/AppData.d.ts +7 -0
- package/dist/order-book/generated/models/AppDataHash.d.ts +2 -0
- package/dist/order-book/generated/models/AppDataObject.d.ts +7 -0
- package/dist/order-book/generated/models/OrderCreation.d.ts +4 -3
- package/dist/order-book/generated/models/OrderQuoteRequest.d.ts +16 -1
- package/dist/package.json +2 -2
- package/package.json +2 -2
- package/dist/order-book/generated/models/AppDataDocument.d.ts +0 -12
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index-856e1ad2.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/transformOrder.ts","../src/order-book/request.ts","../src/order-book/api.ts","../src/order-book/generated/models/BuyTokenDestination.ts","../src/order-book/generated/models/EcdsaSigningScheme.ts","../src/order-book/generated/models/FeeAndQuoteError.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/PriceQuality.ts","../src/order-book/generated/models/ReplaceOrderError.ts","../src/order-book/generated/models/SellTokenSource.ts","../src/order-book/generated/models/SigningScheme.ts","../src/subgraph/queries.ts","../src/subgraph/api.ts","../src/order-signing/orderSigningUtils.ts","../src/composable/generated/factories/ComposableCoW__factory.ts","../src/composable/generated/factories/ExtensibleFallbackHandler__factory.ts","../src/composable/extensible.ts","../src/composable/multiplexer.ts","../src/composable/conditionalorder.ts","../src/composable/types/twap.ts"],"sourcesContent":["/**\n * Supported chains and their `chainId` for the SDK.\n * @enum\n */\nexport enum SupportedChainId {\n MAINNET = 1,\n GOERLI = 5,\n GNOSIS_CHAIN = 100,\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} [5] The base URL for the Goerli testnet API.\n * @property {string} [100] The base URL for the Gnosis Chain 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 * - Goerli\n * - Gnosis Chain\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}\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'\nimport contractNetworks from '@cowprotocol/contracts/networks.json'\n\nconst { GPv2Settlement } = JSON.parse(contractNetworks as unknown as string) as typeof contractNetworks\n\nexport const BUY_ETH_ADDRESS = '0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE'\nexport const EXTENSIBLE_FALLBACK_HANDLER = '0x2f55e8b20D0B9FEFA187AA7d00B6Cbe563605bF5'\nexport const COMPOSABLE_COW = '0xfdaFc9d1902f4e0b84f65F49f244b32b31013b74'\n\n/**\n * The list of supported chains.\n */\nexport const ALL_SUPPORTED_CHAIN_IDS: SupportedChainId[] = [\n SupportedChainId.MAINNET,\n SupportedChainId.GOERLI,\n SupportedChainId.GNOSIS_CHAIN,\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 = ALL_SUPPORTED_CHAIN_IDS.reduce<Record<number, string>>(\n (acc, chainId) => ({\n ...acc,\n [chainId]: GPv2Settlement[chainId].address,\n }),\n {}\n)\n\n/**\n * An object containing the addresses of the `ExtensibleFallbackHandler` contracts for each supported chain.\n */\nexport const EXTENSIBLE_FALLBACK_HANDLER_CONTRACT_ADDRESS = ALL_SUPPORTED_CHAIN_IDS.reduce<Record<number, string>>(\n (acc, chainId) => ({\n ...acc,\n [chainId]: EXTENSIBLE_FALLBACK_HANDLER,\n }),\n {}\n)\n\n/**\n * An object containing the addresses of the `ComposableCow` contracts for each supported chain.\n */\nexport const COMPOSABLE_COW_CONTRACT_ADDRESS = ALL_SUPPORTED_CHAIN_IDS.reduce<Record<number, string>>(\n (acc, chainId) => ({\n ...acc,\n [chainId]: COMPOSABLE_COW,\n }),\n {}\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 `executedSurplusFee` represents exactly the fee that was charged (regardless of the fee\n * signed with the order). So, while the protocol currently does not allow placing a limit order\n * with any other fee than 0 - the backend is designed to support these kinds of orders for the\n * future.\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 const totalFee = executedSurplusFee ?? executedFeeAmount\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 { 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 'cross-fetch/polyfill'\nimport {\n Address,\n AppDataDocument,\n AppDataHash,\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 { CowError } from '../common/cow-error'\nimport {\n ApiContext,\n CowEnv,\n DEFAULT_COW_API_CONTEXT,\n ApiBaseUrls,\n ENVS_LIST,\n PartialApiContext,\n RequestOptions,\n} from '../common/configs'\nimport { transformOrder } from './transformOrder'\nimport { EnrichedOrder } from './types'\nimport { SupportedChainId } from '../common/chains'\nimport { RateLimiter } from 'limiter'\nimport { DEFAULT_BACKOFF_OPTIONS, DEFAULT_LIMITER_OPTIONS, FetchParams, OrderBookApiError, request } from './request'\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.GOERLI]: 'https://api.cow.fi/goerli',\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.GOERLI]: 'https://barn.api.cow.fi/goerli',\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 = 5 // Goerli\n * const provider = new Web3Provider(window.ethereum)\n * const signer = provider.getSigner()\n *\n * const quoteRequest = {\n * sellToken: '0xb4fbf271143f4fbf7b91a5ded31805e42b2208d6', // WETH goerli\n * buyToken: '0x02abbdbaaa7b1bb64b5c878f7ac17f8dda169532', // GNO goerli\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.GOERLI })\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 & RequestOptions\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 & RequestOptions = {}) {\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 * 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<AppDataDocument> {\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<AppDataDocument> {\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 & RequestOptions {\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 } = this.getContextWithOverride(contextOverride)\n const baseUrl = this.getApiBaseUrls(env)[chainId]\n const backoffOpts = this.context.backoffOpts || DEFAULT_BACKOFF_OPTIONS\n\n return request(baseUrl, params, this.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\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\nexport type FeeAndQuoteError = {\n errorType: FeeAndQuoteError.errorType;\n description: string;\n};\n\nexport namespace FeeAndQuoteError {\n\n export enum errorType {\n NO_LIQUIDITY = 'NoLiquidity',\n UNSUPPORTED_TOKEN = 'UnsupportedToken',\n AMOUNT_IS_ZERO = 'AmountIsZero',\n SELL_AMOUNT_DOES_NOT_COVER_FEE = 'SellAmountDoesNotCoverFee',\n }\n\n\n}\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 DUPLICATE_ORDER = 'DuplicateOrder',\n INSUFFICIENT_FEE = 'InsufficientFee',\n INSUFFICIENT_ALLOWANCE = 'InsufficientAllowance',\n INSUFFICIENT_BALANCE = 'InsufficientBalance',\n INSUFFICIENT_VALID_TO = 'InsufficientValidTo',\n EXCESSIVE_VALID_TO = 'ExcessiveValidTo',\n INVALID_SIGNATURE = 'InvalidSignature',\n TRANSFER_ETH_TO_CONTRACT = 'TransferEthToContract',\n TRANSFER_SIMULATION_FAILED = 'TransferSimulationFailed',\n UNSUPPORTED_TOKEN = 'UnsupportedToken',\n WRONG_OWNER = 'WrongOwner',\n INVALID_EIP1271SIGNATURE = 'InvalidEip1271Signature',\n MISSING_FROM = 'MissingFrom',\n SAME_BUY_AND_SELL_TOKEN = 'SameBuyAndSellToken',\n ZERO_AMOUNT = 'ZeroAmount',\n UNSUPPORTED_BUY_TOKEN_DESTINATION = 'UnsupportedBuyTokenDestination',\n UNSUPPORTED_SELL_TOKEN_SOURCE = 'UnsupportedSellTokenSource',\n UNSUPPORTED_ORDER_TYPE = 'UnsupportedOrderType',\n UNSUPPORTED_SIGNATURE = 'UnsupportedSignature',\n TOO_MANY_LIMIT_ORDERS = 'TooManyLimitOrders',\n INVALID_APP_DATA = 'InvalidAppData',\n APP_DATA_HASH_MISMATCH = 'AppDataHashMismatch',\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\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` 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\nexport type ReplaceOrderError = {\n errorType: ReplaceOrderError.errorType;\n description: string;\n};\n\nexport namespace ReplaceOrderError {\n\n export enum errorType {\n ALREADY_CANCELLED = 'AlreadyCancelled',\n ORDER_FULLY_EXECUTED = 'OrderFullyExecuted',\n ORDER_EXPIRED = 'OrderExpired',\n ON_CHAIN_ORDER = 'OnChainOrder',\n DUPLICATE_ORDER = 'DuplicateOrder',\n INSUFFICIENT_FEE = 'InsufficientFee',\n INSUFFICIENT_ALLOWANCE = 'InsufficientAllowance',\n INSUFFICIENT_BALANCE = 'InsufficientBalance',\n INSUFFICIENT_VALID_TO = 'InsufficientValidTo',\n EXCESSIVE_VALID_TO = 'ExcessiveValidTo',\n INVALID_SIGNATURE = 'InvalidSignature',\n TRANSFER_ETH_TO_CONTRACT = 'TransferEthToContract',\n TRANSFER_SIMULATION_FAILED = 'TransferSimulationFailed',\n UNSUPPORTED_TOKEN = 'UnsupportedToken',\n WRONG_OWNER = 'WrongOwner',\n SAME_BUY_AND_SELL_TOKEN = 'SameBuyAndSellToken',\n ZERO_AMOUNT = 'ZeroAmount',\n UNSUPPORTED_BUY_TOKEN_DESTINATION = 'UnsupportedBuyTokenDestination',\n UNSUPPORTED_SELL_TOKEN_SOURCE = 'UnsupportedSellTokenSource',\n UNSUPPORTED_ORDER_TYPE = 'UnsupportedOrderType',\n UNSUPPORTED_SIGNATURE = 'UnsupportedSignature',\n }\n\n\n}\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 { 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 { CowError } from '../common/cow-error'\nimport { LastDaysVolumeQuery, LastHoursVolumeQuery, TotalsQuery } from './graphql'\nimport { LAST_DAYS_VOLUME_QUERY, LAST_HOURS_VOLUME_QUERY, TOTALS_QUERY } from './queries'\nimport { DocumentNode } from 'graphql/index'\nimport { request, Variables } from 'graphql-request'\nimport { ApiContext, CowEnv, DEFAULT_COW_API_CONTEXT, ApiBaseUrls, PartialApiContext } from '../common/configs'\nimport { SupportedChainId } from '../common/chains'\n\nconst SUBGRAPH_BASE_URL = 'https://api.thegraph.com/subgraphs/name/cowprotocol'\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 * @see {@link https://api.thegraph.com/subgraphs/name/cowprotocol/cow-goerli}\n */\nexport const SUBGRAPH_PROD_CONFIG: ApiBaseUrls = {\n [SupportedChainId.MAINNET]: SUBGRAPH_BASE_URL + '/cow',\n [SupportedChainId.GNOSIS_CHAIN]: SUBGRAPH_BASE_URL + '/cow-gc',\n [SupportedChainId.GOERLI]: SUBGRAPH_BASE_URL + '/cow-goerli',\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: ApiBaseUrls = {\n [SupportedChainId.MAINNET]: SUBGRAPH_BASE_URL + '/cow-staging',\n [SupportedChainId.GNOSIS_CHAIN]: SUBGRAPH_BASE_URL + '/cow-gc-staging',\n [SupportedChainId.GOERLI]: '',\n}\n\n/**\n * TheGraph API client for CoW Protocol.\n */\nexport class SubgraphApi {\n API_NAME = 'CoW Protocol Subgraph'\n\n public context: ApiContext\n\n /**\n * Create a new CoW Protocol API instance.\n * @param context Any properties of the {@link ApiContext} may be overridden by passing a {@link PartialApiContext}.\n */\n constructor(context: PartialApiContext = {}) {\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: PartialApiContext = {}): 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 {PartialApiContext} contextOverride Override the context for this call only.\n * @returns The volume for the last N days.\n */\n async getLastDaysVolume(days: number, contextOverride: PartialApiContext = {}): 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 {PartialApiContext} contextOverride Override the context for this call only.\n * @returns The volume for the last N hours.\n */\n async getLastHoursVolume(hours: number, contextOverride: PartialApiContext = {}): 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 {PartialApiContext} 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: PartialApiContext = {}\n ): Promise<T> {\n const { chainId, env } = this.getContextWithOverride(contextOverride)\n const baseUrl = this.getEnvConfigs(env)[chainId]\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 {PartialApiContext} contextOverride Override the context for this call only.\n * @returns {ApiContext} The 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 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): ApiBaseUrls {\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 = 5 // Goerli\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","/* 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 { providers } from 'ethers'\nimport {\n COMPOSABLE_COW_CONTRACT_ADDRESS,\n EXTENSIBLE_FALLBACK_HANDLER_CONTRACT_ADDRESS,\n SupportedChainId,\n} from '../common'\nimport { ExtensibleFallbackHandler__factory } from './generated'\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","import { StandardMerkleTree } from '@openzeppelin/merkle-tree'\nimport { BigNumber, providers, utils } from 'ethers'\n\nimport { COMPOSABLE_COW_CONTRACT_ADDRESS, SupportedChainId } from '../common'\nimport { BaseConditionalOrder, ConditionalOrderParams } from './conditionalorder'\n\nimport { ComposableCoW__factory } from './generated'\nimport { ComposableCoW, GPv2Order } from './generated/ComposableCoW'\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, BaseConditionalOrder<any, any>>\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: any[]\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\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: any[]) => BaseConditionalOrder<any, any>> = {}\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 const orderArgs = Object.values(orderData)\n orders[orderKey] = new OrderConstructor(...orderArgs)\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 BaseConditionalOrder<any, any>\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: BaseConditionalOrder<T, P>): void {\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 `BaseConditionalOrder` 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 `BaseConditionalOrder` to update.\n * @param updater A function that takes the existing `BaseConditionalOrder` and context, returning an updated `BaseConditionalOrder`.\n */\n update<T, P>(\n id: string,\n updater: (order: BaseConditionalOrder<T, P>, ctx?: string) => BaseConditionalOrder<T, P>\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 `BaseConditionalOrder` to retrieve.\n * @returns A `BaseConditionalOrder` with the given `id`.\n */\n getById(id: string): BaseConditionalOrder<any, any> {\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 `BaseConditionalOrder` to retrieve.\n * @returns A `BaseConditionalOrder` at the given index.\n */\n getByIndex(i: number): BaseConditionalOrder<any, any> {\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.DataStructOutput, string]> {\n const contract = ComposableCoW__factory.connect(COMPOSABLE_COW_CONTRACT_ADDRESS[chain], provider)\n const offChainInput = offChainInputFn ? await offChainInputFn(owner, p.params) : '0x'\n return await contract.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[]) => BaseConditionalOrder<any, any>\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 { BigNumber, ethers, utils } from 'ethers'\nimport { ContextFactory } from './multiplexer'\nimport { keccak256 } from 'ethers/lib/utils'\nimport { ComposableCoW__factory } from './generated'\nimport { IConditionalOrder } from './generated/ComposableCoW'\n\n// Define the ABI tuple for the TWAPData struct\nexport const CONDITIONAL_ORDER_PARAMS_ABI = ['tuple(address handler, bytes32 salt, bytes staticInput)']\n\nexport type ConditionalOrderParams = {\n readonly handler: string\n readonly salt: string\n readonly staticInput: string\n}\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 BaseConditionalOrder<T, P> {\n public readonly handler: string\n public readonly salt: string\n public readonly staticInput: T\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 `BaseConditionalOrder`.\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 staticInput The static input for the conditional 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(\n handler: string,\n salt: string = keccak256(ethers.utils.randomBytes(32)),\n staticInput: P,\n hasOffChainInput = false\n ) {\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.staticInput = this.transformParamsToData(staticInput)\n this.hasOffChainInput = hasOffChainInput\n }\n\n /**\n * Get the concrete type of the conditional order.\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 /**\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 const context = this.context\n const composableCow = ComposableCoW__factory.createInterface()\n const paramsStruct: IConditionalOrder.ConditionalOrderParamsStruct = {\n handler: this.handler,\n salt: this.salt,\n staticInput: this.encodeStaticInput(),\n }\n\n if (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 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 const composableCow = ComposableCoW__factory.createInterface()\n return composableCow.encodeFunctionData('remove', [this.id])\n }\n\n /**\n * Calculate the id of the conditional order.\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 * 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(BaseConditionalOrder.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 * 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 */\n protected static isValidAbi(types: readonly (string | ethers.utils.ParamType)[], values: any[]): boolean {\n try {\n ethers.utils.defaultAbiCoder.encode(types, values)\n } catch (e) {\n return false\n }\n return true\n }\n\n /**\n * Create a human-readable string representation of the conditional order.\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 * @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 * @param orderDataTypes ABI types for the order's data struct.\n * @param staticInput The order's data struct.\n * @returns An ABI-encoded representation of the order's data struct.\n */\n protected encodeStaticInputHelper(orderDataTypes: string[], staticInput: T): string {\n try {\n return utils.defaultAbiCoder.encode(orderDataTypes, [staticInput])\n } catch (e) {\n throw new Error('SerializationFailed')\n }\n }\n\n /**\n * Apply any transformations to the parameters that are passed in to the constructor.\n *\n * **NOTE**: This should be overridden by any conditional order that requires transformations.\n * This implementation is a no-op.\n * @param params {P} Parameters that are passed in to the constructor.\n * @returns {T} The static input for the conditional order.\n */\n protected transformParamsToData(params: P): T {\n return params as unknown as T\n }\n\n /**\n * Encode the `ConditionalOrderParams` for the conditional order.\n * @param leaf The `ConditionalOrderParams` struct representing the conditional order as taken from a merkle tree.\n * @returns The ABI-encoded conditional order.\n * @see ConditionalOrderParams\n */\n static encodeParams(leaf: ConditionalOrderParams): string {\n try {\n return utils.defaultAbiCoder.encode(CONDITIONAL_ORDER_PARAMS_ABI, [leaf])\n } catch (e) {\n throw new Error('SerializationFailed')\n }\n }\n\n /**\n * Decode the `ConditionalOrderParams` for the conditional order.\n * @param encoded The encoded conditional order.\n * @returns The decoded conditional order.\n */\n static decodeParams(encoded: string): ConditionalOrderParams {\n try {\n return utils.defaultAbiCoder.decode(CONDITIONAL_ORDER_PARAMS_ABI, encoded)[0]\n } catch (e) {\n throw new Error('DeserializationFailed')\n }\n }\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 } = BaseConditionalOrder.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 { BigNumber, constants, ethers, utils } from 'ethers'\n\nimport { BaseConditionalOrder } from '../conditionalorder'\nimport { ContextFactory } from '../multiplexer'\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_DATA_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 * Parameters for a TWAP order, made a little more user-friendly for SDK users.\n * @see {@link TWAPData} for the native struct.\n */\nexport type TWAPDataParams = Omit<TWAPData, 'partSellAmount' | 'minPartLimit'> & {\n // total amount of sellToken to sell across the entire TWAP\n readonly sellAmount: BigNumber\n // minimum amount of buyToken that must be bought across the entire TWAP\n readonly buyAmount: BigNumber\n}\n\n/**\n * Parameters for a TWAP order, as expected by the contract's `staticInput`.\n */\nexport type TWAPData = {\n // which token to sell\n readonly sellToken: string\n // which token to buy\n readonly buyToken: string\n // who to send the tokens to\n readonly receiver: string\n // amount of sellToken to sell in each part\n readonly partSellAmount: BigNumber\n // minimum amount of buyToken that must be bought in each part\n readonly minPartLimit: BigNumber\n // start time of the TWAP\n readonly t0: BigNumber\n // number of parts\n readonly n: BigNumber\n // duration of the TWAP interval\n readonly t: BigNumber\n // whether the TWAP is valid for the entire interval or not\n readonly span: BigNumber\n // appData\n readonly appData: string\n}\n\n/**\n * `ComposableCoW` implementation of a TWAP order.\n * @author mfw78 <mfw78@rndlabs.xyz>\n */\nexport class TWAP extends BaseConditionalOrder<TWAPData, TWAPDataParams> {\n /**\n * @see {@link BaseConditionalOrder.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(\n handler: string,\n salt: string = utils.keccak256(ethers.utils.randomBytes(32)),\n staticInput: TWAPDataParams,\n hasOffChainInput = false\n ) {\n // First, verify that the handler is the TWAP address\n if (handler !== TWAP_ADDRESS) throw new Error('InvalidHandler')\n\n // Second, verify that the order params are logically valid\n TWAP.isValid(staticInput)\n\n // Third, construct the base class using transformed parameters\n super(TWAP_ADDRESS, salt, staticInput, hasOffChainInput)\n\n // Finally, verify that the transformed data is ABI-encodable\n if (!TWAP.isValidAbi(TWAP_DATA_ABI, [this.staticInput])) throw new Error('InvalidData')\n }\n\n /**\n * Create a TWAP order with sound defaults.\n * @param staticInput The TWAP order parameters in a more user-friendly format.\n * @returns An instance of the TWAP order.\n */\n static default(staticInput: TWAPDataParams): BaseConditionalOrder<TWAPData, TWAPDataParams> {\n return new TWAP(TWAP_ADDRESS, undefined, staticInput)\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 BaseConditionalOrder.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 TWAPData} for the native struct.\n */\n static isValid(data: TWAPDataParams): boolean {\n if (!(data.sellToken != data.buyToken)) throw new Error('InvalidSameToken')\n if (!(data.sellToken != constants.AddressZero && data.buyToken != constants.AddressZero))\n throw new Error('InvalidToken')\n if (!data.sellAmount.gt(constants.Zero)) throw new Error('InvalidSellAmount')\n if (!data.buyAmount.gt(constants.Zero)) throw new Error('InvalidMinBuyAmount')\n if (!(data.t0.gte(constants.Zero) && data.t0.lt(MAX_UINT32))) throw new Error('InvalidStartTime')\n if (!(data.n.gt(constants.One) && data.n.lte(MAX_UINT32))) throw new Error('InvalidNumParts')\n if (!(data.t.gt(constants.Zero) && data.t.lte(MAX_FREQUENCY))) throw new Error('InvalidFrequency')\n if (!data.span.lte(data.t)) throw new Error('InvalidSpan')\n return true\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 BaseConditionalOrder.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_DATA_ABI, this.staticInput)\n }\n\n /**\n * Deserialize a TWAP order from it's ABI-encoded form.\n * @param {string} s ABI-encoded TWAP order to deserialize.\n * @returns A deserialized TWAP order.\n */\n static deserialize(s: string): TWAP {\n return super.deserializeHelper(\n s,\n TWAP_ADDRESS,\n TWAP_DATA_ABI,\n (o: TWAPData, salt: string) =>\n new TWAP(TWAP_ADDRESS, salt, {\n ...o,\n ...TWAP.partsToTotal(o),\n })\n )\n }\n\n /**\n * Create a human-readable string representation of the TWAP order.\n * @param {((address: string, amount: BigNumber) => string) | undefined} tokenFormatter An optional\n * function that takes an address and an amount and returns a human-readable string.\n * @returns {string} A human-readable string representation of the TWAP order.\n */\n toString(tokenFormatter?: (address: string, amount: BigNumber) => string): string {\n const defaultFormatter = (address: string, amount: BigNumber) => `${address}@${amount}`\n tokenFormatter = tokenFormatter || defaultFormatter\n\n const { sellAmount, buyAmount } = TWAP.partsToTotal(this.staticInput)\n\n return `${this.orderType}: Sell total ${tokenFormatter(\n this.staticInput.sellToken,\n sellAmount\n )} for a minimum of ${tokenFormatter(this.staticInput.buyToken, buyAmount)} over ${\n this.staticInput.n\n } parts with a spacing of ${this.staticInput.t}s beginning at ${\n this.staticInput.t0.eq(0) ? 'time of mining' : new Date(Number(this.staticInput.t0) * 1000)\n }`\n }\n\n /**\n * Transform parameters into a native struct.\n * @param {TWAPDataParams} params As passed by the consumer of the API.\n * @returns {TWAPData} A formatted struct as expected by the smart contract.\n */\n transformParamsToData(params: TWAPDataParams): TWAPData {\n return {\n ...params,\n ...TWAP.totalToPart(params),\n }\n }\n\n /**\n * Convert TWAP parts to total amounts.\n * @param {TWAPData} o The TWAP order.\n * @returns {object} The total sell amount and total minimum buy amount.\n */\n private static partsToTotal(o: TWAPData): {\n sellAmount: BigNumber\n buyAmount: BigNumber\n } {\n return {\n sellAmount: o.partSellAmount.mul(o.n),\n buyAmount: o.minPartLimit.mul(o.n),\n }\n }\n\n /**\n * Convert total amounts to TWAP parts.\n * @param {TWAPDataParams} o The TWAP order parameters.\n * @returns {object} The part sell amount and minimum part limit.\n * @throws If the number of parts is less than 1.\n */\n private static totalToPart(o: TWAPDataParams): {\n partSellAmount: BigNumber\n minPartLimit: BigNumber\n } {\n return {\n partSellAmount: o.sellAmount.div(o.n),\n minPartLimit: o.buyAmount.div(o.n),\n }\n }\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","GPv2Settlement","JSON","parse","BUY_ETH_ADDRESS","EXTENSIBLE_FALLBACK_HANDLER","COMPOSABLE_COW","ALL_SUPPORTED_CHAIN_IDS","GOERLI","GNOSIS_CHAIN","COW_PROTOCOL_SETTLEMENT_CONTRACT_ADDRESS","reduce","acc","_extends","address","EXTENSIBLE_FALLBACK_HANDLER_CONTRACT_ADDRESS","COMPOSABLE_COW_CONTRACT_ADDRESS","transformOrder","order","ethflowData","userValidTo","validTo","owner","onchainUser","sellToken","transformEthFlowOrder","dto","executedFeeAmount","executedSurplusFee","totalFee","addTotalFeeToOrder","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","stringify","Accept","backOff","removeTokens","fetch","responseBody","Promise","reject","ORDER_BOOK_PROD_CONFIG","ORDER_BOOK_STAGING_CONFIG","cleanObjectFromUndefinedValues","obj","Object","keys","key","val","OrderBookApi","context","RateLimiter","limiterOpts","getVersion","contextOverride","getTrades","orderUid","URLSearchParams","getOrders","offset","limit","toString","then","orders","map","getTxOrders","txHash","getOrder","getOrderMultiEnv","getContextWithOverride","otherEnvs","filter","i","attemptsCount","fallback","nextEnv","catch","getQuote","requestBody","sendSignedOrderCancellations","sendOrder","getNativePrice","tokenAddress","getTotalSurplus","getAppData","appDataHash","uploadAppData","fullAppData","getSolverCompetition","auctionIdorTx","getOrderLink","getApiBaseUrls","baseUrls","params","BuyTokenDestination","EcdsaSigningScheme","FeeAndQuoteError","OnchainOrderData","OrderCancellationError","OrderClass","OrderKind","OrderPostError","OrderQuoteSideKindBuy","OrderQuoteSideKindSell","OrderStatus","PriceQuality","ReplaceOrderError","SellTokenSource","SigningScheme","errorType","placementError","_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","type","_abi","inputs","internalType","stateMutability","anonymous","indexed","components","outputs","ComposableCoW__factory","utils","Interface","signerOrProvider","Contract","abi","ExtensibleFallbackHandler__factory","isExtensibleFallbackHandler","handler","isComposableCow","getDomainVerifier","safe","domain","provider","contract","connect","callStatic","domainVerifiers","createSetDomainVerifierTx","verifier","createInterface","encodeFunctionData","_excluded","CONDITIONAL_ORDER_LEAF_ABI","PAYLOAD_EMITTED_ABI","ProofLocation","Multiplexer","chain","root","location","PRIVATE","tree","ctx","length","orderKey","hasOwnProperty","orderTypeRegistry","orderType","getOrGenerateTree","s","reviver","k","v","_v$orderKey","orderData","_objectWithoutPropertiesLoose","OrderConstructor","orderArgs","values","BigNumber","from","m","toJSON","conditionalOrder","add","id","reset","remove","update","updater","getById","getByIndex","orderIds","StandardMerkleTree","of","leaf","uploader","_this","EMITTED","encodeToABI","SWARM","WAKU","IPFS","encodeToJSON","e","data","d","hexlify","arrayify","p","offChainInputFn","offChainInput","getTradeableOrderWithSignature","proof","dumpProofs","dumpProofsAndParams","getProofs","entries","idx","value","x","salt","staticInput","push","getProof","defaultAbiCoder","encode","conditionalOrderClass","CONDITIONAL_ORDER_PARAMS_ABI","BaseConditionalOrder","keccak256","ethers","randomBytes","hasOffChainInput","isAddress","isHexString","hexDataLength","transformParamsToData","createCalldata","composableCow","paramsStruct","encodeStaticInput","contextArgsAbi","factoryArgs","argsType","args","removeCalldata","serialize","encodeParams","types","encodeStaticInputHelper","orderDataTypes","encoded","decode","callback","recoveredHandler","decodeParams","TWAP_ADDRESS","CURRENT_BLOCK_TIMESTAMP_FACTORY_ADDRESS","MAX_UINT32","pow","sub","MAX_FREQUENCY","TWAP_DATA_ABI","TWAP","isValid","isValidAbi","t0","gt","buyToken","constants","AddressZero","sellAmount","Zero","buyAmount","gte","lt","n","One","lte","span","deserializeHelper","o","partsToTotal","tokenFormatter","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S,eAAgBT,EAAEV,WAAWsB,IAAIZ,EAAEL,GACnCgB,aAAcX,EAAER,UAAUoB,IAAIZ,EAAEL,GAEpC"}
|
|
1
|
+
{"version":3,"file":"index-856e1ad2.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/transformOrder.ts","../src/order-book/request.ts","../src/order-book/api.ts","../src/order-book/generated/models/BuyTokenDestination.ts","../src/order-book/generated/models/EcdsaSigningScheme.ts","../src/order-book/generated/models/FeeAndQuoteError.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/PriceQuality.ts","../src/order-book/generated/models/ReplaceOrderError.ts","../src/order-book/generated/models/SellTokenSource.ts","../src/order-book/generated/models/SigningScheme.ts","../src/subgraph/queries.ts","../src/subgraph/api.ts","../src/order-signing/orderSigningUtils.ts","../src/composable/generated/factories/ComposableCoW__factory.ts","../src/composable/generated/factories/ExtensibleFallbackHandler__factory.ts","../src/composable/extensible.ts","../src/composable/multiplexer.ts","../src/composable/conditionalorder.ts","../src/composable/types/twap.ts"],"sourcesContent":["/**\n * Supported chains and their `chainId` for the SDK.\n * @enum\n */\nexport enum SupportedChainId {\n MAINNET = 1,\n GOERLI = 5,\n GNOSIS_CHAIN = 100,\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} [5] The base URL for the Goerli testnet API.\n * @property {string} [100] The base URL for the Gnosis Chain 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 * - Goerli\n * - Gnosis Chain\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}\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'\nimport contractNetworks from '@cowprotocol/contracts/networks.json'\n\nconst { GPv2Settlement } = JSON.parse(contractNetworks as unknown as string) as typeof contractNetworks\n\nexport const BUY_ETH_ADDRESS = '0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE'\nexport const EXTENSIBLE_FALLBACK_HANDLER = '0x2f55e8b20D0B9FEFA187AA7d00B6Cbe563605bF5'\nexport const COMPOSABLE_COW = '0xfdaFc9d1902f4e0b84f65F49f244b32b31013b74'\n\n/**\n * The list of supported chains.\n */\nexport const ALL_SUPPORTED_CHAIN_IDS: SupportedChainId[] = [\n SupportedChainId.MAINNET,\n SupportedChainId.GOERLI,\n SupportedChainId.GNOSIS_CHAIN,\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 = ALL_SUPPORTED_CHAIN_IDS.reduce<Record<number, string>>(\n (acc, chainId) => ({\n ...acc,\n [chainId]: GPv2Settlement[chainId].address,\n }),\n {}\n)\n\n/**\n * An object containing the addresses of the `ExtensibleFallbackHandler` contracts for each supported chain.\n */\nexport const EXTENSIBLE_FALLBACK_HANDLER_CONTRACT_ADDRESS = ALL_SUPPORTED_CHAIN_IDS.reduce<Record<number, string>>(\n (acc, chainId) => ({\n ...acc,\n [chainId]: EXTENSIBLE_FALLBACK_HANDLER,\n }),\n {}\n)\n\n/**\n * An object containing the addresses of the `ComposableCow` contracts for each supported chain.\n */\nexport const COMPOSABLE_COW_CONTRACT_ADDRESS = ALL_SUPPORTED_CHAIN_IDS.reduce<Record<number, string>>(\n (acc, chainId) => ({\n ...acc,\n [chainId]: COMPOSABLE_COW,\n }),\n {}\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 `executedSurplusFee` represents exactly the fee that was charged (regardless of the fee\n * signed with the order). So, while the protocol currently does not allow placing a limit order\n * with any other fee than 0 - the backend is designed to support these kinds of orders for the\n * future.\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 const totalFee = executedSurplusFee ?? executedFeeAmount\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 { 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 'cross-fetch/polyfill'\nimport {\n Address,\n AppDataHash,\n AppDataObject,\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 { CowError } from '../common/cow-error'\nimport {\n ApiBaseUrls,\n ApiContext,\n CowEnv,\n DEFAULT_COW_API_CONTEXT,\n ENVS_LIST,\n PartialApiContext,\n RequestOptions,\n} from '../common/configs'\nimport { transformOrder } from './transformOrder'\nimport { EnrichedOrder } from './types'\nimport { SupportedChainId } from '../common/chains'\nimport { RateLimiter } from 'limiter'\nimport { DEFAULT_BACKOFF_OPTIONS, DEFAULT_LIMITER_OPTIONS, FetchParams, OrderBookApiError, request } from './request'\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.GOERLI]: 'https://api.cow.fi/goerli',\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.GOERLI]: 'https://barn.api.cow.fi/goerli',\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 = 5 // Goerli\n * const provider = new Web3Provider(window.ethereum)\n * const signer = provider.getSigner()\n *\n * const quoteRequest = {\n * sellToken: '0xb4fbf271143f4fbf7b91a5ded31805e42b2208d6', // WETH goerli\n * buyToken: '0x02abbdbaaa7b1bb64b5c878f7ac17f8dda169532', // GNO goerli\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.GOERLI })\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 & RequestOptions\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 & RequestOptions = {}) {\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 * 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 & RequestOptions {\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 } = this.getContextWithOverride(contextOverride)\n const baseUrl = this.getApiBaseUrls(env)[chainId]\n const backoffOpts = this.context.backoffOpts || DEFAULT_BACKOFF_OPTIONS\n\n return request(baseUrl, params, this.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\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\nexport type FeeAndQuoteError = {\n errorType: FeeAndQuoteError.errorType;\n description: string;\n};\n\nexport namespace FeeAndQuoteError {\n\n export enum errorType {\n NO_LIQUIDITY = 'NoLiquidity',\n UNSUPPORTED_TOKEN = 'UnsupportedToken',\n AMOUNT_IS_ZERO = 'AmountIsZero',\n SELL_AMOUNT_DOES_NOT_COVER_FEE = 'SellAmountDoesNotCoverFee',\n }\n\n\n}\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 DUPLICATE_ORDER = 'DuplicateOrder',\n INSUFFICIENT_FEE = 'InsufficientFee',\n INSUFFICIENT_ALLOWANCE = 'InsufficientAllowance',\n INSUFFICIENT_BALANCE = 'InsufficientBalance',\n INSUFFICIENT_VALID_TO = 'InsufficientValidTo',\n EXCESSIVE_VALID_TO = 'ExcessiveValidTo',\n INVALID_SIGNATURE = 'InvalidSignature',\n TRANSFER_ETH_TO_CONTRACT = 'TransferEthToContract',\n TRANSFER_SIMULATION_FAILED = 'TransferSimulationFailed',\n UNSUPPORTED_TOKEN = 'UnsupportedToken',\n WRONG_OWNER = 'WrongOwner',\n INVALID_EIP1271SIGNATURE = 'InvalidEip1271Signature',\n MISSING_FROM = 'MissingFrom',\n SAME_BUY_AND_SELL_TOKEN = 'SameBuyAndSellToken',\n ZERO_AMOUNT = 'ZeroAmount',\n UNSUPPORTED_BUY_TOKEN_DESTINATION = 'UnsupportedBuyTokenDestination',\n UNSUPPORTED_SELL_TOKEN_SOURCE = 'UnsupportedSellTokenSource',\n UNSUPPORTED_ORDER_TYPE = 'UnsupportedOrderType',\n UNSUPPORTED_SIGNATURE = 'UnsupportedSignature',\n TOO_MANY_LIMIT_ORDERS = 'TooManyLimitOrders',\n INVALID_APP_DATA = 'InvalidAppData',\n APP_DATA_HASH_MISMATCH = 'AppDataHashMismatch',\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\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` 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\nexport type ReplaceOrderError = {\n errorType: ReplaceOrderError.errorType;\n description: string;\n};\n\nexport namespace ReplaceOrderError {\n\n export enum errorType {\n ALREADY_CANCELLED = 'AlreadyCancelled',\n ORDER_FULLY_EXECUTED = 'OrderFullyExecuted',\n ORDER_EXPIRED = 'OrderExpired',\n ON_CHAIN_ORDER = 'OnChainOrder',\n DUPLICATE_ORDER = 'DuplicateOrder',\n INSUFFICIENT_FEE = 'InsufficientFee',\n INSUFFICIENT_ALLOWANCE = 'InsufficientAllowance',\n INSUFFICIENT_BALANCE = 'InsufficientBalance',\n INSUFFICIENT_VALID_TO = 'InsufficientValidTo',\n EXCESSIVE_VALID_TO = 'ExcessiveValidTo',\n INVALID_SIGNATURE = 'InvalidSignature',\n TRANSFER_ETH_TO_CONTRACT = 'TransferEthToContract',\n TRANSFER_SIMULATION_FAILED = 'TransferSimulationFailed',\n UNSUPPORTED_TOKEN = 'UnsupportedToken',\n WRONG_OWNER = 'WrongOwner',\n SAME_BUY_AND_SELL_TOKEN = 'SameBuyAndSellToken',\n ZERO_AMOUNT = 'ZeroAmount',\n UNSUPPORTED_BUY_TOKEN_DESTINATION = 'UnsupportedBuyTokenDestination',\n UNSUPPORTED_SELL_TOKEN_SOURCE = 'UnsupportedSellTokenSource',\n UNSUPPORTED_ORDER_TYPE = 'UnsupportedOrderType',\n UNSUPPORTED_SIGNATURE = 'UnsupportedSignature',\n }\n\n\n}\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 { 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 { CowError } from '../common/cow-error'\nimport { LastDaysVolumeQuery, LastHoursVolumeQuery, TotalsQuery } from './graphql'\nimport { LAST_DAYS_VOLUME_QUERY, LAST_HOURS_VOLUME_QUERY, TOTALS_QUERY } from './queries'\nimport { DocumentNode } from 'graphql/index'\nimport { request, Variables } from 'graphql-request'\nimport { ApiContext, CowEnv, DEFAULT_COW_API_CONTEXT, ApiBaseUrls, PartialApiContext } from '../common/configs'\nimport { SupportedChainId } from '../common/chains'\n\nconst SUBGRAPH_BASE_URL = 'https://api.thegraph.com/subgraphs/name/cowprotocol'\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 * @see {@link https://api.thegraph.com/subgraphs/name/cowprotocol/cow-goerli}\n */\nexport const SUBGRAPH_PROD_CONFIG: ApiBaseUrls = {\n [SupportedChainId.MAINNET]: SUBGRAPH_BASE_URL + '/cow',\n [SupportedChainId.GNOSIS_CHAIN]: SUBGRAPH_BASE_URL + '/cow-gc',\n [SupportedChainId.GOERLI]: SUBGRAPH_BASE_URL + '/cow-goerli',\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: ApiBaseUrls = {\n [SupportedChainId.MAINNET]: SUBGRAPH_BASE_URL + '/cow-staging',\n [SupportedChainId.GNOSIS_CHAIN]: SUBGRAPH_BASE_URL + '/cow-gc-staging',\n [SupportedChainId.GOERLI]: '',\n}\n\n/**\n * TheGraph API client for CoW Protocol.\n */\nexport class SubgraphApi {\n API_NAME = 'CoW Protocol Subgraph'\n\n public context: ApiContext\n\n /**\n * Create a new CoW Protocol API instance.\n * @param context Any properties of the {@link ApiContext} may be overridden by passing a {@link PartialApiContext}.\n */\n constructor(context: PartialApiContext = {}) {\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: PartialApiContext = {}): 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 {PartialApiContext} contextOverride Override the context for this call only.\n * @returns The volume for the last N days.\n */\n async getLastDaysVolume(days: number, contextOverride: PartialApiContext = {}): 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 {PartialApiContext} contextOverride Override the context for this call only.\n * @returns The volume for the last N hours.\n */\n async getLastHoursVolume(hours: number, contextOverride: PartialApiContext = {}): 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 {PartialApiContext} 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: PartialApiContext = {}\n ): Promise<T> {\n const { chainId, env } = this.getContextWithOverride(contextOverride)\n const baseUrl = this.getEnvConfigs(env)[chainId]\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 {PartialApiContext} contextOverride Override the context for this call only.\n * @returns {ApiContext} The 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 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): ApiBaseUrls {\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 = 5 // Goerli\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","/* 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 { providers } from 'ethers'\nimport {\n COMPOSABLE_COW_CONTRACT_ADDRESS,\n EXTENSIBLE_FALLBACK_HANDLER_CONTRACT_ADDRESS,\n SupportedChainId,\n} from '../common'\nimport { ExtensibleFallbackHandler__factory } from './generated'\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","import { StandardMerkleTree } from '@openzeppelin/merkle-tree'\nimport { BigNumber, providers, utils } from 'ethers'\n\nimport { COMPOSABLE_COW_CONTRACT_ADDRESS, SupportedChainId } from '../common'\nimport { BaseConditionalOrder, ConditionalOrderParams } from './conditionalorder'\n\nimport { ComposableCoW__factory } from './generated'\nimport { ComposableCoW, GPv2Order } from './generated/ComposableCoW'\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, BaseConditionalOrder<any, any>>\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: any[]\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\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: any[]) => BaseConditionalOrder<any, any>> = {}\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 const orderArgs = Object.values(orderData)\n orders[orderKey] = new OrderConstructor(...orderArgs)\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 BaseConditionalOrder<any, any>\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: BaseConditionalOrder<T, P>): void {\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 `BaseConditionalOrder` 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 `BaseConditionalOrder` to update.\n * @param updater A function that takes the existing `BaseConditionalOrder` and context, returning an updated `BaseConditionalOrder`.\n */\n update<T, P>(\n id: string,\n updater: (order: BaseConditionalOrder<T, P>, ctx?: string) => BaseConditionalOrder<T, P>\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 `BaseConditionalOrder` to retrieve.\n * @returns A `BaseConditionalOrder` with the given `id`.\n */\n getById(id: string): BaseConditionalOrder<any, any> {\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 `BaseConditionalOrder` to retrieve.\n * @returns A `BaseConditionalOrder` at the given index.\n */\n getByIndex(i: number): BaseConditionalOrder<any, any> {\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.DataStructOutput, string]> {\n const contract = ComposableCoW__factory.connect(COMPOSABLE_COW_CONTRACT_ADDRESS[chain], provider)\n const offChainInput = offChainInputFn ? await offChainInputFn(owner, p.params) : '0x'\n return await contract.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[]) => BaseConditionalOrder<any, any>\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 { BigNumber, ethers, utils } from 'ethers'\nimport { ContextFactory } from './multiplexer'\nimport { keccak256 } from 'ethers/lib/utils'\nimport { ComposableCoW__factory } from './generated'\nimport { IConditionalOrder } from './generated/ComposableCoW'\n\n// Define the ABI tuple for the TWAPData struct\nexport const CONDITIONAL_ORDER_PARAMS_ABI = ['tuple(address handler, bytes32 salt, bytes staticInput)']\n\nexport type ConditionalOrderParams = {\n readonly handler: string\n readonly salt: string\n readonly staticInput: string\n}\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 BaseConditionalOrder<T, P> {\n public readonly handler: string\n public readonly salt: string\n public readonly staticInput: T\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 `BaseConditionalOrder`.\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 staticInput The static input for the conditional 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(\n handler: string,\n salt: string = keccak256(ethers.utils.randomBytes(32)),\n staticInput: P,\n hasOffChainInput = false\n ) {\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.staticInput = this.transformParamsToData(staticInput)\n this.hasOffChainInput = hasOffChainInput\n }\n\n /**\n * Get the concrete type of the conditional order.\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 /**\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 const context = this.context\n const composableCow = ComposableCoW__factory.createInterface()\n const paramsStruct: IConditionalOrder.ConditionalOrderParamsStruct = {\n handler: this.handler,\n salt: this.salt,\n staticInput: this.encodeStaticInput(),\n }\n\n if (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 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 const composableCow = ComposableCoW__factory.createInterface()\n return composableCow.encodeFunctionData('remove', [this.id])\n }\n\n /**\n * Calculate the id of the conditional order.\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 * 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(BaseConditionalOrder.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 * 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 */\n protected static isValidAbi(types: readonly (string | ethers.utils.ParamType)[], values: any[]): boolean {\n try {\n ethers.utils.defaultAbiCoder.encode(types, values)\n } catch (e) {\n return false\n }\n return true\n }\n\n /**\n * Create a human-readable string representation of the conditional order.\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 * @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 * @param orderDataTypes ABI types for the order's data struct.\n * @param staticInput The order's data struct.\n * @returns An ABI-encoded representation of the order's data struct.\n */\n protected encodeStaticInputHelper(orderDataTypes: string[], staticInput: T): string {\n try {\n return utils.defaultAbiCoder.encode(orderDataTypes, [staticInput])\n } catch (e) {\n throw new Error('SerializationFailed')\n }\n }\n\n /**\n * Apply any transformations to the parameters that are passed in to the constructor.\n *\n * **NOTE**: This should be overridden by any conditional order that requires transformations.\n * This implementation is a no-op.\n * @param params {P} Parameters that are passed in to the constructor.\n * @returns {T} The static input for the conditional order.\n */\n protected transformParamsToData(params: P): T {\n return params as unknown as T\n }\n\n /**\n * Encode the `ConditionalOrderParams` for the conditional order.\n * @param leaf The `ConditionalOrderParams` struct representing the conditional order as taken from a merkle tree.\n * @returns The ABI-encoded conditional order.\n * @see ConditionalOrderParams\n */\n static encodeParams(leaf: ConditionalOrderParams): string {\n try {\n return utils.defaultAbiCoder.encode(CONDITIONAL_ORDER_PARAMS_ABI, [leaf])\n } catch (e) {\n throw new Error('SerializationFailed')\n }\n }\n\n /**\n * Decode the `ConditionalOrderParams` for the conditional order.\n * @param encoded The encoded conditional order.\n * @returns The decoded conditional order.\n */\n static decodeParams(encoded: string): ConditionalOrderParams {\n try {\n return utils.defaultAbiCoder.decode(CONDITIONAL_ORDER_PARAMS_ABI, encoded)[0]\n } catch (e) {\n throw new Error('DeserializationFailed')\n }\n }\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 } = BaseConditionalOrder.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 { BigNumber, constants, ethers, utils } from 'ethers'\n\nimport { BaseConditionalOrder } from '../conditionalorder'\nimport { ContextFactory } from '../multiplexer'\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_DATA_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 * Parameters for a TWAP order, made a little more user-friendly for SDK users.\n * @see {@link TWAPData} for the native struct.\n */\nexport type TWAPDataParams = Omit<TWAPData, 'partSellAmount' | 'minPartLimit'> & {\n // total amount of sellToken to sell across the entire TWAP\n readonly sellAmount: BigNumber\n // minimum amount of buyToken that must be bought across the entire TWAP\n readonly buyAmount: BigNumber\n}\n\n/**\n * Parameters for a TWAP order, as expected by the contract's `staticInput`.\n */\nexport type TWAPData = {\n // which token to sell\n readonly sellToken: string\n // which token to buy\n readonly buyToken: string\n // who to send the tokens to\n readonly receiver: string\n // amount of sellToken to sell in each part\n readonly partSellAmount: BigNumber\n // minimum amount of buyToken that must be bought in each part\n readonly minPartLimit: BigNumber\n // start time of the TWAP\n readonly t0: BigNumber\n // number of parts\n readonly n: BigNumber\n // duration of the TWAP interval\n readonly t: BigNumber\n // whether the TWAP is valid for the entire interval or not\n readonly span: BigNumber\n // appData\n readonly appData: string\n}\n\n/**\n * `ComposableCoW` implementation of a TWAP order.\n * @author mfw78 <mfw78@rndlabs.xyz>\n */\nexport class TWAP extends BaseConditionalOrder<TWAPData, TWAPDataParams> {\n /**\n * @see {@link BaseConditionalOrder.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(\n handler: string,\n salt: string = utils.keccak256(ethers.utils.randomBytes(32)),\n staticInput: TWAPDataParams,\n hasOffChainInput = false\n ) {\n // First, verify that the handler is the TWAP address\n if (handler !== TWAP_ADDRESS) throw new Error('InvalidHandler')\n\n // Second, verify that the order params are logically valid\n TWAP.isValid(staticInput)\n\n // Third, construct the base class using transformed parameters\n super(TWAP_ADDRESS, salt, staticInput, hasOffChainInput)\n\n // Finally, verify that the transformed data is ABI-encodable\n if (!TWAP.isValidAbi(TWAP_DATA_ABI, [this.staticInput])) throw new Error('InvalidData')\n }\n\n /**\n * Create a TWAP order with sound defaults.\n * @param staticInput The TWAP order parameters in a more user-friendly format.\n * @returns An instance of the TWAP order.\n */\n static default(staticInput: TWAPDataParams): BaseConditionalOrder<TWAPData, TWAPDataParams> {\n return new TWAP(TWAP_ADDRESS, undefined, staticInput)\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 BaseConditionalOrder.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 TWAPData} for the native struct.\n */\n static isValid(data: TWAPDataParams): boolean {\n if (!(data.sellToken != data.buyToken)) throw new Error('InvalidSameToken')\n if (!(data.sellToken != constants.AddressZero && data.buyToken != constants.AddressZero))\n throw new Error('InvalidToken')\n if (!data.sellAmount.gt(constants.Zero)) throw new Error('InvalidSellAmount')\n if (!data.buyAmount.gt(constants.Zero)) throw new Error('InvalidMinBuyAmount')\n if (!(data.t0.gte(constants.Zero) && data.t0.lt(MAX_UINT32))) throw new Error('InvalidStartTime')\n if (!(data.n.gt(constants.One) && data.n.lte(MAX_UINT32))) throw new Error('InvalidNumParts')\n if (!(data.t.gt(constants.Zero) && data.t.lte(MAX_FREQUENCY))) throw new Error('InvalidFrequency')\n if (!data.span.lte(data.t)) throw new Error('InvalidSpan')\n return true\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 BaseConditionalOrder.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_DATA_ABI, this.staticInput)\n }\n\n /**\n * Deserialize a TWAP order from it's ABI-encoded form.\n * @param {string} s ABI-encoded TWAP order to deserialize.\n * @returns A deserialized TWAP order.\n */\n static deserialize(s: string): TWAP {\n return super.deserializeHelper(\n s,\n TWAP_ADDRESS,\n TWAP_DATA_ABI,\n (o: TWAPData, salt: string) =>\n new TWAP(TWAP_ADDRESS, salt, {\n ...o,\n ...TWAP.partsToTotal(o),\n })\n )\n }\n\n /**\n * Create a human-readable string representation of the TWAP order.\n * @param {((address: string, amount: BigNumber) => string) | undefined} tokenFormatter An optional\n * function that takes an address and an amount and returns a human-readable string.\n * @returns {string} A human-readable string representation of the TWAP order.\n */\n toString(tokenFormatter?: (address: string, amount: BigNumber) => string): string {\n const defaultFormatter = (address: string, amount: BigNumber) => `${address}@${amount}`\n tokenFormatter = tokenFormatter || defaultFormatter\n\n const { sellAmount, buyAmount } = TWAP.partsToTotal(this.staticInput)\n\n return `${this.orderType}: Sell total ${tokenFormatter(\n this.staticInput.sellToken,\n sellAmount\n )} for a minimum of ${tokenFormatter(this.staticInput.buyToken, buyAmount)} over ${\n this.staticInput.n\n } parts with a spacing of ${this.staticInput.t}s beginning at ${\n this.staticInput.t0.eq(0) ? 'time of mining' : new Date(Number(this.staticInput.t0) * 1000)\n }`\n }\n\n /**\n * Transform parameters into a native struct.\n * @param {TWAPDataParams} params As passed by the consumer of the API.\n * @returns {TWAPData} A formatted struct as expected by the smart contract.\n */\n transformParamsToData(params: TWAPDataParams): TWAPData {\n return {\n ...params,\n ...TWAP.totalToPart(params),\n }\n }\n\n /**\n * Convert TWAP parts to total amounts.\n * @param {TWAPData} o The TWAP order.\n * @returns {object} The total sell amount and total minimum buy amount.\n */\n private static partsToTotal(o: TWAPData): {\n sellAmount: BigNumber\n buyAmount: BigNumber\n } {\n return {\n sellAmount: o.partSellAmount.mul(o.n),\n buyAmount: o.minPartLimit.mul(o.n),\n }\n }\n\n /**\n * Convert total amounts to TWAP parts.\n * @param {TWAPDataParams} o The TWAP order parameters.\n * @returns {object} The part sell amount and minimum part limit.\n * @throws If the number of parts is less than 1.\n */\n private static totalToPart(o: TWAPDataParams): {\n partSellAmount: BigNumber\n minPartLimit: BigNumber\n } {\n return {\n partSellAmount: o.sellAmount.div(o.n),\n minPartLimit: o.buyAmount.div(o.n),\n }\n }\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","GPv2Settlement","JSON","parse","BUY_ETH_ADDRESS","EXTENSIBLE_FALLBACK_HANDLER","COMPOSABLE_COW","ALL_SUPPORTED_CHAIN_IDS","GOERLI","GNOSIS_CHAIN","COW_PROTOCOL_SETTLEMENT_CONTRACT_ADDRESS","reduce","acc","_extends","address","EXTENSIBLE_FALLBACK_HANDLER_CONTRACT_ADDRESS","COMPOSABLE_COW_CONTRACT_ADDRESS","transformOrder","order","ethflowData","userValidTo","validTo","owner","onchainUser","sellToken","transformEthFlowOrder","dto","executedFeeAmount","executedSurplusFee","totalFee","addTotalFeeToOrder","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","stringify","Accept","backOff","removeTokens","fetch","responseBody","Promise","reject","ORDER_BOOK_PROD_CONFIG","ORDER_BOOK_STAGING_CONFIG","cleanObjectFromUndefinedValues","obj","Object","keys","key","val","OrderBookApi","context","RateLimiter","limiterOpts","getVersion","contextOverride","getTrades","orderUid","URLSearchParams","getOrders","offset","limit","toString","then","orders","map","getTxOrders","txHash","getOrder","getOrderMultiEnv","getContextWithOverride","otherEnvs","filter","i","attemptsCount","fallback","nextEnv","catch","getQuote","requestBody","sendSignedOrderCancellations","sendOrder","getNativePrice","tokenAddress","getTotalSurplus","getAppData","appDataHash","uploadAppData","fullAppData","getSolverCompetition","auctionIdorTx","getOrderLink","getApiBaseUrls","baseUrls","params","BuyTokenDestination","EcdsaSigningScheme","FeeAndQuoteError","OnchainOrderData","OrderCancellationError","OrderClass","OrderKind","OrderPostError","OrderQuoteSideKindBuy","OrderQuoteSideKindSell","OrderStatus","PriceQuality","ReplaceOrderError","SellTokenSource","SigningScheme","errorType","placementError","_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","type","_abi","inputs","internalType","stateMutability","anonymous","indexed","components","outputs","ComposableCoW__factory","utils","Interface","signerOrProvider","Contract","abi","ExtensibleFallbackHandler__factory","isExtensibleFallbackHandler","handler","isComposableCow","getDomainVerifier","safe","domain","provider","contract","connect","callStatic","domainVerifiers","createSetDomainVerifierTx","verifier","createInterface","encodeFunctionData","_excluded","CONDITIONAL_ORDER_LEAF_ABI","PAYLOAD_EMITTED_ABI","ProofLocation","Multiplexer","chain","root","location","PRIVATE","tree","ctx","length","orderKey","hasOwnProperty","orderTypeRegistry","orderType","getOrGenerateTree","s","reviver","k","v","_v$orderKey","orderData","_objectWithoutPropertiesLoose","OrderConstructor","orderArgs","values","BigNumber","from","m","toJSON","conditionalOrder","add","id","reset","remove","update","updater","getById","getByIndex","orderIds","StandardMerkleTree","of","leaf","uploader","_this","EMITTED","encodeToABI","SWARM","WAKU","IPFS","encodeToJSON","e","data","d","hexlify","arrayify","p","offChainInputFn","offChainInput","getTradeableOrderWithSignature","proof","dumpProofs","dumpProofsAndParams","getProofs","entries","idx","value","x","salt","staticInput","push","getProof","defaultAbiCoder","encode","conditionalOrderClass","CONDITIONAL_ORDER_PARAMS_ABI","BaseConditionalOrder","keccak256","ethers","randomBytes","hasOffChainInput","isAddress","isHexString","hexDataLength","transformParamsToData","createCalldata","composableCow","paramsStruct","encodeStaticInput","contextArgsAbi","factoryArgs","argsType","args","removeCalldata","serialize","encodeParams","types","encodeStaticInputHelper","orderDataTypes","encoded","decode","callback","recoveredHandler","decodeParams","TWAP_ADDRESS","CURRENT_BLOCK_TIMESTAMP_FACTORY_ADDRESS","MAX_UINT32","pow","sub","MAX_FREQUENCY","TWAP_DATA_ABI","TWAP","isValid","isValidAbi","t0","gt","buyToken","constants","AddressZero","sellAmount","Zero","buyAmount","gte","lt","n","One","lte","span","deserializeHelper","o","partsToTotal","tokenFormatter","defaultFormatter","amount","eq","Date","Number","totalToPart","partSellAmount","mul","minPartLimit","div"],"mappings":"uWAIY,IAAAA,GAAZ,SAAYA,GACVA,EAAAA,EAAA,QAAA,GAAA,UACAA,EAAAA,EAAA,OAAA,GAAA,SACAA,EAAAA,EAAA,aAAA,KAAA,cACD,CAJD,CAAYA,IAAAA,EAIX,CAAA,ICkEY,MAAAC,EAAsB,CAAC,OAAQ,WAK/BC,EAAsC,CACjDC,IAAK,OACLC,QAASJ,EAAiBK,SCjFf,MAAAC,UAAiBC,MAG5BC,YAAYC,EAAiBC,GAC3BC,MAAMF,GAAQG,KAHhBF,gBAIE,EAAAE,KAAKF,WAAaA,CACpB,EAGW,MAAAG,EAAY,WCTZC,EA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