@cowprotocol/sdk-trading 0.2.6-beta.0 → 0.3.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 CHANGED
@@ -44,9 +44,20 @@ Main functions:
44
44
  - `postLimitOrder` - Create a limit order.
45
45
  - `getQuote` - Fetch a quote for a swap order.
46
46
 
47
+ Order Management:
48
+
49
+ - `getOrder` - Retrieve order details by UID.
50
+ - `offChainCancelOrder` - Cancel an order off-chain (soft cancel, free and fast).
51
+ - `onChainCancelOrder` - Cancel an order on-chain (hard cancel, requires gas).
52
+
53
+ Token Approval:
54
+
55
+ - `getCowProtocolAllowance` - Check current token allowance for CoW Protocol.
56
+ - `approveCowProtocol` - Approve CoW Protocol to spend tokens.
57
+
47
58
  Special cases:
48
59
 
49
- - 'setTraderParams' - In case if you work with different chains and need to switch between them in runtime.
60
+ - `setTraderParams` - In case if you work with different chains and need to switch between them in runtime.
50
61
  - `postSellNativeCurrencyOrder` - Sell blockchain native tokens (e.g., ETH on Ethereum).
51
62
  - `getPreSignTransaction` - Sign an order using a smart contract wallet.
52
63
 
@@ -75,6 +86,7 @@ const adapter = new ViemAdapter({
75
86
  chain: sepolia,
76
87
  transport: http('YOUR_RPC_URL')
77
88
  }),
89
+ // You also can set `walletClient` instead of `signer` using `useWalletClient` from wagmi
78
90
  signer: privateKeyToAccount('YOUR_PRIVATE_KEY' as `0x${string}`)
79
91
  })
80
92
 
@@ -104,63 +116,6 @@ const orderId = await sdk.postSwapOrder(parameters)
104
116
  console.log('Order created, id: ', orderId)
105
117
  ```
106
118
 
107
- ### Usage with Umbrella SDK
108
-
109
- ```typescript
110
- import { CowSdk, SupportedChainId, OrderKind, TradeParameters } from '@cowprotocol/cow-sdk'
111
- import { ViemAdapter } from '@cowprotocol/sdk-viem-adapter'
112
- import { createPublicClient, http, privateKeyToAccount } from 'viem'
113
- import { sepolia } from 'viem/chains'
114
-
115
- const adapter = new ViemAdapter({
116
- provider: createPublicClient({
117
- chain: sepolia,
118
- transport: http('YOUR_RPC_URL')
119
- }),
120
- signer: privateKeyToAccount('YOUR_PRIVATE_KEY' as `0x${string}`)
121
- })
122
-
123
- // Initialize the unified SDK
124
- const sdk = new CowSdk({
125
- chainId: SupportedChainId.SEPOLIA,
126
- adapter,
127
- tradingOptions: {
128
- traderParams: {
129
- appCode: 'YOUR_APP_CODE',
130
- },
131
- options: {
132
- chainId: SupportedChainId.SEPOLIA,
133
- },
134
- },
135
- })
136
-
137
- // Define trade parameters
138
- const parameters: TradeParameters = {
139
- kind: OrderKind.BUY,
140
- sellToken: '0xfff9976782d46cc05630d1f6ebab18b2324d6b14',
141
- sellTokenDecimals: 18,
142
- buyToken: '0x0625afb445c3b6b7b929342a04a22599fd5dbb59',
143
- buyTokenDecimals: 18,
144
- amount: '120000000000000000',
145
- }
146
-
147
- // Post the order
148
- const orderId = await sdk.trading.postSwapOrder(parameters)
149
- console.log('Order created, id: ', orderId)
150
-
151
- // Or you can just initialize the SDK and import the trading class in another file:
152
- // you don't necessarily need to use the trading from inside of CowSdk:
153
- //...
154
- const sdk = new CowSdk({
155
- chainId: SupportedChainId.SEPOLIA,
156
- adapter,
157
- })
158
- // Other file:
159
- import { TradingSdk } from '@cowprotocol/cow-sdk'
160
- // parameters without passing the adapter. the adapter will be controlled by the umbrella
161
- const trading = new TradingSdk(...)
162
- ```
163
-
164
119
  ### Options
165
120
 
166
121
  For detailed information about trading steps you can enable the SDK logging:
@@ -176,6 +131,7 @@ const adapter = new ViemAdapter({
176
131
  chain: sepolia,
177
132
  transport: http('YOUR_RPC_URL')
178
133
  }),
134
+ // You also can set `walletClient` instead of `signer` using `useWalletClient` from wagmi
179
135
  signer: privateKeyToAccount('YOUR_PRIVATE_KEY' as `0x${string}`)
180
136
  })
181
137
 
@@ -224,6 +180,7 @@ const adapter = new ViemAdapter({
224
180
  chain: sepolia,
225
181
  transport: http('YOUR_RPC_URL')
226
182
  }),
183
+ // You also can set `walletClient` instead of `signer` using `useWalletClient` from wagmi
227
184
  signer: privateKeyToAccount('YOUR_PRIVATE_KEY' as `0x${string}`)
228
185
  })
229
186
 
@@ -281,6 +238,7 @@ const adapter = new ViemAdapter({
281
238
  chain: sepolia,
282
239
  transport: http('YOUR_RPC_URL')
283
240
  }),
241
+ // You also can set `walletClient` instead of `signer` using `useWalletClient` from wagmi
284
242
  signer: privateKeyToAccount('YOUR_PRIVATE_KEY' as `0x${string}`)
285
243
  })
286
244
 
@@ -334,6 +292,7 @@ const adapter = new ViemAdapter({
334
292
  chain: sepolia,
335
293
  transport: http('YOUR_RPC_URL')
336
294
  }),
295
+ // You also can set `walletClient` instead of `signer` using `useWalletClient` from wagmi
337
296
  signer: privateKeyToAccount('YOUR_PRIVATE_KEY' as `0x${string}`)
338
297
  })
339
298
 
@@ -693,3 +652,199 @@ console.log('Order created, id: ', orderId)
693
652
  #### Limit order
694
653
 
695
654
  Same as for the swap order but without the `quoteRequest` parameter.
655
+
656
+ ## Order Management
657
+
658
+ The SDK provides methods to manage existing orders, including retrieving order details and canceling orders.
659
+
660
+ ### getOrder
661
+
662
+ Fetches details about an existing order by its UID.
663
+
664
+ **Parameters:**
665
+ - `orderUid` - The unique identifier of the order
666
+ - `chainId` - (Optional) Chain ID, uses trader params if not provided
667
+
668
+ **Returns:** `Promise<EnrichedOrder>` - Full order details including status, amounts, and metadata
669
+
670
+ #### Example
671
+
672
+ ```typescript
673
+ import { TradingSdk } from '@cowprotocol/sdk-trading'
674
+
675
+ const sdk = new TradingSdk({
676
+ chainId: SupportedChainId.MAINNET,
677
+ appCode: '<YOUR_APP_CODE>',
678
+ }, {}, adapter)
679
+
680
+ const orderUid = '0xd64389693b6cf89ad6c140a113b10df08073e5ef3063d05a02f3f42e1a42f0ad...'
681
+
682
+ const order = await sdk.getOrder({ orderUid })
683
+
684
+ console.log('Order status:', order.status)
685
+ console.log('Sell amount:', order.sellAmount)
686
+ console.log('Buy amount:', order.buyAmount)
687
+ ```
688
+
689
+ ### offChainCancelOrder
690
+
691
+ Cancels an order off-chain by sending a signed cancellation request to the order book API. This is a "soft cancel" that is faster and doesn't require gas, but requires order book support.
692
+
693
+ **Parameters:**
694
+ - `orderUid` - The unique identifier of the order to cancel
695
+ - `chainId` - (Optional) Chain ID, uses trader params if not provided
696
+ - `signer` - (Optional) Custom signer, uses trader params signer if not provided
697
+
698
+ **Returns:** `Promise<boolean>` - True if cancellation was successful
699
+
700
+ #### Example
701
+
702
+ ```typescript
703
+ import { TradingSdk } from '@cowprotocol/sdk-trading'
704
+
705
+ const sdk = new TradingSdk({
706
+ chainId: SupportedChainId.MAINNET,
707
+ appCode: '<YOUR_APP_CODE>',
708
+ }, {}, adapter)
709
+
710
+ const orderUid = '0xd64389693b6cf89ad6c140a113b10df08073e5ef3063d05a02f3f42e1a42f0ad...'
711
+
712
+ const success = await sdk.offChainCancelOrder({ orderUid })
713
+
714
+ if (success) {
715
+ console.log('Order cancelled successfully (off-chain)')
716
+ }
717
+ ```
718
+
719
+ ### onChainCancelOrder
720
+
721
+ Cancels an order on-chain by sending a transaction to invalidate it. This is a "hard cancel" that requires gas but guarantees cancellation. Automatically detects whether to use the Settlement contract or EthFlow contract based on order type.
722
+
723
+ **Parameters:**
724
+ - `orderUid` - The unique identifier of the order to cancel
725
+ - `chainId` - (Optional) Chain ID, uses trader params if not provided
726
+ - `signer` - (Optional) Custom signer, uses trader params signer if not provided
727
+
728
+ **Returns:** `Promise<string>` - Transaction hash of the cancellation
729
+
730
+ #### Example
731
+
732
+ ```typescript
733
+ import { TradingSdk } from '@cowprotocol/sdk-trading'
734
+
735
+ const sdk = new TradingSdk({
736
+ chainId: SupportedChainId.MAINNET,
737
+ appCode: '<YOUR_APP_CODE>',
738
+ }, {}, adapter)
739
+
740
+ const orderUid = '0xd64389693b6cf89ad6c140a113b10df08073e5ef3063d05a02f3f42e1a42f0ad...'
741
+
742
+ const txHash = await sdk.onChainCancelOrder({ orderUid })
743
+
744
+ console.log('Cancellation transaction:', txHash)
745
+ ```
746
+
747
+ ## Token Approval
748
+
749
+ Before trading ERC-20 tokens, you need to approve the CoW Protocol to spend them. The SDK provides methods to check and manage token approvals.
750
+
751
+ ### getCowProtocolAllowance
752
+
753
+ Checks the current allowance for the CoW Protocol Vault Relayer to spend an ERC-20 token.
754
+
755
+ **Parameters:**
756
+ - `tokenAddress` - The ERC-20 token contract address
757
+ - `owner` - The address of the token owner
758
+ - `chainId` - (Optional) Chain ID, uses trader params if not provided
759
+
760
+ **Returns:** `Promise<bigint>` - Current allowance amount
761
+
762
+ #### Example
763
+
764
+ ```typescript
765
+ import { TradingSdk } from '@cowprotocol/sdk-trading'
766
+
767
+ const sdk = new TradingSdk({
768
+ chainId: SupportedChainId.MAINNET,
769
+ appCode: '<YOUR_APP_CODE>',
770
+ }, {}, adapter)
771
+
772
+ const tokenAddress = '0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48' // USDC
773
+ const owner = '0x...' // Your wallet address
774
+
775
+ const allowance = await sdk.getCowProtocolAllowance({
776
+ tokenAddress,
777
+ owner,
778
+ })
779
+
780
+ console.log('Current allowance:', allowance.toString())
781
+ ```
782
+
783
+ ### approveCowProtocol
784
+
785
+ Approves the CoW Protocol Vault Relayer to spend a specified amount of an ERC-20 token. This creates an on-chain approval transaction.
786
+
787
+ **Parameters:**
788
+ - `tokenAddress` - The ERC-20 token contract address
789
+ - `amount` - The amount to approve (as bigint)
790
+ - `chainId` - (Optional) Chain ID, uses trader params if not provided
791
+ - `signer` - (Optional) Custom signer, uses trader params signer if not provided
792
+
793
+ **Returns:** `Promise<string>` - Transaction hash of the approval
794
+
795
+ #### Example
796
+
797
+ ```typescript
798
+ import { TradingSdk } from '@cowprotocol/sdk-trading'
799
+ import { parseUnits } from 'viem' // or ethers
800
+
801
+ const sdk = new TradingSdk({
802
+ chainId: SupportedChainId.MAINNET,
803
+ appCode: '<YOUR_APP_CODE>',
804
+ }, {}, adapter)
805
+
806
+ const tokenAddress = '0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48' // USDC
807
+ const amount = parseUnits('1000', 6) // 1000 USDC (6 decimals)
808
+
809
+ const txHash = await sdk.approveCowProtocol({
810
+ tokenAddress,
811
+ amount,
812
+ })
813
+
814
+ console.log('Approval transaction:', txHash)
815
+ ```
816
+
817
+ #### Smart Approval Flow
818
+
819
+ It's recommended to check the current allowance before approving to avoid unnecessary transactions:
820
+
821
+ ```typescript
822
+ import { TradingSdk } from '@cowprotocol/sdk-trading'
823
+ import { parseUnits } from 'viem'
824
+
825
+ const sdk = new TradingSdk({
826
+ chainId: SupportedChainId.MAINNET,
827
+ appCode: '<YOUR_APP_CODE>',
828
+ }, {}, adapter)
829
+
830
+ const tokenAddress = '0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48' // USDC
831
+ const owner = '0x...' // Your wallet address
832
+ const requiredAmount = parseUnits('1000', 6) // 1000 USDC
833
+
834
+ // Check current allowance
835
+ const currentAllowance = await sdk.getCowProtocolAllowance({
836
+ tokenAddress,
837
+ owner,
838
+ })
839
+
840
+ // Only approve if needed
841
+ if (currentAllowance < requiredAmount) {
842
+ const txHash = await sdk.approveCowProtocol({
843
+ tokenAddress,
844
+ amount: requiredAmount,
845
+ })
846
+ console.log('Approval transaction:', txHash)
847
+ } else {
848
+ console.log('Sufficient allowance already exists')
849
+ }
850
+ ```
package/dist/index.d.mts CHANGED
@@ -1,5 +1,5 @@
1
1
  import { cowAppDataLatestScheme, AppDataParams, LatestAppDataDocVersion } from '@cowprotocol/sdk-app-data';
2
- import { OrderKind, OrderParameters, TokenAmount, SigningScheme, OrderQuoteRequest, QuoteAmountsAndCosts, OrderQuoteResponse, AppData, AppDataHash, Signature, OrderBookApi } from '@cowprotocol/sdk-order-book';
2
+ import { OrderKind, OrderParameters, TokenAmount, SigningScheme, OrderQuoteRequest, QuoteAmountsAndCosts, OrderQuoteResponse, AppData, AppDataHash, Signature, OrderBookApi, EnrichedOrder } from '@cowprotocol/sdk-order-book';
3
3
  import { AccountAddress, SignerLike, AbstractSigner, Signer, AbstractProviderAdapter, EthFlowContract } from '@cowprotocol/sdk-common';
4
4
  import { UnsignedOrder } from '@cowprotocol/sdk-order-signing';
5
5
  import { CowEnv, SupportedChainId } from '@cowprotocol/sdk-config';
@@ -69,6 +69,16 @@ interface TraderParameters {
69
69
  type QuoterParameters = Omit<TraderParameters, 'signer'> & {
70
70
  account: AccountAddress;
71
71
  };
72
+ interface SlippageToleranceResponse {
73
+ slippageBps: number | null;
74
+ }
75
+ interface SlippageToleranceRequest {
76
+ chainId: SupportedChainId;
77
+ sellToken: OrderParameters['sellToken'];
78
+ buyToken: OrderParameters['buyToken'];
79
+ sellAmount?: bigint;
80
+ buyAmount?: bigint;
81
+ }
72
82
  /**
73
83
  * Trade type, assets, amounts, and optional parameters.
74
84
  */
@@ -108,6 +118,10 @@ interface SwapAdvancedSettings {
108
118
  appData?: AppDataParams;
109
119
  additionalParams?: PostTradeAdditionalParams;
110
120
  quoteSigner?: SignerLike;
121
+ /**
122
+ * An optional callback to use custom logic for slippage suggestion
123
+ */
124
+ getSlippageSuggestion?(request: SlippageToleranceRequest): Promise<SlippageToleranceResponse>;
111
125
  }
112
126
  interface LimitOrderAdvancedSettings {
113
127
  appData?: AppDataParams;
@@ -234,14 +248,15 @@ declare function getQuoteWithSigner(swapParameters: SwapParameters, advancedSett
234
248
 
235
249
  declare function postSellNativeCurrencyOrder(orderBookApi: OrderBookApi, appData: Pick<TradingAppDataInfo, 'fullAppData' | 'appDataKeccak256'>, _params: LimitTradeParametersFromQuote, additionalParams?: PostTradeAdditionalParams, paramSigner?: SignerLike): Promise<OrderPostingResult>;
236
250
 
237
- declare function getPreSignTransaction(signer: Signer, chainId: SupportedChainId, account: string, orderId: string): Promise<TradingTransactionParams>;
251
+ declare function getPreSignTransaction(signer: Signer, chainId: SupportedChainId, orderId: string): Promise<TradingTransactionParams>;
238
252
 
239
253
  type WithPartialTraderParams<T> = T & Partial<TraderParameters>;
254
+ type OrderTraderParams = WithPartialTraderParams<{
255
+ orderUid: string;
256
+ }>;
240
257
  interface TradingSdkOptions {
241
258
  enableLogging: boolean;
242
259
  orderBookApi: OrderBookApi;
243
- utmContent?: string;
244
- disableUtm?: boolean;
245
260
  }
246
261
  declare class TradingSdk {
247
262
  traderParams: Partial<TraderParameters>;
@@ -275,10 +290,56 @@ declare class TradingSdk {
275
290
  * ```
276
291
  */
277
292
  postSellNativeCurrencyOrder(params: WithPartialTraderParams<TradeParameters>, advancedSettings?: SwapAdvancedSettings): Promise<ReturnType<typeof postSellNativeCurrencyOrder>>;
278
- getPreSignTransaction(params: WithPartialTraderParams<{
279
- orderId: string;
280
- account: string;
281
- }>): ReturnType<typeof getPreSignTransaction>;
293
+ getPreSignTransaction(params: OrderTraderParams): ReturnType<typeof getPreSignTransaction>;
294
+ getOrder(params: OrderTraderParams): Promise<EnrichedOrder>;
295
+ offChainCancelOrder(params: OrderTraderParams): Promise<boolean>;
296
+ onChainCancelOrder(params: OrderTraderParams, _order?: EnrichedOrder): Promise<string>;
297
+ /**
298
+ * Checks the current allowance for the CoW Protocol Vault Relayer to spend an ERC-20 token.
299
+ *
300
+ * @param params - Parameters including token address and owner address
301
+ * @returns Promise resolving to the current allowance amount as a bigint
302
+ *
303
+ * @example
304
+ * ```typescript
305
+ * const params = {
306
+ * tokenAddress: '0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48', // USDC
307
+ * owner: '0x123...',
308
+ * chainId: 1,
309
+ * }
310
+ *
311
+ * const allowance = await sdk.getCowProtocolAllowance(params)
312
+ * console.log('Current allowance:', allowance.toString())
313
+ * ```
314
+ */
315
+ getCowProtocolAllowance(params: WithPartialTraderParams<{
316
+ tokenAddress: string;
317
+ owner: string;
318
+ }>): Promise<bigint>;
319
+ /**
320
+ * Approves the CoW Protocol Vault Relayer to spend a specified amount of an ERC-20 token.
321
+ * This method creates an on-chain approval transaction.
322
+ *
323
+ * @param params - Parameters including token address and amount to approve
324
+ * @returns Promise resolving to the transaction hash of the approval transaction
325
+ *
326
+ * @example
327
+ * ```typescript
328
+ * const params = {
329
+ * tokenAddress: '0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48', // USDC
330
+ * amount: '1000000000', // 1000 USDC (6 decimals)
331
+ * chainId: 1,
332
+ * }
333
+ *
334
+ * const txHash = await sdk.approveCowProtocol(params)
335
+ * console.log('Approval transaction:', txHash)
336
+ * ```
337
+ */
338
+ approveCowProtocol(params: WithPartialTraderParams<{
339
+ tokenAddress: string;
340
+ amount: bigint;
341
+ }>): Promise<string>;
342
+ private resolveOrderBookApi;
282
343
  private mergeParams;
283
344
  }
284
345
 
@@ -335,4 +396,4 @@ declare function getTradeParametersAfterQuote({ quoteParameters, sellToken, }: {
335
396
  sellToken: string;
336
397
  }): TradeParameters;
337
398
 
338
- export { type AppDataRootSchema, type BuildAppDataParams, type EthFlowOrderExistsCallback, type LimitOrderAdvancedSettings, type LimitOrderParameters, type LimitTradeParameters, type LimitTradeParametersFromQuote, ORDER_PRIMARY_TYPE, type OrderPostingResult, type OrderTypedData, type PostTradeAdditionalParams, type QuoteAndPost, type QuoteResults, type QuoteResultsSerialized, type QuoteResultsWithSigner, type QuoterParameters, type SigningStepManager, type SwapAdvancedSettings, type SwapParameters, type TradeBaseParameters, type TradeOptionalParameters, type TradeParameters, type TraderParameters, type TradingAppDataInfo, TradingSdk, type TradingSdkOptions, type TradingTransactionParams, type WithPartialTraderParams, buildAppData, calculateUniqueOrderId, generateAppDataFromDoc, getEthFlowContract, getEthFlowTransaction, getOrderToSign, getPartnerFeeBps, getPreSignTransaction, getQuote, getQuoteWithSigner, getTradeParametersAfterQuote, mapQuoteAmountsAndCosts, mergeAppDataDoc, postCoWProtocolTrade, postLimitOrder, postSellNativeCurrencyOrder, postSwapOrder, postSwapOrderFromQuote, suggestSlippageBps, swapParamsToLimitOrderParams };
399
+ export { type AppDataRootSchema, type BuildAppDataParams, type EthFlowOrderExistsCallback, type LimitOrderAdvancedSettings, type LimitOrderParameters, type LimitTradeParameters, type LimitTradeParametersFromQuote, ORDER_PRIMARY_TYPE, type OrderPostingResult, type OrderTraderParams, type OrderTypedData, type PostTradeAdditionalParams, type QuoteAndPost, type QuoteResults, type QuoteResultsSerialized, type QuoteResultsWithSigner, type QuoterParameters, type SigningStepManager, type SlippageToleranceRequest, type SlippageToleranceResponse, type SwapAdvancedSettings, type SwapParameters, type TradeBaseParameters, type TradeOptionalParameters, type TradeParameters, type TraderParameters, type TradingAppDataInfo, TradingSdk, type TradingSdkOptions, type TradingTransactionParams, type WithPartialTraderParams, buildAppData, calculateUniqueOrderId, generateAppDataFromDoc, getEthFlowContract, getEthFlowTransaction, getOrderToSign, getPartnerFeeBps, getPreSignTransaction, getQuote, getQuoteWithSigner, getTradeParametersAfterQuote, mapQuoteAmountsAndCosts, mergeAppDataDoc, postCoWProtocolTrade, postLimitOrder, postSellNativeCurrencyOrder, postSwapOrder, postSwapOrderFromQuote, suggestSlippageBps, swapParamsToLimitOrderParams };
package/dist/index.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import { cowAppDataLatestScheme, AppDataParams, LatestAppDataDocVersion } from '@cowprotocol/sdk-app-data';
2
- import { OrderKind, OrderParameters, TokenAmount, SigningScheme, OrderQuoteRequest, QuoteAmountsAndCosts, OrderQuoteResponse, AppData, AppDataHash, Signature, OrderBookApi } from '@cowprotocol/sdk-order-book';
2
+ import { OrderKind, OrderParameters, TokenAmount, SigningScheme, OrderQuoteRequest, QuoteAmountsAndCosts, OrderQuoteResponse, AppData, AppDataHash, Signature, OrderBookApi, EnrichedOrder } from '@cowprotocol/sdk-order-book';
3
3
  import { AccountAddress, SignerLike, AbstractSigner, Signer, AbstractProviderAdapter, EthFlowContract } from '@cowprotocol/sdk-common';
4
4
  import { UnsignedOrder } from '@cowprotocol/sdk-order-signing';
5
5
  import { CowEnv, SupportedChainId } from '@cowprotocol/sdk-config';
@@ -69,6 +69,16 @@ interface TraderParameters {
69
69
  type QuoterParameters = Omit<TraderParameters, 'signer'> & {
70
70
  account: AccountAddress;
71
71
  };
72
+ interface SlippageToleranceResponse {
73
+ slippageBps: number | null;
74
+ }
75
+ interface SlippageToleranceRequest {
76
+ chainId: SupportedChainId;
77
+ sellToken: OrderParameters['sellToken'];
78
+ buyToken: OrderParameters['buyToken'];
79
+ sellAmount?: bigint;
80
+ buyAmount?: bigint;
81
+ }
72
82
  /**
73
83
  * Trade type, assets, amounts, and optional parameters.
74
84
  */
@@ -108,6 +118,10 @@ interface SwapAdvancedSettings {
108
118
  appData?: AppDataParams;
109
119
  additionalParams?: PostTradeAdditionalParams;
110
120
  quoteSigner?: SignerLike;
121
+ /**
122
+ * An optional callback to use custom logic for slippage suggestion
123
+ */
124
+ getSlippageSuggestion?(request: SlippageToleranceRequest): Promise<SlippageToleranceResponse>;
111
125
  }
112
126
  interface LimitOrderAdvancedSettings {
113
127
  appData?: AppDataParams;
@@ -234,14 +248,15 @@ declare function getQuoteWithSigner(swapParameters: SwapParameters, advancedSett
234
248
 
235
249
  declare function postSellNativeCurrencyOrder(orderBookApi: OrderBookApi, appData: Pick<TradingAppDataInfo, 'fullAppData' | 'appDataKeccak256'>, _params: LimitTradeParametersFromQuote, additionalParams?: PostTradeAdditionalParams, paramSigner?: SignerLike): Promise<OrderPostingResult>;
236
250
 
237
- declare function getPreSignTransaction(signer: Signer, chainId: SupportedChainId, account: string, orderId: string): Promise<TradingTransactionParams>;
251
+ declare function getPreSignTransaction(signer: Signer, chainId: SupportedChainId, orderId: string): Promise<TradingTransactionParams>;
238
252
 
239
253
  type WithPartialTraderParams<T> = T & Partial<TraderParameters>;
254
+ type OrderTraderParams = WithPartialTraderParams<{
255
+ orderUid: string;
256
+ }>;
240
257
  interface TradingSdkOptions {
241
258
  enableLogging: boolean;
242
259
  orderBookApi: OrderBookApi;
243
- utmContent?: string;
244
- disableUtm?: boolean;
245
260
  }
246
261
  declare class TradingSdk {
247
262
  traderParams: Partial<TraderParameters>;
@@ -275,10 +290,56 @@ declare class TradingSdk {
275
290
  * ```
276
291
  */
277
292
  postSellNativeCurrencyOrder(params: WithPartialTraderParams<TradeParameters>, advancedSettings?: SwapAdvancedSettings): Promise<ReturnType<typeof postSellNativeCurrencyOrder>>;
278
- getPreSignTransaction(params: WithPartialTraderParams<{
279
- orderId: string;
280
- account: string;
281
- }>): ReturnType<typeof getPreSignTransaction>;
293
+ getPreSignTransaction(params: OrderTraderParams): ReturnType<typeof getPreSignTransaction>;
294
+ getOrder(params: OrderTraderParams): Promise<EnrichedOrder>;
295
+ offChainCancelOrder(params: OrderTraderParams): Promise<boolean>;
296
+ onChainCancelOrder(params: OrderTraderParams, _order?: EnrichedOrder): Promise<string>;
297
+ /**
298
+ * Checks the current allowance for the CoW Protocol Vault Relayer to spend an ERC-20 token.
299
+ *
300
+ * @param params - Parameters including token address and owner address
301
+ * @returns Promise resolving to the current allowance amount as a bigint
302
+ *
303
+ * @example
304
+ * ```typescript
305
+ * const params = {
306
+ * tokenAddress: '0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48', // USDC
307
+ * owner: '0x123...',
308
+ * chainId: 1,
309
+ * }
310
+ *
311
+ * const allowance = await sdk.getCowProtocolAllowance(params)
312
+ * console.log('Current allowance:', allowance.toString())
313
+ * ```
314
+ */
315
+ getCowProtocolAllowance(params: WithPartialTraderParams<{
316
+ tokenAddress: string;
317
+ owner: string;
318
+ }>): Promise<bigint>;
319
+ /**
320
+ * Approves the CoW Protocol Vault Relayer to spend a specified amount of an ERC-20 token.
321
+ * This method creates an on-chain approval transaction.
322
+ *
323
+ * @param params - Parameters including token address and amount to approve
324
+ * @returns Promise resolving to the transaction hash of the approval transaction
325
+ *
326
+ * @example
327
+ * ```typescript
328
+ * const params = {
329
+ * tokenAddress: '0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48', // USDC
330
+ * amount: '1000000000', // 1000 USDC (6 decimals)
331
+ * chainId: 1,
332
+ * }
333
+ *
334
+ * const txHash = await sdk.approveCowProtocol(params)
335
+ * console.log('Approval transaction:', txHash)
336
+ * ```
337
+ */
338
+ approveCowProtocol(params: WithPartialTraderParams<{
339
+ tokenAddress: string;
340
+ amount: bigint;
341
+ }>): Promise<string>;
342
+ private resolveOrderBookApi;
282
343
  private mergeParams;
283
344
  }
284
345
 
@@ -335,4 +396,4 @@ declare function getTradeParametersAfterQuote({ quoteParameters, sellToken, }: {
335
396
  sellToken: string;
336
397
  }): TradeParameters;
337
398
 
338
- export { type AppDataRootSchema, type BuildAppDataParams, type EthFlowOrderExistsCallback, type LimitOrderAdvancedSettings, type LimitOrderParameters, type LimitTradeParameters, type LimitTradeParametersFromQuote, ORDER_PRIMARY_TYPE, type OrderPostingResult, type OrderTypedData, type PostTradeAdditionalParams, type QuoteAndPost, type QuoteResults, type QuoteResultsSerialized, type QuoteResultsWithSigner, type QuoterParameters, type SigningStepManager, type SwapAdvancedSettings, type SwapParameters, type TradeBaseParameters, type TradeOptionalParameters, type TradeParameters, type TraderParameters, type TradingAppDataInfo, TradingSdk, type TradingSdkOptions, type TradingTransactionParams, type WithPartialTraderParams, buildAppData, calculateUniqueOrderId, generateAppDataFromDoc, getEthFlowContract, getEthFlowTransaction, getOrderToSign, getPartnerFeeBps, getPreSignTransaction, getQuote, getQuoteWithSigner, getTradeParametersAfterQuote, mapQuoteAmountsAndCosts, mergeAppDataDoc, postCoWProtocolTrade, postLimitOrder, postSellNativeCurrencyOrder, postSwapOrder, postSwapOrderFromQuote, suggestSlippageBps, swapParamsToLimitOrderParams };
399
+ export { type AppDataRootSchema, type BuildAppDataParams, type EthFlowOrderExistsCallback, type LimitOrderAdvancedSettings, type LimitOrderParameters, type LimitTradeParameters, type LimitTradeParametersFromQuote, ORDER_PRIMARY_TYPE, type OrderPostingResult, type OrderTraderParams, type OrderTypedData, type PostTradeAdditionalParams, type QuoteAndPost, type QuoteResults, type QuoteResultsSerialized, type QuoteResultsWithSigner, type QuoterParameters, type SigningStepManager, type SlippageToleranceRequest, type SlippageToleranceResponse, type SwapAdvancedSettings, type SwapParameters, type TradeBaseParameters, type TradeOptionalParameters, type TradeParameters, type TraderParameters, type TradingAppDataInfo, TradingSdk, type TradingSdkOptions, type TradingTransactionParams, type WithPartialTraderParams, buildAppData, calculateUniqueOrderId, generateAppDataFromDoc, getEthFlowContract, getEthFlowTransaction, getOrderToSign, getPartnerFeeBps, getPreSignTransaction, getQuote, getQuoteWithSigner, getTradeParametersAfterQuote, mapQuoteAmountsAndCosts, mergeAppDataDoc, postCoWProtocolTrade, postLimitOrder, postSellNativeCurrencyOrder, postSwapOrder, postSwapOrderFromQuote, suggestSlippageBps, swapParamsToLimitOrderParams };