@cowprotocol/sdk-trading 0.3.1-beta.0 → 0.3.1
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 +208 -1
- package/dist/index.d.mts +70 -7
- package/dist/index.d.ts +70 -7
- package/dist/index.js +342 -68
- package/dist/index.mjs +322 -48
- package/package.json +10 -10
package/dist/index.js
CHANGED
|
@@ -63,17 +63,62 @@ var import_sdk_order_book = require("@cowprotocol/sdk-order-book");
|
|
|
63
63
|
var import_sdk_config = require("@cowprotocol/sdk-config");
|
|
64
64
|
var DEFAULT_QUOTE_VALIDITY = 60 * 30;
|
|
65
65
|
var DEFAULT_SLIPPAGE_BPS = 50;
|
|
66
|
-
var ETH_FLOW_DEFAULT_SLIPPAGE_BPS =
|
|
67
|
-
...(0, import_sdk_config.mapSupportedNetworks)(DEFAULT_SLIPPAGE_BPS),
|
|
68
|
-
// 0.5% by default for most chains
|
|
69
|
-
[import_sdk_config.SupportedChainId.MAINNET]: 200
|
|
70
|
-
// 2% for mainnet
|
|
71
|
-
};
|
|
66
|
+
var ETH_FLOW_DEFAULT_SLIPPAGE_BPS = (0, import_sdk_config.mapSupportedNetworks)(DEFAULT_SLIPPAGE_BPS);
|
|
72
67
|
var SIGN_SCHEME_MAP = {
|
|
73
68
|
[import_sdk_order_book.EcdsaSigningScheme.EIP712]: import_sdk_order_book.SigningScheme.EIP712,
|
|
74
69
|
[import_sdk_order_book.EcdsaSigningScheme.ETHSIGN]: import_sdk_order_book.SigningScheme.ETHSIGN
|
|
75
70
|
};
|
|
76
71
|
var GAS_LIMIT_DEFAULT = BigInt(15e4);
|
|
72
|
+
var ERC20_APPROVE_ABI = [
|
|
73
|
+
{
|
|
74
|
+
constant: false,
|
|
75
|
+
inputs: [
|
|
76
|
+
{
|
|
77
|
+
name: "_spender",
|
|
78
|
+
type: "address"
|
|
79
|
+
},
|
|
80
|
+
{
|
|
81
|
+
name: "_value",
|
|
82
|
+
type: "uint256"
|
|
83
|
+
}
|
|
84
|
+
],
|
|
85
|
+
name: "approve",
|
|
86
|
+
outputs: [
|
|
87
|
+
{
|
|
88
|
+
name: "",
|
|
89
|
+
type: "bool"
|
|
90
|
+
}
|
|
91
|
+
],
|
|
92
|
+
payable: false,
|
|
93
|
+
stateMutability: "nonpayable",
|
|
94
|
+
type: "function"
|
|
95
|
+
}
|
|
96
|
+
];
|
|
97
|
+
var ERC20_ALLOWANCE_ABI = [
|
|
98
|
+
{
|
|
99
|
+
constant: true,
|
|
100
|
+
inputs: [
|
|
101
|
+
{
|
|
102
|
+
name: "_owner",
|
|
103
|
+
type: "address"
|
|
104
|
+
},
|
|
105
|
+
{
|
|
106
|
+
name: "_spender",
|
|
107
|
+
type: "address"
|
|
108
|
+
}
|
|
109
|
+
],
|
|
110
|
+
name: "allowance",
|
|
111
|
+
outputs: [
|
|
112
|
+
{
|
|
113
|
+
name: "",
|
|
114
|
+
type: "uint256"
|
|
115
|
+
}
|
|
116
|
+
],
|
|
117
|
+
payable: false,
|
|
118
|
+
stateMutability: "view",
|
|
119
|
+
type: "function"
|
|
120
|
+
}
|
|
121
|
+
];
|
|
77
122
|
|
|
78
123
|
// src/postCoWProtocolTrade.ts
|
|
79
124
|
var import_sdk_order_signing2 = require("@cowprotocol/sdk-order-signing");
|
|
@@ -365,10 +410,18 @@ async function postSellNativeCurrencyOrder(orderBookApi, appData, _params, addit
|
|
|
365
410
|
}
|
|
366
411
|
|
|
367
412
|
// src/postCoWProtocolTrade.ts
|
|
413
|
+
var import_sdk_common5 = require("@cowprotocol/sdk-common");
|
|
414
|
+
|
|
415
|
+
// src/utils/resolveSigner.ts
|
|
368
416
|
var import_sdk_common4 = require("@cowprotocol/sdk-common");
|
|
369
|
-
|
|
417
|
+
function resolveSigner(signer) {
|
|
370
418
|
const adapter = (0, import_sdk_common4.getGlobalAdapter)();
|
|
371
|
-
|
|
419
|
+
return signer ? adapter.createSigner(signer) : adapter.signer;
|
|
420
|
+
}
|
|
421
|
+
|
|
422
|
+
// src/postCoWProtocolTrade.ts
|
|
423
|
+
async function postCoWProtocolTrade(orderBookApi, appData, params, additionalParams = {}, paramSigner) {
|
|
424
|
+
const signer = resolveSigner(paramSigner);
|
|
372
425
|
const { networkCostsAmount = "0", signingScheme: _signingScheme = import_sdk_order_book4.SigningScheme.EIP712 } = additionalParams;
|
|
373
426
|
const isEthFlow = getIsEthFlowOrder(params);
|
|
374
427
|
if (isEthFlow) {
|
|
@@ -384,7 +437,7 @@ async function postCoWProtocolTrade(orderBookApi, appData, params, additionalPar
|
|
|
384
437
|
const chainId = orderBookApi.context.chainId;
|
|
385
438
|
const from = owner || await signer.getAddress();
|
|
386
439
|
const orderToSign = getOrderToSign({ chainId, from, networkCostsAmount, isEthFlow }, params, appData.appDataKeccak256);
|
|
387
|
-
(0,
|
|
440
|
+
(0, import_sdk_common5.log)("Signing order...");
|
|
388
441
|
const { signature, signingScheme } = await (async () => {
|
|
389
442
|
if (_signingScheme === import_sdk_order_book4.SigningScheme.PRESIGN) {
|
|
390
443
|
return { signature: from, signingScheme: import_sdk_order_book4.SigningScheme.PRESIGN };
|
|
@@ -402,24 +455,24 @@ async function postCoWProtocolTrade(orderBookApi, appData, params, additionalPar
|
|
|
402
455
|
appData: fullAppData,
|
|
403
456
|
appDataHash: appDataKeccak256
|
|
404
457
|
};
|
|
405
|
-
(0,
|
|
458
|
+
(0, import_sdk_common5.log)("Posting order...");
|
|
406
459
|
const orderId = await orderBookApi.sendOrder(orderBody);
|
|
407
|
-
(0,
|
|
460
|
+
(0, import_sdk_common5.log)(`Order created, id: ${orderId}`);
|
|
408
461
|
return { orderId, signature, signingScheme, orderToSign };
|
|
409
462
|
}
|
|
410
463
|
|
|
411
464
|
// src/getQuote.ts
|
|
412
|
-
var
|
|
413
|
-
var
|
|
465
|
+
var import_sdk_common11 = require("@cowprotocol/sdk-common");
|
|
466
|
+
var import_sdk_order_book7 = require("@cowprotocol/sdk-order-book");
|
|
414
467
|
|
|
415
468
|
// src/appDataUtils.ts
|
|
416
469
|
var import_sdk_app_data = require("@cowprotocol/sdk-app-data");
|
|
417
|
-
var
|
|
470
|
+
var import_sdk_common6 = require("@cowprotocol/sdk-common");
|
|
418
471
|
var import_deepmerge = __toESM(require("deepmerge"));
|
|
419
472
|
async function buildAppData({ slippageBps, appCode, orderClass: orderClassName, partnerFee }, advancedParams) {
|
|
420
473
|
const quoteParams = { slippageBips: slippageBps };
|
|
421
474
|
const orderClass = { orderClass: orderClassName };
|
|
422
|
-
const metadataApiSdk = new import_sdk_app_data.MetadataApi((0,
|
|
475
|
+
const metadataApiSdk = new import_sdk_app_data.MetadataApi((0, import_sdk_common6.getGlobalAdapter)());
|
|
423
476
|
const doc = await metadataApiSdk.generateAppDataDoc(
|
|
424
477
|
(0, import_deepmerge.default)(
|
|
425
478
|
{
|
|
@@ -437,7 +490,7 @@ async function buildAppData({ slippageBps, appCode, orderClass: orderClassName,
|
|
|
437
490
|
return { doc, fullAppData, appDataKeccak256 };
|
|
438
491
|
}
|
|
439
492
|
async function generateAppDataFromDoc(doc) {
|
|
440
|
-
const adapter = (0,
|
|
493
|
+
const adapter = (0, import_sdk_common6.getGlobalAdapter)();
|
|
441
494
|
const fullAppData = await (0, import_sdk_app_data.stringifyDeterministic)(doc);
|
|
442
495
|
const appDataKeccak256 = adapter.utils.keccak256(adapter.utils.toUtf8Bytes(fullAppData));
|
|
443
496
|
return { fullAppData, appDataKeccak256 };
|
|
@@ -487,11 +540,11 @@ async function getOrderTypedData(chainId, orderToSign) {
|
|
|
487
540
|
}
|
|
488
541
|
|
|
489
542
|
// src/suggestSlippageBps.ts
|
|
490
|
-
var
|
|
543
|
+
var import_sdk_common9 = require("@cowprotocol/sdk-common");
|
|
491
544
|
var import_sdk_order_book5 = require("@cowprotocol/sdk-order-book");
|
|
492
545
|
|
|
493
546
|
// src/suggestSlippageFromFee.ts
|
|
494
|
-
var
|
|
547
|
+
var import_sdk_common7 = require("@cowprotocol/sdk-common");
|
|
495
548
|
function suggestSlippageFromFee(params) {
|
|
496
549
|
const { feeAmount, multiplyingFactorPercent } = params;
|
|
497
550
|
if (feeAmount < 0n) {
|
|
@@ -500,11 +553,11 @@ function suggestSlippageFromFee(params) {
|
|
|
500
553
|
if (multiplyingFactorPercent < 0) {
|
|
501
554
|
throw new Error("multiplyingFactorPercent must be non-negative: " + multiplyingFactorPercent);
|
|
502
555
|
}
|
|
503
|
-
return (0,
|
|
556
|
+
return (0, import_sdk_common7.applyPercentage)(feeAmount, multiplyingFactorPercent);
|
|
504
557
|
}
|
|
505
558
|
|
|
506
559
|
// src/suggestSlippageFromVolume.ts
|
|
507
|
-
var
|
|
560
|
+
var import_sdk_common8 = require("@cowprotocol/sdk-common");
|
|
508
561
|
function suggestSlippageFromVolume(params) {
|
|
509
562
|
const { sellAmountBeforeNetworkCosts, sellAmountAfterNetworkCosts, isSell, slippagePercent } = params;
|
|
510
563
|
const sellAmount = isSell ? sellAmountAfterNetworkCosts : sellAmountBeforeNetworkCosts;
|
|
@@ -514,7 +567,7 @@ function suggestSlippageFromVolume(params) {
|
|
|
514
567
|
if (slippagePercent < 0) {
|
|
515
568
|
throw new Error("slippagePercent must be non-negative: " + slippagePercent);
|
|
516
569
|
}
|
|
517
|
-
return (0,
|
|
570
|
+
return (0, import_sdk_common8.applyPercentage)(sellAmount, slippagePercent);
|
|
518
571
|
}
|
|
519
572
|
|
|
520
573
|
// src/suggestSlippageBps.ts
|
|
@@ -548,13 +601,55 @@ function suggestSlippageBps(params) {
|
|
|
548
601
|
sellAmountAfterNetworkCosts,
|
|
549
602
|
slippage: totalSlippageBps
|
|
550
603
|
});
|
|
551
|
-
const slippageBps = (0,
|
|
552
|
-
|
|
604
|
+
const slippageBps = (0, import_sdk_common9.percentageToBps)(slippagePercent);
|
|
605
|
+
const lowerCap = isEthFlow ? ETH_FLOW_DEFAULT_SLIPPAGE_BPS[trader.chainId] : 0;
|
|
606
|
+
return Math.max(Math.min(slippageBps, MAX_SLIPPAGE_BPS), lowerCap);
|
|
607
|
+
}
|
|
608
|
+
|
|
609
|
+
// src/resolveSlippageSuggestion.ts
|
|
610
|
+
var import_sdk_order_book6 = require("@cowprotocol/sdk-order-book");
|
|
611
|
+
var import_sdk_common10 = require("@cowprotocol/sdk-common");
|
|
612
|
+
async function resolveSlippageSuggestion(chainId, tradeParameters, trader, quote, isEthFlow, advancedSettings) {
|
|
613
|
+
const suggestSlippageParams = {
|
|
614
|
+
isEthFlow,
|
|
615
|
+
quote,
|
|
616
|
+
tradeParameters,
|
|
617
|
+
trader,
|
|
618
|
+
advancedSettings
|
|
619
|
+
};
|
|
620
|
+
const getSlippageSuggestion = advancedSettings?.getSlippageSuggestion;
|
|
621
|
+
const priceQuality = advancedSettings?.quoteRequest?.priceQuality ?? import_sdk_order_book6.PriceQuality.OPTIMAL;
|
|
622
|
+
const defaultSuggestion = suggestSlippageBps(suggestSlippageParams);
|
|
623
|
+
if (priceQuality === import_sdk_order_book6.PriceQuality.FAST || !getSlippageSuggestion) {
|
|
624
|
+
return { slippageBps: defaultSuggestion };
|
|
625
|
+
}
|
|
626
|
+
const amountsAndCosts = (0, import_sdk_order_book6.getQuoteAmountsAndCosts)({
|
|
627
|
+
orderParams: quote.quote,
|
|
628
|
+
slippagePercentBps: 0,
|
|
629
|
+
partnerFeeBps: getPartnerFeeBps(tradeParameters.partnerFee),
|
|
630
|
+
sellDecimals: tradeParameters.sellTokenDecimals,
|
|
631
|
+
buyDecimals: tradeParameters.buyTokenDecimals
|
|
632
|
+
});
|
|
633
|
+
try {
|
|
634
|
+
const suggestedSlippage = await getSlippageSuggestion({
|
|
635
|
+
chainId,
|
|
636
|
+
sellToken: tradeParameters.sellToken,
|
|
637
|
+
buyToken: tradeParameters.buyToken,
|
|
638
|
+
sellAmount: amountsAndCosts.afterSlippage.sellAmount,
|
|
639
|
+
buyAmount: amountsAndCosts.afterSlippage.buyAmount
|
|
640
|
+
});
|
|
641
|
+
return {
|
|
642
|
+
slippageBps: Math.max(suggestedSlippage.slippageBps ?? 0, defaultSuggestion)
|
|
643
|
+
};
|
|
644
|
+
} catch (e) {
|
|
645
|
+
(0, import_sdk_common10.log)(`getSlippageSuggestion() error: ${e.message || String(e)}`);
|
|
646
|
+
return { slippageBps: defaultSuggestion };
|
|
647
|
+
}
|
|
553
648
|
}
|
|
554
649
|
|
|
555
650
|
// src/getQuote.ts
|
|
556
651
|
var ETH_FLOW_AUX_QUOTE_PARAMS = {
|
|
557
|
-
signingScheme:
|
|
652
|
+
signingScheme: import_sdk_order_book7.SigningScheme.EIP1271,
|
|
558
653
|
onchainOrder: true,
|
|
559
654
|
// Ethflow orders are subsidized in the backend.
|
|
560
655
|
// This means we can assume the verification gas costs are zero for the quote/fee estimation
|
|
@@ -574,13 +669,13 @@ async function getQuoteRaw(_tradeParameters, trader, advancedSettings, _orderBoo
|
|
|
574
669
|
slippageBps,
|
|
575
670
|
env = "prod"
|
|
576
671
|
} = tradeParameters;
|
|
577
|
-
(0,
|
|
672
|
+
(0, import_sdk_common11.log)(
|
|
578
673
|
`getQuote for: Swap ${amount} ${sellToken} for ${buyToken} on chain ${chainId} with ${slippageBps !== void 0 ? `${slippageBps} BPS` : "AUTO"} slippage`
|
|
579
674
|
);
|
|
580
|
-
const orderBookApi = _orderBookApi || new
|
|
675
|
+
const orderBookApi = _orderBookApi || new import_sdk_order_book7.OrderBookApi({ chainId, env });
|
|
581
676
|
const receiver = tradeParameters.receiver || from;
|
|
582
677
|
const isSell = kind === "sell";
|
|
583
|
-
(0,
|
|
678
|
+
(0, import_sdk_common11.log)("Building app data...");
|
|
584
679
|
const defaultSlippageBps = getDefaultSlippageBps(chainId, isEthFlow);
|
|
585
680
|
const slippageBpsOrDefault = slippageBps ?? defaultSlippageBps;
|
|
586
681
|
const buildAppDataParams = {
|
|
@@ -591,7 +686,7 @@ async function getQuoteRaw(_tradeParameters, trader, advancedSettings, _orderBoo
|
|
|
591
686
|
};
|
|
592
687
|
const appDataInfo = await buildAppData(buildAppDataParams, advancedSettings?.appData);
|
|
593
688
|
const { appDataKeccak256, fullAppData } = appDataInfo;
|
|
594
|
-
(0,
|
|
689
|
+
(0, import_sdk_common11.log)(`App data: appDataKeccak256=${appDataKeccak256} fullAppData=${fullAppData}`);
|
|
595
690
|
const quoteRequest = {
|
|
596
691
|
from,
|
|
597
692
|
sellToken,
|
|
@@ -600,31 +695,32 @@ async function getQuoteRaw(_tradeParameters, trader, advancedSettings, _orderBoo
|
|
|
600
695
|
validFor,
|
|
601
696
|
appData: fullAppData,
|
|
602
697
|
appDataHash: appDataKeccak256,
|
|
603
|
-
priceQuality:
|
|
698
|
+
priceQuality: import_sdk_order_book7.PriceQuality.OPTIMAL,
|
|
604
699
|
// Do not change this parameter because we rely on the fact that quote has id
|
|
605
|
-
signingScheme:
|
|
700
|
+
signingScheme: import_sdk_order_book7.SigningScheme.EIP712,
|
|
606
701
|
...isEthFlow ? ETH_FLOW_AUX_QUOTE_PARAMS : {},
|
|
607
|
-
...isSell ? { kind:
|
|
702
|
+
...isSell ? { kind: import_sdk_order_book7.OrderQuoteSideKindSell.SELL, sellAmountBeforeFee: amount } : { kind: import_sdk_order_book7.OrderQuoteSideKindBuy.BUY, buyAmountAfterFee: amount },
|
|
608
703
|
...advancedSettings?.quoteRequest
|
|
609
704
|
};
|
|
610
|
-
(0,
|
|
705
|
+
(0, import_sdk_common11.log)("Getting quote...");
|
|
611
706
|
const quote = await orderBookApi.getQuote(quoteRequest);
|
|
612
|
-
const suggestedSlippageBps =
|
|
613
|
-
|
|
614
|
-
quote,
|
|
707
|
+
const { slippageBps: suggestedSlippageBps } = await resolveSlippageSuggestion(
|
|
708
|
+
chainId,
|
|
615
709
|
tradeParameters,
|
|
616
710
|
trader,
|
|
711
|
+
quote,
|
|
712
|
+
isEthFlow,
|
|
617
713
|
advancedSettings
|
|
618
|
-
|
|
714
|
+
);
|
|
619
715
|
const commonResult = {
|
|
620
716
|
isEthFlow,
|
|
621
717
|
quote,
|
|
622
718
|
orderBookApi,
|
|
623
|
-
suggestedSlippageBps
|
|
719
|
+
suggestedSlippageBps: suggestedSlippageBps || defaultSlippageBps
|
|
624
720
|
};
|
|
625
721
|
if (slippageBps === void 0) {
|
|
626
|
-
if (suggestedSlippageBps
|
|
627
|
-
(0,
|
|
722
|
+
if (suggestedSlippageBps) {
|
|
723
|
+
(0, import_sdk_common11.log)(
|
|
628
724
|
`Suggested slippage is greater than ${defaultSlippageBps} BPS (default), using the suggested slippage (${suggestedSlippageBps} BPS)`
|
|
629
725
|
);
|
|
630
726
|
const newAppDataInfo = await buildAppData(
|
|
@@ -634,7 +730,7 @@ async function getQuoteRaw(_tradeParameters, trader, advancedSettings, _orderBoo
|
|
|
634
730
|
},
|
|
635
731
|
advancedSettings?.appData
|
|
636
732
|
);
|
|
637
|
-
(0,
|
|
733
|
+
(0, import_sdk_common11.log)(
|
|
638
734
|
`App data with new suggested slippage: appDataKeccak256=${newAppDataInfo.appDataKeccak256} fullAppData=${newAppDataInfo.fullAppData}`
|
|
639
735
|
);
|
|
640
736
|
return {
|
|
@@ -644,9 +740,7 @@ async function getQuoteRaw(_tradeParameters, trader, advancedSettings, _orderBoo
|
|
|
644
740
|
slippageBps: suggestedSlippageBps
|
|
645
741
|
};
|
|
646
742
|
} else {
|
|
647
|
-
(0,
|
|
648
|
-
`Suggested slippage is only ${suggestedSlippageBps} BPS. Using the default slippage (${defaultSlippageBps} BPS)`
|
|
649
|
-
);
|
|
743
|
+
(0, import_sdk_common11.log)(`No suggested slippage. Using the default slippage (${defaultSlippageBps} BPS)`);
|
|
650
744
|
}
|
|
651
745
|
}
|
|
652
746
|
return {
|
|
@@ -661,7 +755,7 @@ async function getQuote(_tradeParameters, trader, advancedSettings, _orderBookAp
|
|
|
661
755
|
const { quote, orderBookApi, tradeParameters, slippageBps, suggestedSlippageBps, appDataInfo, isEthFlow } = await getQuoteRaw(_tradeParameters, trader, advancedSettings, _orderBookApi);
|
|
662
756
|
const { partnerFee, sellTokenDecimals, buyTokenDecimals } = tradeParameters;
|
|
663
757
|
const { chainId, account: from } = trader;
|
|
664
|
-
const amountsAndCosts = (0,
|
|
758
|
+
const amountsAndCosts = (0, import_sdk_order_book7.getQuoteAmountsAndCosts)({
|
|
665
759
|
orderParams: quote.quote,
|
|
666
760
|
slippagePercentBps: slippageBps,
|
|
667
761
|
partnerFeeBps: getPartnerFeeBps(partnerFee),
|
|
@@ -688,7 +782,7 @@ async function getQuote(_tradeParameters, trader, advancedSettings, _orderBookAp
|
|
|
688
782
|
};
|
|
689
783
|
}
|
|
690
784
|
async function getTrader(swapParameters) {
|
|
691
|
-
const signer = (0,
|
|
785
|
+
const signer = (0, import_sdk_common11.getGlobalAdapter)().signerOrNull();
|
|
692
786
|
const account = swapParameters.owner || await signer?.getAddress();
|
|
693
787
|
return {
|
|
694
788
|
chainId: swapParameters.chainId,
|
|
@@ -697,8 +791,7 @@ async function getTrader(swapParameters) {
|
|
|
697
791
|
};
|
|
698
792
|
}
|
|
699
793
|
async function getQuoteWithSigner(swapParameters, advancedSettings, orderBookApi) {
|
|
700
|
-
const
|
|
701
|
-
const signer = swapParameters.signer ? adapter.createSigner(swapParameters.signer) : adapter.signer;
|
|
794
|
+
const signer = resolveSigner(swapParameters.signer);
|
|
702
795
|
const trader = await getTrader(swapParameters);
|
|
703
796
|
const result = await getQuote(swapParameters, trader, advancedSettings, orderBookApi);
|
|
704
797
|
return {
|
|
@@ -754,8 +847,8 @@ async function postSwapOrderFromQuote({
|
|
|
754
847
|
}
|
|
755
848
|
|
|
756
849
|
// src/postLimitOrder.ts
|
|
757
|
-
var
|
|
758
|
-
var
|
|
850
|
+
var import_sdk_order_book8 = require("@cowprotocol/sdk-order-book");
|
|
851
|
+
var import_sdk_common12 = require("@cowprotocol/sdk-common");
|
|
759
852
|
async function postLimitOrder(params, advancedSettings, _orderBookApi) {
|
|
760
853
|
const appDataSlippage = advancedSettings?.appData?.metadata?.quote?.slippageBips;
|
|
761
854
|
const partnerFeeOverride = advancedSettings?.appData?.metadata?.partnerFee;
|
|
@@ -772,9 +865,9 @@ async function postLimitOrder(params, advancedSettings, _orderBookApi) {
|
|
|
772
865
|
params.env = "prod";
|
|
773
866
|
}
|
|
774
867
|
const { appCode, chainId, sellToken, buyToken, sellAmount, buyAmount, partnerFee } = params;
|
|
775
|
-
(0,
|
|
776
|
-
const orderBookApi = _orderBookApi || new
|
|
777
|
-
(0,
|
|
868
|
+
(0, import_sdk_common12.log)(`Limit order ${sellAmount} ${sellToken} for ${buyAmount} ${buyToken} on chain ${chainId}`);
|
|
869
|
+
const orderBookApi = _orderBookApi || new import_sdk_order_book8.OrderBookApi({ chainId, env: params.env });
|
|
870
|
+
(0, import_sdk_common12.log)("Building app data...");
|
|
778
871
|
const appDataInfo = await buildAppData(
|
|
779
872
|
{
|
|
780
873
|
slippageBps: params.slippageBps,
|
|
@@ -787,35 +880,109 @@ async function postLimitOrder(params, advancedSettings, _orderBookApi) {
|
|
|
787
880
|
return postCoWProtocolTrade(orderBookApi, appDataInfo, params, advancedSettings?.additionalParams, params.signer);
|
|
788
881
|
}
|
|
789
882
|
|
|
790
|
-
// src/
|
|
883
|
+
// src/getSettlementContract.ts
|
|
884
|
+
var import_sdk_common13 = require("@cowprotocol/sdk-common");
|
|
791
885
|
var import_sdk_config5 = require("@cowprotocol/sdk-config");
|
|
792
|
-
|
|
793
|
-
|
|
794
|
-
|
|
795
|
-
|
|
886
|
+
function getSettlementContract(chainId, signer) {
|
|
887
|
+
return import_sdk_common13.ContractFactory.createSettlementContract(import_sdk_config5.COW_PROTOCOL_SETTLEMENT_CONTRACT_ADDRESS[chainId], signer);
|
|
888
|
+
}
|
|
889
|
+
|
|
890
|
+
// src/getPreSignTransaction.ts
|
|
891
|
+
async function getPreSignTransaction(signer, chainId, orderId) {
|
|
892
|
+
const contract = getSettlementContract(chainId, signer);
|
|
796
893
|
const preSignatureCall = contract.interface.encodeFunctionData("setPreSignature", [orderId, true]);
|
|
797
894
|
const gas = await contract.estimateGas.setPreSignature?.(orderId, true).catch(() => GAS_LIMIT_DEFAULT) || GAS_LIMIT_DEFAULT;
|
|
798
895
|
return {
|
|
799
896
|
data: preSignatureCall,
|
|
800
897
|
gasLimit: "0x" + calculateGasMargin(gas).toString(16),
|
|
801
|
-
to:
|
|
802
|
-
// Para onde enviar a transação
|
|
898
|
+
to: contract.address,
|
|
803
899
|
value: "0"
|
|
804
900
|
};
|
|
805
901
|
}
|
|
806
902
|
|
|
807
903
|
// src/tradingSdk.ts
|
|
808
|
-
var
|
|
809
|
-
var
|
|
904
|
+
var import_sdk_common14 = require("@cowprotocol/sdk-common");
|
|
905
|
+
var import_sdk_order_signing4 = require("@cowprotocol/sdk-order-signing");
|
|
906
|
+
|
|
907
|
+
// src/onChainCancellation.ts
|
|
908
|
+
var CANCELLATION_GAS_LIMIT_DEFAULT = 150000n;
|
|
909
|
+
async function getEthFlowCancellation(ethFlowContract, order) {
|
|
910
|
+
const cancelOrderParams = {
|
|
911
|
+
buyToken: order.buyToken,
|
|
912
|
+
receiver: order.receiver || order.owner,
|
|
913
|
+
sellAmount: order.sellAmount,
|
|
914
|
+
buyAmount: order.buyAmount,
|
|
915
|
+
appData: order.appData.toString(),
|
|
916
|
+
feeAmount: order.feeAmount,
|
|
917
|
+
validTo: order.validTo.toString(),
|
|
918
|
+
partiallyFillable: false,
|
|
919
|
+
quoteId: 0
|
|
920
|
+
// value doesn't matter, set to 0 for reducing gas costs
|
|
921
|
+
};
|
|
922
|
+
return getOnChainCancellation(ethFlowContract, cancelOrderParams);
|
|
923
|
+
}
|
|
924
|
+
async function getSettlementCancellation(settlementContract, order) {
|
|
925
|
+
const cancelOrderParams = order.uid;
|
|
926
|
+
return getOnChainCancellation(settlementContract, cancelOrderParams);
|
|
927
|
+
}
|
|
928
|
+
async function getOnChainCancellation(contract, cancelOrderParams) {
|
|
929
|
+
const estimatedGas = await (async () => {
|
|
930
|
+
try {
|
|
931
|
+
if (contract.estimateGas.invalidateOrder) {
|
|
932
|
+
const estimated = await contract.estimateGas.invalidateOrder(cancelOrderParams);
|
|
933
|
+
return BigInt(estimated.toHexString ? estimated.toHexString() : `0x${estimated.toString(16)}`);
|
|
934
|
+
}
|
|
935
|
+
return CANCELLATION_GAS_LIMIT_DEFAULT;
|
|
936
|
+
} catch (error) {
|
|
937
|
+
console.error(error);
|
|
938
|
+
return CANCELLATION_GAS_LIMIT_DEFAULT;
|
|
939
|
+
}
|
|
940
|
+
})();
|
|
941
|
+
const data = contract.interface.encodeFunctionData("invalidateOrder", [cancelOrderParams]);
|
|
942
|
+
return {
|
|
943
|
+
estimatedGas,
|
|
944
|
+
transaction: {
|
|
945
|
+
data,
|
|
946
|
+
gasLimit: "0x" + estimatedGas.toString(16),
|
|
947
|
+
to: contract.address,
|
|
948
|
+
value: "0x0"
|
|
949
|
+
}
|
|
950
|
+
};
|
|
951
|
+
}
|
|
952
|
+
|
|
953
|
+
// src/utils/resolveOrderBookApi.ts
|
|
954
|
+
var import_sdk_order_book9 = require("@cowprotocol/sdk-order-book");
|
|
955
|
+
var orderBookApiCache = /* @__PURE__ */ new Map([
|
|
956
|
+
["prod", /* @__PURE__ */ new Map()],
|
|
957
|
+
["staging", /* @__PURE__ */ new Map()]
|
|
958
|
+
]);
|
|
959
|
+
function resolveOrderBookApi(chainId, env, existingOrderBookApi) {
|
|
960
|
+
if (existingOrderBookApi) {
|
|
961
|
+
existingOrderBookApi.context.chainId = chainId;
|
|
962
|
+
existingOrderBookApi.context.env = env;
|
|
963
|
+
return existingOrderBookApi;
|
|
964
|
+
}
|
|
965
|
+
const envCache = orderBookApiCache.get(env) ?? /* @__PURE__ */ new Map();
|
|
966
|
+
const cached = envCache.get(chainId);
|
|
967
|
+
if (cached)
|
|
968
|
+
return cached;
|
|
969
|
+
const orderBookApi = new import_sdk_order_book9.OrderBookApi({ chainId, env });
|
|
970
|
+
envCache.set(chainId, orderBookApi);
|
|
971
|
+
orderBookApiCache.set(env, envCache);
|
|
972
|
+
return orderBookApi;
|
|
973
|
+
}
|
|
974
|
+
|
|
975
|
+
// src/tradingSdk.ts
|
|
976
|
+
var import_sdk_config6 = require("@cowprotocol/sdk-config");
|
|
810
977
|
var TradingSdk = class {
|
|
811
978
|
constructor(traderParams = {}, options = {}, adapter) {
|
|
812
979
|
this.traderParams = traderParams;
|
|
813
980
|
this.options = options;
|
|
814
981
|
if (options.enableLogging !== void 0) {
|
|
815
|
-
(0,
|
|
982
|
+
(0, import_sdk_common14.enableLogging)(options.enableLogging);
|
|
816
983
|
}
|
|
817
984
|
if (adapter) {
|
|
818
|
-
(0,
|
|
985
|
+
(0, import_sdk_common14.setGlobalAdapter)(adapter);
|
|
819
986
|
}
|
|
820
987
|
}
|
|
821
988
|
setTraderParams(params) {
|
|
@@ -847,7 +1014,7 @@ var TradingSdk = class {
|
|
|
847
1014
|
}),
|
|
848
1015
|
// It's important to get a fresh instance of the signer
|
|
849
1016
|
// Because quote might be called with another signer
|
|
850
|
-
signer: (0,
|
|
1017
|
+
signer: (0, import_sdk_common14.getGlobalAdapter)().signer
|
|
851
1018
|
}
|
|
852
1019
|
},
|
|
853
1020
|
advancedSettings2
|
|
@@ -908,16 +1075,123 @@ var TradingSdk = class {
|
|
|
908
1075
|
);
|
|
909
1076
|
}
|
|
910
1077
|
async getPreSignTransaction(params) {
|
|
911
|
-
const adapter = (0, import_sdk_common12.getGlobalAdapter)();
|
|
912
1078
|
const traderParams = this.mergeParams(params);
|
|
913
|
-
const signer =
|
|
914
|
-
return getPreSignTransaction(signer, traderParams.chainId, params.
|
|
1079
|
+
const signer = resolveSigner(traderParams.signer);
|
|
1080
|
+
return getPreSignTransaction(signer, traderParams.chainId, params.orderUid);
|
|
1081
|
+
}
|
|
1082
|
+
async getOrder(params) {
|
|
1083
|
+
const orderBookApi = this.resolveOrderBookApi(params);
|
|
1084
|
+
return orderBookApi.getOrder(params.orderUid);
|
|
1085
|
+
}
|
|
1086
|
+
async offChainCancelOrder(params) {
|
|
1087
|
+
const orderBookApi = this.resolveOrderBookApi(params);
|
|
1088
|
+
const signer = resolveSigner(params.signer);
|
|
1089
|
+
const { orderUid } = params;
|
|
1090
|
+
const chainId = params.chainId || this.traderParams.chainId;
|
|
1091
|
+
if (!chainId) {
|
|
1092
|
+
throw new Error("Chain ID is missing in offChainCancelOrder() call");
|
|
1093
|
+
}
|
|
1094
|
+
const orderCancellationSigning = await import_sdk_order_signing4.OrderSigningUtils.signOrderCancellations([orderUid], chainId, signer);
|
|
1095
|
+
await orderBookApi.sendSignedOrderCancellations({
|
|
1096
|
+
...orderCancellationSigning,
|
|
1097
|
+
orderUids: [orderUid]
|
|
1098
|
+
});
|
|
1099
|
+
return true;
|
|
1100
|
+
}
|
|
1101
|
+
async onChainCancelOrder(params, _order) {
|
|
1102
|
+
const chainId = params.chainId || this.traderParams.chainId;
|
|
1103
|
+
if (!chainId) {
|
|
1104
|
+
throw new Error("Chain ID is missing in offChainCancelOrder() call");
|
|
1105
|
+
}
|
|
1106
|
+
const order = _order ?? await this.getOrder(params);
|
|
1107
|
+
const isEthFlowOrder = !!order.onchainOrderData;
|
|
1108
|
+
const signer = params.signer ? (0, import_sdk_common14.getGlobalAdapter)().createSigner(params.signer) : (0, import_sdk_common14.getGlobalAdapter)().signer;
|
|
1109
|
+
const { transaction } = await (isEthFlowOrder ? getEthFlowCancellation(getEthFlowContract(signer, chainId, params.env ?? this.traderParams.env), order) : getSettlementCancellation(getSettlementContract(chainId, signer), order));
|
|
1110
|
+
const txReceipt = await signer.sendTransaction(transaction);
|
|
1111
|
+
return txReceipt.hash;
|
|
1112
|
+
}
|
|
1113
|
+
/**
|
|
1114
|
+
* Checks the current allowance for the CoW Protocol Vault Relayer to spend an ERC-20 token.
|
|
1115
|
+
*
|
|
1116
|
+
* @param params - Parameters including token address and owner address
|
|
1117
|
+
* @returns Promise resolving to the current allowance amount as a bigint
|
|
1118
|
+
*
|
|
1119
|
+
* @example
|
|
1120
|
+
* ```typescript
|
|
1121
|
+
* const params = {
|
|
1122
|
+
* tokenAddress: '0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48', // USDC
|
|
1123
|
+
* owner: '0x123...',
|
|
1124
|
+
* chainId: 1,
|
|
1125
|
+
* }
|
|
1126
|
+
*
|
|
1127
|
+
* const allowance = await sdk.getCowProtocolAllowance(params)
|
|
1128
|
+
* console.log('Current allowance:', allowance.toString())
|
|
1129
|
+
* ```
|
|
1130
|
+
*/
|
|
1131
|
+
async getCowProtocolAllowance(params) {
|
|
1132
|
+
const chainId = params.chainId || this.traderParams.chainId;
|
|
1133
|
+
if (!chainId) {
|
|
1134
|
+
throw new Error("Chain ID is missing in getCowProtocolAllowance() call");
|
|
1135
|
+
}
|
|
1136
|
+
const adapter = (0, import_sdk_common14.getGlobalAdapter)();
|
|
1137
|
+
const vaultRelayerAddress = import_sdk_config6.COW_PROTOCOL_VAULT_RELAYER_ADDRESS[chainId];
|
|
1138
|
+
return await adapter.readContract({
|
|
1139
|
+
address: params.tokenAddress,
|
|
1140
|
+
abi: ERC20_ALLOWANCE_ABI,
|
|
1141
|
+
functionName: "allowance",
|
|
1142
|
+
args: [params.owner, vaultRelayerAddress]
|
|
1143
|
+
});
|
|
1144
|
+
}
|
|
1145
|
+
/**
|
|
1146
|
+
* Approves the CoW Protocol Vault Relayer to spend a specified amount of an ERC-20 token.
|
|
1147
|
+
* This method creates an on-chain approval transaction.
|
|
1148
|
+
*
|
|
1149
|
+
* @param params - Parameters including token address and amount to approve
|
|
1150
|
+
* @returns Promise resolving to the transaction hash of the approval transaction
|
|
1151
|
+
*
|
|
1152
|
+
* @example
|
|
1153
|
+
* ```typescript
|
|
1154
|
+
* const params = {
|
|
1155
|
+
* tokenAddress: '0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48', // USDC
|
|
1156
|
+
* amount: '1000000000', // 1000 USDC (6 decimals)
|
|
1157
|
+
* chainId: 1,
|
|
1158
|
+
* }
|
|
1159
|
+
*
|
|
1160
|
+
* const txHash = await sdk.approveCowProtocol(params)
|
|
1161
|
+
* console.log('Approval transaction:', txHash)
|
|
1162
|
+
* ```
|
|
1163
|
+
*/
|
|
1164
|
+
async approveCowProtocol(params) {
|
|
1165
|
+
const chainId = params.chainId || this.traderParams.chainId;
|
|
1166
|
+
if (!chainId) {
|
|
1167
|
+
throw new Error("Chain ID is missing in approveCowProtocol() call");
|
|
1168
|
+
}
|
|
1169
|
+
const adapter = (0, import_sdk_common14.getGlobalAdapter)();
|
|
1170
|
+
const signer = resolveSigner(params.signer);
|
|
1171
|
+
const vaultRelayerAddress = import_sdk_config6.COW_PROTOCOL_VAULT_RELAYER_ADDRESS[chainId];
|
|
1172
|
+
const txParams = {
|
|
1173
|
+
to: params.tokenAddress,
|
|
1174
|
+
data: adapter.utils.encodeFunction(ERC20_APPROVE_ABI, "approve", [
|
|
1175
|
+
vaultRelayerAddress,
|
|
1176
|
+
"0x" + params.amount.toString(16)
|
|
1177
|
+
])
|
|
1178
|
+
};
|
|
1179
|
+
const txReceipt = await signer.sendTransaction(txParams);
|
|
1180
|
+
return txReceipt.hash;
|
|
1181
|
+
}
|
|
1182
|
+
resolveOrderBookApi(params) {
|
|
1183
|
+
const chainId = params.chainId ?? this.traderParams.chainId;
|
|
1184
|
+
const env = params.env ?? this.traderParams.env ?? "prod";
|
|
1185
|
+
if (!chainId) {
|
|
1186
|
+
throw new Error("Chain ID is missing in getOrder() call");
|
|
1187
|
+
}
|
|
1188
|
+
return resolveOrderBookApi(chainId, env);
|
|
915
1189
|
}
|
|
916
1190
|
mergeParams(params) {
|
|
917
1191
|
const { chainId, signer, appCode, env } = params;
|
|
918
1192
|
const traderParams = {
|
|
919
1193
|
chainId: chainId || this.traderParams.chainId,
|
|
920
|
-
signer: signer || this.traderParams.signer || (0,
|
|
1194
|
+
signer: signer || this.traderParams.signer || (0, import_sdk_common14.getGlobalAdapter)().signer,
|
|
921
1195
|
appCode: appCode || this.traderParams.appCode,
|
|
922
1196
|
env: env || this.traderParams.env
|
|
923
1197
|
};
|