@cowprotocol/cow-sdk 2.3.1 → 3.0.0-rc.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/common/chains.d.ts +4 -0
- package/dist/common/configs.d.ts +48 -0
- package/dist/common/consts.d.ts +17 -0
- package/dist/composable/conditionalorder.d.ts +160 -0
- package/dist/composable/extensible.d.ts +6 -0
- package/dist/composable/generated/ComposableCoW.d.ts +340 -0
- package/dist/composable/generated/ExtensibleFallbackHandler.d.ts +282 -0
- package/dist/composable/generated/TWAP.d.ts +141 -0
- package/dist/composable/generated/common.d.ts +21 -0
- package/dist/composable/generated/factories/ComposableCoW__factory.d.ts +475 -0
- package/dist/composable/generated/factories/ExtensibleFallbackHandler__factory.d.ts +389 -0
- package/dist/composable/generated/factories/TWAP__factory.d.ts +260 -0
- package/dist/composable/generated/factories/index.d.ts +3 -0
- package/dist/composable/generated/index.d.ts +7 -0
- package/dist/composable/index.d.ts +4 -0
- package/dist/composable/multiplexer.d.ts +221 -0
- package/dist/composable/types/index.d.ts +1 -0
- package/dist/composable/types/twap.d.ts +114 -0
- package/dist/index-856e1ad2.js +29 -0
- package/dist/index-856e1ad2.js.map +1 -0
- package/dist/index.d.ts +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 +4 -4
- package/dist/index.module.js.map +1 -1
- package/dist/order-book/api.d.ts +206 -12
- package/dist/order-book/generated/index.d.ts +2 -1
- package/dist/order-book/generated/models/AppData.d.ts +7 -0
- package/dist/order-book/generated/models/AppDataHash.d.ts +2 -0
- package/dist/order-book/generated/models/AppDataObject.d.ts +7 -0
- package/dist/order-book/generated/models/OrderCreation.d.ts +4 -3
- package/dist/order-book/generated/models/OrderQuoteRequest.d.ts +16 -1
- package/dist/order-book/request.d.ts +33 -0
- package/dist/order-book/transformOrder.d.ts +7 -1
- package/dist/order-book/types.d.ts +3 -0
- package/dist/order-signing/orderSigningUtils.d.ts +79 -2
- package/dist/order-signing/types.d.ts +28 -1
- package/dist/order-signing/utils.d.ts +17 -5
- package/dist/package.json +15 -6
- package/dist/subgraph/api.d.ts +54 -0
- package/dist/subgraph/queries.d.ts +11 -0
- package/dist/utils-16a884bc.js +2 -0
- package/dist/utils-16a884bc.js.map +1 -0
- package/dist/utils-3ea4a36c.js +2 -0
- package/dist/utils-3ea4a36c.js.map +1 -0
- package/dist/utils-6743154b.js +2 -0
- package/dist/utils-6743154b.js.map +1 -0
- package/package.json +15 -6
- package/dist/index-b3af985a.js +0 -29
- package/dist/index-b3af985a.js.map +0 -1
- package/dist/order-book/generated/models/AppDataDocument.d.ts +0 -12
- package/dist/order-book/transformError.d.ts +0 -6
- package/dist/utils-1129d544.js +0 -2
- package/dist/utils-1129d544.js.map +0 -1
- package/dist/utils-53748714.js +0 -2
- package/dist/utils-53748714.js.map +0 -1
- package/dist/utils-e73b1f14.js +0 -2
- package/dist/utils-e73b1f14.js.map +0 -1
|
@@ -0,0 +1,221 @@
|
|
|
1
|
+
import { providers } from 'ethers';
|
|
2
|
+
import { SupportedChainId } from '../common';
|
|
3
|
+
import { BaseConditionalOrder, ConditionalOrderParams } from './conditionalorder';
|
|
4
|
+
import { ComposableCoW, GPv2Order } from './generated/ComposableCoW';
|
|
5
|
+
export type Orders = Record<string, BaseConditionalOrder<any, any>>;
|
|
6
|
+
export declare enum ProofLocation {
|
|
7
|
+
PRIVATE = 0,
|
|
8
|
+
EMITTED = 1,
|
|
9
|
+
SWARM = 2,
|
|
10
|
+
WAKU = 3,
|
|
11
|
+
RESERVED = 4,
|
|
12
|
+
IPFS = 5
|
|
13
|
+
}
|
|
14
|
+
/**
|
|
15
|
+
* A factory and it's arguments that are called at transaction mining time to generate the context
|
|
16
|
+
* for a conditional order(s).
|
|
17
|
+
*
|
|
18
|
+
* This allows to support the case where conditional orders may want to *commence* validity at the
|
|
19
|
+
* time of transaction mining, like in the case of a `TWAP` executed by a DAO or `Safe` that takes
|
|
20
|
+
* a reasonable amount of time to aggregate signatures or collect votes.
|
|
21
|
+
*
|
|
22
|
+
* @remarks This is used in conjunction with `setRootWithContext` or `createWithContext`.
|
|
23
|
+
*/
|
|
24
|
+
export type ContextFactory = {
|
|
25
|
+
address: string;
|
|
26
|
+
factoryArgs?: {
|
|
27
|
+
args: any[];
|
|
28
|
+
argsType: string[];
|
|
29
|
+
};
|
|
30
|
+
};
|
|
31
|
+
/**
|
|
32
|
+
* A struct for a proof that can be used with `setRoot` and `setRootWithContext` on a
|
|
33
|
+
* ComposableCoW-enabled Safe.
|
|
34
|
+
*/
|
|
35
|
+
export type ProofStruct = {
|
|
36
|
+
location: ProofLocation;
|
|
37
|
+
data: string | '0x';
|
|
38
|
+
};
|
|
39
|
+
/**
|
|
40
|
+
* Payload for emitting a merkle root to a ComposableCoW-enabled Safe.
|
|
41
|
+
*
|
|
42
|
+
* If setting `ProofLocation.EMITTED`, this type should be used as the `data` in the `Proof` struct.
|
|
43
|
+
*/
|
|
44
|
+
export type PayloadLocationEmitted = {
|
|
45
|
+
proofs: ProofWithParams[];
|
|
46
|
+
};
|
|
47
|
+
/**
|
|
48
|
+
* A proof for a conditional order and it's parameters.
|
|
49
|
+
*/
|
|
50
|
+
export type ProofWithParams = {
|
|
51
|
+
proof: string[];
|
|
52
|
+
params: ConditionalOrderParams;
|
|
53
|
+
};
|
|
54
|
+
/**
|
|
55
|
+
* Multiplexer for conditional orders - using `ComposableCoW`!
|
|
56
|
+
*
|
|
57
|
+
* This class provides functionality to:
|
|
58
|
+
* - Generate a merkle tree of conditional orders
|
|
59
|
+
* - Generate proofs for all orders in the merkle tree
|
|
60
|
+
* - Save proofs, with the ability to omit / skip specific conditional orders
|
|
61
|
+
* - Support for passing an optional upload function to upload the proofs to a decentralized storage network
|
|
62
|
+
*/
|
|
63
|
+
export declare class Multiplexer {
|
|
64
|
+
static orderTypeRegistry: Record<string, new (...args: any[]) => BaseConditionalOrder<any, any>>;
|
|
65
|
+
chain: SupportedChainId;
|
|
66
|
+
location: ProofLocation;
|
|
67
|
+
private orders;
|
|
68
|
+
private tree?;
|
|
69
|
+
private ctx?;
|
|
70
|
+
/**
|
|
71
|
+
* @param chain The `chainId` for where we're using `ComposableCoW`.
|
|
72
|
+
* @param orders An optional array of conditional orders to initialize the merkle tree with.
|
|
73
|
+
* @param root An optional root to verify against.
|
|
74
|
+
* @param location The location of the proofs for the conditional orders.
|
|
75
|
+
*/
|
|
76
|
+
constructor(chain: SupportedChainId, orders?: Orders, root?: string, location?: ProofLocation);
|
|
77
|
+
/**
|
|
78
|
+
* Given a serialized multiplexer, create the multiplexer and rehydrate all conditional orders.
|
|
79
|
+
* Integrity of the multiplexer will be verified by generating the merkle tree and verifying
|
|
80
|
+
* the root.
|
|
81
|
+
*
|
|
82
|
+
* **NOTE**: Before using this method, you must register all conditional order types using `Multiplexer.registerOrderType`.
|
|
83
|
+
* @param s The serialized multiplexer.
|
|
84
|
+
* @returns The multiplexer with all conditional orders rehydrated.
|
|
85
|
+
* @throws If the multiplexer cannot be deserialized.
|
|
86
|
+
* @throws If the merkle tree cannot be generated.
|
|
87
|
+
* @throws If the merkle tree cannot be verified against the root.
|
|
88
|
+
*/
|
|
89
|
+
static fromJSON(s: string): Multiplexer;
|
|
90
|
+
/**
|
|
91
|
+
* Serialize the multiplexer to JSON.
|
|
92
|
+
*
|
|
93
|
+
* This will include all state necessary to reconstruct the multiplexer, including the root.
|
|
94
|
+
* @remarks This will **NOT** include the merkle tree.
|
|
95
|
+
* @returns The JSON representation of the multiplexer, including the root but excluding the merkle tree.
|
|
96
|
+
*/
|
|
97
|
+
toJSON(): string;
|
|
98
|
+
/**
|
|
99
|
+
* Add a conditional order to the merkle tree.
|
|
100
|
+
* @param order The order to add to the merkle tree.
|
|
101
|
+
*/
|
|
102
|
+
add<T, P>(order: BaseConditionalOrder<T, P>): void;
|
|
103
|
+
/**
|
|
104
|
+
* Remove a conditional order from the merkle tree.
|
|
105
|
+
* @param id The id of the `BaseConditionalOrder` to remove from the merkle tree.
|
|
106
|
+
*/
|
|
107
|
+
remove(id: string): void;
|
|
108
|
+
/**
|
|
109
|
+
* Update a given conditional order in the merkle tree.
|
|
110
|
+
* @param id The id of the `BaseConditionalOrder` to update.
|
|
111
|
+
* @param updater A function that takes the existing `BaseConditionalOrder` and context, returning an updated `BaseConditionalOrder`.
|
|
112
|
+
*/
|
|
113
|
+
update<T, P>(id: string, updater: (order: BaseConditionalOrder<T, P>, ctx?: string) => BaseConditionalOrder<T, P>): void;
|
|
114
|
+
/**
|
|
115
|
+
* Accessor for a given conditional order in the multiplexer.
|
|
116
|
+
* @param id The `id` of the `BaseConditionalOrder` to retrieve.
|
|
117
|
+
* @returns A `BaseConditionalOrder` with the given `id`.
|
|
118
|
+
*/
|
|
119
|
+
getById(id: string): BaseConditionalOrder<any, any>;
|
|
120
|
+
/**
|
|
121
|
+
* Accessor for a given conditional order in the multiplexer.
|
|
122
|
+
* @param i The index of the `BaseConditionalOrder` to retrieve.
|
|
123
|
+
* @returns A `BaseConditionalOrder` at the given index.
|
|
124
|
+
*/
|
|
125
|
+
getByIndex(i: number): BaseConditionalOrder<any, any>;
|
|
126
|
+
/**
|
|
127
|
+
* Get all the conditional order ids in the multiplexer.
|
|
128
|
+
*/
|
|
129
|
+
get orderIds(): string[];
|
|
130
|
+
get root(): string;
|
|
131
|
+
/**
|
|
132
|
+
* Retrieve the merkle tree of orders, or generate it if it doesn't exist.
|
|
133
|
+
*
|
|
134
|
+
* **CAUTION**: Developers of the SDK should prefer to use this method instead of generating the
|
|
135
|
+
* merkle tree themselves. This method makes use of caching to avoid generating the
|
|
136
|
+
* merkle tree needlessly.
|
|
137
|
+
* @throws If the merkle tree cannot be generated.
|
|
138
|
+
* @returns The merkle tree for the current set of conditional orders.
|
|
139
|
+
*/
|
|
140
|
+
private getOrGenerateTree;
|
|
141
|
+
/**
|
|
142
|
+
* The primary method for watch towers to use when deserializing the proofs and parameters for the conditional orders.
|
|
143
|
+
* @param s The serialized proofs with parameters for consumption by watchtowers / indexers.
|
|
144
|
+
* @returns The `ProofWithParams` array.
|
|
145
|
+
* @throws If the `ProofWithParams` array cannot be deserialized.
|
|
146
|
+
*/
|
|
147
|
+
static decodeFromJSON(s: string): ProofWithParams[];
|
|
148
|
+
/**
|
|
149
|
+
* The primary entry point for dapps integrating with `ComposableCoW` to generate the proofs and
|
|
150
|
+
* parameters for the conditional orders.
|
|
151
|
+
*
|
|
152
|
+
* After populating the multiplexer with conditional orders, this method can be used to generate
|
|
153
|
+
* the proofs and parameters for the conditional orders. The returned `ProofStruct` can then be
|
|
154
|
+
* used with `setRoot` or `setRootWithContext` on a `ComposableCoW`-enabled Safe.
|
|
155
|
+
*
|
|
156
|
+
* @param filter {@link getProofs}
|
|
157
|
+
* @parma locFn A function that takes the off-chain encoded input, and returns the `location`
|
|
158
|
+
* for the `ProofStruct`, and the `data` for the `ProofStruct`.
|
|
159
|
+
* @returns The ABI-encoded `ProofStruct` for `setRoot` and `setRootWithContext`.
|
|
160
|
+
*/
|
|
161
|
+
prepareProofStruct(location?: ProofLocation, filter?: (v: string[]) => boolean, uploader?: (offChainEncoded: string) => Promise<string>): Promise<ComposableCoW.ProofStruct>;
|
|
162
|
+
/**
|
|
163
|
+
* Poll a conditional order to see if it is tradeable.
|
|
164
|
+
* @param owner The owner of the conditional order.
|
|
165
|
+
* @param p The proof and parameters.
|
|
166
|
+
* @param chain Which chain to use for the ComposableCoW contract.
|
|
167
|
+
* @param provider An RPC provider for the chain.
|
|
168
|
+
* @param offChainInputFn A function, if provided, that will return the off-chain input for the conditional order.
|
|
169
|
+
* @throws If the conditional order is not tradeable.
|
|
170
|
+
* @returns The tradeable `GPv2Order.Data` struct and the `signature` for the conditional order.
|
|
171
|
+
*/
|
|
172
|
+
static poll(owner: string, p: ProofWithParams, chain: SupportedChainId, provider: providers.Provider, offChainInputFn?: (owner: string, params: ConditionalOrderParams) => Promise<string>): Promise<[GPv2Order.DataStructOutput, string]>;
|
|
173
|
+
/**
|
|
174
|
+
* The primary entry point for dumping the proofs and parameters for the conditional orders.
|
|
175
|
+
*
|
|
176
|
+
* This is to be used by watchtowers / indexers to store the proofs and parameters for the
|
|
177
|
+
* conditional orders off-chain. The encoding returned by this method may **NOT** contain all
|
|
178
|
+
* proofs and parameters, depending on the `filter` provided, and therefore should not be used
|
|
179
|
+
* to rehydrate the multiplexer from a user's perspective.
|
|
180
|
+
* @param filter {@link getProofs}
|
|
181
|
+
* @returns A JSON-encoded string of the proofs and parameters for the conditional orders.
|
|
182
|
+
*/
|
|
183
|
+
dumpProofs(filter?: (v: string[]) => boolean): string;
|
|
184
|
+
dumpProofsAndParams(filter?: (v: string[]) => boolean): ProofWithParams[];
|
|
185
|
+
/**
|
|
186
|
+
* Get the proofs with parameters for the conditional orders in the merkle tree.
|
|
187
|
+
* @param filter A function that takes a conditional order and returns a boolean indicating
|
|
188
|
+
* whether the order should be included in the proof.
|
|
189
|
+
* @returns An array of proofs and their order's parameters for the conditional orders in the
|
|
190
|
+
* merkle tree.
|
|
191
|
+
*/
|
|
192
|
+
private getProofs;
|
|
193
|
+
/**
|
|
194
|
+
* ABI-encode the proofs and parameters for the conditional orders in the merkle tree.
|
|
195
|
+
* @param filter {@link getProofs}
|
|
196
|
+
* @returns ABI-encoded `data` for the `ProofStruct`.
|
|
197
|
+
*/
|
|
198
|
+
private encodeToABI;
|
|
199
|
+
/**
|
|
200
|
+
* JSON-encode the proofs and parameters for the conditional orders in the merkle tree.
|
|
201
|
+
* @param filter {@link getProofs}
|
|
202
|
+
* @returns The JSON-encoded data for storage off-chain.
|
|
203
|
+
*/
|
|
204
|
+
private encodeToJSON;
|
|
205
|
+
/**
|
|
206
|
+
* A helper to reset the merkle tree.
|
|
207
|
+
*/
|
|
208
|
+
private reset;
|
|
209
|
+
/**
|
|
210
|
+
* Register a conditional order type with the multiplexer.
|
|
211
|
+
*
|
|
212
|
+
* **CAUTION**: This is required for using `Multiplexer.fromJSON` and `Multiplexer.toJSON`.
|
|
213
|
+
* @param orderType The order type to register.
|
|
214
|
+
* @param conditionalOrderClass The class to use for the given order type.
|
|
215
|
+
*/
|
|
216
|
+
static registerOrderType(orderType: string, conditionalOrderClass: new (...args: any[]) => BaseConditionalOrder<any, any>): void;
|
|
217
|
+
/**
|
|
218
|
+
* Reset the order type registry.
|
|
219
|
+
*/
|
|
220
|
+
static resetOrderTypeRegistry(): void;
|
|
221
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export * from './twap';
|
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
import { BigNumber } from 'ethers';
|
|
2
|
+
import { BaseConditionalOrder } from '../conditionalorder';
|
|
3
|
+
import { ContextFactory } from '../multiplexer';
|
|
4
|
+
export declare const TWAP_ADDRESS = "0x6cF1e9cA41f7611dEf408122793c358a3d11E5a5";
|
|
5
|
+
/**
|
|
6
|
+
* The address of the `CurrentBlockTimestampFactory` contract
|
|
7
|
+
*
|
|
8
|
+
* **NOTE**: This is used in the event that TWAP's have a `t0` of `0`.
|
|
9
|
+
*/
|
|
10
|
+
export declare const CURRENT_BLOCK_TIMESTAMP_FACTORY_ADDRESS = "0x52eD56Da04309Aca4c3FECC595298d80C2f16BAc";
|
|
11
|
+
export declare const MAX_UINT32: BigNumber;
|
|
12
|
+
export declare const MAX_FREQUENCY: BigNumber;
|
|
13
|
+
/**
|
|
14
|
+
* Parameters for a TWAP order, made a little more user-friendly for SDK users.
|
|
15
|
+
* @see {@link TWAPData} for the native struct.
|
|
16
|
+
*/
|
|
17
|
+
export type TWAPDataParams = Omit<TWAPData, 'partSellAmount' | 'minPartLimit'> & {
|
|
18
|
+
readonly sellAmount: BigNumber;
|
|
19
|
+
readonly buyAmount: BigNumber;
|
|
20
|
+
};
|
|
21
|
+
/**
|
|
22
|
+
* Parameters for a TWAP order, as expected by the contract's `staticInput`.
|
|
23
|
+
*/
|
|
24
|
+
export type TWAPData = {
|
|
25
|
+
readonly sellToken: string;
|
|
26
|
+
readonly buyToken: string;
|
|
27
|
+
readonly receiver: string;
|
|
28
|
+
readonly partSellAmount: BigNumber;
|
|
29
|
+
readonly minPartLimit: BigNumber;
|
|
30
|
+
readonly t0: BigNumber;
|
|
31
|
+
readonly n: BigNumber;
|
|
32
|
+
readonly t: BigNumber;
|
|
33
|
+
readonly span: BigNumber;
|
|
34
|
+
readonly appData: string;
|
|
35
|
+
};
|
|
36
|
+
/**
|
|
37
|
+
* `ComposableCoW` implementation of a TWAP order.
|
|
38
|
+
* @author mfw78 <mfw78@rndlabs.xyz>
|
|
39
|
+
*/
|
|
40
|
+
export declare class TWAP extends BaseConditionalOrder<TWAPData, TWAPDataParams> {
|
|
41
|
+
/**
|
|
42
|
+
* @see {@link BaseConditionalOrder.constructor}
|
|
43
|
+
* @throws If the TWAP order is invalid.
|
|
44
|
+
* @throws If the TWAP order is not ABI-encodable.
|
|
45
|
+
* @throws If the handler is not the TWAP address.
|
|
46
|
+
*/
|
|
47
|
+
constructor(handler: string, salt: string | undefined, staticInput: TWAPDataParams, hasOffChainInput?: boolean);
|
|
48
|
+
/**
|
|
49
|
+
* Create a TWAP order with sound defaults.
|
|
50
|
+
* @param staticInput The TWAP order parameters in a more user-friendly format.
|
|
51
|
+
* @returns An instance of the TWAP order.
|
|
52
|
+
*/
|
|
53
|
+
static default(staticInput: TWAPDataParams): BaseConditionalOrder<TWAPData, TWAPDataParams>;
|
|
54
|
+
/**
|
|
55
|
+
* Enforces that TWAPs will commence at the beginning of a block by use of the
|
|
56
|
+
* `CurrentBlockTimestampFactory` contract to provide the current block timestamp
|
|
57
|
+
* as the start time of the TWAP.
|
|
58
|
+
*/
|
|
59
|
+
get context(): ContextFactory | undefined;
|
|
60
|
+
/**
|
|
61
|
+
* @inheritdoc {@link BaseConditionalOrder.orderType}
|
|
62
|
+
*/
|
|
63
|
+
get orderType(): string;
|
|
64
|
+
/**
|
|
65
|
+
* Validate the TWAP order.
|
|
66
|
+
* @param data The TWAP order to validate.
|
|
67
|
+
* @returns Whether the TWAP order is valid.
|
|
68
|
+
* @throws If the TWAP order is invalid.
|
|
69
|
+
* @see {@link TWAPData} for the native struct.
|
|
70
|
+
*/
|
|
71
|
+
static isValid(data: TWAPDataParams): boolean;
|
|
72
|
+
/**
|
|
73
|
+
* Serialize the TWAP order into it's ABI-encoded form.
|
|
74
|
+
* @returns {string} The ABI-encoded TWAP order.
|
|
75
|
+
*/
|
|
76
|
+
serialize(): string;
|
|
77
|
+
/**
|
|
78
|
+
* Get the encoded static input for the TWAP order.
|
|
79
|
+
* @returns {string} The ABI-encoded TWAP order.
|
|
80
|
+
*/
|
|
81
|
+
encodeStaticInput(): string;
|
|
82
|
+
/**
|
|
83
|
+
* Deserialize a TWAP order from it's ABI-encoded form.
|
|
84
|
+
* @param {string} s ABI-encoded TWAP order to deserialize.
|
|
85
|
+
* @returns A deserialized TWAP order.
|
|
86
|
+
*/
|
|
87
|
+
static deserialize(s: string): TWAP;
|
|
88
|
+
/**
|
|
89
|
+
* Create a human-readable string representation of the TWAP order.
|
|
90
|
+
* @param {((address: string, amount: BigNumber) => string) | undefined} tokenFormatter An optional
|
|
91
|
+
* function that takes an address and an amount and returns a human-readable string.
|
|
92
|
+
* @returns {string} A human-readable string representation of the TWAP order.
|
|
93
|
+
*/
|
|
94
|
+
toString(tokenFormatter?: (address: string, amount: BigNumber) => string): string;
|
|
95
|
+
/**
|
|
96
|
+
* Transform parameters into a native struct.
|
|
97
|
+
* @param {TWAPDataParams} params As passed by the consumer of the API.
|
|
98
|
+
* @returns {TWAPData} A formatted struct as expected by the smart contract.
|
|
99
|
+
*/
|
|
100
|
+
transformParamsToData(params: TWAPDataParams): TWAPData;
|
|
101
|
+
/**
|
|
102
|
+
* Convert TWAP parts to total amounts.
|
|
103
|
+
* @param {TWAPData} o The TWAP order.
|
|
104
|
+
* @returns {object} The total sell amount and total minimum buy amount.
|
|
105
|
+
*/
|
|
106
|
+
private static partsToTotal;
|
|
107
|
+
/**
|
|
108
|
+
* Convert total amounts to TWAP parts.
|
|
109
|
+
* @param {TWAPDataParams} o The TWAP order parameters.
|
|
110
|
+
* @returns {object} The part sell amount and minimum part limit.
|
|
111
|
+
* @throws If the number of parts is less than 1.
|
|
112
|
+
*/
|
|
113
|
+
private static totalToPart;
|
|
114
|
+
}
|
|
@@ -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 a}from"graphql-request";import{utils as r,Contract as s,BigNumber as i,ethers as o,constants as d}from"ethers";import{StandardMerkleTree as p}from"@openzeppelin/merkle-tree";import{keccak256 as y}from"ethers/lib/utils";var c;!function(e){e[e.MAINNET=1]="MAINNET",e[e.GOERLI=5]="GOERLI",e[e.GNOSIS_CHAIN=100]="GNOSIS_CHAIN"}(c||(c={}));const u=["prod","staging"],l={env:"prod",chainId:c.MAINNET};class f extends Error{constructor(e,t){super(e),this.error_code=void 0,this.error_code=t}}const m="cow-sdk:",b="https://gnosis.mypinata.cloud/ipfs",T="https://api.pinata.cloud";function h(){return h=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var a in n)Object.prototype.hasOwnProperty.call(n,a)&&(e[a]=n[a])}return e},h.apply(this,arguments)}function E(e,t){if(null==e)return{};var n,a,r={},s=Object.keys(e);for(a=0;a<s.length;a++)t.indexOf(n=s[a])>=0||(r[n]=e[n]);return 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}'),A="0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE",O="0x2f55e8b20D0B9FEFA187AA7d00B6Cbe563605bF5",S="0xfdaFc9d1902f4e0b84f65F49f244b32b31013b74",g=[c.MAINNET,c.GOERLI,c.GNOSIS_CHAIN],v=g.reduce((e,t)=>h({},e,{[t]:I[t].address}),{}),w=g.reduce((e,t)=>h({},e,{[t]:O}),{}),N=g.reduce((e,t)=>h({},e,{[t]:S}),{});function D(e){return function(e){const{ethflowData:t}=e;if(!t)return e;const{userValidTo:n}=t;return h({},e,{validTo:n,owner:e.onchainUser||e.owner,sellToken:A})}(function(e){const{executedFeeAmount:t,executedSurplusFee:n}=e;return h({},e,{totalFee:null!=n?n:t})}(e))}class C 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 x=[408,425,429,500,502,503,504],_={numOfAttempts:10,maxDelay:Infinity,jitter:"none",retry:e=>!(e instanceof C)||x.includes(e.response.status)},R={tokensPerInterval:5,interval:"second"},P=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 U(e,{path:n,query:a,method:r,body:s},i,o){const d=`${e}${n}${a?"?"+a:""}`,p={method:r,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(d,p),t=await P(e);return e.status>=200&&e.status<300?t:Promise.reject(new C(e,t))},o)}const L={[c.MAINNET]:"https://api.cow.fi/mainnet",[c.GNOSIS_CHAIN]:"https://api.cow.fi/xdai",[c.GOERLI]:"https://api.cow.fi/goerli"},F={[c.MAINNET]:"https://barn.api.cow.fi/mainnet",[c.GNOSIS_CHAIN]:"https://barn.api.cow.fi/xdai",[c.GOERLI]:"https://barn.api.cow.fi/goerli"};function M(e){return Object.keys(e).reduce((t,n)=>{const a=e[n];return void 0!==a&&(t[n]=a),t},{})}class G{constructor(t={}){this.context=void 0,this.rateLimiter=void 0,this.context=h({},l,t),this.rateLimiter=new e(t.limiterOpts||R)}getVersion(e={}){return this.fetch({path:"/api/v1/version",method:"GET"},e)}getTrades(e,t={}){if(e.owner&&e.orderUid)return Promise.reject(new f("Cannot specify both owner and orderId"));if(!e.owner&&!e.orderUid)return Promise.reject(new f("Must specify either owner or orderId"));const n=new URLSearchParams(M(e));return this.fetch({path:"/api/v1/trades",method:"GET",query:n},t)}getOrders({owner:e,offset:t=0,limit:n=1e3},a={}){const r=new URLSearchParams(M({offset:t.toString(),limit:n.toString()}));return this.fetch({path:`/api/v1/account/${e}/orders`,method:"GET",query:r},a).then(e=>e.map(D))}getTxOrders(e,t={}){return this.fetch({path:`/api/v1/transactions/${e}/orders`,method:"GET"},t).then(e=>e.map(D))}getOrder(e,t={}){return this.fetch({path:`/api/v1/orders/${e}`,method:"GET"},t).then(e=>D(e))}getOrderMultiEnv(e,t={}){const{env:n}=this.getContextWithOverride(t),a=u.filter(e=>e!==n);let r=0;const s=n=>{const i=a[r];return n instanceof C&&404===n.response.status&&i?(r++,this.getOrder(e,h({},t,{env:i})).catch(s)):Promise.reject(n)};return this.getOrder(e,h({},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:a}=this.getContextWithOverride(t);return this.getApiBaseUrls(a)[n]+`/api/v1/orders/${e}`}getContextWithOverride(e={}){return h({},this.context,e)}getApiBaseUrls(e){return this.context.baseUrls?this.context.baseUrls:"prod"===e?L:F}fetch(e,t={}){const{chainId:n,env:a}=this.getContextWithOverride(t);return U(this.getApiBaseUrls(a)[n],e,this.rateLimiter,this.context.backoffOpts||_)}}var V,k,B,H,$,W,j,q,Y,J,K,z,Z,Q,X;!function(e){e.ERC20="erc20",e.INTERNAL="internal"}(V||(V={})),function(e){e.EIP712="eip712",e.ETHSIGN="ethsign"}(k||(k={})),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"}(B||(B={})),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"}($||($={})),function(e){e.MARKET="market",e.LIMIT="limit",e.LIQUIDITY="liquidity"}(W||(W={})),function(e){e.BUY="buy",e.SELL="sell"}(j||(j={})),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.INVALID_EIP1271SIGNATURE="InvalidEip1271Signature",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",t.INVALID_APP_DATA="InvalidAppData",t.APP_DATA_HASH_MISMATCH="AppDataHashMismatch"}(q||(q={})),function(e){e.BUY="buy"}(Y||(Y={})),function(e){e.SELL="sell"}(J||(J={})),function(e){e.PRESIGNATURE_PENDING="presignaturePending",e.OPEN="open",e.FULFILLED="fulfilled",e.CANCELLED="cancelled",e.EXPIRED="expired"}(K||(K={})),function(e){e.FAST="fast",e.OPTIMAL="optimal",e.VERIFIED="verified"}(z||(z={})),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"}(Z||(Z={})),function(e){e.ERC20="erc20",e.INTERNAL="internal",e.EXTERNAL="external"}(Q||(Q={})),function(e){e.EIP712="eip712",e.ETHSIGN="ethsign",e.PRESIGN="presign",e.EIP1271="eip1271"}(X||(X={}));let ee,te,ne,ae=e=>e;const re=n(ee||(ee=ae`
|
|
2
|
+
query Totals {
|
|
3
|
+
totals {
|
|
4
|
+
tokens
|
|
5
|
+
orders
|
|
6
|
+
traders
|
|
7
|
+
settlements
|
|
8
|
+
volumeUsd
|
|
9
|
+
volumeEth
|
|
10
|
+
feesUsd
|
|
11
|
+
feesEth
|
|
12
|
+
}
|
|
13
|
+
}
|
|
14
|
+
`)),se=n(te||(te=ae`
|
|
15
|
+
query LastDaysVolume($days: Int!) {
|
|
16
|
+
dailyTotals(orderBy: timestamp, orderDirection: desc, first: $days) {
|
|
17
|
+
timestamp
|
|
18
|
+
volumeUsd
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
`)),ie=n(ne||(ne=ae`
|
|
22
|
+
query LastHoursVolume($hours: Int!) {
|
|
23
|
+
hourlyTotals(orderBy: timestamp, orderDirection: desc, first: $hours) {
|
|
24
|
+
timestamp
|
|
25
|
+
volumeUsd
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
`)),oe="https://api.thegraph.com/subgraphs/name/cowprotocol",de={[c.MAINNET]:oe+"/cow",[c.GNOSIS_CHAIN]:oe+"/cow-gc",[c.GOERLI]:oe+"/cow-goerli"},pe={[c.MAINNET]:oe+"/cow-staging",[c.GNOSIS_CHAIN]:oe+"/cow-gc-staging",[c.GOERLI]:""};class ye{constructor(e={}){this.API_NAME="CoW Protocol Subgraph",this.context=void 0,this.context=h({},l,e)}async getTotals(e={}){return(await this.runQuery(re,void 0,e)).totals[0]}async getLastDaysVolume(e,t={}){return this.runQuery(se,{days:e},t)}async getLastHoursVolume(e,t={}){return this.runQuery(ie,{hours:e},t)}async runQuery(e,t=undefined,n={}){const{chainId:r,env:s}=this.getContextWithOverride(n),i=this.getEnvConfigs(s)[r];try{return await a(i,e,t)}catch(n){throw console.error(`[subgraph:${this.API_NAME}]`,n),new f(`Error running query: ${e}. Variables: ${JSON.stringify(t)}. API: ${i}. Inner Error: ${n}`)}}getContextWithOverride(e={}){return h({},this.context,e)}getEnvConfigs(e){return this.context.baseUrls?this.context.baseUrls:"prod"===e?de:pe}}const ce=()=>import("./utils-16a884bc.js");class ue{static async signOrder(e,t,n){const{signOrder:a}=await ce();return a(e,t,n)}static async signOrderCancellation(e,t,n){const{signOrderCancellation:a}=await ce();return a(e,t,n)}static async signOrderCancellations(e,t,n){const{signOrderCancellations:a}=await ce();return a(e,t,n)}static async getDomain(e){const{getDomain:t}=await ce();return t(e)}static async getDomainSeparator(e){const{getDomain:t}=await ce(),{_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"}]}}}const le=[{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 fe{static createInterface(){return new r.Interface(le)}static connect(e,t){return new s(e,le,t)}}fe.abi=le;const me=[{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 be{static createInterface(){return new r.Interface(me)}static connect(e,t){return new s(e,me,t)}}function Te(e,t){return e===w[t]}function he(e,t){return e===N[t]}async function Ee(e,t,n,a){const r=be.connect(w[n],a);return await r.callStatic.domainVerifiers(e,t)}function Ie(e,t){return be.createInterface().encodeFunctionData("setDomainVerifier",[e,t])}be.abi=me;const Ae=["orderType"],Oe=["address","bytes32","bytes"],Se=["tuple(bytes32[] proof, tuple(address handler, bytes32 salt, bytes staticInput) params)[]"];var ge;!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"}(ge||(ge={}));class ve{constructor(e,t,n,a=ge.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=a,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(!ve.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:a,location:r}=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 a=t[n],{orderType:r}=a,s=E(a,Ae);if(!ve.orderTypeRegistry.hasOwnProperty(r))throw new Error(`Unknown order type: ${r}`);{const t=ve.orderTypeRegistry[r],a=Object.values(s);e[n]=new t(...a)}}return e}return"object"==typeof t&&null!==t&&t.hasOwnProperty("type")&&t.hasOwnProperty("hex")&&"BigNumber"===t.type?i.from(t):t}),s=new ve(t,n,a);return s.location=r,s}toJSON(){const e=this.getOrGenerateTree().root;return JSON.stringify(h({},this,{root:e}),(e,t)=>{if("tree"!==e)return"object"==typeof t&&null!==t&&"orderType"in t?h({},t,{orderType:t.orderType}):t})}add(e){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=p.of(Object.values(this.orders).map(e=>[...Object.values(e.leaf)]),Oe)),this.tree}static decodeFromJSON(e){return JSON.parse(e)}async prepareProofStruct(e=this.location,t,n){var a=this;return await async function(){switch(e){case ge.PRIVATE:return"0x";case ge.EMITTED:return a.encodeToABI(t);case ge.SWARM:case ge.WAKU:case ge.IPFS:if(!n)throw new Error("Must provide an uploader function");try{return await n(a.encodeToJSON(t))}catch(t){throw new Error(`Error uploading to decentralized storage ${e}: ${t}`)}default:throw new Error("Unsupported location")}}().then(t=>{try{return r.hexlify(r.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,a,r){const s=fe.connect(N[n],a),i=r?await r(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 r.defaultAbiCoder.encode(Se,[this.getProofs(e)])}encodeToJSON(e){return JSON.stringify(this.getProofs(e))}reset(){this.tree=void 0}static registerOrderType(e,t){ve.orderTypeRegistry[e]=t}static resetOrderTypeRegistry(){ve.orderTypeRegistry={}}}ve.orderTypeRegistry={};const we=["tuple(address handler, bytes32 salt, bytes staticInput)"];class Ne{constructor(e,t=y(o.utils.randomBytes(32)),n,a=!1){if(this.handler=void 0,this.salt=void 0,this.staticInput=void 0,this.hasOffChainInput=void 0,!o.utils.isAddress(e))throw new Error(`Invalid handler: ${e}`);if(!o.utils.isHexString(t)||32!==o.utils.hexDataLength(t))throw new Error(`Invalid salt: ${t}`);this.handler=e,this.salt=t,this.staticInput=this.transformParamsToData(n),this.hasOffChainInput=a}get context(){}get createCalldata(){const e=this.context,t=fe.createInterface(),n={handler:this.handler,salt:this.salt,staticInput:this.encodeStaticInput()};if(e){const a=e.factoryArgs?r.defaultAbiCoder.encode(e.factoryArgs.argsType,e.factoryArgs.args):"0x";return t.encodeFunctionData("createWithContext",[n,e.address,a,!0])}return t.encodeFunctionData("create",[n,!0])}get removeCalldata(){return fe.createInterface().encodeFunctionData("remove",[this.id])}get id(){return r.keccak256(this.serialize())}get leaf(){return{handler:this.handler,salt:this.salt,staticInput:this.encodeStaticInput()}}static leafToId(e){return r.keccak256(Ne.encodeParams(e))}get offChainInput(){return"0x"}static isValidAbi(e,t){try{o.utils.defaultAbiCoder.encode(e,t)}catch(e){return!1}return!0}encodeStaticInputHelper(e,t){try{return r.defaultAbiCoder.encode(e,[t])}catch(e){throw new Error("SerializationFailed")}}transformParamsToData(e){return e}static encodeParams(e){try{return r.defaultAbiCoder.encode(we,[e])}catch(e){throw new Error("SerializationFailed")}}static decodeParams(e){try{return r.defaultAbiCoder.decode(we,e)[0]}catch(e){throw new Error("DeserializationFailed")}}static deserializeHelper(e,t,n,a){try{const{handler:s,salt:i,staticInput:o}=Ne.decodeParams(e);if(s!=t)throw new Error("HandlerMismatch");const[d]=r.defaultAbiCoder.decode(n,o);return a(d,i)}catch(e){throw"HandlerMismatch"===e.message?e:new Error("InvalidSerializedConditionalOrder")}}}const De="0x6cF1e9cA41f7611dEf408122793c358a3d11E5a5",Ce="0x52eD56Da04309Aca4c3FECC595298d80C2f16BAc",xe=i.from(2).pow(32).sub(1),_e=i.from(31536e3),Re=["tuple(address sellToken, address buyToken, address receiver, uint256 partSellAmount, uint256 minPartLimit, uint256 t0, uint256 n, uint256 t, uint256 span, bytes32 appData)"];class Pe extends Ne{constructor(e,t=r.keccak256(o.utils.randomBytes(32)),n,a=!1){if(e!==De)throw new Error("InvalidHandler");if(Pe.isValid(n),super(De,t,n,a),!Pe.isValidAbi(Re,[this.staticInput]))throw new Error("InvalidData")}static default(e){return new Pe(De,void 0,e)}get context(){return this.staticInput.t0.gt(0)?super.context:{address:Ce,factoryArgs:void 0}}get orderType(){return"TWAP"}static isValid(e){if(e.sellToken==e.buyToken)throw new Error("InvalidSameToken");if(e.sellToken==d.AddressZero||e.buyToken==d.AddressZero)throw new Error("InvalidToken");if(!e.sellAmount.gt(d.Zero))throw new Error("InvalidSellAmount");if(!e.buyAmount.gt(d.Zero))throw new Error("InvalidMinBuyAmount");if(!e.t0.gte(d.Zero)||!e.t0.lt(xe))throw new Error("InvalidStartTime");if(!e.n.gt(d.One)||!e.n.lte(xe))throw new Error("InvalidNumParts");if(!e.t.gt(d.Zero)||!e.t.lte(_e))throw new Error("InvalidFrequency");if(!e.span.lte(e.t))throw new Error("InvalidSpan");return!0}serialize(){return Ne.encodeParams(this.leaf)}encodeStaticInput(){return super.encodeStaticInputHelper(Re,this.staticInput)}static deserialize(e){return super.deserializeHelper(e,De,Re,(e,t)=>new Pe(De,t,h({},e,Pe.partsToTotal(e))))}toString(e){e=e||((e,t)=>`${e}@${t}`);const{sellAmount:t,buyAmount:n}=Pe.partsToTotal(this.staticInput);return`${this.orderType}: Sell total ${e(this.staticInput.sellToken,t)} for a minimum of ${e(this.staticInput.buyToken,n)} over ${this.staticInput.n} parts with a spacing of ${this.staticInput.t}s beginning at ${this.staticInput.t0.eq(0)?"time of mining":new Date(1e3*Number(this.staticInput.t0))}`}transformParamsToData(e){return h({},e,Pe.totalToPart(e))}static partsToTotal(e){return{sellAmount:e.partSellAmount.mul(e.n),buyAmount:e.minPartLimit.mul(e.n)}}static totalToPart(e){return{partSellAmount:e.sellAmount.div(e.n),minPartLimit:e.buyAmount.div(e.n)}}}export{Pe as $,g as A,A as B,f as C,l as D,k as E,B as F,de as G,pe as H,ye as I,ue as J,Te as K,he as L,Ee as M,Ie as N,L as O,z as P,ge as Q,Z as R,c as S,ve as T,we as U,Ne as V,De as W,Ce as X,xe as Y,_e as Z,h as _,v as a,u as b,b as c,T as d,O as e,S as f,w as g,N as h,F as i,G as j,V as k,m as l,H as m,$ as n,W as o,j as p,q,Y as r,J as s,K as t,Q as u,X as v,C as w,_ as x,R as y,U as z};
|
|
29
|
+
//# sourceMappingURL=index-856e1ad2.js.map
|