@cowprotocol/cow-sdk 4.1.0 → 5.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +11 -11
- package/dist/README.md +11 -11
- package/dist/common/chains.d.ts +0 -1
- package/dist/common/configs.d.ts +2 -2
- package/dist/composable/types.d.ts +1 -5
- package/dist/index-35b5803e.js +29 -0
- package/dist/index-35b5803e.js.map +1 -0
- package/dist/index.js +4 -4
- package/dist/index.js.map +1 -1
- package/dist/index.modern.mjs +1 -1
- package/dist/index.module.js +2 -2
- package/dist/index.module.js.map +1 -1
- package/dist/order-book/api.d.ts +4 -4
- package/dist/order-signing/orderSigningUtils.d.ts +1 -1
- package/dist/package.json +1 -1
- package/dist/subgraph/api.d.ts +0 -1
- package/dist/{utils-e0d336bc.js → utils-33f6a4bd.js} +2 -2
- package/dist/{utils-e0d336bc.js.map → utils-33f6a4bd.js.map} +1 -1
- package/dist/{utils-7365d86f.js → utils-88601eb2.js} +1 -1
- package/dist/{utils-7365d86f.js.map → utils-88601eb2.js.map} +1 -1
- package/dist/{utils-7c531a39.js → utils-89a3986d.js} +1 -1
- package/dist/{utils-7c531a39.js.map → utils-89a3986d.js.map} +1 -1
- package/package.json +1 -1
- package/dist/index-f02c2df3.js +0 -29
- package/dist/index-f02c2df3.js.map +0 -1
package/README.md
CHANGED
|
@@ -44,7 +44,7 @@ const orderSigningUtils = new OrderSigningUtils()
|
|
|
44
44
|
### Sign, fetch, post and cancel order
|
|
45
45
|
|
|
46
46
|
For clarity, let's look at the use of the API with a practical example:
|
|
47
|
-
Exchanging `0.4 GNO` to `WETH` on `
|
|
47
|
+
Exchanging `0.4 GNO` to `WETH` on `Gnosis chain` network.
|
|
48
48
|
|
|
49
49
|
We will do the following operations:
|
|
50
50
|
1. Get a quote
|
|
@@ -62,20 +62,20 @@ import { OrderBookApi, OrderSigningUtils, SupportedChainId } from '@cowprotocol/
|
|
|
62
62
|
import { Web3Provider } from '@ethersproject/providers'
|
|
63
63
|
|
|
64
64
|
const account = 'YOUR_WALLET_ADDRESS'
|
|
65
|
-
const chainId =
|
|
65
|
+
const chainId = 100 // Gnosis chain
|
|
66
66
|
const provider = new Web3Provider(window.ethereum)
|
|
67
67
|
const signer = provider.getSigner()
|
|
68
68
|
|
|
69
69
|
const quoteRequest = {
|
|
70
|
-
sellToken: '
|
|
71
|
-
buyToken: '
|
|
70
|
+
sellToken: '0x6a023ccd1ff6f2045c3309768ead9e68f978f6e1', // WETH gnosis chain
|
|
71
|
+
buyToken: '0x9c58bacc331c9aa871afd802db6379a98e80cedb', // GNO gnosis chain
|
|
72
72
|
from: account,
|
|
73
73
|
receiver: account,
|
|
74
74
|
sellAmountBeforeFee: (0.4 * 10 ** 18).toString(), // 0.4 WETH
|
|
75
75
|
kind: OrderQuoteSide.kind.SELL,
|
|
76
76
|
}
|
|
77
77
|
|
|
78
|
-
const orderBookApi = new OrderBookApi({ chainId: SupportedChainId.
|
|
78
|
+
const orderBookApi = new OrderBookApi({ chainId: SupportedChainId.GNOSIS_CHAIN })
|
|
79
79
|
|
|
80
80
|
async function main() {
|
|
81
81
|
const { quote } = await orderBookApi.getQuote(quoteRequest)
|
|
@@ -103,7 +103,7 @@ Since the API supports different networks and environments, there are some optio
|
|
|
103
103
|
|
|
104
104
|
#### Environment configuration
|
|
105
105
|
|
|
106
|
-
`chainId` - can be one of `SupportedChainId.MAINNET`, `SupportedChainId.GNOSIS_CHAIN`, or `SupportedChainId.
|
|
106
|
+
`chainId` - can be one of `SupportedChainId.MAINNET`, `SupportedChainId.GNOSIS_CHAIN`, or `SupportedChainId.SEPOLIA`
|
|
107
107
|
|
|
108
108
|
`env` - this parameter affects which environment will be used:
|
|
109
109
|
- `https://api.cow.fi` for `prod` (default)
|
|
@@ -113,7 +113,7 @@ Since the API supports different networks and environments, there are some optio
|
|
|
113
113
|
import { OrderBookApi } from '@cowprotocol/cow-sdk'
|
|
114
114
|
|
|
115
115
|
const orderBookApi = new OrderBookApi({
|
|
116
|
-
chainId: SupportedChainId.
|
|
116
|
+
chainId: SupportedChainId.GNOSIS_CHAIN,
|
|
117
117
|
env: 'staging' // <-----
|
|
118
118
|
})
|
|
119
119
|
```
|
|
@@ -126,11 +126,11 @@ In case you need to use custom endpoints (e.g. you use a proxy), you can do it t
|
|
|
126
126
|
import { OrderBookApi } from '@cowprotocol/cow-sdk'
|
|
127
127
|
|
|
128
128
|
const orderBookApi = new OrderBookApi({
|
|
129
|
-
chainId: SupportedChainId.
|
|
129
|
+
chainId: SupportedChainId.GNOSIS_CHAIN,
|
|
130
130
|
baseUrls: { // <-----
|
|
131
131
|
[SupportedChainId.MAINNET]: 'https://YOUR_ENDPOINT/mainnet',
|
|
132
|
-
[SupportedChainId.GNOSIS_CHAIN]: 'https://YOUR_ENDPOINT/
|
|
133
|
-
[SupportedChainId.
|
|
132
|
+
[SupportedChainId.GNOSIS_CHAIN]: 'https://YOUR_ENDPOINT/gnosis-chain',
|
|
133
|
+
[SupportedChainId.SEPOLIA]: 'https://YOUR_ENDPOINT/sepolia',
|
|
134
134
|
}
|
|
135
135
|
})
|
|
136
136
|
```
|
|
@@ -157,7 +157,7 @@ const backOffOpts: BackoffOptions = {
|
|
|
157
157
|
}
|
|
158
158
|
|
|
159
159
|
const orderBookApi = new OrderBookApi(
|
|
160
|
-
{chainId: SupportedChainId.
|
|
160
|
+
{chainId: SupportedChainId.GNOSIS_CHAIN, limiterOpts, backOffOpts},
|
|
161
161
|
)
|
|
162
162
|
```
|
|
163
163
|
|
package/dist/README.md
CHANGED
|
@@ -44,7 +44,7 @@ const orderSigningUtils = new OrderSigningUtils()
|
|
|
44
44
|
### Sign, fetch, post and cancel order
|
|
45
45
|
|
|
46
46
|
For clarity, let's look at the use of the API with a practical example:
|
|
47
|
-
Exchanging `0.4 GNO` to `WETH` on `
|
|
47
|
+
Exchanging `0.4 GNO` to `WETH` on `Gnosis chain` network.
|
|
48
48
|
|
|
49
49
|
We will do the following operations:
|
|
50
50
|
1. Get a quote
|
|
@@ -62,20 +62,20 @@ import { OrderBookApi, OrderSigningUtils, SupportedChainId } from '@cowprotocol/
|
|
|
62
62
|
import { Web3Provider } from '@ethersproject/providers'
|
|
63
63
|
|
|
64
64
|
const account = 'YOUR_WALLET_ADDRESS'
|
|
65
|
-
const chainId =
|
|
65
|
+
const chainId = 100 // Gnosis chain
|
|
66
66
|
const provider = new Web3Provider(window.ethereum)
|
|
67
67
|
const signer = provider.getSigner()
|
|
68
68
|
|
|
69
69
|
const quoteRequest = {
|
|
70
|
-
sellToken: '
|
|
71
|
-
buyToken: '
|
|
70
|
+
sellToken: '0x6a023ccd1ff6f2045c3309768ead9e68f978f6e1', // WETH gnosis chain
|
|
71
|
+
buyToken: '0x9c58bacc331c9aa871afd802db6379a98e80cedb', // GNO gnosis chain
|
|
72
72
|
from: account,
|
|
73
73
|
receiver: account,
|
|
74
74
|
sellAmountBeforeFee: (0.4 * 10 ** 18).toString(), // 0.4 WETH
|
|
75
75
|
kind: OrderQuoteSide.kind.SELL,
|
|
76
76
|
}
|
|
77
77
|
|
|
78
|
-
const orderBookApi = new OrderBookApi({ chainId: SupportedChainId.
|
|
78
|
+
const orderBookApi = new OrderBookApi({ chainId: SupportedChainId.GNOSIS_CHAIN })
|
|
79
79
|
|
|
80
80
|
async function main() {
|
|
81
81
|
const { quote } = await orderBookApi.getQuote(quoteRequest)
|
|
@@ -103,7 +103,7 @@ Since the API supports different networks and environments, there are some optio
|
|
|
103
103
|
|
|
104
104
|
#### Environment configuration
|
|
105
105
|
|
|
106
|
-
`chainId` - can be one of `SupportedChainId.MAINNET`, `SupportedChainId.GNOSIS_CHAIN`, or `SupportedChainId.
|
|
106
|
+
`chainId` - can be one of `SupportedChainId.MAINNET`, `SupportedChainId.GNOSIS_CHAIN`, or `SupportedChainId.SEPOLIA`
|
|
107
107
|
|
|
108
108
|
`env` - this parameter affects which environment will be used:
|
|
109
109
|
- `https://api.cow.fi` for `prod` (default)
|
|
@@ -113,7 +113,7 @@ Since the API supports different networks and environments, there are some optio
|
|
|
113
113
|
import { OrderBookApi } from '@cowprotocol/cow-sdk'
|
|
114
114
|
|
|
115
115
|
const orderBookApi = new OrderBookApi({
|
|
116
|
-
chainId: SupportedChainId.
|
|
116
|
+
chainId: SupportedChainId.GNOSIS_CHAIN,
|
|
117
117
|
env: 'staging' // <-----
|
|
118
118
|
})
|
|
119
119
|
```
|
|
@@ -126,11 +126,11 @@ In case you need to use custom endpoints (e.g. you use a proxy), you can do it t
|
|
|
126
126
|
import { OrderBookApi } from '@cowprotocol/cow-sdk'
|
|
127
127
|
|
|
128
128
|
const orderBookApi = new OrderBookApi({
|
|
129
|
-
chainId: SupportedChainId.
|
|
129
|
+
chainId: SupportedChainId.GNOSIS_CHAIN,
|
|
130
130
|
baseUrls: { // <-----
|
|
131
131
|
[SupportedChainId.MAINNET]: 'https://YOUR_ENDPOINT/mainnet',
|
|
132
|
-
[SupportedChainId.GNOSIS_CHAIN]: 'https://YOUR_ENDPOINT/
|
|
133
|
-
[SupportedChainId.
|
|
132
|
+
[SupportedChainId.GNOSIS_CHAIN]: 'https://YOUR_ENDPOINT/gnosis-chain',
|
|
133
|
+
[SupportedChainId.SEPOLIA]: 'https://YOUR_ENDPOINT/sepolia',
|
|
134
134
|
}
|
|
135
135
|
})
|
|
136
136
|
```
|
|
@@ -157,7 +157,7 @@ const backOffOpts: BackoffOptions = {
|
|
|
157
157
|
}
|
|
158
158
|
|
|
159
159
|
const orderBookApi = new OrderBookApi(
|
|
160
|
-
{chainId: SupportedChainId.
|
|
160
|
+
{chainId: SupportedChainId.GNOSIS_CHAIN, limiterOpts, backOffOpts},
|
|
161
161
|
)
|
|
162
162
|
```
|
|
163
163
|
|
package/dist/common/chains.d.ts
CHANGED
package/dist/common/configs.d.ts
CHANGED
|
@@ -36,8 +36,8 @@ export type CowEnv = 'prod' | 'staging';
|
|
|
36
36
|
export type PartialApiContext = Partial<ApiContext>;
|
|
37
37
|
/**
|
|
38
38
|
* @property {string} [1] The base URL for the mainnet API.
|
|
39
|
-
* @property {string} [5] The base URL for the Goerli testnet API.
|
|
40
39
|
* @property {string} [100] The base URL for the Gnosis Chain API.
|
|
40
|
+
* @property {string} [11155111] The base URL for the Sepolia testnet API.
|
|
41
41
|
*/
|
|
42
42
|
export type ApiBaseUrls = Record<SupportedChainId, string>;
|
|
43
43
|
/**
|
|
@@ -46,8 +46,8 @@ export type ApiBaseUrls = Record<SupportedChainId, string>;
|
|
|
46
46
|
* CoW Protocol is a set of smart contracts and off-chain services, deployed on **multiple chains**.
|
|
47
47
|
* {@link SupportedChainId Supported chains} are:
|
|
48
48
|
* - Mainnet
|
|
49
|
-
* - Goerli
|
|
50
49
|
* - Gnosis Chain
|
|
50
|
+
* - Sepolia
|
|
51
51
|
*
|
|
52
52
|
* Each chain has it's own API, and each API has it's own base URL.
|
|
53
53
|
*
|
|
@@ -67,18 +67,14 @@ export type OwnerContext = {
|
|
|
67
67
|
provider: providers.Provider;
|
|
68
68
|
};
|
|
69
69
|
export type PollParams = OwnerContext & {
|
|
70
|
+
orderBookApi: OrderBookApi;
|
|
70
71
|
offchainInput?: string;
|
|
71
72
|
proof?: string[];
|
|
72
73
|
/**
|
|
73
74
|
* If present, it can be used for custom conditional order validations. If not present, the orders will need to get the block info themselves
|
|
74
75
|
*/
|
|
75
76
|
blockInfo?: BlockInfo;
|
|
76
|
-
/**
|
|
77
|
-
* Allows to optional pass the config of the orderbook API
|
|
78
|
-
*/
|
|
79
|
-
orderbookApiConfig?: OrderBookApiConfig;
|
|
80
77
|
};
|
|
81
|
-
export type OrderBookApiConfig = Omit<ConstructorParameters<typeof OrderBookApi>[0], 'chainId'>;
|
|
82
78
|
export type BlockInfo = {
|
|
83
79
|
blockNumber: number;
|
|
84
80
|
blockTimestamp: number;
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import"cross-fetch/polyfill";import{RateLimiter as e}from"limiter";import{backOff as t}from"exponential-backoff";import{gql as n,request as r}from"graphql-request";import{utils as a,Contract as s,ethers as i,constants as o,BigNumber as p}from"ethers";import{OrderBalance as d,OrderKind as u}from"@cowprotocol/contracts";import{StandardMerkleTree as l}from"@openzeppelin/merkle-tree";var y;!function(e){e[e.MAINNET=1]="MAINNET",e[e.GNOSIS_CHAIN=100]="GNOSIS_CHAIN",e[e.SEPOLIA=11155111]="SEPOLIA"}(y||(y={}));const c=["prod","staging"],T={env:"prod",chainId:y.MAINNET};class m extends Error{constructor(e,t){super(e),this.error_code=void 0,this.error_code=t}}const f="cow-sdk:",h="https://gnosis.mypinata.cloud/ipfs",b="https://api.pinata.cloud";function I(){return I=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},I.apply(this,arguments)}function E(e,t){if(null==e)return{};var n,r,a={},s=Object.keys(e);for(r=0;r<s.length;r++)t.indexOf(n=s[r])>=0||(a[n]=e[n]);return a}const O="0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE",A="0x2f55e8b20D0B9FEFA187AA7d00B6Cbe563605bF5",S="0xfdaFc9d1902f4e0b84f65F49f244b32b31013b74",N=Object.values(y).filter(e=>"number"==typeof e);function _(e){return N.reduce((t,n)=>I({},t,{[n]:"function"==typeof e?e(n):e}),{})}function g(e){return _(e)}const v=g("0x9008D19f58AAbD9eD0D60971565AA8510560ab41"),w=g("0xC92E8bdf79f0507f65a392b0ab4667716BFE0110"),P=g(A),R=g(S);function C(e){return function(e){const{ethflowData:t}=e;if(!t)return e;const{userValidTo:n}=t;return I({},e,{validTo:n,owner:e.onchainUser||e.owner,sellToken:O})}(function(e){const{executedFeeAmount:t,executedSurplusFee:n}=e,r=BigInt(t||"0"),a=BigInt(n||"0");return I({},e,{totalFee:String(r+a)})}(e))}class D 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 U=[408,425,429,500,502,503,504],x={numOfAttempts:10,maxDelay:Infinity,jitter:"none",retry:e=>!(e instanceof D)||U.includes(e.response.status)},L={tokensPerInterval:5,interval:"second"},M=async e=>{if(204!==e.status)try{const t=e.headers.get("Content-Type");if(t)return t.toLowerCase().startsWith("application/json")?await e.json():await e.text()}catch(e){console.error(e)}};async function k(e,{path:n,query:r,method:a,body:s},i,o){const p=`${e}${n}${r?"?"+r:""}`,d={method:a,body:(()=>{if(s)return"string"==typeof s?s:JSON.stringify(s)})(),headers:{Accept:"application/json","Content-Type":"application/json"}};return t(async()=>{await i.removeTokens(1);const e=await fetch(p,d),t=await M(e);return e.status>=200&&e.status<300?t:Promise.reject(new D(e,t))},o)}const F={[y.MAINNET]:"https://api.cow.fi/mainnet",[y.GNOSIS_CHAIN]:"https://api.cow.fi/xdai",[y.SEPOLIA]:"https://api.cow.fi/sepolia"},V={[y.MAINNET]:"https://barn.api.cow.fi/mainnet",[y.GNOSIS_CHAIN]:"https://barn.api.cow.fi/xdai",[y.SEPOLIA]:"https://barn.api.cow.fi/sepolia"};function G(e){return Object.keys(e).reduce((t,n)=>{const r=e[n];return void 0!==r&&(t[n]=r),t},{})}class ${constructor(t={}){this.context=void 0,this.rateLimiter=void 0,this.context=I({},T,t),this.rateLimiter=new e(t.limiterOpts||L)}getVersion(e={}){return this.fetch({path:"/api/v1/version",method:"GET"},e)}getTrades(e,t={}){if(e.owner&&e.orderUid)return Promise.reject(new m("Cannot specify both owner and orderId"));if(!e.owner&&!e.orderUid)return Promise.reject(new m("Must specify either owner or orderId"));const n=new URLSearchParams(G(e));return this.fetch({path:"/api/v1/trades",method:"GET",query:n},t)}getOrders({owner:e,offset:t=0,limit:n=1e3},r={}){const a=new URLSearchParams(G({offset:t.toString(),limit:n.toString()}));return this.fetch({path:`/api/v1/account/${e}/orders`,method:"GET",query:a},r).then(e=>e.map(C))}getTxOrders(e,t={}){return this.fetch({path:`/api/v1/transactions/${e}/orders`,method:"GET"},t).then(e=>e.map(C))}getOrder(e,t={}){return this.fetch({path:`/api/v1/orders/${e}`,method:"GET"},t).then(e=>C(e))}getOrderMultiEnv(e,t={}){const{env:n}=this.getContextWithOverride(t),r=c.filter(e=>e!==n);let a=0;const s=n=>{const i=r[a];return n instanceof D&&404===n.response.status&&i?(a++,this.getOrder(e,I({},t,{env:i})).catch(s)):Promise.reject(n)};return this.getOrder(e,I({},t,{env:n})).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)}getTotalSurplus(e,t={}){return this.fetch({path:`/api/v1/users/${e}/total_surplus`,method:"GET"},t)}getAppData(e,t={}){return this.fetch({path:`/api/v1/app_data/${e}`,method:"GET"},t)}uploadAppData(e,t,n={}){return this.fetch({path:`/api/v1/app_data/${e}`,method:"PUT",body:{fullAppData:t}},n)}getSolverCompetition(e,t={}){return this.fetch({path:`/api/v1/solver_competition${"string"==typeof e?"/by_tx_hash":""}/${e}`,method:"GET"},t)}getOrderLink(e,t){const{chainId:n,env:r}=this.getContextWithOverride(t);return this.getApiBaseUrls(r)[n]+`/api/v1/orders/${e}`}getContextWithOverride(e={}){return I({},this.context,e)}getApiBaseUrls(e){return this.context.baseUrls?this.context.baseUrls:"prod"===e?F:V}fetch(e,t={}){const{chainId:n,env:r}=this.getContextWithOverride(t);return k(this.getApiBaseUrls(r)[n],e,this.rateLimiter,this.context.backoffOpts||x)}}var B,W,H,Y,j,K,Z,X,q,z,J,Q,ee,te,ne;!function(e){e.ERC20="erc20",e.INTERNAL="internal"}(B||(B={})),function(e){e.EIP712="eip712",e.ETHSIGN="ethsign"}(W||(W={})),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"}(H||(H={})),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"}(Y||(Y={})),function(e){e.MARKET="market",e.LIMIT="limit",e.LIQUIDITY="liquidity"}(j||(j={})),function(e){e.BUY="buy",e.SELL="sell"}(K||(K={})),function(e){var t;(t=e.errorType||(e.errorType={})).DUPLICATED_ORDER="DuplicatedOrder",t.QUOTE_NOT_FOUND="QuoteNotFound",t.INVALID_QUOTE="InvalidQuote",t.MISSING_FROM="MissingFrom",t.WRONG_OWNER="WrongOwner",t.INVALID_EIP1271SIGNATURE="InvalidEip1271Signature",t.INSUFFICIENT_BALANCE="InsufficientBalance",t.INSUFFICIENT_ALLOWANCE="InsufficientAllowance",t.INVALID_SIGNATURE="InvalidSignature",t.INSUFFICIENT_FEE="InsufficientFee",t.SELL_AMOUNT_OVERFLOW="SellAmountOverflow",t.TRANSFER_SIMULATION_FAILED="TransferSimulationFailed",t.ZERO_AMOUNT="ZeroAmount",t.INCOMPATIBLE_SIGNING_SCHEME="IncompatibleSigningScheme",t.TOO_MANY_LIMIT_ORDERS_UNSUPPORTED_BUY_TOKEN_DESTINATION="TooManyLimitOrders UnsupportedBuyTokenDestination",t.UNSUPPORTED_SELL_TOKEN_SOURCE="UnsupportedSellTokenSource",t.UNSUPPORTED_ORDER_TYPE="UnsupportedOrderType",t.INSUFFICIENT_VALID_TO="InsufficientValidTo",t.EXCESSIVE_VALID_TO="ExcessiveValidTo",t.TRANSFER_ETH_TO_CONTRACT="TransferEthToContract",t.INVALID_NATIVE_SELL_TOKEN_SAME_BUY_AND_SELL_TOKEN="InvalidNativeSellToken SameBuyAndSellToken",t.UNSUPPORTED_SIGNATURE="UnsupportedSignature",t.UNSUPPORTED_TOKEN="UnsupportedToken",t.UNSUPPORTED_CUSTOM_INTERACTION_INVALID_APP_DATA="UnsupportedCustomInteraction InvalidAppData",t.APP_DATA_HASH_MISMATCH="AppDataHashMismatch"}(Z||(Z={})),function(e){e.BUY="buy"}(X||(X={})),function(e){e.SELL="sell"}(q||(q={})),function(e){e.PRESIGNATURE_PENDING="presignaturePending",e.OPEN="open",e.FULFILLED="fulfilled",e.CANCELLED="cancelled",e.EXPIRED="expired"}(z||(z={})),function(e){var t;(t=e.errorType||(e.errorType={})).UNSUPPORTED_TOKEN="UnsupportedToken",t.ZERO_AMOUNT="ZeroAmount",t.UNSUPPORTED_ORDER_TYPE="UnsupportedOrderType"}(J||(J={})),function(e){e.FAST="fast",e.OPTIMAL="optimal",e.VERIFIED="verified"}(Q||(Q={})),function(e){var t;(t=e.errorType||(e.errorType={})).ALREADY_CANCELLED="AlreadyCancelled",t.ORDER_FULLY_EXECUTED="OrderFullyExecuted",t.ORDER_EXPIRED="OrderExpired",t.ON_CHAIN_ORDER="OnChainOrder",t.DUPLICATED_ORDER="DuplicatedOrder",t.INSUFFICIENT_FEE="InsufficientFee",t.INSUFFICIENT_ALLOWANCE="InsufficientAllowance",t.INSUFFICIENT_BALANCE="InsufficientBalance",t.INSUFFICIENT_VALID_TO="InsufficientValidTo",t.EXCESSIVE_VALID_TO="ExcessiveValidTo",t.INVALID_SIGNATURE="InvalidSignature",t.TRANSFER_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"}(ee||(ee={})),function(e){e.ERC20="erc20",e.INTERNAL="internal",e.EXTERNAL="external"}(te||(te={})),function(e){e.EIP712="eip712",e.ETHSIGN="ethsign",e.PRESIGN="presign",e.EIP1271="eip1271"}(ne||(ne={}));let re,ae,se,ie=e=>e;const oe=n(re||(re=ie`
|
|
2
|
+
query Totals {
|
|
3
|
+
totals {
|
|
4
|
+
tokens
|
|
5
|
+
orders
|
|
6
|
+
traders
|
|
7
|
+
settlements
|
|
8
|
+
volumeUsd
|
|
9
|
+
volumeEth
|
|
10
|
+
feesUsd
|
|
11
|
+
feesEth
|
|
12
|
+
}
|
|
13
|
+
}
|
|
14
|
+
`)),pe=n(ae||(ae=ie`
|
|
15
|
+
query LastDaysVolume($days: Int!) {
|
|
16
|
+
dailyTotals(orderBy: timestamp, orderDirection: desc, first: $days) {
|
|
17
|
+
timestamp
|
|
18
|
+
volumeUsd
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
`)),de=n(se||(se=ie`
|
|
22
|
+
query LastHoursVolume($hours: Int!) {
|
|
23
|
+
hourlyTotals(orderBy: timestamp, orderDirection: desc, first: $hours) {
|
|
24
|
+
timestamp
|
|
25
|
+
volumeUsd
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
`)),ue="https://api.thegraph.com/subgraphs/name/cowprotocol",le={[y.MAINNET]:ue+"/cow",[y.GNOSIS_CHAIN]:ue+"/cow-gc",[y.SEPOLIA]:null},ye={[y.MAINNET]:ue+"/cow-staging",[y.GNOSIS_CHAIN]:ue+"/cow-gc-staging",[y.SEPOLIA]:null};class ce{constructor(e={}){this.API_NAME="CoW Protocol Subgraph",this.context=void 0,this.context=I({},T,e)}async getTotals(e={}){return(await this.runQuery(oe,void 0,e)).totals[0]}async getLastDaysVolume(e,t={}){return this.runQuery(pe,{days:e},t)}async getLastHoursVolume(e,t={}){return this.runQuery(de,{hours:e},t)}async runQuery(e,t=undefined,n={}){const{chainId:a,env:s}=this.getContextWithOverride(n),i=this.getEnvConfigs(s)[a];if(null===i)throw new Error("Unsupported Network. The subgraph API is not available in the Network "+a);try{return await r(i,e,t)}catch(n){throw console.error(`[subgraph:${this.API_NAME}]`,n),new m(`Error running query: ${e}. Variables: ${JSON.stringify(t)}. API: ${i}. Inner Error: ${n}`)}}getContextWithOverride(e={}){return I({},this.context,e)}getEnvConfigs(e){return this.context.baseUrls?this.context.baseUrls:"prod"===e?le:ye}}const Te=()=>import("./utils-33f6a4bd.js");class me{static async signOrder(e,t,n){const{signOrder:r}=await Te();return r(e,t,n)}static async signOrderCancellation(e,t,n){const{signOrderCancellation:r}=await Te();return r(e,t,n)}static async signOrderCancellations(e,t,n){const{signOrderCancellations:r}=await Te();return r(e,t,n)}static async getDomain(e){const{getDomain:t}=await Te();return t(e)}static async getDomainSeparator(e){const{getDomain:t}=await Te(),{_TypedDataEncoder:n}=await import("ethers/lib/utils");return n.hashDomain(t(e))}static getEIP712Types(){return{Order:[{name:"sellToken",type:"address"},{name:"buyToken",type:"address"},{name:"receiver",type:"address"},{name:"sellAmount",type:"uint256"},{name:"buyAmount",type:"uint256"},{name:"validTo",type:"uint32"},{name:"appData",type:"bytes32"},{name:"feeAmount",type:"uint256"},{name:"kind",type:"string"},{name:"partiallyFillable",type:"bool"},{name:"sellTokenBalance",type:"string"},{name:"buyTokenBalance",type:"string"}]}}}var fe,he;!function(e){e[e.PRIVATE=0]="PRIVATE",e[e.EMITTED=1]="EMITTED",e[e.SWARM=2]="SWARM",e[e.WAKU=3]="WAKU",e[e.RESERVED=4]="RESERVED",e[e.IPFS=5]="IPFS"}(fe||(fe={})),function(e){e.SUCCESS="SUCCESS",e.UNEXPECTED_ERROR="UNEXPECTED_ERROR",e.TRY_NEXT_BLOCK="TRY_NEXT_BLOCK",e.TRY_ON_BLOCK="TRY_ON_BLOCK",e.TRY_AT_EPOCH="TRY_AT_EPOCH",e.DONT_TRY_AGAIN="DONT_TRY_AGAIN"}(he||(he={}));const be=[{inputs:[{internalType:"address",name:"_settlement",type:"address"}],stateMutability:"nonpayable",type:"constructor"},{inputs:[],name:"InterfaceNotSupported",type:"error"},{inputs:[],name:"InvalidHandler",type:"error"},{inputs:[],name:"ProofNotAuthed",type:"error"},{inputs:[],name:"SingleOrderNotAuthed",type:"error"},{inputs:[],name:"SwapGuardRestricted",type:"error"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"owner",type:"address"},{components:[{internalType:"contract IConditionalOrder",name:"handler",type:"address"},{internalType:"bytes32",name:"salt",type:"bytes32"},{internalType:"bytes",name:"staticInput",type:"bytes"}],indexed:!1,internalType:"struct IConditionalOrder.ConditionalOrderParams",name:"params",type:"tuple"}],name:"ConditionalOrderCreated",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"owner",type:"address"},{indexed:!1,internalType:"bytes32",name:"root",type:"bytes32"},{components:[{internalType:"uint256",name:"location",type:"uint256"},{internalType:"bytes",name:"data",type:"bytes"}],indexed:!1,internalType:"struct ComposableCoW.Proof",name:"proof",type:"tuple"}],name:"MerkleRootSet",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"owner",type:"address"},{indexed:!1,internalType:"contract ISwapGuard",name:"swapGuard",type:"address"}],name:"SwapGuardSet",type:"event"},{inputs:[{internalType:"address",name:"",type:"address"},{internalType:"bytes32",name:"",type:"bytes32"}],name:"cabinet",outputs:[{internalType:"bytes32",name:"",type:"bytes32"}],stateMutability:"view",type:"function"},{inputs:[{components:[{internalType:"contract IConditionalOrder",name:"handler",type:"address"},{internalType:"bytes32",name:"salt",type:"bytes32"},{internalType:"bytes",name:"staticInput",type:"bytes"}],internalType:"struct IConditionalOrder.ConditionalOrderParams",name:"params",type:"tuple"},{internalType:"bool",name:"dispatch",type:"bool"}],name:"create",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{components:[{internalType:"contract IConditionalOrder",name:"handler",type:"address"},{internalType:"bytes32",name:"salt",type:"bytes32"},{internalType:"bytes",name:"staticInput",type:"bytes"}],internalType:"struct IConditionalOrder.ConditionalOrderParams",name:"params",type:"tuple"},{internalType:"contract IValueFactory",name:"factory",type:"address"},{internalType:"bytes",name:"data",type:"bytes"},{internalType:"bool",name:"dispatch",type:"bool"}],name:"createWithContext",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[],name:"domainSeparator",outputs:[{internalType:"bytes32",name:"",type:"bytes32"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"owner",type:"address"},{components:[{internalType:"contract IConditionalOrder",name:"handler",type:"address"},{internalType:"bytes32",name:"salt",type:"bytes32"},{internalType:"bytes",name:"staticInput",type:"bytes"}],internalType:"struct IConditionalOrder.ConditionalOrderParams",name:"params",type:"tuple"},{internalType:"bytes",name:"offchainInput",type:"bytes"},{internalType:"bytes32[]",name:"proof",type:"bytes32[]"}],name:"getTradeableOrderWithSignature",outputs:[{components:[{internalType:"contract IERC20",name:"sellToken",type:"address"},{internalType:"contract IERC20",name:"buyToken",type:"address"},{internalType:"address",name:"receiver",type:"address"},{internalType:"uint256",name:"sellAmount",type:"uint256"},{internalType:"uint256",name:"buyAmount",type:"uint256"},{internalType:"uint32",name:"validTo",type:"uint32"},{internalType:"bytes32",name:"appData",type:"bytes32"},{internalType:"uint256",name:"feeAmount",type:"uint256"},{internalType:"bytes32",name:"kind",type:"bytes32"},{internalType:"bool",name:"partiallyFillable",type:"bool"},{internalType:"bytes32",name:"sellTokenBalance",type:"bytes32"},{internalType:"bytes32",name:"buyTokenBalance",type:"bytes32"}],internalType:"struct GPv2Order.Data",name:"order",type:"tuple"},{internalType:"bytes",name:"signature",type:"bytes"}],stateMutability:"view",type:"function"},{inputs:[{components:[{internalType:"contract IConditionalOrder",name:"handler",type:"address"},{internalType:"bytes32",name:"salt",type:"bytes32"},{internalType:"bytes",name:"staticInput",type:"bytes"}],internalType:"struct IConditionalOrder.ConditionalOrderParams",name:"params",type:"tuple"}],name:"hash",outputs:[{internalType:"bytes32",name:"",type:"bytes32"}],stateMutability:"pure",type:"function"},{inputs:[{internalType:"contract Safe",name:"safe",type:"address"},{internalType:"address",name:"sender",type:"address"},{internalType:"bytes32",name:"_hash",type:"bytes32"},{internalType:"bytes32",name:"_domainSeparator",type:"bytes32"},{internalType:"bytes32",name:"",type:"bytes32"},{internalType:"bytes",name:"encodeData",type:"bytes"},{internalType:"bytes",name:"payload",type:"bytes"}],name:"isValidSafeSignature",outputs:[{internalType:"bytes4",name:"magic",type:"bytes4"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"bytes32",name:"singleOrderHash",type:"bytes32"}],name:"remove",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"",type:"address"}],name:"roots",outputs:[{internalType:"bytes32",name:"",type:"bytes32"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"bytes32",name:"root",type:"bytes32"},{components:[{internalType:"uint256",name:"location",type:"uint256"},{internalType:"bytes",name:"data",type:"bytes"}],internalType:"struct ComposableCoW.Proof",name:"proof",type:"tuple"}],name:"setRoot",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"bytes32",name:"root",type:"bytes32"},{components:[{internalType:"uint256",name:"location",type:"uint256"},{internalType:"bytes",name:"data",type:"bytes"}],internalType:"struct ComposableCoW.Proof",name:"proof",type:"tuple"},{internalType:"contract IValueFactory",name:"factory",type:"address"},{internalType:"bytes",name:"data",type:"bytes"}],name:"setRootWithContext",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"contract ISwapGuard",name:"swapGuard",type:"address"}],name:"setSwapGuard",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"",type:"address"},{internalType:"bytes32",name:"",type:"bytes32"}],name:"singleOrders",outputs:[{internalType:"bool",name:"",type:"bool"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"",type:"address"}],name:"swapGuards",outputs:[{internalType:"contract ISwapGuard",name:"",type:"address"}],stateMutability:"view",type:"function"}];class Ie{static createInterface(){return new a.Interface(be)}static connect(e,t){return new s(e,be,t)}}Ie.abi=be;const Ee=[{anonymous:!1,inputs:[{indexed:!0,internalType:"contract Safe",name:"safe",type:"address"},{indexed:!1,internalType:"bytes32",name:"domainSeparator",type:"bytes32"},{indexed:!1,internalType:"contract ISafeSignatureVerifier",name:"verifier",type:"address"}],name:"AddedDomainVerifier",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"contract Safe",name:"safe",type:"address"},{indexed:!1,internalType:"bytes4",name:"interfaceId",type:"bytes4"}],name:"AddedInterface",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"contract Safe",name:"safe",type:"address"},{indexed:!1,internalType:"bytes4",name:"selector",type:"bytes4"},{indexed:!1,internalType:"bytes32",name:"method",type:"bytes32"}],name:"AddedSafeMethod",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"contract Safe",name:"safe",type:"address"},{indexed:!1,internalType:"bytes32",name:"domainSeparator",type:"bytes32"},{indexed:!1,internalType:"contract ISafeSignatureVerifier",name:"oldVerifier",type:"address"},{indexed:!1,internalType:"contract ISafeSignatureVerifier",name:"newVerifier",type:"address"}],name:"ChangedDomainVerifier",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"contract Safe",name:"safe",type:"address"},{indexed:!1,internalType:"bytes4",name:"selector",type:"bytes4"},{indexed:!1,internalType:"bytes32",name:"oldMethod",type:"bytes32"},{indexed:!1,internalType:"bytes32",name:"newMethod",type:"bytes32"}],name:"ChangedSafeMethod",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"contract Safe",name:"safe",type:"address"},{indexed:!1,internalType:"bytes32",name:"domainSeparator",type:"bytes32"}],name:"RemovedDomainVerifier",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"contract Safe",name:"safe",type:"address"},{indexed:!1,internalType:"bytes4",name:"interfaceId",type:"bytes4"}],name:"RemovedInterface",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"contract Safe",name:"safe",type:"address"},{indexed:!1,internalType:"bytes4",name:"selector",type:"bytes4"}],name:"RemovedSafeMethod",type:"event"},{stateMutability:"nonpayable",type:"fallback"},{inputs:[{internalType:"contract Safe",name:"",type:"address"},{internalType:"bytes32",name:"",type:"bytes32"}],name:"domainVerifiers",outputs:[{internalType:"contract ISafeSignatureVerifier",name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"bytes32",name:"_hash",type:"bytes32"},{internalType:"bytes",name:"signature",type:"bytes"}],name:"isValidSignature",outputs:[{internalType:"bytes4",name:"magic",type:"bytes4"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"",type:"address"},{internalType:"address",name:"",type:"address"},{internalType:"uint256[]",name:"",type:"uint256[]"},{internalType:"uint256[]",name:"",type:"uint256[]"},{internalType:"bytes",name:"",type:"bytes"}],name:"onERC1155BatchReceived",outputs:[{internalType:"bytes4",name:"",type:"bytes4"}],stateMutability:"pure",type:"function"},{inputs:[{internalType:"address",name:"",type:"address"},{internalType:"address",name:"",type:"address"},{internalType:"uint256",name:"",type:"uint256"},{internalType:"uint256",name:"",type:"uint256"},{internalType:"bytes",name:"",type:"bytes"}],name:"onERC1155Received",outputs:[{internalType:"bytes4",name:"",type:"bytes4"}],stateMutability:"pure",type:"function"},{inputs:[{internalType:"address",name:"",type:"address"},{internalType:"address",name:"",type:"address"},{internalType:"uint256",name:"",type:"uint256"},{internalType:"bytes",name:"",type:"bytes"}],name:"onERC721Received",outputs:[{internalType:"bytes4",name:"",type:"bytes4"}],stateMutability:"pure",type:"function"},{inputs:[{internalType:"contract Safe",name:"",type:"address"},{internalType:"bytes4",name:"",type:"bytes4"}],name:"safeInterfaces",outputs:[{internalType:"bool",name:"",type:"bool"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"contract Safe",name:"",type:"address"},{internalType:"bytes4",name:"",type:"bytes4"}],name:"safeMethods",outputs:[{internalType:"bytes32",name:"",type:"bytes32"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"bytes32",name:"domainSeparator",type:"bytes32"},{internalType:"contract ISafeSignatureVerifier",name:"newVerifier",type:"address"}],name:"setDomainVerifier",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"bytes4",name:"selector",type:"bytes4"},{internalType:"bytes32",name:"newMethod",type:"bytes32"}],name:"setSafeMethod",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"bytes4",name:"interfaceId",type:"bytes4"},{internalType:"bool",name:"supported",type:"bool"}],name:"setSupportedInterface",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"bytes4",name:"_interfaceId",type:"bytes4"},{internalType:"bytes32[]",name:"handlerWithSelectors",type:"bytes32[]"}],name:"setSupportedInterfaceBatch",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"bytes4",name:"interfaceId",type:"bytes4"}],name:"supportsInterface",outputs:[{internalType:"bool",name:"",type:"bool"}],stateMutability:"view",type:"function"}];class Oe{static createInterface(){return new a.Interface(Ee)}static connect(e,t){return new s(e,Ee,t)}}Oe.abi=Ee;const Ae=["erc20","0x5a28e9363bb942b639270062aa6bb295f434bcdfc42c97267bf003f272060dc9"],Se=["external","0xabee3b73373acd583a130924aad6dc38cfdc44ba0555ba94ce2ff63980ea0632"],Ne=["internal","0x4ac99ace14ee0a5ef932dc609df0943ab7ac16b7583634612f8dc35a4289a6ce"],_e=["sell","0xf3b277728b3fee749481eb3e0b3b48980dbbab78658fc419025cb16eee346775"],ge=["buy","0x6ed88e868af0a1983e3886d5f3e95a2fafbd6c3450bc229e27342283dc429ccc"],ve=["tuple(address handler, bytes32 salt, bytes staticInput)"],we=(e,t)=>`${t}@${e}`;function Pe(e,t){return e===P[t]}function Re(e,t){return e===R[t]}async function Ce(e,t,n,r){const a=Oe.connect(P[n],r);return await a.callStatic.domainVerifiers(e,t)}function De(e,t){return Oe.createInterface().encodeFunctionData("setDomainVerifier",[e,t])}function Ue(e){return a.defaultAbiCoder.encode(ve,[e])}function xe(e){const{handler:t,salt:n,staticInput:r}=a.defaultAbiCoder.decode(ve,e)[0];return{handler:t,salt:n,staticInput:r}}function Le(e,t){try{a.defaultAbiCoder.encode(e,t)}catch(e){return!1}return!0}async function Me(e){const t=await e.getBlock("latest");return{blockNumber:t.number,blockTimestamp:t.timestamp}}function ke(e){return new Date(1e3*e).toISOString()}function Fe(e){if(Ae.includes(e))return d.ERC20;if(Se.includes(e))return d.EXTERNAL;if(Ne.includes(e))return d.INTERNAL;throw new Error(`Unknown balance type: ${e}`)}function Ve(e){if(_e.includes(e))return u.SELL;if(ge.includes(e))return u.BUY;throw new Error(`Unknown kind: ${e}`)}function Ge(e){const{sellToken:t,sellAmount:n,buyToken:r,buyAmount:a,buyTokenBalance:s,sellTokenBalance:i,feeAmount:o,kind:p,receiver:d,validTo:u,partiallyFillable:l,appData:y}=e;return{sellToken:t,sellAmount:n,buyToken:r,buyAmount:a,feeAmount:o,receiver:d,partiallyFillable:l,appData:y,validTo:Number(u),kind:Ve(p.toString()),sellTokenBalance:Fe(i.toString()),buyTokenBalance:Fe(s.toString())}}let $e,Be;function We(){return $e||($e=Ie.createInterface()),$e}function He(e,t){return Be||(Be=Ie.connect(R[e],t)),Be}class Ye{constructor(e){this.handler=void 0,this.salt=void 0,this.data=void 0,this.staticInput=void 0,this.hasOffChainInput=void 0;const{handler:t,salt:n=a.keccak256(a.randomBytes(32)),data:r,hasOffChainInput:s=!1}=e;if(!i.utils.isAddress(t))throw new Error(`Invalid handler: ${t}`);if(!i.utils.isHexString(n)||32!==i.utils.hexDataLength(n))throw new Error(`Invalid salt: ${n}`);this.handler=t,this.salt=n,this.data=r,this.staticInput=this.transformDataToStruct(r),this.hasOffChainInput=s}get context(){}assertIsValid(){const e=this.isValid();if(!e.isValid)throw new Error(`Invalid order: ${e.reason}`)}get createCalldata(){this.assertIsValid();const e=this.context,t=We(),n={handler:this.handler,salt:this.salt,staticInput:this.encodeStaticInput()};if(e){const r=e.factoryArgs?a.defaultAbiCoder.encode(e.factoryArgs.argsType,e.factoryArgs.args):"0x";return t.encodeFunctionData("createWithContext",[n,e.address,r,!0])}return t.encodeFunctionData("create",[n,!0])}get removeCalldata(){return this.assertIsValid(),We().encodeFunctionData("remove",[this.id])}get id(){return a.keccak256(this.serialize())}get ctx(){return this.isSingleOrder?this.id:o.HashZero}get leaf(){return{handler:this.handler,salt:this.salt,staticInput:this.encodeStaticInput()}}static leafToId(e){return a.keccak256(Ue(e))}get offChainInput(){return"0x"}encodeStaticInputHelper(e,t){return a.defaultAbiCoder.encode(e,[t])}async poll(e){const{chainId:t,owner:n,provider:r,orderBookApi:a}=e,s=He(t,r);try{const r=this.isValid();if(!r.isValid)return{result:he.DONT_TRY_AGAIN,reason:`InvalidConditionalOrder. Reason: ${r.reason}`};const i=await this.pollValidate(e);if(i)return i;if(!await this.isAuthorized(e))return{result:he.DONT_TRY_AGAIN,reason:`NotAuthorized: Order ${this.id} is not authorized for ${n} on chain ${t}`};const[o,p]=await s.getTradeableOrderWithSignature(n,this.leaf,this.offChainInput,[]),d=await async function(e,t,n){const{computeOrderUid:r}=await import("@cowprotocol/contracts");return r(await me.getDomain(e),n,t)}(t,n,Ge(o));return await a.getOrder(d).then(()=>!0).catch(()=>!1)?await this.handlePollFailedAlreadyPresent(d,o,e)||{result:he.TRY_NEXT_BLOCK,reason:"Order already in orderbook"}:{result:he.SUCCESS,order:o,signature:p}}catch(e){return{result:he.UNEXPECTED_ERROR,error:e}}}isAuthorized(e){const{chainId:t,owner:n,provider:r}=e;return He(t,r).callStatic.singleOrders(n,this.id)}cabinet(e){const{chainId:t,owner:n,provider:r}=e;return He(t,r).callStatic.cabinet(n,this.ctx)}static deserializeHelper(e,t,n,r){try{const{handler:s,salt:i,staticInput:o}=xe(e);if(s!=t)throw new Error("HandlerMismatch");const[p]=a.defaultAbiCoder.decode(n,o);return r(p,i)}catch(e){throw"HandlerMismatch"===e.message?e:new Error("InvalidSerializedConditionalOrder")}}}const je=["orderType"],Ke=["address","bytes32","bytes"],Ze=["tuple(bytes32[] proof, tuple(address handler, bytes32 salt, bytes staticInput) params)[]"];class Xe{constructor(e,t,n,r=fe.PRIVATE){if(this.chain=void 0,this.location=void 0,this.orders={},this.tree=void 0,this.ctx=void 0,this.chain=e,this.location=r,t&&0===Object.keys(t).length)throw new Error("orders must have non-zero length");if(t&&!n||!t&&n)throw new Error("orders cannot have undefined root");for(const e in t)if(t.hasOwnProperty(e)){const n=t[e];if(!Xe.orderTypeRegistry.hasOwnProperty(n.orderType))throw new Error(`Unknown order type: ${n.orderType}`)}if(t&&(this.orders=t,this.getOrGenerateTree().root!==n))throw new Error("root mismatch")}static fromJSON(e){const{chain:t,orders:n,root:r,location:a}=JSON.parse(e,(e,t)=>{if("orders"===e&&"object"==typeof t&&null!==t){const e={};for(const n in t)if(t.hasOwnProperty(n)){const r=t[n],{orderType:a}=r,s=E(r,je);if(!Xe.orderTypeRegistry.hasOwnProperty(a))throw new Error(`Unknown order type: ${a}`);e[n]=new(0,Xe.orderTypeRegistry[a])(s)}return e}return"object"==typeof t&&null!==t&&t.hasOwnProperty("type")&&t.hasOwnProperty("hex")&&"BigNumber"===t.type?p.from(t):t}),s=new Xe(t,n,r);return s.location=a,s}toJSON(){const e=this.getOrGenerateTree().root;return JSON.stringify(I({},this,{root:e}),(e,t)=>{if("tree"!==e)return"object"==typeof t&&null!==t&&"orderType"in t?I({},t,{orderType:t.orderType}):t})}add(e){e.assertIsValid(),this.orders[e.id]=e,this.reset()}remove(e){delete this.orders[e],this.reset()}update(e,t){const n=t(this.orders[e],this.ctx);delete this.orders[e],this.orders[n.id]=n,this.reset()}getById(e){return this.orders[e]}getByIndex(e){return this.orders[this.orderIds[e]]}get orderIds(){return Object.keys(this.orders)}get root(){return this.getOrGenerateTree().root}getOrGenerateTree(){return this.tree||(this.tree=l.of(Object.values(this.orders).map(e=>[...Object.values(e.leaf)]),Ke)),this.tree}static decodeFromJSON(e){return JSON.parse(e)}async prepareProofStruct(e=this.location,t,n){var r=this;return await async function(){switch(e){case fe.PRIVATE:return"0x";case fe.EMITTED:return r.encodeToABI(t);case fe.SWARM:case fe.WAKU:case fe.IPFS:if(!n)throw new Error("Must provide an uploader function");try{return await n(r.encodeToJSON(t))}catch(t){throw new Error(`Error uploading to decentralized storage ${e}: ${t}`)}default:throw new Error("Unsupported location")}}().then(t=>{try{return a.hexlify(a.arrayify(t)),this.location=e,{location:e,data:t}}catch(e){throw new Error("data returned by uploader is invalid")}}).catch(e=>{throw new Error(`Error preparing proof struct: ${e}`)})}static async poll(e,t,n,r,a){const s=He(n,r),i=a?await a(e,t.params):"0x";return await s.getTradeableOrderWithSignature(e,t.params,i,t.proof)}dumpProofs(e){return this.encodeToJSON(e)}dumpProofsAndParams(e){return this.getProofs(e)}getProofs(e){return[...this.getOrGenerateTree().entries()].map(([t,n])=>e&&e(n)||void 0===e?{idx:t,value:n}:void 0).reduce((e,t)=>{if(t){const n={handler:t.value[0],salt:t.value[1],staticInput:t.value[2]};e.push({proof:this.getOrGenerateTree().getProof(t.idx),params:n})}return e},[])}encodeToABI(e){return a.defaultAbiCoder.encode(Ze,[this.getProofs(e)])}encodeToJSON(e){return JSON.stringify(this.getProofs(e))}reset(){this.tree=void 0}static registerOrderType(e,t){Xe.orderTypeRegistry[e]=t}static resetOrderTypeRegistry(){Xe.orderTypeRegistry={}}}Xe.orderTypeRegistry={};class qe{constructor(e){this.knownOrderTypes=void 0,this.knownOrderTypes=e}fromParams(e){const{handler:t}=e,n=this.knownOrderTypes[t];if(n)return n(e)}}const ze=["sellAmount","buyAmount","numberOfParts","startTime","timeBetweenParts","durationOfPart"],Je=["n","partSellAmount","minPartLimit","t","t0","span"],Qe="0x6cF1e9cA41f7611dEf408122793c358a3d11E5a5",et="0x52eD56Da04309Aca4c3FECC595298d80C2f16BAc",tt=p.from(2).pow(32).sub(1),nt=p.from(31536e3),rt=["tuple(address sellToken, address buyToken, address receiver, uint256 partSellAmount, uint256 minPartLimit, uint256 t0, uint256 n, uint256 t, uint256 span, bytes32 appData)"];var at,st;!function(e){e.AUTO="AUTO",e.LIMIT_DURATION="LIMIT_DURATION"}(at||(at={})),function(e){e.AT_MINING_TIME="AT_MINING_TIME",e.AT_EPOCH="AT_EPOCH"}(st||(st={}));const it={startType:st.AT_MINING_TIME},ot={durationType:at.AUTO};class pt extends Ye{constructor(e){const{handler:t,salt:n,data:r,hasOffChainInput:a}=e;if(t!==Qe)throw new Error(`InvalidHandler: Expected: ${Qe}, provided: ${t}`);super({handler:Qe,salt:n,data:r,hasOffChainInput:a}),this.isSingleOrder=!0}static fromData(e,t){return new pt({handler:Qe,data:e,salt:t})}static fromParams(e){return pt.deserialize(Ue(e))}get context(){return this.staticInput.t0.gt(0)?super.context:{address:et,factoryArgs:void 0}}get orderType(){return"twap"}isValid(){const e=(()=>{const{sellToken:e,sellAmount:t,buyToken:n,buyAmount:r,startTime:a=it,numberOfParts:s,timeBetweenParts:i,durationOfPart:p=ot}=this.data;if(e==n)return"InvalidSameToken";if(e==o.AddressZero||n==o.AddressZero)return"InvalidToken";if(!t.gt(o.Zero))return"InvalidSellAmount";if(!r.gt(o.Zero))return"InvalidMinBuyAmount";if(a.startType===st.AT_EPOCH){const e=a.epoch;if(!e.gte(o.Zero)||!e.lt(tt))return"InvalidStartTime"}return s.gt(o.One)&&s.lte(tt)?i.gt(o.Zero)&&i.lte(nt)?p.durationType!==at.LIMIT_DURATION||p.duration.lte(i)?Le(rt,[this.staticInput])?void 0:"InvalidData":"InvalidSpan":"InvalidFrequency":"InvalidNumParts"})();return e?{isValid:!1,reason:e}:{isValid:!0}}async startTimestamp(e){const{startTime:t}=this.data;if((null==t?void 0:t.startType)===st.AT_EPOCH)return t.epoch.toNumber();const n=await this.cabinet(e),r=a.defaultAbiCoder.decode(["uint256"],n)[0];if(r.gt(tt))throw new Error(`Cabinet epoch out of range: ${r.toString()}`);const s=r.toNumber();if(0===s)throw new Error("Cabinet is not set. Required for TWAP orders that start at mining time.");return s}endTimestamp(e){const{numberOfParts:t,timeBetweenParts:n,durationOfPart:r}=this.data;return r&&r.durationType===at.LIMIT_DURATION?e+t.sub(1).mul(n).add(r.duration).toNumber():e+t.mul(n).toNumber()}async pollValidate(e){const{blockInfo:t=await Me(e.provider)}=e,{blockTimestamp:n}=t;try{const t=await this.startTimestamp(e);if(t>n)return{result:he.TRY_AT_EPOCH,epoch:t,reason:`TWAP hasn't started yet. Starts at ${t} (${ke(t)})`};const r=this.endTimestamp(t);return n>=r?{result:he.DONT_TRY_AGAIN,reason:`TWAP has expired. Expired at ${r} (${ke(r)})`}:void 0}catch(e){var r,a;return null!=e&&null!=(r=e.message)&&r.includes("Cabinet is not set")?{result:he.DONT_TRY_AGAIN,reason:`${null==e?void 0:e.message}. User likely removed the order.`}:null!=e&&null!=(a=e.message)&&a.includes("Cabinet epoch out of range")?{result:he.DONT_TRY_AGAIN,reason:`${null==e?void 0:e.message}`}:{result:he.UNEXPECTED_ERROR,reason:`Unexpected error: ${e.message}`,error:e}}}async handlePollFailedAlreadyPresent(e,t,n){const{blockInfo:r=await Me(n.provider)}=n,{blockTimestamp:a}=r,s=this.data.timeBetweenParts.toNumber(),{numberOfParts:i}=this.data,o=await this.startTimestamp(n);if(a<o)return{result:he.UNEXPECTED_ERROR,reason:`TWAP part hash't started. First TWAP part start at ${o} (${ke(o)})`,error:void 0};const p=i.mul(s).add(o).toNumber();if(a>=p)return{result:he.UNEXPECTED_ERROR,reason:`TWAP is expired. Expired at ${p} (${ke(p)})`,error:void 0};const d=Math.floor((a-o)/s);if(d===i.toNumber()-1)return{result:he.DONT_TRY_AGAIN,reason:`Current active TWAP part (${d+1}/${i}) is already in the Order Book. This was the last TWAP part, no more orders need to be placed`};const u=o+(d+1)*s;return{result:he.TRY_AT_EPOCH,epoch:u,reason:`Current active TWAP part (${d+1}/${i}) is already in the Order Book. TWAP part ${d+2} doesn't start until ${u} (${ke(u)})`}}serialize(){return Ue(this.leaf)}encodeStaticInput(){return super.encodeStaticInputHelper(rt,this.staticInput)}static deserialize(e){return super.deserializeHelper(e,Qe,rt,(e,t)=>new pt({handler:Qe,salt:t,data:ut(e)}))}toString(){const{sellAmount:e,sellToken:t,buyAmount:n,buyToken:r,numberOfParts:a,startTime:s=it,timeBetweenParts:i,durationOfPart:o=ot,receiver:p,appData:d}=this.data,u=s.startType===st.AT_MINING_TIME?"AT_MINING_TIME":s.epoch.toNumber(),l=o.durationType===at.AUTO?"AUTO":o.duration.toNumber(),y={sellAmount:e.toString(),sellToken:t,buyAmount:n.toString(),buyToken:r,numberOfParts:a.toString(),startTime:u,timeBetweenParts:i.toNumber(),durationOfPart:l,receiver:p,appData:d};return`${this.orderType} (${this.id}): ${JSON.stringify(y)}`}transformDataToStruct(e){return dt(e)}transformStructToData(e){return ut(e)}}function dt(e){const{sellAmount:t,buyAmount:n,numberOfParts:r,startTime:a=it,timeBetweenParts:s,durationOfPart:i=ot}=e,p=E(e,ze),{partSellAmount:d,minPartLimit:u}=r&&!r.isZero()?{partSellAmount:t.div(r),minPartLimit:n.div(r)}:{partSellAmount:o.Zero,minPartLimit:o.Zero};return I({partSellAmount:d,minPartLimit:u,t0:a.startType===st.AT_MINING_TIME?o.Zero:a.epoch,n:r,t:s,span:i.durationType===at.AUTO?o.Zero:i.duration},p)}function ut(e){const{n:t,partSellAmount:n,minPartLimit:r,t:a,t0:s,span:i}=e,o=E(e,Je),p=i.isZero()?{durationType:at.AUTO}:{durationType:at.LIMIT_DURATION,duration:i},d=i.isZero()?{startType:st.AT_MINING_TIME}:{startType:st.AT_EPOCH,epoch:s};return I({sellAmount:n.mul(t),buyAmount:r.mul(t),startTime:d,numberOfParts:t,timeBetweenParts:a,durationOfPart:p},o)}const lt={[Qe]:e=>pt.fromParams(e)};export{xe as $,N as A,O as B,m as C,T as D,W as E,D as F,x as G,L as H,k as I,le as J,ye as K,ce as L,me as M,fe as N,F as O,J as P,he as Q,ee as R,y as S,ve as T,we as U,Pe as V,Re as W,Ce as X,De as Y,Ue as Z,I as _,v as a,Le as a0,Me as a1,ke as a2,Ge as a3,Ye as a4,Xe as a5,qe as a6,lt as a7,Qe as a8,et as a9,tt as aa,nt as ab,at as ac,st as ad,pt as ae,dt as af,ut as ag,c as b,h as c,b as d,A as e,S as f,g,w as h,P as i,R as j,V as k,f as l,_ as m,$ as n,B as o,H as p,Y as q,j as r,K as s,Z as t,X as u,q as v,z as w,Q as x,te as y,ne as z};
|
|
29
|
+
//# sourceMappingURL=index-35b5803e.js.map
|