Socket
Socket
Sign inDemoInstall

@cowprotocol/cow-sdk

Package Overview
Dependencies
Maintainers
8
Versions
95
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@cowprotocol/cow-sdk - npm Package Compare versions

Comparing version 2.0.0-alpha.4 to 2.1.0

dist/common/consts.d.ts

9

dist/common/configs.d.ts
import { SupportedChainId } from './chains';
import { BackoffOptions } from 'exponential-backoff';
import { RateLimiterOpts } from 'limiter/dist/esm';
export interface IpfsConfig {

@@ -9,10 +11,15 @@ uri?: string;

}
export interface RequestOptions {
limiterOpts?: RateLimiterOpts;
backoffOpts?: BackoffOptions;
}
export type CowEnv = 'prod' | 'staging';
export type PartialApiContext = Partial<ApiContext>;
export type EnvConfigs = Record<SupportedChainId, string>;
export type ApiBaseUrls = Record<SupportedChainId, string>;
export interface ApiContext {
chainId: SupportedChainId;
env: CowEnv;
baseUrls?: ApiBaseUrls;
}
export declare const ENVS_LIST: CowEnv[];
export declare const DEFAULT_COW_API_CONTEXT: ApiContext;

@@ -5,1 +5,2 @@ export * from './chains';

export * from './ipfs';
export * from './consts';
export * from './common';
export * from './order-book';
export * from './subgraph';
export * from './order-signing';

8

dist/index.js

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

var e,r=require("graphql-request");exports.SupportedChainId=void 0,(e=exports.SupportedChainId||(exports.SupportedChainId={}))[e.MAINNET=1]="MAINNET",e[e.GOERLI=5]="GOERLI",e[e.GNOSIS_CHAIN=100]="GNOSIS_CHAIN";const t=["prod","staging"],o={env:"prod",chainId:exports.SupportedChainId.MAINNET};class n extends Error{constructor(e,r){super(e),this.error_code=void 0,this.error_code=r}}class s{constructor(e){this.config=void 0,this.config=e}}class i extends Error{constructor(e,r,t){super(t),this.url=void 0,this.status=void 0,this.statusText=void 0,this.body=void 0,this.request=void 0,this.name="ApiError",this.url=r.url,this.status=r.status,this.statusText=r.statusText,this.body=r.body,this.request=e}}let a;class d extends Error{constructor(e){super(e),this.name="CancelError"}get isCancelled(){return!0}}a=Symbol.toStringTag;class c{constructor(e){this[a]=void 0,this._isResolved=void 0,this._isRejected=void 0,this._isCancelled=void 0,this._cancelHandlers=void 0,this._promise=void 0,this._resolve=void 0,this._reject=void 0,this._isResolved=!1,this._isRejected=!1,this._isCancelled=!1,this._cancelHandlers=[],this._promise=new Promise((r,t)=>{this._resolve=r,this._reject=t;const o=e=>{this._isResolved||this._isRejected||this._isCancelled||this._cancelHandlers.push(e)};return Object.defineProperty(o,"isResolved",{get:()=>this._isResolved}),Object.defineProperty(o,"isRejected",{get:()=>this._isRejected}),Object.defineProperty(o,"isCancelled",{get:()=>this._isCancelled}),e(e=>{this._isResolved||this._isRejected||this._isCancelled||(this._isResolved=!0,this._resolve?.(e))},e=>{this._isResolved||this._isRejected||this._isCancelled||(this._isRejected=!0,this._reject?.(e))},o)})}then(e,r){return this._promise.then(e,r)}catch(e){return this._promise.catch(e)}finally(e){return this._promise.finally(e)}cancel(){if(!(this._isResolved||this._isRejected||this._isCancelled)){if(this._isCancelled=!0,this._cancelHandlers.length)try{for(const e of this._cancelHandlers)e()}catch(e){return void console.warn("Cancellation threw an error",e)}this._cancelHandlers.length=0,this._reject?.(new d("Request aborted"))}}get isCancelled(){return this._isCancelled}}function u(e,r){try{var t=e()}catch(e){return r(e)}return t&&t.then?t.then(void 0,r):t}const p=e=>null!=e,h=e=>"string"==typeof e,l=e=>h(e)&&""!==e,E=e=>"object"==typeof e&&"string"==typeof e.type&&"function"==typeof e.stream&&"function"==typeof e.arrayBuffer&&"function"==typeof e.constructor&&"string"==typeof e.constructor.name&&/^(Blob|File)$/.test(e.constructor.name)&&/^(Blob|File)$/.test(e[Symbol.toStringTag]),T=e=>e instanceof FormData,O=function(e,r){try{return Promise.resolve("function"==typeof r?r(e):r)}catch(e){return Promise.reject(e)}},S=function(e,r){try{return Promise.resolve(O(r,e.TOKEN)).then(function(t){return Promise.resolve(O(r,e.USERNAME)).then(function(o){return Promise.resolve(O(r,e.PASSWORD)).then(function(n){return Promise.resolve(O(r,e.HEADERS)).then(function(e){const s=Object.entries({Accept:"application/json",...e,...r.headers}).filter(([e,r])=>p(r)).reduce((e,[r,t])=>({...e,[r]:String(t)}),{});if(l(t)&&(s.Authorization=`Bearer ${t}`),l(o)&&l(n)){const e=(e=>{try{return btoa(e)}catch(r){return Buffer.from(e).toString("base64")}})(`${o}:${n}`);s.Authorization=`Basic ${e}`}return r.body&&(r.mediaType?s["Content-Type"]=r.mediaType:E(r.body)?s["Content-Type"]=r.body.type||"application/octet-stream":h(r.body)?s["Content-Type"]="text/plain":T(r.body)||(s["Content-Type"]="application/json")),new Headers(s)})})})})}catch(e){return Promise.reject(e)}},I=(e,r)=>new c(function(t,o,n){try{const s=u(function(){const o=((e,r)=>{const t=e.ENCODE_PATH||encodeURI,o=r.url.replace("{api-version}",e.VERSION).replace(/{(.*?)}/g,(e,o)=>r.path?.hasOwnProperty(o)?t(String(r.path[o])):e),n=`${e.BASE}${o}`;return r.query?`${n}${(e=>{const r=[],t=(e,o)=>{p(o)&&(Array.isArray(o)?o.forEach(r=>{t(e,r)}):"object"==typeof o?Object.entries(o).forEach(([r,o])=>{t(`${e}[${r}]`,o)}):((e,t)=>{r.push(`${encodeURIComponent(e)}=${encodeURIComponent(String(t))}`)})(e,o))};return Object.entries(e).forEach(([e,r])=>{t(e,r)}),r.length>0?`?${r.join("&")}`:""})(r.query)}`:n})(e,r),s=(e=>{if(e.formData){const r=new FormData,t=(e,t)=>{h(t)||E(t)?r.append(e,t):r.append(e,JSON.stringify(t))};return Object.entries(e.formData).filter(([e,r])=>p(r)).forEach(([e,r])=>{Array.isArray(r)?r.forEach(r=>t(e,r)):t(e,r)}),r}})(r),a=(e=>{if(e.body)return e.mediaType?.includes("/json")?JSON.stringify(e.body):h(e.body)||E(e.body)||T(e.body)?e.body:JSON.stringify(e.body)})(r);return Promise.resolve(S(e,r)).then(function(d){const c=function(){if(!n.isCancelled)return Promise.resolve(function(e,r,t,o,n,s,i){try{const a=new AbortController,d={headers:s,body:null!=o?o:n,method:r.method,signal:a.signal};return e.WITH_CREDENTIALS&&(d.credentials=e.CREDENTIALS),i(()=>a.abort()),Promise.resolve(fetch(t,d))}catch(e){return Promise.reject(e)}}(e,r,o,a,s,d,n)).then(function(e){return Promise.resolve(function(e){try{let r;const t=function(){if(204!==e.status)return u(function(){const t=e.headers.get("Content-Type");return function(){if(t)return t.toLowerCase().startsWith("application/json")?Promise.resolve(e.json()).then(function(e){return r=1,e}):Promise.resolve(e.text()).then(function(e){return r=1,e})}()},function(e){console.error(e)})}();return Promise.resolve(t&&t.then?t.then(function(e){return r?e:void 0}):r?t:void 0)}catch(e){return Promise.reject(e)}}(e)).then(function(n){const s=((e,r)=>{if(r){const t=e.headers.get(r);if(h(t))return t}})(e,r.responseHeader),a={url:o,ok:e.ok,status:e.status,statusText:e.statusText,body:null!=s?s:n};((e,r)=>{const t={400:"Bad Request",401:"Unauthorized",403:"Forbidden",404:"Not Found",500:"Internal Server Error",502:"Bad Gateway",503:"Service Unavailable",...e.errors}[r.status];if(t)throw new i(e,r,t);if(!r.ok)throw new i(e,r,"Generic Error")})(r,a),t(a.body)})})}();if(c&&c.then)return c.then(function(){})})},function(e){o(e)});return Promise.resolve(s&&s.then?s.then(function(){}):void 0)}catch(e){return Promise.reject(e)}});class _ extends s{constructor(e){super(e)}request(e){return I(this.config,e)}}class N{constructor(e){this.httpRequest=void 0,this.httpRequest=e}postApiV1Orders(e){return this.httpRequest.request({method:"POST",url:"/api/v1/orders",body:e,mediaType:"application/json",errors:{400:"Error during order validation",403:"Forbidden, your account is deny-listed",429:"Too many order placements",500:"Error adding an order"}})}deleteApiV1Orders(e){return this.httpRequest.request({method:"DELETE",url:"/api/v1/orders",body:e,mediaType:"application/json",errors:{400:"Malformed signature",401:"Invalid signature",404:"One or more orders were not found and no orders were cancelled."}})}getApiV1Orders(e){return this.httpRequest.request({method:"GET",url:"/api/v1/orders/{UID}",path:{UID:e},errors:{404:"Order was not found"}})}deleteApiV1Orders1(e,r){return this.httpRequest.request({method:"DELETE",url:"/api/v1/orders/{UID}",path:{UID:e},body:r,mediaType:"application/json",errors:{400:"Malformed signature",401:"Invalid signature",404:"Order was not found"}})}patchApiV1Orders(e,r){return this.httpRequest.request({method:"PATCH",url:"/api/v1/orders/{UID}",path:{UID:e},body:r,mediaType:"application/json",errors:{400:"Error cancelling and replacing new order with an old one.",401:"Invalid replacement order. This can happen if the old and new orders have\n different signers, the new order's app data is not an encoded cancellation of\n the old order, or the new order is based on presign or EIP-1271 signatures.\n ",403:"Forbidden",404:"Order was not found"}})}getApiV1TransactionsOrders(e){return this.httpRequest.request({method:"GET",url:"/api/v1/transactions/{txHash}/orders",path:{txHash:e}})}getApiV1Trades(e,r){return this.httpRequest.request({method:"GET",url:"/api/v1/trades",query:{owner:e,orderUid:r}})}getApiV1Auction(){return this.httpRequest.request({method:"GET",url:"/api/v1/auction"})}getApiV1AccountOrders(e,r,t){return this.httpRequest.request({method:"GET",url:"/api/v1/account/{owner}/orders",path:{owner:e},query:{offset:r,limit:t},errors:{400:"Problem with parameters like limit being too large."}})}getApiV1TokenNativePrice(e){return this.httpRequest.request({method:"GET",url:"/api/v1/token/{token}/native_price",path:{token:e},errors:{400:"Error finding the price.",404:"No liquidity was found",500:"Unexpected error"}})}postApiV1Quote(e){return this.httpRequest.request({method:"POST",url:"/api/v1/quote",body:e,mediaType:"application/json",errors:{400:"Error quoting order.",403:"Forbidden, your account is deny-listed",429:"Too many order quotes",500:"Unexpected error quoting an order"}})}getApiV1SolverCompetition(e){return this.httpRequest.request({method:"GET",url:"/api/v1/solver_competition/{auction_id}",path:{auction_id:e},errors:{404:"No competition information available for this auction id."}})}getApiV1SolverCompetitionByTxHash(e){return this.httpRequest.request({method:"GET",url:"/api/v1/solver_competition/by_tx_hash/{tx_hash}",path:{tx_hash:e},errors:{404:"No competition information available for this tx hash."}})}getApiV1Version(){return this.httpRequest.request({method:"GET",url:"/api/v1/version"})}}class f{constructor(e,r=_){var t,o,n,s;this.default=void 0,this.request=void 0,this.request=new r({BASE:null!==(t=e?.BASE)&&void 0!==t?t:"https://api.cow.fi/mainnet",VERSION:null!==(o=e?.VERSION)&&void 0!==o?o:"0.0.1",WITH_CREDENTIALS:null!==(n=e?.WITH_CREDENTIALS)&&void 0!==n&&n,CREDENTIALS:null!==(s=e?.CREDENTIALS)&&void 0!==s?s:"include",TOKEN:e?.TOKEN,USERNAME:e?.USERNAME,PASSWORD:e?.PASSWORD,HEADERS:e?.HEADERS,ENCODE_PATH:e?.ENCODE_PATH}),this.default=new N(this.request)}}var v,A,R,g,m,y,C,x,D,P,U,L,w,F,b,q;exports.BuyTokenDestination=void 0,(v=exports.BuyTokenDestination||(exports.BuyTokenDestination={})).ERC20="erc20",v.INTERNAL="internal",exports.EcdsaSigningScheme=void 0,(A=exports.EcdsaSigningScheme||(exports.EcdsaSigningScheme={})).EIP712="eip712",A.ETHSIGN="ethsign",exports.FeeAndQuoteError=void 0,(g=(R=exports.FeeAndQuoteError||(exports.FeeAndQuoteError={})).errorType||(R.errorType={})).NO_LIQUIDITY="NoLiquidity",g.UNSUPPORTED_TOKEN="UnsupportedToken",g.AMOUNT_IS_ZERO="AmountIsZero",g.SELL_AMOUNT_DOES_NOT_COVER_FEE="SellAmountDoesNotCoverFee",exports.OnchainOrderData=void 0,(y=(m=exports.OnchainOrderData||(exports.OnchainOrderData={})).placementError||(m.placementError={})).QUOTE_NOT_FOUND="QuoteNotFound",y.VALID_TO_TOO_FAR_IN_FUTURE="ValidToTooFarInFuture",y.PRE_VALIDATION_ERROR="PreValidationError",exports.OrderCancellationError=void 0,function(e){e.INVALID_SIGNATURE="InvalidSignature",e.WRONG_OWNER="WrongOwner",e.ORDER_NOT_FOUND="OrderNotFound",e.ALREADY_CANCELLED="AlreadyCancelled",e.ORDER_FULLY_EXECUTED="OrderFullyExecuted",e.ORDER_EXPIRED="OrderExpired",e.ON_CHAIN_ORDER="OnChainOrder"}((C=exports.OrderCancellationError||(exports.OrderCancellationError={})).errorType||(C.errorType={})),exports.OrderClass=void 0,(x=exports.OrderClass||(exports.OrderClass={})).MARKET="market",x.LIMIT="limit",x.LIQUIDITY="liquidity",exports.OrderKind=void 0,(D=exports.OrderKind||(exports.OrderKind={})).BUY="buy",D.SELL="sell",exports.OrderPostError=void 0,function(e){e.DUPLICATE_ORDER="DuplicateOrder",e.INSUFFICIENT_FEE="InsufficientFee",e.INSUFFICIENT_ALLOWANCE="InsufficientAllowance",e.INSUFFICIENT_BALANCE="InsufficientBalance",e.INSUFFICIENT_VALID_TO="InsufficientValidTo",e.EXCESSIVE_VALID_TO="ExcessiveValidTo",e.INVALID_SIGNATURE="InvalidSignature",e.TRANSFER_ETH_TO_CONTRACT="TransferEthToContract",e.TRANSFER_SIMULATION_FAILED="TransferSimulationFailed",e.UNSUPPORTED_TOKEN="UnsupportedToken",e.WRONG_OWNER="WrongOwner",e.MISSING_FROM="MissingFrom",e.SAME_BUY_AND_SELL_TOKEN="SameBuyAndSellToken",e.ZERO_AMOUNT="ZeroAmount",e.UNSUPPORTED_BUY_TOKEN_DESTINATION="UnsupportedBuyTokenDestination",e.UNSUPPORTED_SELL_TOKEN_SOURCE="UnsupportedSellTokenSource",e.UNSUPPORTED_ORDER_TYPE="UnsupportedOrderType",e.UNSUPPORTED_SIGNATURE="UnsupportedSignature",e.TOO_MANY_LIMIT_ORDERS="TooManyLimitOrders"}((P=exports.OrderPostError||(exports.OrderPostError={})).errorType||(P.errorType={})),exports.OrderQuoteSide=void 0,((U=exports.OrderQuoteSide||(exports.OrderQuoteSide={})).kind||(U.kind={})).SELL="sell",exports.OrderStatus=void 0,(L=exports.OrderStatus||(exports.OrderStatus={})).PRESIGNATURE_PENDING="presignaturePending",L.OPEN="open",L.FULFILLED="fulfilled",L.CANCELLED="cancelled",L.EXPIRED="expired",exports.PriceQuality=void 0,(w=exports.PriceQuality||(exports.PriceQuality={})).FAST="fast",w.OPTIMAL="optimal",exports.ReplaceOrderError=void 0,function(e){e.ALREADY_CANCELLED="AlreadyCancelled",e.ORDER_FULLY_EXECUTED="OrderFullyExecuted",e.ORDER_EXPIRED="OrderExpired",e.ON_CHAIN_ORDER="OnChainOrder",e.DUPLICATE_ORDER="DuplicateOrder",e.INSUFFICIENT_FEE="InsufficientFee",e.INSUFFICIENT_ALLOWANCE="InsufficientAllowance",e.INSUFFICIENT_BALANCE="InsufficientBalance",e.INSUFFICIENT_VALID_TO="InsufficientValidTo",e.EXCESSIVE_VALID_TO="ExcessiveValidTo",e.INVALID_SIGNATURE="InvalidSignature",e.TRANSFER_ETH_TO_CONTRACT="TransferEthToContract",e.TRANSFER_SIMULATION_FAILED="TransferSimulationFailed",e.UNSUPPORTED_TOKEN="UnsupportedToken",e.WRONG_OWNER="WrongOwner",e.SAME_BUY_AND_SELL_TOKEN="SameBuyAndSellToken",e.ZERO_AMOUNT="ZeroAmount",e.UNSUPPORTED_BUY_TOKEN_DESTINATION="UnsupportedBuyTokenDestination",e.UNSUPPORTED_SELL_TOKEN_SOURCE="UnsupportedSellTokenSource",e.UNSUPPORTED_ORDER_TYPE="UnsupportedOrderType",e.UNSUPPORTED_SIGNATURE="UnsupportedSignature"}((F=exports.ReplaceOrderError||(exports.ReplaceOrderError={})).errorType||(F.errorType={})),exports.SellTokenSource=void 0,(b=exports.SellTokenSource||(exports.SellTokenSource={})).ERC20="erc20",b.INTERNAL="internal",b.EXTERNAL="external",exports.SigningScheme=void 0,(q=exports.SigningScheme||(exports.SigningScheme={})).EIP712="eip712",q.ETHSIGN="ethsign",q.PRESIGN="presign",q.EIP1271="eip1271";const V="0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE";function G(e){return function(e){const{ethflowData:r}=e;if(!r)return e;const{userValidTo:t}=r,o=e.onchainUser||e.owner,n=V;return{...e,validTo:t,owner:o,sellToken:n}}(function(e){const{executedFeeAmount:r,executedSurplusFee:t}=e,o=null!=t?t:r;return{...e,totalFee:o}}(e))}const k={[exports.SupportedChainId.MAINNET]:"https://api.cow.fi/mainnet",[exports.SupportedChainId.GNOSIS_CHAIN]:"https://api.cow.fi/xdai",[exports.SupportedChainId.GOERLI]:"https://api.cow.fi/goerli"},j={[exports.SupportedChainId.MAINNET]:"https://barn.api.cow.fi/mainnet",[exports.SupportedChainId.GNOSIS_CHAIN]:"https://barn.api.cow.fi/xdai",[exports.SupportedChainId.GOERLI]:"https://barn.api.cow.fi/goerli"};class H extends s{constructor(e){super(e)}request(e){return I(this.config,{...e,headers:{...e.headers,"Content-Type":"application/json"}})}}const B=r.gql`
require("cross-fetch/polyfill");var e,r=require("limiter"),t=require("exponential-backoff"),n=require("graphql-request");exports.SupportedChainId=void 0,(e=exports.SupportedChainId||(exports.SupportedChainId={}))[e.MAINNET=1]="MAINNET",e[e.GOERLI=5]="GOERLI",e[e.GNOSIS_CHAIN=100]="GNOSIS_CHAIN";const o=["prod","staging"],s={env:"prod",chainId:exports.SupportedChainId.MAINNET};class a extends Error{constructor(e,r){super(e),this.error_code=void 0,this.error_code=r}}const{GPv2Settlement:i}=JSON.parse('{\n "GPv2AllowListAuthentication_Implementation": {\n "1": {\n "address": "0x9E7Ae8Bdba9AA346739792d219a808884996Db67",\n "transactionHash": "0x58340aa44119c74e48635fab0ac344170c6d6e8b42e5714baa4ba4e1651f63ad"\n },\n "4": {\n "address": "0x9E7Ae8Bdba9AA346739792d219a808884996Db67"\n },\n "5": {\n "address": "0x9E7Ae8Bdba9AA346739792d219a808884996Db67",\n "transactionHash": "0x24f4f80b46a17345011065f9ea2af823f582db56be81098b3b66cc2db9659ea7"\n },\n "100": {\n "address": "0x9E7Ae8Bdba9AA346739792d219a808884996Db67",\n "transactionHash": "0xe52d425fe34d6d5215ccfc9ddfa485d490b3018f0ee5bbed708f2d172044d60d"\n }\n },\n "GPv2AllowListAuthentication_Proxy": {\n "1": {\n "address": "0x2c4c28DDBdAc9C5E7055b4C863b72eA0149D8aFE",\n "transactionHash": "0xb84bf720364f94c749f1ec1cdf0d4c44c70411b716459aaccfd24fc677013375"\n },\n "4": {\n "address": "0x2c4c28DDBdAc9C5E7055b4C863b72eA0149D8aFE",\n "transactionHash": "0x57b2278fd3a13ab1b132031024475ba1a4e28d7d4d37f556134c84512b742c1f"\n },\n "5": {\n "address": "0x2c4c28DDBdAc9C5E7055b4C863b72eA0149D8aFE",\n "transactionHash": "0x39dcf30baf887a5db54551a84de8bfdb6cf418bb284b09680d13aed17d5fa0c1"\n },\n "100": {\n "address": "0x2c4c28DDBdAc9C5E7055b4C863b72eA0149D8aFE",\n "transactionHash": "0x1a2d87a05a94bc6680a4faee31bbafbd74e9ddb63dd3941c717b5c609c08b957"\n }\n },\n "GPv2AllowListAuthentication": {\n "1": {\n "address": "0x2c4c28DDBdAc9C5E7055b4C863b72eA0149D8aFE",\n "transactionHash": "0xb84bf720364f94c749f1ec1cdf0d4c44c70411b716459aaccfd24fc677013375"\n },\n "4": {\n "address": "0x2c4c28DDBdAc9C5E7055b4C863b72eA0149D8aFE",\n "transactionHash": "0x57b2278fd3a13ab1b132031024475ba1a4e28d7d4d37f556134c84512b742c1f"\n },\n "5": {\n "address": "0x2c4c28DDBdAc9C5E7055b4C863b72eA0149D8aFE",\n "transactionHash": "0x39dcf30baf887a5db54551a84de8bfdb6cf418bb284b09680d13aed17d5fa0c1"\n },\n "100": {\n "address": "0x2c4c28DDBdAc9C5E7055b4C863b72eA0149D8aFE",\n "transactionHash": "0x1a2d87a05a94bc6680a4faee31bbafbd74e9ddb63dd3941c717b5c609c08b957"\n }\n },\n "GPv2Settlement": {\n "1": {\n "address": "0x9008D19f58AAbD9eD0D60971565AA8510560ab41",\n "transactionHash": "0xf49f90aa5a268c40001d1227b76bb4dd8247f18361fcad9fffd4a7a44f1320d3"\n },\n "4": {\n "address": "0x9008D19f58AAbD9eD0D60971565AA8510560ab41",\n "transactionHash": "0x609fa2e8f32c73c1f5dc21ff60a26238dacb50d4674d336c90d6950bdda17a21"\n },\n "5": {\n "address": "0x9008D19f58AAbD9eD0D60971565AA8510560ab41",\n "transactionHash": "0x982f089060ff66e19d0683ef1cc6a637297331a9ba95b65d8eb84b9f8dc64b04"\n },\n "100": {\n "address": "0x9008D19f58AAbD9eD0D60971565AA8510560ab41",\n "transactionHash": "0x9ddc538f89cd8433f4a19bc4de0de27e7c68a1d04a14b327185e4bba9af87133"\n }\n },\n "GPv2VaultRelayer": {\n "1": {\n "address": "0xC92E8bdf79f0507f65a392b0ab4667716BFE0110",\n "transactionHash": "0xf49f90aa5a268c40001d1227b76bb4dd8247f18361fcad9fffd4a7a44f1320d3"\n },\n "4": {\n "address": "0xC92E8bdf79f0507f65a392b0ab4667716BFE0110",\n "transactionHash": "0x609fa2e8f32c73c1f5dc21ff60a26238dacb50d4674d336c90d6950bdda17a21"\n },\n "5": {\n "address": "0xC92E8bdf79f0507f65a392b0ab4667716BFE0110",\n "transactionHash": "0x982f089060ff66e19d0683ef1cc6a637297331a9ba95b65d8eb84b9f8dc64b04"\n },\n "100": {\n "address": "0xC92E8bdf79f0507f65a392b0ab4667716BFE0110",\n "transactionHash": "0x9ddc538f89cd8433f4a19bc4de0de27e7c68a1d04a14b327185e4bba9af87133"\n }\n }\n}'),d=[exports.SupportedChainId.MAINNET,exports.SupportedChainId.GOERLI,exports.SupportedChainId.GNOSIS_CHAIN],c=d.reduce((e,r)=>({...e,[r]:i[r].address}),{}),p="0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE";function u(e){return function(e){const{ethflowData:r}=e;if(!r)return e;const{userValidTo:t}=r,n=e.onchainUser||e.owner,o=p;return{...e,validTo:t,owner:n,sellToken:o}}(function(e){const{executedFeeAmount:r,executedSurplusFee:t}=e,n=null!=t?t:r;return{...e,totalFee:n}}(e))}const E=function(e,{path:r,query:n,method:o,body:s},a,i){try{const d={Accept:"application/json","Content-Type":"application/json"},c=`${e}${r}${n?"?"+n:""}`,p={method:o,body:s?JSON.stringify(s):void 0,headers:d};return Promise.resolve(t.backOff(function(){try{return Promise.resolve(a.removeTokens(1)).then(function(){return Promise.resolve(fetch(c,p)).then(function(e){return Promise.resolve(I(e)).then(function(r){return e.status>=200&&e.status<300?r:Promise.reject(new h(e,r))})})})}catch(e){return Promise.reject(e)}},i))}catch(e){return Promise.reject(e)}};class h extends Error{constructor(e,r){super("string"==typeof r?r:e.statusText),this.response=void 0,this.body=void 0,this.response=e,this.body=r}}const f=[408,425,429,500,502,503,504],O={numOfAttempts:10,maxDelay:Infinity,jitter:"none",retry:e=>!(e instanceof h)||f.includes(e.response.status)},l={tokensPerInterval:5,interval:"second"},I=function(e){try{let r;const t=function(){if(204!==e.status)return function(t,n){try{var o=function(){const t=e.headers.get("Content-Type");return function(){if(t)return t.toLowerCase().startsWith("application/json")?Promise.resolve(e.json()).then(function(e){return r=1,e}):Promise.resolve(e.text()).then(function(e){return r=1,e})}()}()}catch(e){return n(e)}return o&&o.then?o.then(void 0,n):o}(0,function(e){console.error(e)})}();return Promise.resolve(t&&t.then?t.then(function(e){return r?e:void 0}):r?t:void 0)}catch(e){return Promise.reject(e)}},T={[exports.SupportedChainId.MAINNET]:"https://api.cow.fi/mainnet",[exports.SupportedChainId.GNOSIS_CHAIN]:"https://api.cow.fi/xdai",[exports.SupportedChainId.GOERLI]:"https://api.cow.fi/goerli"},A={[exports.SupportedChainId.MAINNET]:"https://barn.api.cow.fi/mainnet",[exports.SupportedChainId.GNOSIS_CHAIN]:"https://barn.api.cow.fi/xdai",[exports.SupportedChainId.GOERLI]:"https://barn.api.cow.fi/goerli"};function S(e){return Object.keys(e).reduce((r,t)=>{const n=e[t];return void 0!==n&&(r[t]=n),r},{})}var b,x,N,_,D,C,m,R,P,g,U,v,L,y,F,G;exports.BuyTokenDestination=void 0,(b=exports.BuyTokenDestination||(exports.BuyTokenDestination={})).ERC20="erc20",b.INTERNAL="internal",exports.EcdsaSigningScheme=void 0,(x=exports.EcdsaSigningScheme||(exports.EcdsaSigningScheme={})).EIP712="eip712",x.ETHSIGN="ethsign",exports.FeeAndQuoteError=void 0,(_=(N=exports.FeeAndQuoteError||(exports.FeeAndQuoteError={})).errorType||(N.errorType={})).NO_LIQUIDITY="NoLiquidity",_.UNSUPPORTED_TOKEN="UnsupportedToken",_.AMOUNT_IS_ZERO="AmountIsZero",_.SELL_AMOUNT_DOES_NOT_COVER_FEE="SellAmountDoesNotCoverFee",exports.OnchainOrderData=void 0,(C=(D=exports.OnchainOrderData||(exports.OnchainOrderData={})).placementError||(D.placementError={})).QUOTE_NOT_FOUND="QuoteNotFound",C.VALID_TO_TOO_FAR_IN_FUTURE="ValidToTooFarInFuture",C.PRE_VALIDATION_ERROR="PreValidationError",exports.OrderCancellationError=void 0,function(e){e.INVALID_SIGNATURE="InvalidSignature",e.WRONG_OWNER="WrongOwner",e.ORDER_NOT_FOUND="OrderNotFound",e.ALREADY_CANCELLED="AlreadyCancelled",e.ORDER_FULLY_EXECUTED="OrderFullyExecuted",e.ORDER_EXPIRED="OrderExpired",e.ON_CHAIN_ORDER="OnChainOrder"}((m=exports.OrderCancellationError||(exports.OrderCancellationError={})).errorType||(m.errorType={})),exports.OrderClass=void 0,(R=exports.OrderClass||(exports.OrderClass={})).MARKET="market",R.LIMIT="limit",R.LIQUIDITY="liquidity",exports.OrderKind=void 0,(P=exports.OrderKind||(exports.OrderKind={})).BUY="buy",P.SELL="sell",exports.OrderPostError=void 0,function(e){e.DUPLICATE_ORDER="DuplicateOrder",e.INSUFFICIENT_FEE="InsufficientFee",e.INSUFFICIENT_ALLOWANCE="InsufficientAllowance",e.INSUFFICIENT_BALANCE="InsufficientBalance",e.INSUFFICIENT_VALID_TO="InsufficientValidTo",e.EXCESSIVE_VALID_TO="ExcessiveValidTo",e.INVALID_SIGNATURE="InvalidSignature",e.TRANSFER_ETH_TO_CONTRACT="TransferEthToContract",e.TRANSFER_SIMULATION_FAILED="TransferSimulationFailed",e.UNSUPPORTED_TOKEN="UnsupportedToken",e.WRONG_OWNER="WrongOwner",e.MISSING_FROM="MissingFrom",e.SAME_BUY_AND_SELL_TOKEN="SameBuyAndSellToken",e.ZERO_AMOUNT="ZeroAmount",e.UNSUPPORTED_BUY_TOKEN_DESTINATION="UnsupportedBuyTokenDestination",e.UNSUPPORTED_SELL_TOKEN_SOURCE="UnsupportedSellTokenSource",e.UNSUPPORTED_ORDER_TYPE="UnsupportedOrderType",e.UNSUPPORTED_SIGNATURE="UnsupportedSignature",e.TOO_MANY_LIMIT_ORDERS="TooManyLimitOrders"}((g=exports.OrderPostError||(exports.OrderPostError={})).errorType||(g.errorType={})),exports.OrderQuoteSide=void 0,((U=exports.OrderQuoteSide||(exports.OrderQuoteSide={})).kind||(U.kind={})).SELL="sell",exports.OrderStatus=void 0,(v=exports.OrderStatus||(exports.OrderStatus={})).PRESIGNATURE_PENDING="presignaturePending",v.OPEN="open",v.FULFILLED="fulfilled",v.CANCELLED="cancelled",v.EXPIRED="expired",exports.PriceQuality=void 0,(L=exports.PriceQuality||(exports.PriceQuality={})).FAST="fast",L.OPTIMAL="optimal",exports.ReplaceOrderError=void 0,function(e){e.ALREADY_CANCELLED="AlreadyCancelled",e.ORDER_FULLY_EXECUTED="OrderFullyExecuted",e.ORDER_EXPIRED="OrderExpired",e.ON_CHAIN_ORDER="OnChainOrder",e.DUPLICATE_ORDER="DuplicateOrder",e.INSUFFICIENT_FEE="InsufficientFee",e.INSUFFICIENT_ALLOWANCE="InsufficientAllowance",e.INSUFFICIENT_BALANCE="InsufficientBalance",e.INSUFFICIENT_VALID_TO="InsufficientValidTo",e.EXCESSIVE_VALID_TO="ExcessiveValidTo",e.INVALID_SIGNATURE="InvalidSignature",e.TRANSFER_ETH_TO_CONTRACT="TransferEthToContract",e.TRANSFER_SIMULATION_FAILED="TransferSimulationFailed",e.UNSUPPORTED_TOKEN="UnsupportedToken",e.WRONG_OWNER="WrongOwner",e.SAME_BUY_AND_SELL_TOKEN="SameBuyAndSellToken",e.ZERO_AMOUNT="ZeroAmount",e.UNSUPPORTED_BUY_TOKEN_DESTINATION="UnsupportedBuyTokenDestination",e.UNSUPPORTED_SELL_TOKEN_SOURCE="UnsupportedSellTokenSource",e.UNSUPPORTED_ORDER_TYPE="UnsupportedOrderType",e.UNSUPPORTED_SIGNATURE="UnsupportedSignature"}((y=exports.ReplaceOrderError||(exports.ReplaceOrderError={})).errorType||(y.errorType={})),exports.SellTokenSource=void 0,(F=exports.SellTokenSource||(exports.SellTokenSource={})).ERC20="erc20",F.INTERNAL="internal",F.EXTERNAL="external",exports.SigningScheme=void 0,(G=exports.SigningScheme||(exports.SigningScheme={})).EIP712="eip712",G.ETHSIGN="ethsign",G.PRESIGN="presign",G.EIP1271="eip1271";const B=n.gql`
query Totals {

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

}
`,M=r.gql`
`,w=n.gql`
query LastDaysVolume($days: Int!) {

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

}
`,W=r.gql`
`,H=n.gql`
query LastHoursVolume($hours: Int!) {

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

}
`,$={[exports.SupportedChainId.MAINNET]:"https://api.thegraph.com/subgraphs/name/cowprotocol/cow",[exports.SupportedChainId.GNOSIS_CHAIN]:"https://api.thegraph.com/subgraphs/name/cowprotocol/cow-gc",[exports.SupportedChainId.GOERLI]:"https://api.thegraph.com/subgraphs/name/cowprotocol/cow-goerli"},Q={[exports.SupportedChainId.MAINNET]:"https://api.thegraph.com/subgraphs/name/cowprotocol/cow-staging",[exports.SupportedChainId.GNOSIS_CHAIN]:"https://api.thegraph.com/subgraphs/name/cowprotocol/cow-gc-staging",[exports.SupportedChainId.GOERLI]:""};exports.ApiError=i,exports.BaseHttpRequest=s,exports.CancelError=d,exports.CancelablePromise=c,exports.CowError=n,exports.DEFAULT_COW_API_CONTEXT=o,exports.DEFAULT_IPFS_READ_URI="https://gnosis.mypinata.cloud/ipfs",exports.DEFAULT_IPFS_WRITE_URI="https://api.pinata.cloud",exports.DefaultService=N,exports.ENVS_LIST=t,exports.ORDER_BOOK_PROD_CONFIG=k,exports.ORDER_BOOK_STAGING_CONFIG=j,exports.OpenAPI={BASE:"https://api.cow.fi/mainnet",VERSION:"0.0.1",WITH_CREDENTIALS:!1,CREDENTIALS:"include",TOKEN:void 0,USERNAME:void 0,PASSWORD:void 0,HEADERS:void 0,ENCODE_PATH:void 0},exports.OrderBookApi=class{constructor(e={},r){this.context=void 0,this.customEnvConfigs=void 0,this.servicePerNetwork={},this.context={...o,...e},this.customEnvConfigs=r}getTrades({owner:e,orderId:r},t={}){return e&&r?new c((e,r)=>{r(new n("Cannot specify both owner and orderId"))}):this.getServiceForNetwork(t).getApiV1Trades(e,r)}getOrders({owner:e,offset:r=0,limit:t=1e3},o={}){return this.getServiceForNetwork(o).getApiV1AccountOrders(e,r,t).then(e=>e.map(G))}getTxOrders(e,r={}){return this.getServiceForNetwork(r).getApiV1TransactionsOrders(e).then(e=>e.map(G))}getOrder(e,r={}){return this.getServiceForNetwork(r).getApiV1Orders(e).then(e=>G(e))}getOrderMultiEnv(e,r={}){const{env:o}=this.getContextWithOverride(r),n=t.filter(e=>e!==o);let s=0;const a=t=>{const o=n[s];return t instanceof i&&404===t.status&&o?(s++,this.getOrder(e,{...r,env:o}).catch(a)):Promise.reject(t)};return this.getOrder(e,{...r,env:o}).catch(a)}getQuote(e,r={}){return this.getServiceForNetwork(r).postApiV1Quote(e)}sendSignedOrderCancellation(e,r,t={}){return this.getServiceForNetwork(t).deleteApiV1Orders1(e,r)}sendOrder(e,r={}){return this.getServiceForNetwork(r).postApiV1Orders(e).catch(e=>{const r=e.body;if(r?.errorType)throw new Error(r.errorType);throw e})}getNativePrice(e,r={}){return this.getServiceForNetwork(r).getApiV1TokenNativePrice(e)}getOrderLink(e,r={}){const{chainId:t,env:o}=this.getContextWithOverride(r);return this.getEnvConfigs(o)[t]+`/api/v1/orders/${e}`}getServiceForNetwork(e){const{chainId:r,env:t}=this.getContextWithOverride(e),o=`${t}|${r}`,n=this.servicePerNetwork[o];if(n)return n.default;const s=new f({BASE:this.getEnvConfigs(t)[r]},H);return this.servicePerNetwork[o]=s,s.default}getContextWithOverride(e={}){return{...this.context,...e}}getEnvConfigs(e){return this.customEnvConfigs?this.customEnvConfigs:"prod"===e?k:j}},exports.OrderBookClient=f,exports.SUBGRAPH_PROD_CONFIG=$,exports.SUBGRAPH_STAGING_CONFIG=Q,exports.SubgraphApi=class{constructor(e={},r){this.API_NAME="CoW Protocol Subgraph",this.context=void 0,this.customEnvConfigs=void 0,this.context={...o,...e},this.customEnvConfigs=r}getTotals(e={}){try{return Promise.resolve(this.runQuery(B,void 0,e)).then(function(e){return e.totals[0]})}catch(e){return Promise.reject(e)}}getLastDaysVolume(e,r={}){try{return Promise.resolve(this.runQuery(M,{days:e},r))}catch(e){return Promise.reject(e)}}getLastHoursVolume(e,r={}){try{return Promise.resolve(this.runQuery(W,{hours:e},r))}catch(e){return Promise.reject(e)}}runQuery(e,t=undefined,o={}){try{const s=this,{chainId:i,env:a}=s.getContextWithOverride(o),d=s.getEnvConfigs(a)[i];return Promise.resolve(function(o,n){try{var s=Promise.resolve(r.request(d,e,t))}catch(e){return n(e)}return s&&s.then?s.then(void 0,n):s}(0,function(r){throw console.error(`[subgraph:${s.API_NAME}]`,r),new n(`Error running query: ${e}. Variables: ${JSON.stringify(t)}. API: ${d}. Inner Error: ${r}`)}))}catch(e){return Promise.reject(e)}}getContextWithOverride(e={}){return{...this.context,...e}}getEnvConfigs(e){return this.customEnvConfigs?this.customEnvConfigs:"prod"===e?$:Q}},exports.logPrefix="cow-sdk:";
`,k={[exports.SupportedChainId.MAINNET]:"https://api.thegraph.com/subgraphs/name/cowprotocol/cow",[exports.SupportedChainId.GNOSIS_CHAIN]:"https://api.thegraph.com/subgraphs/name/cowprotocol/cow-gc",[exports.SupportedChainId.GOERLI]:"https://api.thegraph.com/subgraphs/name/cowprotocol/cow-goerli"},M={[exports.SupportedChainId.MAINNET]:"https://api.thegraph.com/subgraphs/name/cowprotocol/cow-staging",[exports.SupportedChainId.GNOSIS_CHAIN]:"https://api.thegraph.com/subgraphs/name/cowprotocol/cow-gc-staging",[exports.SupportedChainId.GOERLI]:""},V=()=>Promise.resolve().then(function(){return require("./utils-b35881cd.js")});exports.ALL_SUPPORTED_CHAIN_IDS=d,exports.COW_PROTOCOL_SETTLEMENT_CONTRACT_ADDRESS=c,exports.CowError=a,exports.DEFAULT_BACKOFF_OPTIONS=O,exports.DEFAULT_COW_API_CONTEXT=s,exports.DEFAULT_IPFS_READ_URI="https://gnosis.mypinata.cloud/ipfs",exports.DEFAULT_IPFS_WRITE_URI="https://api.pinata.cloud",exports.DEFAULT_LIMITER_OPTIONS=l,exports.ENVS_LIST=o,exports.ORDER_BOOK_PROD_CONFIG=T,exports.ORDER_BOOK_STAGING_CONFIG=A,exports.OrderBookApi=class{constructor(e={}){this.context=void 0,this.rateLimiter=void 0,this.context={...s,...e},this.rateLimiter=new r.RateLimiter(e.limiterOpts||l)}getTrades(e,r={}){if(e.owner&&e.orderUid)return Promise.reject(new a("Cannot specify both owner and orderId"));const t=new URLSearchParams(S(e));return this.fetch({path:"/api/v1/trades",method:"GET",query:t},r)}getOrders({owner:e,offset:r=0,limit:t=1e3},n={}){const o=new URLSearchParams(S({offset:r.toString(),limit:t.toString()}));return this.fetch({path:`/api/v1/account/${e}/orders`,method:"GET",query:o},n).then(e=>e.map(u))}getTxOrders(e,r={}){return this.fetch({path:`/api/v1/transactions/${e}/orders`,method:"GET"},r).then(e=>e.map(u))}getOrder(e,r={}){return this.fetch({path:`/api/v1/orders/${e}`,method:"GET"},r).then(e=>u(e))}getOrderMultiEnv(e,r={}){const{env:t}=this.getContextWithOverride(r),n=o.filter(e=>e!==t);let s=0;const a=t=>{const o=n[s];return t instanceof h&&404===t.response.status&&o?(s++,this.getOrder(e,{...r,env:o}).catch(a)):Promise.reject(t)};return this.getOrder(e,{...r,env:t}).catch(a)}getQuote(e,r={}){return this.fetch({path:"/api/v1/quote",method:"POST",body:e},r)}sendSignedOrderCancellations(e,r={}){return this.fetch({path:"/api/v1/orders",method:"DELETE",body:e},r)}sendOrder(e,r={}){return this.fetch({path:"/api/v1/orders",method:"POST",body:e},r)}getNativePrice(e,r={}){return this.fetch({path:`/api/v1/token/${e}/native_price`,method:"GET"},r)}getOrderLink(e,r){const{chainId:t,env:n}=this.getContextWithOverride(r);return this.getApiBaseUrls(n)[t]+`/api/v1/orders/${e}`}getContextWithOverride(e={}){return{...this.context,...e}}getApiBaseUrls(e){return this.context.baseUrls?this.context.baseUrls:"prod"===e?T:A}fetch(e,r={}){const{chainId:t,env:n}=this.getContextWithOverride(r),o=this.getApiBaseUrls(n)[t];return E(o,e,this.rateLimiter,this.context.backoffOpts||O)}},exports.OrderBookApiError=h,exports.OrderSigningUtils=class{static signOrder(e,r,t){try{return Promise.resolve(V()).then(function({signOrder:n}){return n(e,r,t)})}catch(e){return Promise.reject(e)}}static signOrderCancellation(e,r,t){try{return Promise.resolve(V()).then(function({signOrderCancellation:n}){return n(e,r,t)})}catch(e){return Promise.reject(e)}}static signOrderCancellations(e,r,t){try{return Promise.resolve(V()).then(function({signOrderCancellations:n}){return n(e,r,t)})}catch(e){return Promise.reject(e)}}static getDomain(e){try{return Promise.resolve(V()).then(function({getDomain:r}){return r(e)})}catch(e){return Promise.reject(e)}}},exports.SUBGRAPH_PROD_CONFIG=k,exports.SUBGRAPH_STAGING_CONFIG=M,exports.SubgraphApi=class{constructor(e={}){this.API_NAME="CoW Protocol Subgraph",this.context=void 0,this.context={...s,...e}}getTotals(e={}){try{return Promise.resolve(this.runQuery(B,void 0,e)).then(function(e){return e.totals[0]})}catch(e){return Promise.reject(e)}}getLastDaysVolume(e,r={}){try{return Promise.resolve(this.runQuery(w,{days:e},r))}catch(e){return Promise.reject(e)}}getLastHoursVolume(e,r={}){try{return Promise.resolve(this.runQuery(H,{hours:e},r))}catch(e){return Promise.reject(e)}}runQuery(e,r=undefined,t={}){try{const o=this,{chainId:s,env:i}=o.getContextWithOverride(t),d=o.getEnvConfigs(i)[s];return Promise.resolve(function(t,o){try{var s=Promise.resolve(n.request(d,e,r))}catch(e){return o(e)}return s&&s.then?s.then(void 0,o):s}(0,function(t){throw console.error(`[subgraph:${o.API_NAME}]`,t),new a(`Error running query: ${e}. Variables: ${JSON.stringify(r)}. API: ${d}. Inner Error: ${t}`)}))}catch(e){return Promise.reject(e)}}getContextWithOverride(e={}){return{...this.context,...e}}getEnvConfigs(e){return this.context.baseUrls?this.context.baseUrls:"prod"===e?k:M}},exports.logPrefix="cow-sdk:",exports.request=E;
//# sourceMappingURL=index.js.map

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

import{gql as e,request as t}from"graphql-request";var r;!function(e){e[e.MAINNET=1]="MAINNET",e[e.GOERLI=5]="GOERLI",e[e.GNOSIS_CHAIN=100]="GNOSIS_CHAIN"}(r||(r={}));const o=["prod","staging"],n={env:"prod",chainId:r.MAINNET};class i extends Error{constructor(e,t){super(e),this.error_code=void 0,this.error_code=t}}const s="cow-sdk:",a="https://gnosis.mypinata.cloud/ipfs",c="https://api.pinata.cloud";class u{constructor(e){this.config=void 0,this.config=e}}class d extends Error{constructor(e,t,r){super(r),this.url=void 0,this.status=void 0,this.statusText=void 0,this.body=void 0,this.request=void 0,this.name="ApiError",this.url=t.url,this.status=t.status,this.statusText=t.statusText,this.body=t.body,this.request=e}}let h;class l extends Error{constructor(e){super(e),this.name="CancelError"}get isCancelled(){return!0}}h=Symbol.toStringTag;class E{constructor(e){this[h]=void 0,this._isResolved=void 0,this._isRejected=void 0,this._isCancelled=void 0,this._cancelHandlers=void 0,this._promise=void 0,this._resolve=void 0,this._reject=void 0,this._isResolved=!1,this._isRejected=!1,this._isCancelled=!1,this._cancelHandlers=[],this._promise=new Promise((t,r)=>{this._resolve=t,this._reject=r;const o=e=>{this._isResolved||this._isRejected||this._isCancelled||this._cancelHandlers.push(e)};return Object.defineProperty(o,"isResolved",{get:()=>this._isResolved}),Object.defineProperty(o,"isRejected",{get:()=>this._isRejected}),Object.defineProperty(o,"isCancelled",{get:()=>this._isCancelled}),e(e=>{this._isResolved||this._isRejected||this._isCancelled||(this._isResolved=!0,this._resolve?.(e))},e=>{this._isResolved||this._isRejected||this._isCancelled||(this._isRejected=!0,this._reject?.(e))},o)})}then(e,t){return this._promise.then(e,t)}catch(e){return this._promise.catch(e)}finally(e){return this._promise.finally(e)}cancel(){if(!(this._isResolved||this._isRejected||this._isCancelled)){if(this._isCancelled=!0,this._cancelHandlers.length)try{for(const e of this._cancelHandlers)e()}catch(e){return void console.warn("Cancellation threw an error",e)}this._cancelHandlers.length=0,this._reject?.(new l("Request aborted"))}}get isCancelled(){return this._isCancelled}}function p(e,t){try{var r=e()}catch(e){return t(e)}return r&&r.then?r.then(void 0,t):r}const T=e=>null!=e,f=e=>"string"==typeof e,N=e=>f(e)&&""!==e,O=e=>"object"==typeof e&&"string"==typeof e.type&&"function"==typeof e.stream&&"function"==typeof e.arrayBuffer&&"function"==typeof e.constructor&&"string"==typeof e.constructor.name&&/^(Blob|File)$/.test(e.constructor.name)&&/^(Blob|File)$/.test(e[Symbol.toStringTag]),_=e=>e instanceof FormData,I=function(e,t){try{return Promise.resolve("function"==typeof t?t(e):t)}catch(e){return Promise.reject(e)}},v=function(e,t){try{return Promise.resolve(I(t,e.TOKEN)).then(function(r){return Promise.resolve(I(t,e.USERNAME)).then(function(o){return Promise.resolve(I(t,e.PASSWORD)).then(function(n){return Promise.resolve(I(t,e.HEADERS)).then(function(e){const i=Object.entries({Accept:"application/json",...e,...t.headers}).filter(([e,t])=>T(t)).reduce((e,[t,r])=>({...e,[t]:String(r)}),{});if(N(r)&&(i.Authorization=`Bearer ${r}`),N(o)&&N(n)){const e=(e=>{try{return btoa(e)}catch(t){return Buffer.from(e).toString("base64")}})(`${o}:${n}`);i.Authorization=`Basic ${e}`}return t.body&&(t.mediaType?i["Content-Type"]=t.mediaType:O(t.body)?i["Content-Type"]=t.body.type||"application/octet-stream":f(t.body)?i["Content-Type"]="text/plain":_(t.body)||(i["Content-Type"]="application/json")),new Headers(i)})})})})}catch(e){return Promise.reject(e)}},A=(e,t)=>new E(function(r,o,n){try{const i=p(function(){const o=((e,t)=>{const r=e.ENCODE_PATH||encodeURI,o=t.url.replace("{api-version}",e.VERSION).replace(/{(.*?)}/g,(e,o)=>t.path?.hasOwnProperty(o)?r(String(t.path[o])):e),n=`${e.BASE}${o}`;return t.query?`${n}${(e=>{const t=[],r=(e,o)=>{T(o)&&(Array.isArray(o)?o.forEach(t=>{r(e,t)}):"object"==typeof o?Object.entries(o).forEach(([t,o])=>{r(`${e}[${t}]`,o)}):((e,r)=>{t.push(`${encodeURIComponent(e)}=${encodeURIComponent(String(r))}`)})(e,o))};return Object.entries(e).forEach(([e,t])=>{r(e,t)}),t.length>0?`?${t.join("&")}`:""})(t.query)}`:n})(e,t),i=(e=>{if(e.formData){const t=new FormData,r=(e,r)=>{f(r)||O(r)?t.append(e,r):t.append(e,JSON.stringify(r))};return Object.entries(e.formData).filter(([e,t])=>T(t)).forEach(([e,t])=>{Array.isArray(t)?t.forEach(t=>r(e,t)):r(e,t)}),t}})(t),s=(e=>{if(e.body)return e.mediaType?.includes("/json")?JSON.stringify(e.body):f(e.body)||O(e.body)||_(e.body)?e.body:JSON.stringify(e.body)})(t);return Promise.resolve(v(e,t)).then(function(a){const c=function(){if(!n.isCancelled)return Promise.resolve(function(e,t,r,o,n,i,s){try{const a=new AbortController,c={headers:i,body:null!=o?o:n,method:t.method,signal:a.signal};return e.WITH_CREDENTIALS&&(c.credentials=e.CREDENTIALS),s(()=>a.abort()),Promise.resolve(fetch(r,c))}catch(e){return Promise.reject(e)}}(e,t,o,s,i,a,n)).then(function(e){return Promise.resolve(function(e){try{let t;const r=function(){if(204!==e.status)return p(function(){const r=e.headers.get("Content-Type");return function(){if(r)return r.toLowerCase().startsWith("application/json")?Promise.resolve(e.json()).then(function(e){return t=1,e}):Promise.resolve(e.text()).then(function(e){return t=1,e})}()},function(e){console.error(e)})}();return Promise.resolve(r&&r.then?r.then(function(e){return t?e:void 0}):t?r:void 0)}catch(e){return Promise.reject(e)}}(e)).then(function(n){const i=((e,t)=>{if(t){const r=e.headers.get(t);if(f(r))return r}})(e,t.responseHeader),s={url:o,ok:e.ok,status:e.status,statusText:e.statusText,body:null!=i?i:n};((e,t)=>{const r={400:"Bad Request",401:"Unauthorized",403:"Forbidden",404:"Not Found",500:"Internal Server Error",502:"Bad Gateway",503:"Service Unavailable",...e.errors}[t.status];if(r)throw new d(e,t,r);if(!t.ok)throw new d(e,t,"Generic Error")})(t,s),r(s.body)})})}();if(c&&c.then)return c.then(function(){})})},function(e){o(e)});return Promise.resolve(i&&i.then?i.then(function(){}):void 0)}catch(e){return Promise.reject(e)}});class m extends u{constructor(e){super(e)}request(e){return A(this.config,e)}}class R{constructor(e){this.httpRequest=void 0,this.httpRequest=e}postApiV1Orders(e){return this.httpRequest.request({method:"POST",url:"/api/v1/orders",body:e,mediaType:"application/json",errors:{400:"Error during order validation",403:"Forbidden, your account is deny-listed",429:"Too many order placements",500:"Error adding an order"}})}deleteApiV1Orders(e){return this.httpRequest.request({method:"DELETE",url:"/api/v1/orders",body:e,mediaType:"application/json",errors:{400:"Malformed signature",401:"Invalid signature",404:"One or more orders were not found and no orders were cancelled."}})}getApiV1Orders(e){return this.httpRequest.request({method:"GET",url:"/api/v1/orders/{UID}",path:{UID:e},errors:{404:"Order was not found"}})}deleteApiV1Orders1(e,t){return this.httpRequest.request({method:"DELETE",url:"/api/v1/orders/{UID}",path:{UID:e},body:t,mediaType:"application/json",errors:{400:"Malformed signature",401:"Invalid signature",404:"Order was not found"}})}patchApiV1Orders(e,t){return this.httpRequest.request({method:"PATCH",url:"/api/v1/orders/{UID}",path:{UID:e},body:t,mediaType:"application/json",errors:{400:"Error cancelling and replacing new order with an old one.",401:"Invalid replacement order. This can happen if the old and new orders have\n different signers, the new order's app data is not an encoded cancellation of\n the old order, or the new order is based on presign or EIP-1271 signatures.\n ",403:"Forbidden",404:"Order was not found"}})}getApiV1TransactionsOrders(e){return this.httpRequest.request({method:"GET",url:"/api/v1/transactions/{txHash}/orders",path:{txHash:e}})}getApiV1Trades(e,t){return this.httpRequest.request({method:"GET",url:"/api/v1/trades",query:{owner:e,orderUid:t}})}getApiV1Auction(){return this.httpRequest.request({method:"GET",url:"/api/v1/auction"})}getApiV1AccountOrders(e,t,r){return this.httpRequest.request({method:"GET",url:"/api/v1/account/{owner}/orders",path:{owner:e},query:{offset:t,limit:r},errors:{400:"Problem with parameters like limit being too large."}})}getApiV1TokenNativePrice(e){return this.httpRequest.request({method:"GET",url:"/api/v1/token/{token}/native_price",path:{token:e},errors:{400:"Error finding the price.",404:"No liquidity was found",500:"Unexpected error"}})}postApiV1Quote(e){return this.httpRequest.request({method:"POST",url:"/api/v1/quote",body:e,mediaType:"application/json",errors:{400:"Error quoting order.",403:"Forbidden, your account is deny-listed",429:"Too many order quotes",500:"Unexpected error quoting an order"}})}getApiV1SolverCompetition(e){return this.httpRequest.request({method:"GET",url:"/api/v1/solver_competition/{auction_id}",path:{auction_id:e},errors:{404:"No competition information available for this auction id."}})}getApiV1SolverCompetitionByTxHash(e){return this.httpRequest.request({method:"GET",url:"/api/v1/solver_competition/by_tx_hash/{tx_hash}",path:{tx_hash:e},errors:{404:"No competition information available for this tx hash."}})}getApiV1Version(){return this.httpRequest.request({method:"GET",url:"/api/v1/version"})}}class g{constructor(e,t=m){var r,o,n,i;this.default=void 0,this.request=void 0,this.request=new t({BASE:null!==(r=e?.BASE)&&void 0!==r?r:"https://api.cow.fi/mainnet",VERSION:null!==(o=e?.VERSION)&&void 0!==o?o:"0.0.1",WITH_CREDENTIALS:null!==(n=e?.WITH_CREDENTIALS)&&void 0!==n&&n,CREDENTIALS:null!==(i=e?.CREDENTIALS)&&void 0!==i?i:"include",TOKEN:e?.TOKEN,USERNAME:e?.USERNAME,PASSWORD:e?.PASSWORD,HEADERS:e?.HEADERS,ENCODE_PATH:e?.ENCODE_PATH}),this.default=new R(this.request)}}const S={BASE:"https://api.cow.fi/mainnet",VERSION:"0.0.1",WITH_CREDENTIALS:!1,CREDENTIALS:"include",TOKEN:void 0,USERNAME:void 0,PASSWORD:void 0,HEADERS:void 0,ENCODE_PATH:void 0};var y,C,D,U,P,w,L,F,b,q,V,x,j,H;!function(e){e.ERC20="erc20",e.INTERNAL="internal"}(y||(y={})),function(e){e.EIP712="eip712",e.ETHSIGN="ethsign"}(C||(C={})),function(e){var t;(t=e.errorType||(e.errorType={})).NO_LIQUIDITY="NoLiquidity",t.UNSUPPORTED_TOKEN="UnsupportedToken",t.AMOUNT_IS_ZERO="AmountIsZero",t.SELL_AMOUNT_DOES_NOT_COVER_FEE="SellAmountDoesNotCoverFee"}(D||(D={})),function(e){var t;(t=e.placementError||(e.placementError={})).QUOTE_NOT_FOUND="QuoteNotFound",t.VALID_TO_TOO_FAR_IN_FUTURE="ValidToTooFarInFuture",t.PRE_VALIDATION_ERROR="PreValidationError"}(U||(U={})),function(e){var t;(t=e.errorType||(e.errorType={})).INVALID_SIGNATURE="InvalidSignature",t.WRONG_OWNER="WrongOwner",t.ORDER_NOT_FOUND="OrderNotFound",t.ALREADY_CANCELLED="AlreadyCancelled",t.ORDER_FULLY_EXECUTED="OrderFullyExecuted",t.ORDER_EXPIRED="OrderExpired",t.ON_CHAIN_ORDER="OnChainOrder"}(P||(P={})),function(e){e.MARKET="market",e.LIMIT="limit",e.LIQUIDITY="liquidity"}(w||(w={})),function(e){e.BUY="buy",e.SELL="sell"}(L||(L={})),function(e){var t;(t=e.errorType||(e.errorType={})).DUPLICATE_ORDER="DuplicateOrder",t.INSUFFICIENT_FEE="InsufficientFee",t.INSUFFICIENT_ALLOWANCE="InsufficientAllowance",t.INSUFFICIENT_BALANCE="InsufficientBalance",t.INSUFFICIENT_VALID_TO="InsufficientValidTo",t.EXCESSIVE_VALID_TO="ExcessiveValidTo",t.INVALID_SIGNATURE="InvalidSignature",t.TRANSFER_ETH_TO_CONTRACT="TransferEthToContract",t.TRANSFER_SIMULATION_FAILED="TransferSimulationFailed",t.UNSUPPORTED_TOKEN="UnsupportedToken",t.WRONG_OWNER="WrongOwner",t.MISSING_FROM="MissingFrom",t.SAME_BUY_AND_SELL_TOKEN="SameBuyAndSellToken",t.ZERO_AMOUNT="ZeroAmount",t.UNSUPPORTED_BUY_TOKEN_DESTINATION="UnsupportedBuyTokenDestination",t.UNSUPPORTED_SELL_TOKEN_SOURCE="UnsupportedSellTokenSource",t.UNSUPPORTED_ORDER_TYPE="UnsupportedOrderType",t.UNSUPPORTED_SIGNATURE="UnsupportedSignature",t.TOO_MANY_LIMIT_ORDERS="TooManyLimitOrders"}(F||(F={})),function(e){(e.kind||(e.kind={})).SELL="sell"}(b||(b={})),function(e){e.PRESIGNATURE_PENDING="presignaturePending",e.OPEN="open",e.FULFILLED="fulfilled",e.CANCELLED="cancelled",e.EXPIRED="expired"}(q||(q={})),function(e){e.FAST="fast",e.OPTIMAL="optimal"}(V||(V={})),function(e){var t;(t=e.errorType||(e.errorType={})).ALREADY_CANCELLED="AlreadyCancelled",t.ORDER_FULLY_EXECUTED="OrderFullyExecuted",t.ORDER_EXPIRED="OrderExpired",t.ON_CHAIN_ORDER="OnChainOrder",t.DUPLICATE_ORDER="DuplicateOrder",t.INSUFFICIENT_FEE="InsufficientFee",t.INSUFFICIENT_ALLOWANCE="InsufficientAllowance",t.INSUFFICIENT_BALANCE="InsufficientBalance",t.INSUFFICIENT_VALID_TO="InsufficientValidTo",t.EXCESSIVE_VALID_TO="ExcessiveValidTo",t.INVALID_SIGNATURE="InvalidSignature",t.TRANSFER_ETH_TO_CONTRACT="TransferEthToContract",t.TRANSFER_SIMULATION_FAILED="TransferSimulationFailed",t.UNSUPPORTED_TOKEN="UnsupportedToken",t.WRONG_OWNER="WrongOwner",t.SAME_BUY_AND_SELL_TOKEN="SameBuyAndSellToken",t.ZERO_AMOUNT="ZeroAmount",t.UNSUPPORTED_BUY_TOKEN_DESTINATION="UnsupportedBuyTokenDestination",t.UNSUPPORTED_SELL_TOKEN_SOURCE="UnsupportedSellTokenSource",t.UNSUPPORTED_ORDER_TYPE="UnsupportedOrderType",t.UNSUPPORTED_SIGNATURE="UnsupportedSignature"}(x||(x={})),function(e){e.ERC20="erc20",e.INTERNAL="internal",e.EXTERNAL="external"}(j||(j={})),function(e){e.EIP712="eip712",e.ETHSIGN="ethsign",e.PRESIGN="presign",e.EIP1271="eip1271"}(H||(H={}));const k="0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE";function G(e){return function(e){const{ethflowData:t}=e;if(!t)return e;const{userValidTo:r}=t,o=e.onchainUser||e.owner,n=k;return{...e,validTo:r,owner:o,sellToken:n}}(function(e){const{executedFeeAmount:t,executedSurplusFee:r}=e,o=null!=r?r:t;return{...e,totalFee:o}}(e))}const M={[r.MAINNET]:"https://api.cow.fi/mainnet",[r.GNOSIS_CHAIN]:"https://api.cow.fi/xdai",[r.GOERLI]:"https://api.cow.fi/goerli"},B={[r.MAINNET]:"https://barn.api.cow.fi/mainnet",[r.GNOSIS_CHAIN]:"https://barn.api.cow.fi/xdai",[r.GOERLI]:"https://barn.api.cow.fi/goerli"};class W extends u{constructor(e){super(e)}request(e){return A(this.config,{...e,headers:{...e.headers,"Content-Type":"application/json"}})}}class ${constructor(e={},t){this.context=void 0,this.customEnvConfigs=void 0,this.servicePerNetwork={},this.context={...n,...e},this.customEnvConfigs=t}getTrades({owner:e,orderId:t},r={}){return e&&t?new E((e,t)=>{t(new i("Cannot specify both owner and orderId"))}):this.getServiceForNetwork(r).getApiV1Trades(e,t)}getOrders({owner:e,offset:t=0,limit:r=1e3},o={}){return this.getServiceForNetwork(o).getApiV1AccountOrders(e,t,r).then(e=>e.map(G))}getTxOrders(e,t={}){return this.getServiceForNetwork(t).getApiV1TransactionsOrders(e).then(e=>e.map(G))}getOrder(e,t={}){return this.getServiceForNetwork(t).getApiV1Orders(e).then(e=>G(e))}getOrderMultiEnv(e,t={}){const{env:r}=this.getContextWithOverride(t),n=o.filter(e=>e!==r);let i=0;const s=r=>{const o=n[i];return r instanceof d&&404===r.status&&o?(i++,this.getOrder(e,{...t,env:o}).catch(s)):Promise.reject(r)};return this.getOrder(e,{...t,env:r}).catch(s)}getQuote(e,t={}){return this.getServiceForNetwork(t).postApiV1Quote(e)}sendSignedOrderCancellation(e,t,r={}){return this.getServiceForNetwork(r).deleteApiV1Orders1(e,t)}sendOrder(e,t={}){return this.getServiceForNetwork(t).postApiV1Orders(e).catch(e=>{const t=e.body;if(t?.errorType)throw new Error(t.errorType);throw e})}getNativePrice(e,t={}){return this.getServiceForNetwork(t).getApiV1TokenNativePrice(e)}getOrderLink(e,t={}){const{chainId:r,env:o}=this.getContextWithOverride(t);return this.getEnvConfigs(o)[r]+`/api/v1/orders/${e}`}getServiceForNetwork(e){const{chainId:t,env:r}=this.getContextWithOverride(e),o=`${r}|${t}`,n=this.servicePerNetwork[o];if(n)return n.default;const i=new g({BASE:this.getEnvConfigs(r)[t]},W);return this.servicePerNetwork[o]=i,i.default}getContextWithOverride(e={}){return{...this.context,...e}}getEnvConfigs(e){return this.customEnvConfigs?this.customEnvConfigs:"prod"===e?M:B}}const K=e`
import"cross-fetch/polyfill";import{RateLimiter as e}from"limiter";import{backOff as t}from"exponential-backoff";import{gql as r,request as n}from"graphql-request";var a;!function(e){e[e.MAINNET=1]="MAINNET",e[e.GOERLI=5]="GOERLI",e[e.GNOSIS_CHAIN=100]="GNOSIS_CHAIN"}(a||(a={}));const o=["prod","staging"],s={env:"prod",chainId:a.MAINNET};class i extends Error{constructor(e,t){super(e),this.error_code=void 0,this.error_code=t}}const c="cow-sdk:",d="https://gnosis.mypinata.cloud/ipfs",u="https://api.pinata.cloud",{GPv2Settlement:E}=JSON.parse('{\n "GPv2AllowListAuthentication_Implementation": {\n "1": {\n "address": "0x9E7Ae8Bdba9AA346739792d219a808884996Db67",\n "transactionHash": "0x58340aa44119c74e48635fab0ac344170c6d6e8b42e5714baa4ba4e1651f63ad"\n },\n "4": {\n "address": "0x9E7Ae8Bdba9AA346739792d219a808884996Db67"\n },\n "5": {\n "address": "0x9E7Ae8Bdba9AA346739792d219a808884996Db67",\n "transactionHash": "0x24f4f80b46a17345011065f9ea2af823f582db56be81098b3b66cc2db9659ea7"\n },\n "100": {\n "address": "0x9E7Ae8Bdba9AA346739792d219a808884996Db67",\n "transactionHash": "0xe52d425fe34d6d5215ccfc9ddfa485d490b3018f0ee5bbed708f2d172044d60d"\n }\n },\n "GPv2AllowListAuthentication_Proxy": {\n "1": {\n "address": "0x2c4c28DDBdAc9C5E7055b4C863b72eA0149D8aFE",\n "transactionHash": "0xb84bf720364f94c749f1ec1cdf0d4c44c70411b716459aaccfd24fc677013375"\n },\n "4": {\n "address": "0x2c4c28DDBdAc9C5E7055b4C863b72eA0149D8aFE",\n "transactionHash": "0x57b2278fd3a13ab1b132031024475ba1a4e28d7d4d37f556134c84512b742c1f"\n },\n "5": {\n "address": "0x2c4c28DDBdAc9C5E7055b4C863b72eA0149D8aFE",\n "transactionHash": "0x39dcf30baf887a5db54551a84de8bfdb6cf418bb284b09680d13aed17d5fa0c1"\n },\n "100": {\n "address": "0x2c4c28DDBdAc9C5E7055b4C863b72eA0149D8aFE",\n "transactionHash": "0x1a2d87a05a94bc6680a4faee31bbafbd74e9ddb63dd3941c717b5c609c08b957"\n }\n },\n "GPv2AllowListAuthentication": {\n "1": {\n "address": "0x2c4c28DDBdAc9C5E7055b4C863b72eA0149D8aFE",\n "transactionHash": "0xb84bf720364f94c749f1ec1cdf0d4c44c70411b716459aaccfd24fc677013375"\n },\n "4": {\n "address": "0x2c4c28DDBdAc9C5E7055b4C863b72eA0149D8aFE",\n "transactionHash": "0x57b2278fd3a13ab1b132031024475ba1a4e28d7d4d37f556134c84512b742c1f"\n },\n "5": {\n "address": "0x2c4c28DDBdAc9C5E7055b4C863b72eA0149D8aFE",\n "transactionHash": "0x39dcf30baf887a5db54551a84de8bfdb6cf418bb284b09680d13aed17d5fa0c1"\n },\n "100": {\n "address": "0x2c4c28DDBdAc9C5E7055b4C863b72eA0149D8aFE",\n "transactionHash": "0x1a2d87a05a94bc6680a4faee31bbafbd74e9ddb63dd3941c717b5c609c08b957"\n }\n },\n "GPv2Settlement": {\n "1": {\n "address": "0x9008D19f58AAbD9eD0D60971565AA8510560ab41",\n "transactionHash": "0xf49f90aa5a268c40001d1227b76bb4dd8247f18361fcad9fffd4a7a44f1320d3"\n },\n "4": {\n "address": "0x9008D19f58AAbD9eD0D60971565AA8510560ab41",\n "transactionHash": "0x609fa2e8f32c73c1f5dc21ff60a26238dacb50d4674d336c90d6950bdda17a21"\n },\n "5": {\n "address": "0x9008D19f58AAbD9eD0D60971565AA8510560ab41",\n "transactionHash": "0x982f089060ff66e19d0683ef1cc6a637297331a9ba95b65d8eb84b9f8dc64b04"\n },\n "100": {\n "address": "0x9008D19f58AAbD9eD0D60971565AA8510560ab41",\n "transactionHash": "0x9ddc538f89cd8433f4a19bc4de0de27e7c68a1d04a14b327185e4bba9af87133"\n }\n },\n "GPv2VaultRelayer": {\n "1": {\n "address": "0xC92E8bdf79f0507f65a392b0ab4667716BFE0110",\n "transactionHash": "0xf49f90aa5a268c40001d1227b76bb4dd8247f18361fcad9fffd4a7a44f1320d3"\n },\n "4": {\n "address": "0xC92E8bdf79f0507f65a392b0ab4667716BFE0110",\n "transactionHash": "0x609fa2e8f32c73c1f5dc21ff60a26238dacb50d4674d336c90d6950bdda17a21"\n },\n "5": {\n "address": "0xC92E8bdf79f0507f65a392b0ab4667716BFE0110",\n "transactionHash": "0x982f089060ff66e19d0683ef1cc6a637297331a9ba95b65d8eb84b9f8dc64b04"\n },\n "100": {\n "address": "0xC92E8bdf79f0507f65a392b0ab4667716BFE0110",\n "transactionHash": "0x9ddc538f89cd8433f4a19bc4de0de27e7c68a1d04a14b327185e4bba9af87133"\n }\n }\n}'),f=[a.MAINNET,a.GOERLI,a.GNOSIS_CHAIN],h=f.reduce((e,t)=>({...e,[t]:E[t].address}),{}),l="0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE";function b(e){return function(e){const{ethflowData:t}=e;if(!t)return e;const{userValidTo:r}=t,n=e.onchainUser||e.owner,a=l;return{...e,validTo:r,owner:n,sellToken:a}}(function(e){const{executedFeeAmount:t,executedSurplusFee:r}=e,n=null!=r?r:t;return{...e,totalFee:n}}(e))}const p=function(e,{path:r,query:n,method:a,body:o},s,i){try{const c={Accept:"application/json","Content-Type":"application/json"},d=`${e}${r}${n?"?"+n:""}`,u={method:a,body:o?JSON.stringify(o):void 0,headers:c};return Promise.resolve(t(function(){try{return Promise.resolve(s.removeTokens(1)).then(function(){return Promise.resolve(fetch(d,u)).then(function(e){return Promise.resolve(N(e)).then(function(t){return e.status>=200&&e.status<300?t:Promise.reject(new A(e,t))})})})}catch(e){return Promise.reject(e)}},i))}catch(e){return Promise.reject(e)}};class A extends Error{constructor(e,t){super("string"==typeof t?t:e.statusText),this.response=void 0,this.body=void 0,this.response=e,this.body=t}}const T=[408,425,429,500,502,503,504],I={numOfAttempts:10,maxDelay:Infinity,jitter:"none",retry:e=>!(e instanceof A)||T.includes(e.response.status)},O={tokensPerInterval:5,interval:"second"},N=function(e){try{let t;const r=function(){if(204!==e.status)return function(r,n){try{var a=function(){const r=e.headers.get("Content-Type");return function(){if(r)return r.toLowerCase().startsWith("application/json")?Promise.resolve(e.json()).then(function(e){return t=1,e}):Promise.resolve(e.text()).then(function(e){return t=1,e})}()}()}catch(e){return n(e)}return a&&a.then?a.then(void 0,n):a}(0,function(e){console.error(e)})}();return Promise.resolve(r&&r.then?r.then(function(e){return t?e:void 0}):t?r:void 0)}catch(e){return Promise.reject(e)}},m={[a.MAINNET]:"https://api.cow.fi/mainnet",[a.GNOSIS_CHAIN]:"https://api.cow.fi/xdai",[a.GOERLI]:"https://api.cow.fi/goerli"},D={[a.MAINNET]:"https://barn.api.cow.fi/mainnet",[a.GNOSIS_CHAIN]:"https://barn.api.cow.fi/xdai",[a.GOERLI]:"https://barn.api.cow.fi/goerli"};function _(e){return Object.keys(e).reduce((t,r)=>{const n=e[r];return void 0!==n&&(t[r]=n),t},{})}class S{constructor(t={}){this.context=void 0,this.rateLimiter=void 0,this.context={...s,...t},this.rateLimiter=new e(t.limiterOpts||O)}getTrades(e,t={}){if(e.owner&&e.orderUid)return Promise.reject(new i("Cannot specify both owner and orderId"));const r=new URLSearchParams(_(e));return this.fetch({path:"/api/v1/trades",method:"GET",query:r},t)}getOrders({owner:e,offset:t=0,limit:r=1e3},n={}){const a=new URLSearchParams(_({offset:t.toString(),limit:r.toString()}));return this.fetch({path:`/api/v1/account/${e}/orders`,method:"GET",query:a},n).then(e=>e.map(b))}getTxOrders(e,t={}){return this.fetch({path:`/api/v1/transactions/${e}/orders`,method:"GET"},t).then(e=>e.map(b))}getOrder(e,t={}){return this.fetch({path:`/api/v1/orders/${e}`,method:"GET"},t).then(e=>b(e))}getOrderMultiEnv(e,t={}){const{env:r}=this.getContextWithOverride(t),n=o.filter(e=>e!==r);let a=0;const s=r=>{const o=n[a];return r instanceof A&&404===r.response.status&&o?(a++,this.getOrder(e,{...t,env:o}).catch(s)):Promise.reject(r)};return this.getOrder(e,{...t,env:r}).catch(s)}getQuote(e,t={}){return this.fetch({path:"/api/v1/quote",method:"POST",body:e},t)}sendSignedOrderCancellations(e,t={}){return this.fetch({path:"/api/v1/orders",method:"DELETE",body:e},t)}sendOrder(e,t={}){return this.fetch({path:"/api/v1/orders",method:"POST",body:e},t)}getNativePrice(e,t={}){return this.fetch({path:`/api/v1/token/${e}/native_price`,method:"GET"},t)}getOrderLink(e,t){const{chainId:r,env:n}=this.getContextWithOverride(t);return this.getApiBaseUrls(n)[r]+`/api/v1/orders/${e}`}getContextWithOverride(e={}){return{...this.context,...e}}getApiBaseUrls(e){return this.context.baseUrls?this.context.baseUrls:"prod"===e?m:D}fetch(e,t={}){const{chainId:r,env:n}=this.getContextWithOverride(t),a=this.getApiBaseUrls(n)[r];return p(a,e,this.rateLimiter,this.context.backoffOpts||I)}}var R,U,C,P,v,L,g,x,y,F,w,G,B,H;!function(e){e.ERC20="erc20",e.INTERNAL="internal"}(R||(R={})),function(e){e.EIP712="eip712",e.ETHSIGN="ethsign"}(U||(U={})),function(e){var t;(t=e.errorType||(e.errorType={})).NO_LIQUIDITY="NoLiquidity",t.UNSUPPORTED_TOKEN="UnsupportedToken",t.AMOUNT_IS_ZERO="AmountIsZero",t.SELL_AMOUNT_DOES_NOT_COVER_FEE="SellAmountDoesNotCoverFee"}(C||(C={})),function(e){var t;(t=e.placementError||(e.placementError={})).QUOTE_NOT_FOUND="QuoteNotFound",t.VALID_TO_TOO_FAR_IN_FUTURE="ValidToTooFarInFuture",t.PRE_VALIDATION_ERROR="PreValidationError"}(P||(P={})),function(e){var t;(t=e.errorType||(e.errorType={})).INVALID_SIGNATURE="InvalidSignature",t.WRONG_OWNER="WrongOwner",t.ORDER_NOT_FOUND="OrderNotFound",t.ALREADY_CANCELLED="AlreadyCancelled",t.ORDER_FULLY_EXECUTED="OrderFullyExecuted",t.ORDER_EXPIRED="OrderExpired",t.ON_CHAIN_ORDER="OnChainOrder"}(v||(v={})),function(e){e.MARKET="market",e.LIMIT="limit",e.LIQUIDITY="liquidity"}(L||(L={})),function(e){e.BUY="buy",e.SELL="sell"}(g||(g={})),function(e){var t;(t=e.errorType||(e.errorType={})).DUPLICATE_ORDER="DuplicateOrder",t.INSUFFICIENT_FEE="InsufficientFee",t.INSUFFICIENT_ALLOWANCE="InsufficientAllowance",t.INSUFFICIENT_BALANCE="InsufficientBalance",t.INSUFFICIENT_VALID_TO="InsufficientValidTo",t.EXCESSIVE_VALID_TO="ExcessiveValidTo",t.INVALID_SIGNATURE="InvalidSignature",t.TRANSFER_ETH_TO_CONTRACT="TransferEthToContract",t.TRANSFER_SIMULATION_FAILED="TransferSimulationFailed",t.UNSUPPORTED_TOKEN="UnsupportedToken",t.WRONG_OWNER="WrongOwner",t.MISSING_FROM="MissingFrom",t.SAME_BUY_AND_SELL_TOKEN="SameBuyAndSellToken",t.ZERO_AMOUNT="ZeroAmount",t.UNSUPPORTED_BUY_TOKEN_DESTINATION="UnsupportedBuyTokenDestination",t.UNSUPPORTED_SELL_TOKEN_SOURCE="UnsupportedSellTokenSource",t.UNSUPPORTED_ORDER_TYPE="UnsupportedOrderType",t.UNSUPPORTED_SIGNATURE="UnsupportedSignature",t.TOO_MANY_LIMIT_ORDERS="TooManyLimitOrders"}(x||(x={})),function(e){(e.kind||(e.kind={})).SELL="sell"}(y||(y={})),function(e){e.PRESIGNATURE_PENDING="presignaturePending",e.OPEN="open",e.FULFILLED="fulfilled",e.CANCELLED="cancelled",e.EXPIRED="expired"}(F||(F={})),function(e){e.FAST="fast",e.OPTIMAL="optimal"}(w||(w={})),function(e){var t;(t=e.errorType||(e.errorType={})).ALREADY_CANCELLED="AlreadyCancelled",t.ORDER_FULLY_EXECUTED="OrderFullyExecuted",t.ORDER_EXPIRED="OrderExpired",t.ON_CHAIN_ORDER="OnChainOrder",t.DUPLICATE_ORDER="DuplicateOrder",t.INSUFFICIENT_FEE="InsufficientFee",t.INSUFFICIENT_ALLOWANCE="InsufficientAllowance",t.INSUFFICIENT_BALANCE="InsufficientBalance",t.INSUFFICIENT_VALID_TO="InsufficientValidTo",t.EXCESSIVE_VALID_TO="ExcessiveValidTo",t.INVALID_SIGNATURE="InvalidSignature",t.TRANSFER_ETH_TO_CONTRACT="TransferEthToContract",t.TRANSFER_SIMULATION_FAILED="TransferSimulationFailed",t.UNSUPPORTED_TOKEN="UnsupportedToken",t.WRONG_OWNER="WrongOwner",t.SAME_BUY_AND_SELL_TOKEN="SameBuyAndSellToken",t.ZERO_AMOUNT="ZeroAmount",t.UNSUPPORTED_BUY_TOKEN_DESTINATION="UnsupportedBuyTokenDestination",t.UNSUPPORTED_SELL_TOKEN_SOURCE="UnsupportedSellTokenSource",t.UNSUPPORTED_ORDER_TYPE="UnsupportedOrderType",t.UNSUPPORTED_SIGNATURE="UnsupportedSignature"}(G||(G={})),function(e){e.ERC20="erc20",e.INTERNAL="internal",e.EXTERNAL="external"}(B||(B={})),function(e){e.EIP712="eip712",e.ETHSIGN="ethsign",e.PRESIGN="presign",e.EIP1271="eip1271"}(H||(H={}));const M=r`
query Totals {

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

}
`,Y=e`
`,V=r`
query LastDaysVolume($days: Int!) {

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

}
`,Q=e`
`,k=r`
query LastHoursVolume($hours: Int!) {

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

}
`,X={[r.MAINNET]:"https://api.thegraph.com/subgraphs/name/cowprotocol/cow",[r.GNOSIS_CHAIN]:"https://api.thegraph.com/subgraphs/name/cowprotocol/cow-gc",[r.GOERLI]:"https://api.thegraph.com/subgraphs/name/cowprotocol/cow-goerli"},Z={[r.MAINNET]:"https://api.thegraph.com/subgraphs/name/cowprotocol/cow-staging",[r.GNOSIS_CHAIN]:"https://api.thegraph.com/subgraphs/name/cowprotocol/cow-gc-staging",[r.GOERLI]:""};class J{constructor(e={},t){this.API_NAME="CoW Protocol Subgraph",this.context=void 0,this.customEnvConfigs=void 0,this.context={...n,...e},this.customEnvConfigs=t}getTotals(e={}){try{return Promise.resolve(this.runQuery(K,void 0,e)).then(function(e){return e.totals[0]})}catch(e){return Promise.reject(e)}}getLastDaysVolume(e,t={}){try{return Promise.resolve(this.runQuery(Y,{days:e},t))}catch(e){return Promise.reject(e)}}getLastHoursVolume(e,t={}){try{return Promise.resolve(this.runQuery(Q,{hours:e},t))}catch(e){return Promise.reject(e)}}runQuery(e,r=undefined,o={}){try{const n=this,{chainId:s,env:a}=n.getContextWithOverride(o),c=n.getEnvConfigs(a)[s];return Promise.resolve(function(o,n){try{var i=Promise.resolve(t(c,e,r))}catch(e){return n(e)}return i&&i.then?i.then(void 0,n):i}(0,function(t){throw console.error(`[subgraph:${n.API_NAME}]`,t),new i(`Error running query: ${e}. Variables: ${JSON.stringify(r)}. API: ${c}. Inner Error: ${t}`)}))}catch(e){return Promise.reject(e)}}getContextWithOverride(e={}){return{...this.context,...e}}getEnvConfigs(e){return this.customEnvConfigs?this.customEnvConfigs:"prod"===e?X:Z}}export{d as ApiError,u as BaseHttpRequest,y as BuyTokenDestination,l as CancelError,E as CancelablePromise,i as CowError,n as DEFAULT_COW_API_CONTEXT,a as DEFAULT_IPFS_READ_URI,c as DEFAULT_IPFS_WRITE_URI,R as DefaultService,o as ENVS_LIST,C as EcdsaSigningScheme,D as FeeAndQuoteError,M as ORDER_BOOK_PROD_CONFIG,B as ORDER_BOOK_STAGING_CONFIG,U as OnchainOrderData,S as OpenAPI,$ as OrderBookApi,g as OrderBookClient,P as OrderCancellationError,w as OrderClass,L as OrderKind,F as OrderPostError,b as OrderQuoteSide,q as OrderStatus,V as PriceQuality,x as ReplaceOrderError,X as SUBGRAPH_PROD_CONFIG,Z as SUBGRAPH_STAGING_CONFIG,j as SellTokenSource,H as SigningScheme,J as SubgraphApi,r as SupportedChainId,s as logPrefix};
`,j={[a.MAINNET]:"https://api.thegraph.com/subgraphs/name/cowprotocol/cow",[a.GNOSIS_CHAIN]:"https://api.thegraph.com/subgraphs/name/cowprotocol/cow-gc",[a.GOERLI]:"https://api.thegraph.com/subgraphs/name/cowprotocol/cow-goerli"},W={[a.MAINNET]:"https://api.thegraph.com/subgraphs/name/cowprotocol/cow-staging",[a.GNOSIS_CHAIN]:"https://api.thegraph.com/subgraphs/name/cowprotocol/cow-gc-staging",[a.GOERLI]:""};class ${constructor(e={}){this.API_NAME="CoW Protocol Subgraph",this.context=void 0,this.context={...s,...e}}getTotals(e={}){try{return Promise.resolve(this.runQuery(M,void 0,e)).then(function(e){return e.totals[0]})}catch(e){return Promise.reject(e)}}getLastDaysVolume(e,t={}){try{return Promise.resolve(this.runQuery(V,{days:e},t))}catch(e){return Promise.reject(e)}}getLastHoursVolume(e,t={}){try{return Promise.resolve(this.runQuery(k,{hours:e},t))}catch(e){return Promise.reject(e)}}runQuery(e,t=undefined,r={}){try{const a=this,{chainId:o,env:s}=a.getContextWithOverride(r),c=a.getEnvConfigs(s)[o];return Promise.resolve(function(r,a){try{var o=Promise.resolve(n(c,e,t))}catch(e){return a(e)}return o&&o.then?o.then(void 0,a):o}(0,function(r){throw console.error(`[subgraph:${a.API_NAME}]`,r),new i(`Error running query: ${e}. Variables: ${JSON.stringify(t)}. API: ${c}. Inner Error: ${r}`)}))}catch(e){return Promise.reject(e)}}getContextWithOverride(e={}){return{...this.context,...e}}getEnvConfigs(e){return this.context.baseUrls?this.context.baseUrls:"prod"===e?j:W}}const Y=()=>import("./utils-65bc03ac.js");class q{static signOrder(e,t,r){try{return Promise.resolve(Y()).then(function({signOrder:n}){return n(e,t,r)})}catch(e){return Promise.reject(e)}}static signOrderCancellation(e,t,r){try{return Promise.resolve(Y()).then(function({signOrderCancellation:n}){return n(e,t,r)})}catch(e){return Promise.reject(e)}}static signOrderCancellations(e,t,r){try{return Promise.resolve(Y()).then(function({signOrderCancellations:n}){return n(e,t,r)})}catch(e){return Promise.reject(e)}}static getDomain(e){try{return Promise.resolve(Y()).then(function({getDomain:t}){return t(e)})}catch(e){return Promise.reject(e)}}}export{f as ALL_SUPPORTED_CHAIN_IDS,R as BuyTokenDestination,h as COW_PROTOCOL_SETTLEMENT_CONTRACT_ADDRESS,i as CowError,I as DEFAULT_BACKOFF_OPTIONS,s as DEFAULT_COW_API_CONTEXT,d as DEFAULT_IPFS_READ_URI,u as DEFAULT_IPFS_WRITE_URI,O as DEFAULT_LIMITER_OPTIONS,o as ENVS_LIST,U as EcdsaSigningScheme,C as FeeAndQuoteError,m as ORDER_BOOK_PROD_CONFIG,D as ORDER_BOOK_STAGING_CONFIG,P as OnchainOrderData,S as OrderBookApi,A as OrderBookApiError,v as OrderCancellationError,L as OrderClass,g as OrderKind,x as OrderPostError,y as OrderQuoteSide,q as OrderSigningUtils,F as OrderStatus,w as PriceQuality,G as ReplaceOrderError,j as SUBGRAPH_PROD_CONFIG,W as SUBGRAPH_STAGING_CONFIG,B as SellTokenSource,H as SigningScheme,$ as SubgraphApi,a as SupportedChainId,c as logPrefix,p as request};
//# sourceMappingURL=index.module.js.map

@@ -1,15 +0,15 @@

import { Address, CancelablePromise, NativePriceResponse, OrderCancellation, OrderCreation, OrderQuoteRequest, OrderQuoteResponse, Trade, TransactionHash, UID } from './generated';
import { ApiContext, EnvConfigs, PartialApiContext } from '../common/configs';
import 'cross-fetch/polyfill';
import { Address, NativePriceResponse, OrderCancellations, OrderCreation, OrderQuoteRequest, OrderQuoteResponse, Trade, TransactionHash, UID } from './generated';
import { ApiContext, ApiBaseUrls, PartialApiContext, RequestOptions } from '../common/configs';
import { EnrichedOrder } from './types';
export declare const ORDER_BOOK_PROD_CONFIG: EnvConfigs;
export declare const ORDER_BOOK_STAGING_CONFIG: EnvConfigs;
export declare const ORDER_BOOK_PROD_CONFIG: ApiBaseUrls;
export declare const ORDER_BOOK_STAGING_CONFIG: ApiBaseUrls;
export declare class OrderBookApi {
context: ApiContext;
customEnvConfigs?: EnvConfigs;
private servicePerNetwork;
constructor(context?: PartialApiContext, customEnvConfigs?: EnvConfigs);
getTrades({ owner, orderId }: {
context: ApiContext & RequestOptions;
private rateLimiter;
constructor(context?: PartialApiContext & RequestOptions);
getTrades(request: {
owner?: Address;
orderId?: UID;
}, contextOverride?: PartialApiContext): CancelablePromise<Array<Trade>>;
orderUid?: UID;
}, contextOverride?: PartialApiContext): Promise<Array<Trade>>;
getOrders({ owner, offset, limit, }: {

@@ -23,10 +23,10 @@ owner: Address;

getOrderMultiEnv(uid: UID, contextOverride?: PartialApiContext): Promise<EnrichedOrder>;
getQuote(requestBody: OrderQuoteRequest, contextOverride?: PartialApiContext): CancelablePromise<OrderQuoteResponse>;
sendSignedOrderCancellation(uid: UID, requestBody: OrderCancellation, contextOverride?: PartialApiContext): CancelablePromise<void>;
getQuote(requestBody: OrderQuoteRequest, contextOverride?: PartialApiContext): Promise<OrderQuoteResponse>;
sendSignedOrderCancellations(requestBody: OrderCancellations, contextOverride?: PartialApiContext): Promise<void>;
sendOrder(requestBody: OrderCreation, contextOverride?: PartialApiContext): Promise<UID>;
getNativePrice(tokenAddress: Address, contextOverride?: PartialApiContext): CancelablePromise<NativePriceResponse>;
getNativePrice(tokenAddress: Address, contextOverride?: PartialApiContext): Promise<NativePriceResponse>;
getOrderLink(uid: UID, contextOverride?: PartialApiContext): string;
private getServiceForNetwork;
private getContextWithOverride;
private getEnvConfigs;
private getApiBaseUrls;
private fetch;
}

@@ -1,20 +0,13 @@

export { OrderBookClient } from './OrderBookClient';
export { ApiError } from './core/ApiError';
export { BaseHttpRequest } from './core/BaseHttpRequest';
export { CancelablePromise, CancelError } from './core/CancelablePromise';
export { OpenAPI } from './core/OpenAPI';
export type { OpenAPIConfig } from './core/OpenAPI';
export type { Address } from './models/Address';
export type { AmountEstimate } from './models/AmountEstimate';
export type { AppData } from './models/AppData';
export type { Auction } from './models/Auction';
export type { AuctionPrices } from './models/AuctionPrices';
export type { BigUint } from './models/BigUint';
export { BuyTokenDestination } from './models/BuyTokenDestination';
export type { CallData } from './models/CallData';
export type { CompetitionAuction } from './models/CompetitionAuction';
export type { EcdsaSignature } from './models/EcdsaSignature';
export { EcdsaSigningScheme } from './models/EcdsaSigningScheme';
export type { EthflowData } from './models/EthflowData';
export type { FeeAndQuoteBuyResponse } from './models/FeeAndQuoteBuyResponse';
export { FeeAndQuoteError } from './models/FeeAndQuoteError';
export type { FeeAndQuoteSellResponse } from './models/FeeAndQuoteSellResponse';
export type { FeeInformation } from './models/FeeInformation';
export type { NativePriceResponse } from './models/NativePriceResponse';

@@ -50,2 +43,1 @@ export { OnchainOrderData } from './models/OnchainOrderData';

export type { VersionResponse } from './models/VersionResponse';
export { DefaultService } from './services/DefaultService';

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

import type { BigUint } from './BigUint';
import type { AuctionPrices } from './AuctionPrices';
import type { Order } from './Order';

@@ -32,10 +32,3 @@ /**

orders?: Array<Order>;
/**
* The reference prices for all traded tokens in the auction as a mapping from token
* addresses to a price denominated in native token (i.e. 1e18 represents a token that
* trades one to one with the native token). These prices are used for solution competition
* for computing surplus and converting fees to native token.
*
*/
prices?: Record<string, BigUint>;
prices?: AuctionPrices;
};

@@ -23,3 +23,4 @@ import type { Address } from './Address';

/**
* Amount of sellToken available for the settlement contract to spend on behalf of the owner. Null if API was unable to fetch balance or if the order status isn't Open.
* Unused field that is currently always set to null and will be removed in the future.
* @deprecated
*/

@@ -26,0 +27,0 @@ availableBalance?: TokenAmount | null;

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

import type { CompetitionAuction } from './CompetitionAuction';
import type { SolverSettlement } from './SolverSettlement';

@@ -24,2 +25,3 @@ import type { TransactionHash } from './TransactionHash';

competitionSimulationBlock?: number;
auction?: CompetitionAuction;
/**

@@ -26,0 +28,0 @@ * Maps from solver name to object describing that solver's settlement.

import type { BigUint } from './BigUint';
import type { CallData } from './CallData';
import type { UID } from './UID';

@@ -8,2 +9,8 @@ export type SolverSettlement = {

solver?: string;
/**
* The address used by the solver to execute the settlement onchain.
* This field is missing for old settlements, the zero address has been used instead.
*
*/
solverAddress?: string;
objective?: {

@@ -20,6 +27,12 @@ /**

/**
* The score of the current auction as defined in CIP-20.
* It is null for old auctions.
*
*/
score?: BigUint | null;
/**
* The prices of tokens for settled user orders as passed to the settlement contract.
*
*/
prices?: Record<string, BigUint>;
clearingPrices?: Record<string, BigUint>;
/**

@@ -33,5 +46,12 @@ * the touched orders

/**
* hex encoded transaction calldata
* Transaction call data that is executed onchain if the settlement is executed.
*/
callData?: string;
callData?: CallData;
/**
* Full call data as generated from the original solver output.
* It can be different from the executed transaction if part of the settlements are internalized (use internal liquidity in lieu of trading against onchain liquidity).
* This field is omitted in case it coincides with callData.
*
*/
uninternalizedCallData?: CallData;
};
export * from './api';
export * from './types';
export * from './generated';
export * from './request';
{
"name": "@cowprotocol/cow-sdk",
"version": "2.0.0-alpha.4",
"version": "2.1.0",
"license": "(MIT OR Apache-2.0)",

@@ -29,8 +29,15 @@ "files": [

"graphql:codegen": "graphql-codegen --config graphql-codegen.yml",
"swagger:codegen": " openapi --input https://raw.githubusercontent.com/cowprotocol/services/fix/orderbook-openapi/crates/orderbook/openapi.yml --output src/order-book/generated --client fetch --name OrderBookClient"
"swagger:codegen": " openapi --input https://raw.githubusercontent.com/cowprotocol/services/main/crates/orderbook/openapi.yml --output src/order-book/generated --exportServices false --exportCore false"
},
"dependencies": {
"graphql": "^16.3.0",
"@cowprotocol/contracts": "^1.4.0",
"@ethersproject/abstract-signer": "^5.7.0",
"exponential-backoff": "^3.1.1",
"limiter": "^2.1.0",
"cross-fetch": "^3.1.5",
"graphql-request": "^4.3.0"
},
"peerDependencies": {
"ethers": "^5.7.2"
},
"devDependencies": {

@@ -53,2 +60,4 @@ "@babel/plugin-proposal-nullish-coalescing-operator": "^7.18.6",

"eslint-plugin-prettier": "^4.2.1",
"ethers": "^5.7.2",
"graphql": "^16.3.0",
"jest": "^29.4.2",

@@ -59,2 +68,3 @@ "jest-fetch-mock": "^3.0.3",

"prettier": "^2.5.1",
"ts-mockito": "^2.6.1",
"tsc-watch": "^6.0.0",

@@ -61,0 +71,0 @@ "typescript": "^4.9.5"

@@ -7,9 +7,16 @@ <p align="center">

[![Styled With Prettier](https://img.shields.io/badge/code_style-prettier-ff69b4.svg)](https://prettier.io/)
[![Coverage Status](https://coveralls.io/repos/github/cowprotocol/cow-sdk/badge.svg?branch=main)](https://coveralls.io/github/cowprotocol/cow-sdk?branch=main)
## 📚 [SDK docs website](https://docs.cow.fi/cow-sdk)
## Test coverage
| Statements | Branches | Functions | Lines |
| ------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------ | ---------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------- |
| ![Statements](https://img.shields.io/badge/statements-94.77%25-brightgreen.svg?style=flat) | ![Branches](https://img.shields.io/badge/branches-76.78%25-red.svg?style=flat) | ![Functions](https://img.shields.io/badge/functions-97.43%25-brightgreen.svg?style=flat) | ![Lines](https://img.shields.io/badge/lines-97.67%25-brightgreen.svg?style=flat) |
## Getting started
Install the SDK:
**Usage examples: [VanillaJS](./examples/vanilla/src/index.ts), [Create React App](./examples/cra/src/pages/getOrders/index.tsx), [NodeJS](./examples/nodejs/src/index.ts)**
### Installation
```bash

@@ -19,360 +26,165 @@ yarn add @cowprotocol/cow-sdk

Instantiate the SDK:
### Content
```js
import { CowSdk } from '@cowprotocol/cow-sdk'
- `OrderBookApi` - provides the ability to retrieve orders and trades from the CowSap order-book, as well as add and cancel them
- `OrderSigningUtils` - serves to sign orders and cancel them using [EIP-712](https://eips.ethereum.org/EIPS/eip-712)
- `SubgraphApi` - provides statistics data about CoW protocol from [Subgraph](https://github.com/cowprotocol/subgraph), such as trading volume, trades count and others
const chainId = 100 // Gnosis chain
const cowSdk = new CowSdk(chainId)
```
The SDK will expose:
```typescript
import { OrderBookApi, OrderSigningUtils, SubgraphApi } from '@cowprotocol/cow-sdk'
- The CoW API (`cowSdk.cowApi`)
- The CoW Subgraph (`cowSdk.cowSubgraphApi`)
- Convenient method to facilitate signing orders (i.e `cowSdk.signOrder`)
const chainId = 100 // Gnosis chain
> For a quick snippet with the full process on posting an order see the [Post an Order Example](./docs/post-order-example.ts)
## CoW API
The SDK provides access to the CoW API. The CoW API allows you:
- Post orders
- Get fee quotes
- Get order details
- Get history of orders: i.e. filtering by account, transaction hash, etc.
For example, you can easily get the last 5 order of a trader:
```js
// i.e. Get last 5 orders for a given trader
const trades = await cowSdk.cowApi.getOrders({
owner: '0x00000000005ef87f8ca7014309ece7260bbcdaeb', // Trader
limit: 5,
offset: 0,
})
console.log(trades)
const orderBookApi = new OrderBookApi({ chainId })
const subgraphApi = new SubgraphApi({ chainId })
const orderSigningUtils = new OrderSigningUtils()
```
> For more information about the API methods, you can check [api.cow.fi/docs](https://api.cow.fi/docs).
## Quick start
## Sign and Post orders
### Sign, fetch, post and cancel order
In order to trade, you will need to create a valid order first.
For clarity, let's look at the use of the API with a practical example:
Exchanging `0.4 GNO` to `WETH` on `Goerli` network.
On the contraty to other decentralised exchanges, creating orders is free in CoW Protocol. This is because, one of the
most common ways to do it is by created offchain signed messages (meta-transactions, uses `EIP-712` or `EIP-1271`).
We will do the following operations:
1. Get a quote
2. Sign the order
3. Send the order to the order-book
4. Get the data of the created order
5. Get trades of the order
6. Cancel the order (signing + sending)
Posting orders is a three steps process:
[You also can check this code in the CRA example](./examples/cra/src/pages/quickStart/index.tsx)
- 1. **Get Market Pricea**: Fee & Price
- 2. **Sign the order**: Using off-chain signing or Meta-transactions
- 3. **Post the signed order to the API**: So, the order becomes `OPEN`
The next sections will guide you through the process of creating a valid order.
```typescript
import { OrderBookApi, OrderSigningUtils, SupportedChainId } from '@cowprotocol/cow-sdk'
import { Web3Provider } from '@ethersproject/providers'
> For a quick snippet with the full process on posting an order see the [Post an Order Example](./docs/post-order-example.ts).
const account = 'YOUR_WALLET_ADDRESS'
const chainId = 5 // Goerli
const provider = new Web3Provider(window.ethereum)
const signer = provider.getSigner()
### Enable tokens (token approval)
Because of the use of off-chain signing (meta-transactions), users will need to **Enable the sell token** before signed
orders can be considered as valid ones.
const quoteRequest = {
sellToken: '0xb4fbf271143f4fbf7b91a5ded31805e42b2208d6', // WETH goerli
buyToken: '0x02abbdbaaa7b1bb64b5c878f7ac17f8dda169532', // GNO goerli
from: account,
receiver: account,
sellAmountBeforeFee: (0.4 * 10 ** 18).toString(), // 0.4 WETH
kind: OrderQuoteSide.kind.SELL,
}
This enabling is technically an `ERC-20` approval, and is something that needs to be done only once. After this all
order creation can be done for free using offchain signing.
const orderBookApi = new OrderBookApi({ chainId: SupportedChainId.GOERLI })
> For more details see https://docs.cow.fi/tutorials/how-to-submit-orders-via-the-api/1.-set-allowance-for-the-sell-token
async function main() {
const { quote } = await orderBookApi.getQuote(quoteRequest)
### Instantiate SDK with a signer
const orderSigningResult = await OrderSigningUtils.signOrder(quote, chainId, signer)
Before you can sign any transaction, you have to instantiate the SDK with a [Ethers.JS signer](https://docs.ethers.io/v5/api/signer/):
const orderId = await orderBookApi.sendOrder({ ...quote, ...orderSigningResult })
```js
import { Wallet } from 'ethers'
import { CowSdk, OrderKind } from '@cowprotocol/cow-sdk'
const order = await orderBookApi.getOrder(orderId)
const mnemonic = 'fall dirt bread cactus...'
const wallet = Wallet.fromMnemonic(mnemonic)
const trades = await orderBookApi.getTrades({ orderId })
const cowSdk = new CowSdk(
100, { // Leaving chainId empty will default to MAINNET
signer: wallet // Provide a signer, so you can sign order
})
```
const orderCancellationSigningResult = await OrderSigningUtils.signOrderCancellations([orderId], chainId, signer)
### STEP 1: Get Market Price
const cancellationResult = await orderBookApi.sendSignedOrderCancellations({...orderCancellationSigningResult, orderUids: [orderId] })
To create an order, you need to get a price/fee quote first:
* The SDK will give you easy access to the API, which returns the `Market Price` and the `Fee` for any given trade you intent to do.
* The returned `Market Price` is not strictly needed, you can use your own pricing logic.
* You can choose a price that is below this Market price (**Market Order**), or above Market Price (**Limit Order**).
* The `Fee` however is very important.
* It is the required amount in sell token the trader agrees on paying for executing the order onchain.
* Normally, its value is proportional to the current Gas Price of the network.
* This fee is never charged if you don't trade.
To get the quote, you simply specify the trade you intent to do:
```js
const quoteResponse = await cowSdk.cowApi.getQuote({
kind: OrderKind.SELL, // Sell order (could also be BUY)
sellToken: '0xc778417e063141139fce010982780140aa0cd5ab', // WETH
buyToken: '0x4dbcdf9b62e891a7cec5a2568c3f4faf9e8abe2b', // USDC
amount: '1000000000000000000', // 1 WETH
userAddress: '0x1811be0994930fe9480eaede25165608b093ad7a', // Trader
validTo: 2524608000,
})
const { sellToken, buyToken, validTo, buyAmount, sellAmount, receiver, feeAmount } = quoteResponse.quote
console.log('Results: ', { orderId, order, trades, orderCancellationSigningResult, cancellationResult })
}
```
### STEP 2: Sign the order
### OrderBookApi
Once you know the price and fee, we can create the order and sign it:
`OrderBookApi` - is a main tool for working with [CoW Protocol API](https://api.cow.fi/docs/#/).
Since the API supports different networks and environments, there are some options to configure it.
- Technically the order is just a signed message with your intent to trade, and contains your `Limit Price` and `Fee`.
- As explained before, you can choose your `Limit Price`, but some general approach is to take the current Market Price
and apply some slippage tolerance to it. `Received Amount = Expected Amount * (1 - Slippage Tolerance)`
- The SDK will provide an easy way to sign orders given the raw data
#### Environment configuration
```js
const { sellToken, buyToken, validTo, buyAmount, sellAmount, receiver, feeAmount } = quoteResponse.quote
`chainId` - can be `SupportedChainId.MAINNET` or `SupportedChainId.GNOSIS_CHAIN` or `SupportedChainId.GOERLI`
// Prepare the RAW order
const order = {
kind: OrderKind.SELL, // SELL || BUY
receiver, // Your account or any other
sellToken,
buyToken,
`env` - this parameter affects which environment will be used:
- `https://api.cow.fi` for `prod` (default)
- `https://barn.api.cow.fi` for `staging`
partiallyFillable: false, // ("false" is for a "Fill or Kill" order, "true" for allowing "Partial execution" which is not supported yet)
```typescript
import { OrderBookApi } from '@cowprotocol/cow-sdk'
// Deadline
validTo,
// Limit Price
// You can apply some slippage tolerance here to make sure the trade is executed.
// CoW protocol protects from MEV, so it can work with higher slippages
sellAmount,
buyAmount,
// Use the fee you received from the API
feeAmount,
// The appData allows you to attach arbitrary information (meta-data) to the order. Its explained in their own section. For now, you can use this 0x0 value
appData: '0x0000000000000000000000000000000000000000000000000000000000000000',
}
// Sign the order
const signedOrder = await cowSdk.signOrder(order)
const orderBookApi = new OrderBookApi({
chainId: SupportedChainId.GOERLI,
env: 'staging' // <-----
})
```
At this point, you have a signed order. So next step will be to post it to the API so it's considered by the solvers and executed.
#### API urls configuration
## STEP 3: **Post the signed order to the API**:
In case you need to use custom endpoints (e.g. you use a proxy), you can do it this way:
Once you have a signed order, last step is to send it to the API.
```typescript
import { OrderBookApi } from '@cowprotocol/cow-sdk'
- The API will accept the order if its correctly signed, the deadline is correct, and the fee is enough to settle it
- Once accepted, the order will be `OPEN` until the specified `validTo` date (expiration)
- The possible outcomes once accepted is:
- The order is `EXECUTED`: you will pay the signed fee, and get at least the `buyAmount` tokens you specified, although you will probably get more! (you will probably get a so-called **Surplus**).
- The order `EXPIRES`: If your price is not good enough, and the order is out of the market price before
expiration, your order will expire. This doesn't have any cost to the user, which **only pays the fee if the trade is executed**.
- You cancel the order, so it becomes `CANCELLED`. Cancelling an order can be done both as a free meta-transaction
(**soft cancelations**) or as a regular on-chain transaction (**hard cancelations**).
- The API will return an `orderId` which identifies the order, and is created as a summary (hash) of it. In other words, the `orderId` is deterministic given all the order parameters.
Post an order using the SDK:
```js
const orderId = await cowSdk.cowApi.sendOrder({
order: { ...order, ...signedOrder },
owner: '0x1811be0994930fe9480eaede25165608b093ad7a',
const orderBookApi = new OrderBookApi({
chainId: SupportedChainId.GOERLI,
baseUrls: { // <-----
[SupportedChainId.MAINNET]: 'https://YOUR_ENDPOINT/mainnet',
[SupportedChainId.GNOSIS_CHAIN]: 'https://YOUR_ENDPOINT/xdai',
[SupportedChainId.GOERLI]: 'https://YOUR_ENDPOINT/goerli',
}
})
```
### BONUS: Show link to Explorer
Once the order is posted, its good to allow to check the state of it.
The [CoW Protocol API](https://api.cow.fi/docs/#/) has restrictions on the backend side to protect against DDOS and other issues.
One easy is to check in the CoW Explorer. You can create a CoW Explorer link if you have the `orderId`:
>The main restrictions is a limit of requests per second: **5 requests per second for each IP address**
```js
// View order in explorer
console.log(`https://explorer.cow.fi/gc/orders/${orderId}`)
```
This settings can be configured as well:
```typescript
import { OrderBookApi } from '@cowprotocol/cow-sdk'
import { BackoffOptions } from 'exponential-backoff'
import { RateLimiterOpts } from 'limiter'
## Create a meta-data document for attaching to an order
Orders in CoW Protocol can contain arbitrary data in a field called `AppData`.
The SDK facilitates the creation of these documents, and getting the `AppData` Hex number that summarizes it.
The most important thing to define in the meta-data is the name of your app, so the order-flow can be credited to it.
```js
const appDataDoc = cowSdk.metadataApi.generateAppDataDoc({
appDataParams: { appCode: 'YourApp' },
})
```
This will create a document similar to:
```json
{
"version": "0.4.0",
"appCode": "YourApp",
"metadata": {}
const limiterOpts: RateLimiterOpts = {
tokensPerInterval: 5,
interval: 'second',
}
```
After creating the most basic document, you can see how to attach additional meta-data items.
For example, you could give information about who referred the user creating the order.
```js
const appDataDoc = cowSdk.metadataApi.generateAppDataDoc({
appDataParams: { appCode: 'YourApp' },
metadataParas: {
referrerParams: {
address: '0x1f5B740436Fc5935622e92aa3b46818906F416E9',
},
},
})
```
This will create a document similar to:
```json
{
"version": "0.4.0",
"appCode": "YourApp",
"metadata": {
"referrer": {
"address": "0x1f5B740436Fc5935622e92aa3b46818906F416E9",
"version": "0.1.0"
}
}
const backOffOpts: BackoffOptions = {
numOfAttempts: 5,
maxDelay: Infinity,
jitter: 'none',
}
```
The method `cowSdk.metadataApi.generateAppDataDoc` will always create the latest schema version.
For a complete list of metadata that can be attached and for previous versions
check `@cowprotocol/app-data` [repository](https://github.com/cowprotocol/app-data)
and [NPM package](https://www.npmjs.com/package/@cowprotocol/app-data)
## Get the AppData Hex
The `AppData` Hex points to an IPFS document with the meta-data attached to the order.
You can calculate the `AppData` Hex, and its corresponding `cidV0` using the SDK:
```js
const { appDataHash, cidv0 } = await cowSdk.metadataApi.calculateAppDataHash(appDataDoc)
```
Note how this operation is deterministic, so given the same document, it will always generate the same hash.
This method can be used to calculate the actual hash before uploading the document to IPFS.
## Get meta-data document uploaded to IPFS from AppData
Given the `AppData` of a document that has been uploaded to IPFS, you can easily retrieve the document.
```js
const appDataDoc = await cowSdk.metadataApi.decodeAppData(
'0x5ddb2c8207c10b96fac92cb934ef9ba004bc007a073c9e5b13edc422f209ed80'
const orderBookApi = new OrderBookApi(
{chainId: SupportedChainId.GOERLI, limiterOpts, backOffOpts},
)
```
This will return a document similar to:
### Querying the Cow Subgraph
```json
{
"version": "0.1.0",
"appCode": "YourApp",
"metadata": {
"referrer": {
"address": "0x1f5B740436Fc5935622e92aa3b46818906F416E9",
"version": "0.1.0"
}
}
}
```
The [Subgraph](https://github.com/cowprotocol/subgraph) is constantly indexing the protocol, making all the information more accessible. It provides information about trades, users, tokens and settlements. Additionally, it has some data aggregations which provides insights on the hourly/daily/totals USD volumes, trades, users, etc.
## Upload document to IPFS
The SDK provides just an easy way to access all this information.
The SDK uses Pinata to upload it to IPFS, so you will need an API Key in order to upload it using the SDK.
You can query the Cow Subgraph either by running some common queries exposed by the `CowSubgraphApi` or by building your own ones:
Alternatively, you can upload the document on your own using any other service.
```typescript
import { SubgraphApi, SupportedChainId } from '@cowprotocol/cow-sdk'
```js
// Make sure you provide the IPFS params when instantiating the SDK
const cowSdk = new CowSdk(100, {
ipfs: {
pinataApiKey: 'YOUR_PINATA_API_KEY',
pinataApiSecret: 'YOUR_PINATA_API_SECRET',
},
})
const subgraphApi = new SubgraphApi({ chainId: SupportedChainId.MAINNET })
// Upload to IPFS
const uploadedAppDataHash = await cowSdk.metadataApi.uploadMetadataDocToIpfs(appDataDoc)
```
## Convert IPFS CIDv0 to AppData (and back)
Given an IPFS CIDv0 you can convert it to an `AppData`
```js
const decodedAppDataHex = await cowSdk.metadataApi.cidToAppDataHex('QmUf2TrpSANVXdgcYfAAACe6kg551cY3rAemB7xfEMjYvs')
```
This will return an `AppData` hex: `0x5ddb2c8207c10b96fac92cb934ef9ba004bc007a073c9e5b13edc422f209ed80`
> This might be handy if you decide to upload the document to IPFS yourself and then you need the AppData to post your order
Similarly, you can do the opposite and convert an `AppData` into an IPFS document:
```js
const decodedAppDataHex = await cowSdk.metadataApi.appDataHexToCid(hash)
```
This will return an IPFS CIDv0: `QmUf2TrpSANVXdgcYfAAACe6kg551cY3rAemB7xfEMjYvs`
## Getting appData schema files
It's possible to get schema files directly for each exported version using `getAppDataSchema`
```js
const schema = await cowSdk.metadataApi.getAppDataSchema('0.4.0')
```
## Validating appDataDocs
If for some reason you decide to create an `appDataDoc` without using the helper function, you can use `validateAppDataDoc` to validate it against the schema
```js
const { success, error } = await cowSdk.metadataApi.validateAppDataDoc({ version: '0.1.0', ... })
```
## Querying the Cow Subgraph
You can query the Cow Subgraph either by running some common queries exposed by the `CowSubgraphApi` or by building your own ones:
```js
const chainId = 1 // Mainnet
const cowSdk = new CowSdk(chainId)
// Get Cow Protocol totals
// Get CoW Protocol totals
const { tokens, orders, traders, settlements, volumeUsd, volumeEth, feesUsd, feesEth } =
await cowSdk.cowSubgraphApi.getTotals()
await csubgraphApi.getTotals()
console.log({ tokens, orders, traders, settlements, volumeUsd, volumeEth, feesUsd, feesEth })
// Get last 24 hours volume in usd
const { hourlyTotals } = await cowSdk.cowSubgraphApi.getLastHoursVolume(24)
const { hourlyTotals } = await cowSubgraphApi.getLastHoursVolume(24)
console.log(hourlyTotals)
// Get last week volume in usd
const { dailyTotals } = await cowSdk.cowSubgraphApi.getLastDaysVolume(7)
const { dailyTotals } = await cowSubgraphApi.getLastDaysVolume(7)
console.log(dailyTotals)

@@ -390,6 +202,15 @@

const variables = { n: 5 }
const response = await cowSdk.cowSubgraphApi.runQuery(query, variables)
const response = await cowSubgraphApi.runQuery(query, variables)
console.log(response)
```
## Architecture
One way to make the most out of the SDK is to get familiar to its architecture.
> See [SDK Architecture](./docs/architecture.md)
## Development
### Install Dependencies

@@ -415,1 +236,10 @@

```
### Code generation
Some parets of the SDK are automatically generated. This is the case for the Order Book APU and the Subgraph API
```bash
# Re-create automatically generated code
yarn codegen
```
import { LastDaysVolumeQuery, LastHoursVolumeQuery, TotalsQuery } from './graphql';
import { DocumentNode } from 'graphql/index';
import { Variables } from 'graphql-request';
import { ApiContext, EnvConfigs, PartialApiContext } from '../common/configs';
export declare const SUBGRAPH_PROD_CONFIG: EnvConfigs;
export declare const SUBGRAPH_STAGING_CONFIG: EnvConfigs;
import { ApiContext, ApiBaseUrls, PartialApiContext } from '../common/configs';
export declare const SUBGRAPH_PROD_CONFIG: ApiBaseUrls;
export declare const SUBGRAPH_STAGING_CONFIG: ApiBaseUrls;
export declare class SubgraphApi {
API_NAME: string;
context: ApiContext;
customEnvConfigs?: EnvConfigs;
constructor(context?: PartialApiContext, customEnvConfigs?: EnvConfigs);
constructor(context?: PartialApiContext);
getTotals(contextOverride?: PartialApiContext): Promise<TotalsQuery['totals'][0]>;

@@ -13,0 +12,0 @@ getLastDaysVolume(days: number, contextOverride?: PartialApiContext): Promise<LastDaysVolumeQuery>;

{
"name": "@cowprotocol/cow-sdk",
"version": "2.0.0-alpha.4",
"version": "2.1.0",
"license": "(MIT OR Apache-2.0)",

@@ -29,8 +29,15 @@ "files": [

"graphql:codegen": "graphql-codegen --config graphql-codegen.yml",
"swagger:codegen": " openapi --input https://raw.githubusercontent.com/cowprotocol/services/fix/orderbook-openapi/crates/orderbook/openapi.yml --output src/order-book/generated --client fetch --name OrderBookClient"
"swagger:codegen": " openapi --input https://raw.githubusercontent.com/cowprotocol/services/main/crates/orderbook/openapi.yml --output src/order-book/generated --exportServices false --exportCore false"
},
"dependencies": {
"graphql": "^16.3.0",
"@cowprotocol/contracts": "^1.4.0",
"@ethersproject/abstract-signer": "^5.7.0",
"exponential-backoff": "^3.1.1",
"limiter": "^2.1.0",
"cross-fetch": "^3.1.5",
"graphql-request": "^4.3.0"
},
"peerDependencies": {
"ethers": "^5.7.2"
},
"devDependencies": {

@@ -53,2 +60,4 @@ "@babel/plugin-proposal-nullish-coalescing-operator": "^7.18.6",

"eslint-plugin-prettier": "^4.2.1",
"ethers": "^5.7.2",
"graphql": "^16.3.0",
"jest": "^29.4.2",

@@ -59,2 +68,3 @@ "jest-fetch-mock": "^3.0.3",

"prettier": "^2.5.1",
"ts-mockito": "^2.6.1",
"tsc-watch": "^6.0.0",

@@ -61,0 +71,0 @@ "typescript": "^4.9.5"

@@ -7,9 +7,16 @@ <p align="center">

[![Styled With Prettier](https://img.shields.io/badge/code_style-prettier-ff69b4.svg)](https://prettier.io/)
[![Coverage Status](https://coveralls.io/repos/github/cowprotocol/cow-sdk/badge.svg?branch=main)](https://coveralls.io/github/cowprotocol/cow-sdk?branch=main)
## 📚 [SDK docs website](https://docs.cow.fi/cow-sdk)
## Test coverage
| Statements | Branches | Functions | Lines |
| ------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------ | ---------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------- |
| ![Statements](https://img.shields.io/badge/statements-94.77%25-brightgreen.svg?style=flat) | ![Branches](https://img.shields.io/badge/branches-76.78%25-red.svg?style=flat) | ![Functions](https://img.shields.io/badge/functions-97.43%25-brightgreen.svg?style=flat) | ![Lines](https://img.shields.io/badge/lines-97.67%25-brightgreen.svg?style=flat) |
## Getting started
Install the SDK:
**Usage examples: [VanillaJS](./examples/vanilla/src/index.ts), [Create React App](./examples/cra/src/pages/getOrders/index.tsx), [NodeJS](./examples/nodejs/src/index.ts)**
### Installation
```bash

@@ -19,360 +26,165 @@ yarn add @cowprotocol/cow-sdk

Instantiate the SDK:
### Content
```js
import { CowSdk } from '@cowprotocol/cow-sdk'
- `OrderBookApi` - provides the ability to retrieve orders and trades from the CowSap order-book, as well as add and cancel them
- `OrderSigningUtils` - serves to sign orders and cancel them using [EIP-712](https://eips.ethereum.org/EIPS/eip-712)
- `SubgraphApi` - provides statistics data about CoW protocol from [Subgraph](https://github.com/cowprotocol/subgraph), such as trading volume, trades count and others
const chainId = 100 // Gnosis chain
const cowSdk = new CowSdk(chainId)
```
The SDK will expose:
```typescript
import { OrderBookApi, OrderSigningUtils, SubgraphApi } from '@cowprotocol/cow-sdk'
- The CoW API (`cowSdk.cowApi`)
- The CoW Subgraph (`cowSdk.cowSubgraphApi`)
- Convenient method to facilitate signing orders (i.e `cowSdk.signOrder`)
const chainId = 100 // Gnosis chain
> For a quick snippet with the full process on posting an order see the [Post an Order Example](./docs/post-order-example.ts)
## CoW API
The SDK provides access to the CoW API. The CoW API allows you:
- Post orders
- Get fee quotes
- Get order details
- Get history of orders: i.e. filtering by account, transaction hash, etc.
For example, you can easily get the last 5 order of a trader:
```js
// i.e. Get last 5 orders for a given trader
const trades = await cowSdk.cowApi.getOrders({
owner: '0x00000000005ef87f8ca7014309ece7260bbcdaeb', // Trader
limit: 5,
offset: 0,
})
console.log(trades)
const orderBookApi = new OrderBookApi({ chainId })
const subgraphApi = new SubgraphApi({ chainId })
const orderSigningUtils = new OrderSigningUtils()
```
> For more information about the API methods, you can check [api.cow.fi/docs](https://api.cow.fi/docs).
## Quick start
## Sign and Post orders
### Sign, fetch, post and cancel order
In order to trade, you will need to create a valid order first.
For clarity, let's look at the use of the API with a practical example:
Exchanging `0.4 GNO` to `WETH` on `Goerli` network.
On the contraty to other decentralised exchanges, creating orders is free in CoW Protocol. This is because, one of the
most common ways to do it is by created offchain signed messages (meta-transactions, uses `EIP-712` or `EIP-1271`).
We will do the following operations:
1. Get a quote
2. Sign the order
3. Send the order to the order-book
4. Get the data of the created order
5. Get trades of the order
6. Cancel the order (signing + sending)
Posting orders is a three steps process:
[You also can check this code in the CRA example](./examples/cra/src/pages/quickStart/index.tsx)
- 1. **Get Market Pricea**: Fee & Price
- 2. **Sign the order**: Using off-chain signing or Meta-transactions
- 3. **Post the signed order to the API**: So, the order becomes `OPEN`
The next sections will guide you through the process of creating a valid order.
```typescript
import { OrderBookApi, OrderSigningUtils, SupportedChainId } from '@cowprotocol/cow-sdk'
import { Web3Provider } from '@ethersproject/providers'
> For a quick snippet with the full process on posting an order see the [Post an Order Example](./docs/post-order-example.ts).
const account = 'YOUR_WALLET_ADDRESS'
const chainId = 5 // Goerli
const provider = new Web3Provider(window.ethereum)
const signer = provider.getSigner()
### Enable tokens (token approval)
Because of the use of off-chain signing (meta-transactions), users will need to **Enable the sell token** before signed
orders can be considered as valid ones.
const quoteRequest = {
sellToken: '0xb4fbf271143f4fbf7b91a5ded31805e42b2208d6', // WETH goerli
buyToken: '0x02abbdbaaa7b1bb64b5c878f7ac17f8dda169532', // GNO goerli
from: account,
receiver: account,
sellAmountBeforeFee: (0.4 * 10 ** 18).toString(), // 0.4 WETH
kind: OrderQuoteSide.kind.SELL,
}
This enabling is technically an `ERC-20` approval, and is something that needs to be done only once. After this all
order creation can be done for free using offchain signing.
const orderBookApi = new OrderBookApi({ chainId: SupportedChainId.GOERLI })
> For more details see https://docs.cow.fi/tutorials/how-to-submit-orders-via-the-api/1.-set-allowance-for-the-sell-token
async function main() {
const { quote } = await orderBookApi.getQuote(quoteRequest)
### Instantiate SDK with a signer
const orderSigningResult = await OrderSigningUtils.signOrder(quote, chainId, signer)
Before you can sign any transaction, you have to instantiate the SDK with a [Ethers.JS signer](https://docs.ethers.io/v5/api/signer/):
const orderId = await orderBookApi.sendOrder({ ...quote, ...orderSigningResult })
```js
import { Wallet } from 'ethers'
import { CowSdk, OrderKind } from '@cowprotocol/cow-sdk'
const order = await orderBookApi.getOrder(orderId)
const mnemonic = 'fall dirt bread cactus...'
const wallet = Wallet.fromMnemonic(mnemonic)
const trades = await orderBookApi.getTrades({ orderId })
const cowSdk = new CowSdk(
100, { // Leaving chainId empty will default to MAINNET
signer: wallet // Provide a signer, so you can sign order
})
```
const orderCancellationSigningResult = await OrderSigningUtils.signOrderCancellations([orderId], chainId, signer)
### STEP 1: Get Market Price
const cancellationResult = await orderBookApi.sendSignedOrderCancellations({...orderCancellationSigningResult, orderUids: [orderId] })
To create an order, you need to get a price/fee quote first:
* The SDK will give you easy access to the API, which returns the `Market Price` and the `Fee` for any given trade you intent to do.
* The returned `Market Price` is not strictly needed, you can use your own pricing logic.
* You can choose a price that is below this Market price (**Market Order**), or above Market Price (**Limit Order**).
* The `Fee` however is very important.
* It is the required amount in sell token the trader agrees on paying for executing the order onchain.
* Normally, its value is proportional to the current Gas Price of the network.
* This fee is never charged if you don't trade.
To get the quote, you simply specify the trade you intent to do:
```js
const quoteResponse = await cowSdk.cowApi.getQuote({
kind: OrderKind.SELL, // Sell order (could also be BUY)
sellToken: '0xc778417e063141139fce010982780140aa0cd5ab', // WETH
buyToken: '0x4dbcdf9b62e891a7cec5a2568c3f4faf9e8abe2b', // USDC
amount: '1000000000000000000', // 1 WETH
userAddress: '0x1811be0994930fe9480eaede25165608b093ad7a', // Trader
validTo: 2524608000,
})
const { sellToken, buyToken, validTo, buyAmount, sellAmount, receiver, feeAmount } = quoteResponse.quote
console.log('Results: ', { orderId, order, trades, orderCancellationSigningResult, cancellationResult })
}
```
### STEP 2: Sign the order
### OrderBookApi
Once you know the price and fee, we can create the order and sign it:
`OrderBookApi` - is a main tool for working with [CoW Protocol API](https://api.cow.fi/docs/#/).
Since the API supports different networks and environments, there are some options to configure it.
- Technically the order is just a signed message with your intent to trade, and contains your `Limit Price` and `Fee`.
- As explained before, you can choose your `Limit Price`, but some general approach is to take the current Market Price
and apply some slippage tolerance to it. `Received Amount = Expected Amount * (1 - Slippage Tolerance)`
- The SDK will provide an easy way to sign orders given the raw data
#### Environment configuration
```js
const { sellToken, buyToken, validTo, buyAmount, sellAmount, receiver, feeAmount } = quoteResponse.quote
`chainId` - can be `SupportedChainId.MAINNET` or `SupportedChainId.GNOSIS_CHAIN` or `SupportedChainId.GOERLI`
// Prepare the RAW order
const order = {
kind: OrderKind.SELL, // SELL || BUY
receiver, // Your account or any other
sellToken,
buyToken,
`env` - this parameter affects which environment will be used:
- `https://api.cow.fi` for `prod` (default)
- `https://barn.api.cow.fi` for `staging`
partiallyFillable: false, // ("false" is for a "Fill or Kill" order, "true" for allowing "Partial execution" which is not supported yet)
```typescript
import { OrderBookApi } from '@cowprotocol/cow-sdk'
// Deadline
validTo,
// Limit Price
// You can apply some slippage tolerance here to make sure the trade is executed.
// CoW protocol protects from MEV, so it can work with higher slippages
sellAmount,
buyAmount,
// Use the fee you received from the API
feeAmount,
// The appData allows you to attach arbitrary information (meta-data) to the order. Its explained in their own section. For now, you can use this 0x0 value
appData: '0x0000000000000000000000000000000000000000000000000000000000000000',
}
// Sign the order
const signedOrder = await cowSdk.signOrder(order)
const orderBookApi = new OrderBookApi({
chainId: SupportedChainId.GOERLI,
env: 'staging' // <-----
})
```
At this point, you have a signed order. So next step will be to post it to the API so it's considered by the solvers and executed.
#### API urls configuration
## STEP 3: **Post the signed order to the API**:
In case you need to use custom endpoints (e.g. you use a proxy), you can do it this way:
Once you have a signed order, last step is to send it to the API.
```typescript
import { OrderBookApi } from '@cowprotocol/cow-sdk'
- The API will accept the order if its correctly signed, the deadline is correct, and the fee is enough to settle it
- Once accepted, the order will be `OPEN` until the specified `validTo` date (expiration)
- The possible outcomes once accepted is:
- The order is `EXECUTED`: you will pay the signed fee, and get at least the `buyAmount` tokens you specified, although you will probably get more! (you will probably get a so-called **Surplus**).
- The order `EXPIRES`: If your price is not good enough, and the order is out of the market price before
expiration, your order will expire. This doesn't have any cost to the user, which **only pays the fee if the trade is executed**.
- You cancel the order, so it becomes `CANCELLED`. Cancelling an order can be done both as a free meta-transaction
(**soft cancelations**) or as a regular on-chain transaction (**hard cancelations**).
- The API will return an `orderId` which identifies the order, and is created as a summary (hash) of it. In other words, the `orderId` is deterministic given all the order parameters.
Post an order using the SDK:
```js
const orderId = await cowSdk.cowApi.sendOrder({
order: { ...order, ...signedOrder },
owner: '0x1811be0994930fe9480eaede25165608b093ad7a',
const orderBookApi = new OrderBookApi({
chainId: SupportedChainId.GOERLI,
baseUrls: { // <-----
[SupportedChainId.MAINNET]: 'https://YOUR_ENDPOINT/mainnet',
[SupportedChainId.GNOSIS_CHAIN]: 'https://YOUR_ENDPOINT/xdai',
[SupportedChainId.GOERLI]: 'https://YOUR_ENDPOINT/goerli',
}
})
```
### BONUS: Show link to Explorer
Once the order is posted, its good to allow to check the state of it.
The [CoW Protocol API](https://api.cow.fi/docs/#/) has restrictions on the backend side to protect against DDOS and other issues.
One easy is to check in the CoW Explorer. You can create a CoW Explorer link if you have the `orderId`:
>The main restrictions is a limit of requests per second: **5 requests per second for each IP address**
```js
// View order in explorer
console.log(`https://explorer.cow.fi/gc/orders/${orderId}`)
```
This settings can be configured as well:
```typescript
import { OrderBookApi } from '@cowprotocol/cow-sdk'
import { BackoffOptions } from 'exponential-backoff'
import { RateLimiterOpts } from 'limiter'
## Create a meta-data document for attaching to an order
Orders in CoW Protocol can contain arbitrary data in a field called `AppData`.
The SDK facilitates the creation of these documents, and getting the `AppData` Hex number that summarizes it.
The most important thing to define in the meta-data is the name of your app, so the order-flow can be credited to it.
```js
const appDataDoc = cowSdk.metadataApi.generateAppDataDoc({
appDataParams: { appCode: 'YourApp' },
})
```
This will create a document similar to:
```json
{
"version": "0.4.0",
"appCode": "YourApp",
"metadata": {}
const limiterOpts: RateLimiterOpts = {
tokensPerInterval: 5,
interval: 'second',
}
```
After creating the most basic document, you can see how to attach additional meta-data items.
For example, you could give information about who referred the user creating the order.
```js
const appDataDoc = cowSdk.metadataApi.generateAppDataDoc({
appDataParams: { appCode: 'YourApp' },
metadataParas: {
referrerParams: {
address: '0x1f5B740436Fc5935622e92aa3b46818906F416E9',
},
},
})
```
This will create a document similar to:
```json
{
"version": "0.4.0",
"appCode": "YourApp",
"metadata": {
"referrer": {
"address": "0x1f5B740436Fc5935622e92aa3b46818906F416E9",
"version": "0.1.0"
}
}
const backOffOpts: BackoffOptions = {
numOfAttempts: 5,
maxDelay: Infinity,
jitter: 'none',
}
```
The method `cowSdk.metadataApi.generateAppDataDoc` will always create the latest schema version.
For a complete list of metadata that can be attached and for previous versions
check `@cowprotocol/app-data` [repository](https://github.com/cowprotocol/app-data)
and [NPM package](https://www.npmjs.com/package/@cowprotocol/app-data)
## Get the AppData Hex
The `AppData` Hex points to an IPFS document with the meta-data attached to the order.
You can calculate the `AppData` Hex, and its corresponding `cidV0` using the SDK:
```js
const { appDataHash, cidv0 } = await cowSdk.metadataApi.calculateAppDataHash(appDataDoc)
```
Note how this operation is deterministic, so given the same document, it will always generate the same hash.
This method can be used to calculate the actual hash before uploading the document to IPFS.
## Get meta-data document uploaded to IPFS from AppData
Given the `AppData` of a document that has been uploaded to IPFS, you can easily retrieve the document.
```js
const appDataDoc = await cowSdk.metadataApi.decodeAppData(
'0x5ddb2c8207c10b96fac92cb934ef9ba004bc007a073c9e5b13edc422f209ed80'
const orderBookApi = new OrderBookApi(
{chainId: SupportedChainId.GOERLI, limiterOpts, backOffOpts},
)
```
This will return a document similar to:
### Querying the Cow Subgraph
```json
{
"version": "0.1.0",
"appCode": "YourApp",
"metadata": {
"referrer": {
"address": "0x1f5B740436Fc5935622e92aa3b46818906F416E9",
"version": "0.1.0"
}
}
}
```
The [Subgraph](https://github.com/cowprotocol/subgraph) is constantly indexing the protocol, making all the information more accessible. It provides information about trades, users, tokens and settlements. Additionally, it has some data aggregations which provides insights on the hourly/daily/totals USD volumes, trades, users, etc.
## Upload document to IPFS
The SDK provides just an easy way to access all this information.
The SDK uses Pinata to upload it to IPFS, so you will need an API Key in order to upload it using the SDK.
You can query the Cow Subgraph either by running some common queries exposed by the `CowSubgraphApi` or by building your own ones:
Alternatively, you can upload the document on your own using any other service.
```typescript
import { SubgraphApi, SupportedChainId } from '@cowprotocol/cow-sdk'
```js
// Make sure you provide the IPFS params when instantiating the SDK
const cowSdk = new CowSdk(100, {
ipfs: {
pinataApiKey: 'YOUR_PINATA_API_KEY',
pinataApiSecret: 'YOUR_PINATA_API_SECRET',
},
})
const subgraphApi = new SubgraphApi({ chainId: SupportedChainId.MAINNET })
// Upload to IPFS
const uploadedAppDataHash = await cowSdk.metadataApi.uploadMetadataDocToIpfs(appDataDoc)
```
## Convert IPFS CIDv0 to AppData (and back)
Given an IPFS CIDv0 you can convert it to an `AppData`
```js
const decodedAppDataHex = await cowSdk.metadataApi.cidToAppDataHex('QmUf2TrpSANVXdgcYfAAACe6kg551cY3rAemB7xfEMjYvs')
```
This will return an `AppData` hex: `0x5ddb2c8207c10b96fac92cb934ef9ba004bc007a073c9e5b13edc422f209ed80`
> This might be handy if you decide to upload the document to IPFS yourself and then you need the AppData to post your order
Similarly, you can do the opposite and convert an `AppData` into an IPFS document:
```js
const decodedAppDataHex = await cowSdk.metadataApi.appDataHexToCid(hash)
```
This will return an IPFS CIDv0: `QmUf2TrpSANVXdgcYfAAACe6kg551cY3rAemB7xfEMjYvs`
## Getting appData schema files
It's possible to get schema files directly for each exported version using `getAppDataSchema`
```js
const schema = await cowSdk.metadataApi.getAppDataSchema('0.4.0')
```
## Validating appDataDocs
If for some reason you decide to create an `appDataDoc` without using the helper function, you can use `validateAppDataDoc` to validate it against the schema
```js
const { success, error } = await cowSdk.metadataApi.validateAppDataDoc({ version: '0.1.0', ... })
```
## Querying the Cow Subgraph
You can query the Cow Subgraph either by running some common queries exposed by the `CowSubgraphApi` or by building your own ones:
```js
const chainId = 1 // Mainnet
const cowSdk = new CowSdk(chainId)
// Get Cow Protocol totals
// Get CoW Protocol totals
const { tokens, orders, traders, settlements, volumeUsd, volumeEth, feesUsd, feesEth } =
await cowSdk.cowSubgraphApi.getTotals()
await csubgraphApi.getTotals()
console.log({ tokens, orders, traders, settlements, volumeUsd, volumeEth, feesUsd, feesEth })
// Get last 24 hours volume in usd
const { hourlyTotals } = await cowSdk.cowSubgraphApi.getLastHoursVolume(24)
const { hourlyTotals } = await cowSubgraphApi.getLastHoursVolume(24)
console.log(hourlyTotals)
// Get last week volume in usd
const { dailyTotals } = await cowSdk.cowSubgraphApi.getLastDaysVolume(7)
const { dailyTotals } = await cowSubgraphApi.getLastDaysVolume(7)
console.log(dailyTotals)

@@ -390,6 +202,15 @@

const variables = { n: 5 }
const response = await cowSdk.cowSubgraphApi.runQuery(query, variables)
const response = await cowSubgraphApi.runQuery(query, variables)
console.log(response)
```
## Architecture
One way to make the most out of the SDK is to get familiar to its architecture.
> See [SDK Architecture](./docs/architecture.md)
## Development
### Install Dependencies

@@ -415,1 +236,10 @@

```
### Code generation
Some parets of the SDK are automatically generated. This is the case for the Order Book APU and the Subgraph API
```bash
# Re-create automatically generated code
yarn codegen
```

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

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

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc