@opensea/seaport-js 1.0.1-beta.0 → 1.0.3

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.
Files changed (81) hide show
  1. package/LICENSE +7 -0
  2. package/README.md +141 -5
  3. package/lib/abi/ERC1155.d.ts +29 -29
  4. package/lib/abi/ERC1155.js +319 -0
  5. package/lib/abi/ERC1155.js.map +1 -0
  6. package/lib/abi/ERC20.d.ts +29 -29
  7. package/lib/abi/ERC20.js +317 -0
  8. package/lib/abi/ERC20.js.map +1 -0
  9. package/lib/abi/ERC721.d.ts +29 -29
  10. package/lib/abi/ERC721.js +337 -0
  11. package/lib/abi/ERC721.js.map +1 -0
  12. package/lib/abi/Seaport.d.ts +112 -112
  13. package/lib/abi/Seaport.js +2585 -0
  14. package/lib/abi/Seaport.js.map +1 -0
  15. package/lib/constants.d.ts +53 -49
  16. package/lib/constants.js +78 -0
  17. package/lib/constants.js.map +1 -0
  18. package/lib/index.d.ts +2 -2
  19. package/lib/index.js +6 -2
  20. package/lib/index.js.map +1 -1
  21. package/lib/seaport.d.ts +184 -181
  22. package/lib/seaport.js +732 -0
  23. package/lib/seaport.js.map +1 -0
  24. package/lib/typechain/ERC1155.d.ts +189 -0
  25. package/lib/typechain/ERC1155.js +3 -0
  26. package/lib/typechain/ERC1155.js.map +1 -0
  27. package/lib/typechain/ERC20.d.ts +209 -0
  28. package/lib/typechain/ERC20.js +3 -0
  29. package/lib/typechain/ERC20.js.map +1 -0
  30. package/lib/typechain/ERC721.d.ts +220 -0
  31. package/lib/typechain/ERC721.js +3 -0
  32. package/lib/typechain/ERC721.js.map +1 -0
  33. package/lib/typechain/Seaport.d.ts +686 -0
  34. package/lib/typechain/Seaport.js +3 -0
  35. package/lib/typechain/Seaport.js.map +1 -0
  36. package/lib/typechain/common.d.ts +21 -0
  37. package/lib/typechain/common.js +3 -0
  38. package/lib/typechain/common.js.map +1 -0
  39. package/lib/types.d.ts +221 -207
  40. package/lib/types.js +3 -0
  41. package/lib/types.js.map +1 -0
  42. package/lib/utils/approval.d.ts +9 -9
  43. package/lib/utils/approval.js +108 -0
  44. package/lib/utils/approval.js.map +1 -0
  45. package/lib/utils/balance.d.ts +4 -4
  46. package/lib/utils/balance.js +86 -0
  47. package/lib/utils/balance.js.map +1 -0
  48. package/lib/utils/balanceAndApprovalCheck.d.ts +108 -108
  49. package/lib/utils/balanceAndApprovalCheck.js +322 -0
  50. package/lib/utils/balanceAndApprovalCheck.js.map +1 -0
  51. package/lib/utils/criteria.d.ts +14 -13
  52. package/lib/utils/criteria.js +91 -0
  53. package/lib/utils/criteria.js.map +1 -0
  54. package/lib/utils/fulfill.d.ts +84 -84
  55. package/lib/utils/fulfill.js +573 -0
  56. package/lib/utils/fulfill.js.map +1 -0
  57. package/lib/utils/gcd.d.ts +3 -3
  58. package/lib/utils/gcd.js +25 -0
  59. package/lib/utils/gcd.js.map +1 -0
  60. package/lib/utils/item.d.ts +29 -30
  61. package/lib/utils/item.js +136 -0
  62. package/lib/utils/item.js.map +1 -0
  63. package/lib/utils/match.d.ts +49 -49
  64. package/lib/utils/match.js +56 -0
  65. package/lib/utils/match.js.map +1 -0
  66. package/lib/utils/merkletree.d.ts +11 -11
  67. package/lib/utils/merkletree.js +32 -0
  68. package/lib/utils/merkletree.js.map +1 -0
  69. package/lib/utils/order.d.ts +37 -37
  70. package/lib/utils/order.js +224 -0
  71. package/lib/utils/order.js.map +1 -0
  72. package/lib/utils/usecase.d.ts +4 -4
  73. package/lib/utils/usecase.js +158 -0
  74. package/lib/utils/usecase.js.map +1 -0
  75. package/package.json +43 -43
  76. package/lib/index.esm.mjs +0 -2
  77. package/lib/index.esm.mjs.map +0 -1
  78. package/lib/index.modern.mjs +0 -2
  79. package/lib/index.modern.mjs.map +0 -1
  80. package/lib/index.umd.js +0 -2
  81. package/lib/index.umd.js.map +0 -1
package/lib/seaport.js ADDED
@@ -0,0 +1,732 @@
1
+ "use strict";
2
+ var __assign = (this && this.__assign) || function () {
3
+ __assign = Object.assign || function(t) {
4
+ for (var s, i = 1, n = arguments.length; i < n; i++) {
5
+ s = arguments[i];
6
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
7
+ t[p] = s[p];
8
+ }
9
+ return t;
10
+ };
11
+ return __assign.apply(this, arguments);
12
+ };
13
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
14
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
15
+ return new (P || (P = Promise))(function (resolve, reject) {
16
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
17
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
18
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
19
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
20
+ });
21
+ };
22
+ var __generator = (this && this.__generator) || function (thisArg, body) {
23
+ var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
24
+ return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
25
+ function verb(n) { return function (v) { return step([n, v]); }; }
26
+ function step(op) {
27
+ if (f) throw new TypeError("Generator is already executing.");
28
+ while (_) try {
29
+ if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
30
+ if (y = 0, t) op = [op[0] & 2, t.value];
31
+ switch (op[0]) {
32
+ case 0: case 1: t = op; break;
33
+ case 4: _.label++; return { value: op[1], done: false };
34
+ case 5: _.label++; y = op[1]; op = [0]; continue;
35
+ case 7: op = _.ops.pop(); _.trys.pop(); continue;
36
+ default:
37
+ if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
38
+ if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
39
+ if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
40
+ if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
41
+ if (t[2]) _.ops.pop();
42
+ _.trys.pop(); continue;
43
+ }
44
+ op = body.call(thisArg, _);
45
+ } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
46
+ if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
47
+ }
48
+ };
49
+ var __read = (this && this.__read) || function (o, n) {
50
+ var m = typeof Symbol === "function" && o[Symbol.iterator];
51
+ if (!m) return o;
52
+ var i = m.call(o), r, ar = [], e;
53
+ try {
54
+ while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
55
+ }
56
+ catch (error) { e = { error: error }; }
57
+ finally {
58
+ try {
59
+ if (r && !r.done && (m = i["return"])) m.call(i);
60
+ }
61
+ finally { if (e) throw e.error; }
62
+ }
63
+ return ar;
64
+ };
65
+ var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {
66
+ if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
67
+ if (ar || !(i in from)) {
68
+ if (!ar) ar = Array.prototype.slice.call(from, 0, i);
69
+ ar[i] = from[i];
70
+ }
71
+ }
72
+ return to.concat(ar || Array.prototype.slice.call(from));
73
+ };
74
+ Object.defineProperty(exports, "__esModule", { value: true });
75
+ exports.Seaport = void 0;
76
+ var multicall_1 = require("@0xsequence/multicall");
77
+ var ethers_1 = require("ethers");
78
+ var utils_1 = require("ethers/lib/utils");
79
+ var Seaport_1 = require("./abi/Seaport");
80
+ var constants_1 = require("./constants");
81
+ var approval_1 = require("./utils/approval");
82
+ var balanceAndApprovalCheck_1 = require("./utils/balanceAndApprovalCheck");
83
+ var fulfill_1 = require("./utils/fulfill");
84
+ var item_1 = require("./utils/item");
85
+ var order_1 = require("./utils/order");
86
+ var usecase_1 = require("./utils/usecase");
87
+ var Seaport = /** @class */ (function () {
88
+ /**
89
+ * @param providerOrSigner - The provider or signer to use for web3-related calls
90
+ * @param considerationConfig - A config to provide flexibility in the usage of Seaport
91
+ */
92
+ function Seaport(providerOrSigner, _a) {
93
+ var _b;
94
+ var _c = _a === void 0 ? {} : _a, overrides = _c.overrides,
95
+ // Five minute buffer
96
+ _d = _c.ascendingAmountFulfillmentBuffer,
97
+ // Five minute buffer
98
+ ascendingAmountFulfillmentBuffer = _d === void 0 ? 300 : _d, _e = _c.balanceAndApprovalChecksOnOrderCreation, balanceAndApprovalChecksOnOrderCreation = _e === void 0 ? true : _e, conduitKeyToConduit = _c.conduitKeyToConduit;
99
+ var _f, _g;
100
+ this.OPENSEA_CONDUIT_KEY = constants_1.OPENSEA_CONDUIT_KEY;
101
+ /**
102
+ * Calculates the order hash of order components so we can forgo executing a request to the contract
103
+ * This saves us RPC calls and latency.
104
+ */
105
+ this.getOrderHash = function (orderComponents) {
106
+ var offerItemTypeString = "OfferItem(uint8 itemType,address token,uint256 identifierOrCriteria,uint256 startAmount,uint256 endAmount)";
107
+ var considerationItemTypeString = "ConsiderationItem(uint8 itemType,address token,uint256 identifierOrCriteria,uint256 startAmount,uint256 endAmount,address recipient)";
108
+ var orderComponentsPartialTypeString = "OrderComponents(address offerer,address zone,OfferItem[] offer,ConsiderationItem[] consideration,uint8 orderType,uint256 startTime,uint256 endTime,bytes32 zoneHash,uint256 salt,bytes32 conduitKey,uint256 counter)";
109
+ var orderTypeString = "".concat(orderComponentsPartialTypeString).concat(considerationItemTypeString).concat(offerItemTypeString);
110
+ var offerItemTypeHash = ethers_1.ethers.utils.keccak256(ethers_1.ethers.utils.toUtf8Bytes(offerItemTypeString));
111
+ var considerationItemTypeHash = ethers_1.ethers.utils.keccak256(ethers_1.ethers.utils.toUtf8Bytes(considerationItemTypeString));
112
+ var orderTypeHash = ethers_1.ethers.utils.keccak256(ethers_1.ethers.utils.toUtf8Bytes(orderTypeString));
113
+ var offerHash = ethers_1.ethers.utils.keccak256("0x" +
114
+ orderComponents.offer
115
+ .map(function (offerItem) {
116
+ return ethers_1.ethers.utils
117
+ .keccak256("0x" +
118
+ [
119
+ offerItemTypeHash.slice(2),
120
+ offerItem.itemType.toString().padStart(64, "0"),
121
+ offerItem.token.slice(2).padStart(64, "0"),
122
+ ethers_1.ethers.BigNumber.from(offerItem.identifierOrCriteria)
123
+ .toHexString()
124
+ .slice(2)
125
+ .padStart(64, "0"),
126
+ ethers_1.ethers.BigNumber.from(offerItem.startAmount)
127
+ .toHexString()
128
+ .slice(2)
129
+ .padStart(64, "0"),
130
+ ethers_1.ethers.BigNumber.from(offerItem.endAmount)
131
+ .toHexString()
132
+ .slice(2)
133
+ .padStart(64, "0"),
134
+ ].join(""))
135
+ .slice(2);
136
+ })
137
+ .join(""));
138
+ var considerationHash = ethers_1.ethers.utils.keccak256("0x" +
139
+ orderComponents.consideration
140
+ .map(function (considerationItem) {
141
+ return ethers_1.ethers.utils
142
+ .keccak256("0x" +
143
+ [
144
+ considerationItemTypeHash.slice(2),
145
+ considerationItem.itemType.toString().padStart(64, "0"),
146
+ considerationItem.token.slice(2).padStart(64, "0"),
147
+ ethers_1.ethers.BigNumber.from(considerationItem.identifierOrCriteria)
148
+ .toHexString()
149
+ .slice(2)
150
+ .padStart(64, "0"),
151
+ ethers_1.ethers.BigNumber.from(considerationItem.startAmount)
152
+ .toHexString()
153
+ .slice(2)
154
+ .padStart(64, "0"),
155
+ ethers_1.ethers.BigNumber.from(considerationItem.endAmount)
156
+ .toHexString()
157
+ .slice(2)
158
+ .padStart(64, "0"),
159
+ considerationItem.recipient.slice(2).padStart(64, "0"),
160
+ ].join(""))
161
+ .slice(2);
162
+ })
163
+ .join(""));
164
+ var derivedOrderHash = ethers_1.ethers.utils.keccak256("0x" +
165
+ [
166
+ orderTypeHash.slice(2),
167
+ orderComponents.offerer.slice(2).padStart(64, "0"),
168
+ orderComponents.zone.slice(2).padStart(64, "0"),
169
+ offerHash.slice(2),
170
+ considerationHash.slice(2),
171
+ orderComponents.orderType.toString().padStart(64, "0"),
172
+ ethers_1.ethers.BigNumber.from(orderComponents.startTime)
173
+ .toHexString()
174
+ .slice(2)
175
+ .padStart(64, "0"),
176
+ ethers_1.ethers.BigNumber.from(orderComponents.endTime)
177
+ .toHexString()
178
+ .slice(2)
179
+ .padStart(64, "0"),
180
+ orderComponents.zoneHash.slice(2),
181
+ orderComponents.salt.slice(2).padStart(64, "0"),
182
+ orderComponents.conduitKey.slice(2).padStart(64, "0"),
183
+ ethers_1.ethers.BigNumber.from(orderComponents.counter)
184
+ .toHexString()
185
+ .slice(2)
186
+ .padStart(64, "0"),
187
+ ].join(""));
188
+ return derivedOrderHash;
189
+ };
190
+ var provider = providerOrSigner instanceof ethers_1.providers.Provider
191
+ ? providerOrSigner
192
+ : providerOrSigner.provider;
193
+ if (!provider) {
194
+ throw new Error("Either a provider or custom signer with provider must be provided");
195
+ }
196
+ this.provider = provider;
197
+ this.multicallProvider = new multicall_1.providers.MulticallProvider(this.provider);
198
+ this.contract = new ethers_1.Contract((_f = overrides === null || overrides === void 0 ? void 0 : overrides.contractAddress) !== null && _f !== void 0 ? _f : constants_1.CROSS_CHAIN_SEAPORT_ADDRESS, Seaport_1.SeaportABI, this.multicallProvider);
199
+ this.config = {
200
+ ascendingAmountFulfillmentBuffer: ascendingAmountFulfillmentBuffer,
201
+ balanceAndApprovalChecksOnOrderCreation: balanceAndApprovalChecksOnOrderCreation,
202
+ conduitKeyToConduit: __assign(__assign(__assign({}, constants_1.KNOWN_CONDUIT_KEYS_TO_CONDUIT), (_b = {}, _b[constants_1.NO_CONDUIT] = this.contract.address, _b)), conduitKeyToConduit),
203
+ };
204
+ this.defaultConduitKey = (_g = overrides === null || overrides === void 0 ? void 0 : overrides.defaultConduitKey) !== null && _g !== void 0 ? _g : constants_1.NO_CONDUIT;
205
+ }
206
+ Seaport.prototype._getSigner = function (accountAddress) {
207
+ if (this.signer) {
208
+ return this.signer;
209
+ }
210
+ if (!(this.provider instanceof ethers_1.providers.JsonRpcProvider)) {
211
+ throw new Error("Either signer or a JsonRpcProvider must be provided");
212
+ }
213
+ return this.provider.getSigner(accountAddress);
214
+ };
215
+ /**
216
+ * Returns the corresponding order type based on whether it allows partial fills and is restricted by zone
217
+ *
218
+ * @param input
219
+ * @param input.allowPartialFills Whether or not the order can be partially filled
220
+ * @param input.restrictedByZone Whether or not the order can only be filled/cancelled by the zone
221
+ * @returns the order type
222
+ */
223
+ Seaport.prototype._getOrderTypeFromOrderOptions = function (_a) {
224
+ var allowPartialFills = _a.allowPartialFills, restrictedByZone = _a.restrictedByZone;
225
+ if (allowPartialFills) {
226
+ return restrictedByZone
227
+ ? constants_1.OrderType.PARTIAL_RESTRICTED
228
+ : constants_1.OrderType.PARTIAL_OPEN;
229
+ }
230
+ return restrictedByZone ? constants_1.OrderType.FULL_RESTRICTED : constants_1.OrderType.FULL_OPEN;
231
+ };
232
+ /**
233
+ * Returns a use case that will create an order.
234
+ * The use case will contain the list of actions necessary to finish creating an order.
235
+ * The list of actions will either be an approval if approvals are necessary
236
+ * or a signature request that will then be supplied into the final Order struct, ready to be fulfilled.
237
+ *
238
+ * @param input
239
+ * @param input.conduitKey The conduitKey key to derive where to source your approvals from. Defaults to 0 which refers to the Seaport contract.
240
+ * Another special value is address(1) will refer to the legacy proxy. All other must derive to the specified address.
241
+ * @param input.zone The zone of the order. Defaults to the zero address.
242
+ * @param input.startTime The start time of the order. Defaults to the current unix time.
243
+ * @param input.endTime The end time of the order. Defaults to "never end".
244
+ * It is HIGHLY recommended to pass in an explicit end time
245
+ * @param input.offer The items you are willing to offer. This is a condensed version of the Seaport struct OfferItem for convenience
246
+ * @param input.consideration The items that will go to their respective recipients upon receiving your offer.
247
+ * @param input.counter The counter from which to create the order with. Automatically fetched from the contract if not provided
248
+ * @param input.allowPartialFills Whether to allow the order to be partially filled
249
+ * @param input.restrictedByZone Whether the order should be restricted by zone
250
+ * @param input.fees Convenience array to apply fees onto the order. The fees will be deducted from the
251
+ * existing consideration items and then tacked on as new consideration items
252
+ * @param input.salt Random salt
253
+ * @param input.offerer The order's creator address. Defaults to the first address on the provider.
254
+ * @param accountAddress Optional address for which to create the order with
255
+ * @returns a use case containing the list of actions needed to be performed in order to create the order
256
+ */
257
+ Seaport.prototype.createOrder = function (_a, accountAddress) {
258
+ var _b;
259
+ var _c = _a.conduitKey, conduitKey = _c === void 0 ? this.defaultConduitKey : _c, _d = _a.zone, zone = _d === void 0 ? ethers_1.ethers.constants.AddressZero : _d, _e = _a.startTime, startTime = _e === void 0 ? Math.floor(Date.now() / 1000).toString() : _e, _f = _a.endTime, endTime = _f === void 0 ? constants_1.MAX_INT.toString() : _f, offer = _a.offer, consideration = _a.consideration, counter = _a.counter, allowPartialFills = _a.allowPartialFills, restrictedByZone = _a.restrictedByZone, fees = _a.fees, _g = _a.salt, salt = _g === void 0 ? (0, order_1.generateRandomSalt)() : _g;
260
+ return __awaiter(this, void 0, void 0, function () {
261
+ var signer, offerer, offerItems, considerationItems, currencies, totalCurrencyAmount, operator, _h, resolvedCounter, balancesAndApprovals, orderType, considerationItemsWithFees, orderParameters, checkBalancesAndApprovals, insufficientApprovals, approvalActions, _j, createOrderAction, actions;
262
+ var _this = this;
263
+ return __generator(this, function (_k) {
264
+ switch (_k.label) {
265
+ case 0:
266
+ signer = this._getSigner(accountAddress);
267
+ return [4 /*yield*/, signer.getAddress()];
268
+ case 1:
269
+ offerer = _k.sent();
270
+ offerItems = offer.map(order_1.mapInputItemToOfferItem);
271
+ considerationItems = __spreadArray([], __read(consideration.map(function (consideration) {
272
+ var _a;
273
+ return (__assign(__assign({}, (0, order_1.mapInputItemToOfferItem)(consideration)), { recipient: (_a = consideration.recipient) !== null && _a !== void 0 ? _a : offerer }));
274
+ })), false);
275
+ if (!(0, order_1.areAllCurrenciesSame)({
276
+ offer: offerItems,
277
+ consideration: considerationItems,
278
+ })) {
279
+ throw new Error("All currency tokens in the order must be the same token");
280
+ }
281
+ currencies = __spreadArray(__spreadArray([], __read(offerItems), false), __read(considerationItems), false).filter(item_1.isCurrencyItem);
282
+ totalCurrencyAmount = (0, order_1.totalItemsAmount)(currencies);
283
+ operator = this.config.conduitKeyToConduit[conduitKey];
284
+ return [4 /*yield*/, Promise.all([
285
+ counter !== null && counter !== void 0 ? counter : this.getCounter(offerer),
286
+ (0, balanceAndApprovalCheck_1.getBalancesAndApprovals)({
287
+ owner: offerer,
288
+ items: offerItems,
289
+ criterias: [],
290
+ multicallProvider: this.multicallProvider,
291
+ operator: operator,
292
+ }),
293
+ ])];
294
+ case 2:
295
+ _h = __read.apply(void 0, [_k.sent(), 2]), resolvedCounter = _h[0], balancesAndApprovals = _h[1];
296
+ orderType = this._getOrderTypeFromOrderOptions({
297
+ allowPartialFills: allowPartialFills,
298
+ restrictedByZone: restrictedByZone,
299
+ });
300
+ considerationItemsWithFees = __spreadArray(__spreadArray([], __read((0, order_1.deductFees)(considerationItems, fees)), false), __read((currencies.length
301
+ ? (_b = fees === null || fees === void 0 ? void 0 : fees.map(function (fee) {
302
+ return (0, order_1.feeToConsiderationItem)({
303
+ fee: fee,
304
+ token: currencies[0].token,
305
+ baseAmount: totalCurrencyAmount.startAmount,
306
+ baseEndAmount: totalCurrencyAmount.endAmount,
307
+ });
308
+ })) !== null && _b !== void 0 ? _b : []
309
+ : [])), false);
310
+ orderParameters = {
311
+ offerer: offerer,
312
+ zone: zone,
313
+ // TODO: Placeholder
314
+ zoneHash: (0, utils_1.formatBytes32String)(resolvedCounter.toString()),
315
+ startTime: startTime,
316
+ endTime: endTime,
317
+ orderType: orderType,
318
+ offer: offerItems,
319
+ consideration: considerationItemsWithFees,
320
+ totalOriginalConsiderationItems: considerationItemsWithFees.length,
321
+ salt: salt,
322
+ conduitKey: conduitKey,
323
+ };
324
+ checkBalancesAndApprovals = this.config.balanceAndApprovalChecksOnOrderCreation;
325
+ insufficientApprovals = checkBalancesAndApprovals
326
+ ? (0, balanceAndApprovalCheck_1.validateOfferBalancesAndApprovals)({
327
+ offer: offerItems,
328
+ criterias: [],
329
+ balancesAndApprovals: balancesAndApprovals,
330
+ throwOnInsufficientBalances: checkBalancesAndApprovals,
331
+ operator: operator,
332
+ })
333
+ : [];
334
+ if (!checkBalancesAndApprovals) return [3 /*break*/, 4];
335
+ return [4 /*yield*/, (0, approval_1.getApprovalActions)(insufficientApprovals, signer)];
336
+ case 3:
337
+ _j = _k.sent();
338
+ return [3 /*break*/, 5];
339
+ case 4:
340
+ _j = [];
341
+ _k.label = 5;
342
+ case 5:
343
+ approvalActions = _j;
344
+ createOrderAction = {
345
+ type: "create",
346
+ getMessageToSign: function () {
347
+ return _this._getMessageToSign(orderParameters, resolvedCounter);
348
+ },
349
+ createOrder: function () { return __awaiter(_this, void 0, void 0, function () {
350
+ var signature;
351
+ return __generator(this, function (_a) {
352
+ switch (_a.label) {
353
+ case 0: return [4 /*yield*/, this.signOrder(orderParameters, resolvedCounter, offerer)];
354
+ case 1:
355
+ signature = _a.sent();
356
+ return [2 /*return*/, {
357
+ parameters: __assign(__assign({}, orderParameters), { counter: resolvedCounter }),
358
+ signature: signature,
359
+ }];
360
+ }
361
+ });
362
+ }); },
363
+ };
364
+ actions = __spreadArray(__spreadArray([], __read(approvalActions), false), [createOrderAction], false);
365
+ return [2 /*return*/, {
366
+ actions: actions,
367
+ executeAllActions: function () {
368
+ return (0, usecase_1.executeAllActions)(actions);
369
+ },
370
+ }];
371
+ }
372
+ });
373
+ });
374
+ };
375
+ /**
376
+ * Returns the domain data used when signing typed data
377
+ * @returns domain data
378
+ */
379
+ Seaport.prototype._getDomainData = function () {
380
+ return __awaiter(this, void 0, void 0, function () {
381
+ var chainId;
382
+ return __generator(this, function (_a) {
383
+ switch (_a.label) {
384
+ case 0: return [4 /*yield*/, this.provider.getNetwork()];
385
+ case 1:
386
+ chainId = (_a.sent()).chainId;
387
+ return [2 /*return*/, {
388
+ name: constants_1.SEAPORT_CONTRACT_NAME,
389
+ version: constants_1.SEAPORT_CONTRACT_VERSION,
390
+ chainId: chainId,
391
+ verifyingContract: this.contract.address,
392
+ }];
393
+ }
394
+ });
395
+ });
396
+ };
397
+ /**
398
+ * Returns a raw message to be signed using EIP-712
399
+ * @param orderParameters order parameter struct
400
+ * @param counter counter of the order
401
+ * @returns JSON string of the message to be signed
402
+ */
403
+ Seaport.prototype._getMessageToSign = function (orderParameters, counter) {
404
+ return __awaiter(this, void 0, void 0, function () {
405
+ var domainData, orderComponents;
406
+ return __generator(this, function (_a) {
407
+ switch (_a.label) {
408
+ case 0: return [4 /*yield*/, this._getDomainData()];
409
+ case 1:
410
+ domainData = _a.sent();
411
+ orderComponents = __assign(__assign({}, orderParameters), { counter: counter });
412
+ return [2 /*return*/, JSON.stringify(utils_1._TypedDataEncoder.getPayload(domainData, constants_1.EIP_712_ORDER_TYPE, orderComponents))];
413
+ }
414
+ });
415
+ });
416
+ };
417
+ /**
418
+ * Submits a request to your provider to sign the order. Signed orders are used for off-chain order books.
419
+ * @param orderParameters standard order parameter struct
420
+ * @param counter counter of the offerer
421
+ * @param accountAddress optional account address from which to sign the order with.
422
+ * @returns the order signature
423
+ */
424
+ Seaport.prototype.signOrder = function (orderParameters, counter, accountAddress) {
425
+ return __awaiter(this, void 0, void 0, function () {
426
+ var signer, domainData, orderComponents, signature;
427
+ return __generator(this, function (_a) {
428
+ switch (_a.label) {
429
+ case 0:
430
+ signer = this._getSigner(accountAddress);
431
+ return [4 /*yield*/, this._getDomainData()];
432
+ case 1:
433
+ domainData = _a.sent();
434
+ orderComponents = __assign(__assign({}, orderParameters), { counter: counter });
435
+ return [4 /*yield*/, signer._signTypedData(domainData, constants_1.EIP_712_ORDER_TYPE, orderComponents)];
436
+ case 2:
437
+ signature = _a.sent();
438
+ // Use EIP-2098 compact signatures to save gas. https://eips.ethereum.org/EIPS/eip-2098
439
+ return [2 /*return*/, ethers_1.ethers.utils.splitSignature(signature).compact];
440
+ }
441
+ });
442
+ });
443
+ };
444
+ /**
445
+ * Cancels a list of orders so that they are no longer fulfillable.
446
+ *
447
+ * @param orders list of order components
448
+ * @param accountAddress optional account address from which to cancel the orders from.
449
+ * @returns the set of transaction methods that can be used
450
+ */
451
+ Seaport.prototype.cancelOrders = function (orders, accountAddress) {
452
+ var signer = this._getSigner(accountAddress);
453
+ return (0, usecase_1.getTransactionMethods)(this.contract.connect(signer), "cancel", [
454
+ orders,
455
+ ]);
456
+ };
457
+ /**
458
+ * Bulk cancels all existing orders for a given account
459
+ * @param offerer the account to bulk cancel orders on
460
+ * @returns the set of transaction methods that can be used
461
+ */
462
+ Seaport.prototype.bulkCancelOrders = function (offerer) {
463
+ var signer = this._getSigner(offerer);
464
+ return (0, usecase_1.getTransactionMethods)(this.contract.connect(signer), "incrementCounter", []);
465
+ };
466
+ /**
467
+ * Approves a list of orders on-chain. This allows accounts to fulfill the order without requiring
468
+ * a signature. Can also check if an order is valid using `callStatic`
469
+ * @param orders list of order structs
470
+ * @param accountAddress optional account address to approve orders.
471
+ * @returns the set of transaction methods that can be used
472
+ */
473
+ Seaport.prototype.validate = function (orders, accountAddress) {
474
+ var signer = this._getSigner(accountAddress);
475
+ return (0, usecase_1.getTransactionMethods)(this.contract.connect(signer), "validate", [
476
+ orders,
477
+ ]);
478
+ };
479
+ /**
480
+ * Returns the order status given an order hash
481
+ * @param orderHash the hash of the order
482
+ * @returns an order status struct
483
+ */
484
+ Seaport.prototype.getOrderStatus = function (orderHash) {
485
+ return this.contract.getOrderStatus(orderHash);
486
+ };
487
+ /**
488
+ * Gets the counter of a given offerer
489
+ * @param offerer the offerer to get the counter of
490
+ * @returns counter as a number
491
+ */
492
+ Seaport.prototype.getCounter = function (offerer) {
493
+ return this.contract
494
+ .getCounter(offerer)
495
+ .then(function (counter) { return counter.toNumber(); });
496
+ };
497
+ /**
498
+ * Fulfills an order through either the basic method or the standard method
499
+ * Units to fill are denominated by the max possible size of the order, which is the greatest common denominator (GCD).
500
+ * We expose a helper to get this: getMaximumSizeForOrder
501
+ * i.e. If the maximum size of an order is 4, supplying 2 as the units to fulfill will fill half of the order: ;
502
+ * @param input
503
+ * @param input.order The standard order struct
504
+ * @param input.unitsToFill the number of units to fill for the given order. Only used if you wish to partially fill an order
505
+ * @param input.offerCriteria an array of criteria with length equal to the number of offer criteria items
506
+ * @param input.considerationCriteria an array of criteria with length equal to the number of consideration criteria items
507
+ * @param input.tips an array of optional condensed consideration items to be added onto a fulfillment
508
+ * @param input.extraData extra data supplied to the order
509
+ * @param input.accountAddress optional address from which to fulfill the order from
510
+ * @param input.conduitKey the conduitKey to source approvals from
511
+ * @param input.recipientAddress optional recipient to forward the offer to as opposed to the fulfiller.
512
+ * Defaults to the zero address which means the offer goes to the fulfiller
513
+ * @returns a use case containing the set of approval actions and fulfillment action
514
+ */
515
+ Seaport.prototype.fulfillOrder = function (_a) {
516
+ var order = _a.order, unitsToFill = _a.unitsToFill, _b = _a.offerCriteria, offerCriteria = _b === void 0 ? [] : _b, _c = _a.considerationCriteria, considerationCriteria = _c === void 0 ? [] : _c, _d = _a.tips, tips = _d === void 0 ? [] : _d, _e = _a.extraData, extraData = _e === void 0 ? "0x" : _e, accountAddress = _a.accountAddress, _f = _a.conduitKey, conduitKey = _f === void 0 ? this.defaultConduitKey : _f, _g = _a.recipientAddress, recipientAddress = _g === void 0 ? ethers_1.ethers.constants.AddressZero : _g;
517
+ return __awaiter(this, void 0, void 0, function () {
518
+ var orderParameters, offerer, offer, consideration, fulfiller, fulfillerAddress, offererOperator, fulfillerOperator, _h, offererBalancesAndApprovals, fulfillerBalancesAndApprovals, currentBlock, orderStatus, currentBlockTimestamp, totalFilled, totalSize, sanitizedOrder, timeBasedItemParams, tipConsiderationItems, isRecipientSelf;
519
+ return __generator(this, function (_j) {
520
+ switch (_j.label) {
521
+ case 0:
522
+ orderParameters = order.parameters;
523
+ offerer = orderParameters.offerer, offer = orderParameters.offer, consideration = orderParameters.consideration;
524
+ fulfiller = this._getSigner(accountAddress);
525
+ return [4 /*yield*/, fulfiller.getAddress()];
526
+ case 1:
527
+ fulfillerAddress = _j.sent();
528
+ offererOperator = this.config.conduitKeyToConduit[orderParameters.conduitKey];
529
+ fulfillerOperator = this.config.conduitKeyToConduit[conduitKey];
530
+ return [4 /*yield*/, Promise.all([
531
+ (0, balanceAndApprovalCheck_1.getBalancesAndApprovals)({
532
+ owner: offerer,
533
+ items: offer,
534
+ criterias: offerCriteria,
535
+ multicallProvider: this.multicallProvider,
536
+ operator: offererOperator,
537
+ }),
538
+ // Get fulfiller balances and approvals of all items in the set, as offer items
539
+ // may be received by the fulfiller for standard fulfills
540
+ (0, balanceAndApprovalCheck_1.getBalancesAndApprovals)({
541
+ owner: fulfillerAddress,
542
+ items: __spreadArray(__spreadArray([], __read(offer), false), __read(consideration), false),
543
+ criterias: __spreadArray(__spreadArray([], __read(offerCriteria), false), __read(considerationCriteria), false),
544
+ multicallProvider: this.multicallProvider,
545
+ operator: fulfillerOperator,
546
+ }),
547
+ this.multicallProvider.getBlock("latest"),
548
+ this.getOrderStatus(this.getOrderHash(orderParameters)),
549
+ ])];
550
+ case 2:
551
+ _h = __read.apply(void 0, [_j.sent(), 4]), offererBalancesAndApprovals = _h[0], fulfillerBalancesAndApprovals = _h[1], currentBlock = _h[2], orderStatus = _h[3];
552
+ currentBlockTimestamp = currentBlock.timestamp;
553
+ totalFilled = orderStatus.totalFilled, totalSize = orderStatus.totalSize;
554
+ sanitizedOrder = (0, fulfill_1.validateAndSanitizeFromOrderStatus)(order, orderStatus);
555
+ timeBasedItemParams = {
556
+ startTime: sanitizedOrder.parameters.startTime,
557
+ endTime: sanitizedOrder.parameters.endTime,
558
+ currentBlockTimestamp: currentBlockTimestamp,
559
+ ascendingAmountTimestampBuffer: this.config.ascendingAmountFulfillmentBuffer,
560
+ };
561
+ tipConsiderationItems = tips.map(function (tip) { return (__assign(__assign({}, (0, order_1.mapInputItemToOfferItem)(tip)), { recipient: tip.recipient })); });
562
+ isRecipientSelf = recipientAddress === ethers_1.ethers.constants.AddressZero;
563
+ // We use basic fulfills as they are more optimal for simple and "hot" use cases
564
+ // We cannot use basic fulfill if user is trying to partially fill though.
565
+ if (!unitsToFill &&
566
+ isRecipientSelf &&
567
+ (0, fulfill_1.shouldUseBasicFulfill)(sanitizedOrder.parameters, totalFilled)) {
568
+ // TODO: Use fulfiller proxy if there are approvals needed directly, but none needed for proxy
569
+ return [2 /*return*/, (0, fulfill_1.fulfillBasicOrder)({
570
+ order: sanitizedOrder,
571
+ seaportContract: this.contract,
572
+ offererBalancesAndApprovals: offererBalancesAndApprovals,
573
+ fulfillerBalancesAndApprovals: fulfillerBalancesAndApprovals,
574
+ timeBasedItemParams: timeBasedItemParams,
575
+ conduitKey: conduitKey,
576
+ offererOperator: offererOperator,
577
+ fulfillerOperator: fulfillerOperator,
578
+ signer: fulfiller,
579
+ tips: tipConsiderationItems,
580
+ })];
581
+ }
582
+ // Else, we fallback to the standard fulfill order
583
+ return [2 /*return*/, (0, fulfill_1.fulfillStandardOrder)({
584
+ order: sanitizedOrder,
585
+ unitsToFill: unitsToFill,
586
+ totalFilled: totalFilled,
587
+ totalSize: totalSize.eq(0)
588
+ ? (0, item_1.getMaximumSizeForOrder)(sanitizedOrder)
589
+ : totalSize,
590
+ offerCriteria: offerCriteria,
591
+ considerationCriteria: considerationCriteria,
592
+ tips: tipConsiderationItems,
593
+ extraData: extraData,
594
+ seaportContract: this.contract,
595
+ offererBalancesAndApprovals: offererBalancesAndApprovals,
596
+ fulfillerBalancesAndApprovals: fulfillerBalancesAndApprovals,
597
+ timeBasedItemParams: timeBasedItemParams,
598
+ conduitKey: conduitKey,
599
+ signer: fulfiller,
600
+ offererOperator: offererOperator,
601
+ fulfillerOperator: fulfillerOperator,
602
+ recipientAddress: recipientAddress,
603
+ })];
604
+ }
605
+ });
606
+ });
607
+ };
608
+ /**
609
+ * Fulfills an order through best-effort fashion. Orders that fail will not revert the whole transaction
610
+ * unless there's an issue with approvals or balance checks
611
+ * @param input
612
+ * @param input.fulfillOrderDetails list of helper order details
613
+ * @param input.accountAddress the account to fulfill orders on
614
+ * @param input.conduitKey the key from which to source approvals from
615
+ * @param input.recipientAddress optional recipient to forward the offer to as opposed to the fulfiller.
616
+ * Defaults to the zero address which means the offer goes to the fulfiller
617
+ * @returns a use case containing the set of approval actions and fulfillment action
618
+ */
619
+ Seaport.prototype.fulfillOrders = function (_a) {
620
+ var fulfillOrderDetails = _a.fulfillOrderDetails, accountAddress = _a.accountAddress, _b = _a.conduitKey, conduitKey = _b === void 0 ? this.defaultConduitKey : _b, _c = _a.recipientAddress, recipientAddress = _c === void 0 ? ethers_1.ethers.constants.AddressZero : _c;
621
+ return __awaiter(this, void 0, void 0, function () {
622
+ var fulfiller, fulfillerAddress, allOffererOperators, fulfillerOperator, allOfferItems, allConsiderationItems, allOfferCriteria, allConsiderationCriteria, _d, offerersBalancesAndApprovals, fulfillerBalancesAndApprovals, currentBlock, orderStatuses, ordersMetadata;
623
+ var _this = this;
624
+ return __generator(this, function (_e) {
625
+ switch (_e.label) {
626
+ case 0:
627
+ fulfiller = this._getSigner(accountAddress);
628
+ return [4 /*yield*/, fulfiller.getAddress()];
629
+ case 1:
630
+ fulfillerAddress = _e.sent();
631
+ allOffererOperators = fulfillOrderDetails.map(function (_a) {
632
+ var order = _a.order;
633
+ return _this.config.conduitKeyToConduit[order.parameters.conduitKey];
634
+ });
635
+ fulfillerOperator = this.config.conduitKeyToConduit[conduitKey];
636
+ allOfferItems = fulfillOrderDetails.flatMap(function (_a) {
637
+ var order = _a.order;
638
+ return order.parameters.offer;
639
+ });
640
+ allConsiderationItems = fulfillOrderDetails.flatMap(function (_a) {
641
+ var order = _a.order;
642
+ return order.parameters.consideration;
643
+ });
644
+ allOfferCriteria = fulfillOrderDetails.flatMap(function (_a) {
645
+ var _b = _a.offerCriteria, offerCriteria = _b === void 0 ? [] : _b;
646
+ return offerCriteria;
647
+ });
648
+ allConsiderationCriteria = fulfillOrderDetails.flatMap(function (_a) {
649
+ var _b = _a.considerationCriteria, considerationCriteria = _b === void 0 ? [] : _b;
650
+ return considerationCriteria;
651
+ });
652
+ return [4 /*yield*/, Promise.all([
653
+ Promise.all(fulfillOrderDetails.map(function (_a, i) {
654
+ var order = _a.order, _b = _a.offerCriteria, offerCriteria = _b === void 0 ? [] : _b;
655
+ return (0, balanceAndApprovalCheck_1.getBalancesAndApprovals)({
656
+ owner: order.parameters.offerer,
657
+ items: order.parameters.offer,
658
+ criterias: offerCriteria,
659
+ operator: allOffererOperators[i],
660
+ multicallProvider: _this.multicallProvider,
661
+ });
662
+ })),
663
+ // Get fulfiller balances and approvals of all items in the set, as offer items
664
+ // may be received by the fulfiller for standard fulfills
665
+ (0, balanceAndApprovalCheck_1.getBalancesAndApprovals)({
666
+ owner: fulfillerAddress,
667
+ items: __spreadArray(__spreadArray([], __read(allOfferItems), false), __read(allConsiderationItems), false),
668
+ criterias: __spreadArray(__spreadArray([], __read(allOfferCriteria), false), __read(allConsiderationCriteria), false),
669
+ operator: fulfillerOperator,
670
+ multicallProvider: this.multicallProvider,
671
+ }),
672
+ this.multicallProvider.getBlock("latest"),
673
+ Promise.all(fulfillOrderDetails.map(function (_a) {
674
+ var order = _a.order;
675
+ return _this.getOrderStatus(_this.getOrderHash(order.parameters));
676
+ })),
677
+ ])];
678
+ case 2:
679
+ _d = __read.apply(void 0, [_e.sent(), 4]), offerersBalancesAndApprovals = _d[0], fulfillerBalancesAndApprovals = _d[1], currentBlock = _d[2], orderStatuses = _d[3];
680
+ ordersMetadata = fulfillOrderDetails.map(function (orderDetails, index) {
681
+ var _a, _b, _c, _d, _e;
682
+ return ({
683
+ order: orderDetails.order,
684
+ unitsToFill: orderDetails.unitsToFill,
685
+ orderStatus: orderStatuses[index],
686
+ offerCriteria: (_a = orderDetails.offerCriteria) !== null && _a !== void 0 ? _a : [],
687
+ considerationCriteria: (_b = orderDetails.considerationCriteria) !== null && _b !== void 0 ? _b : [],
688
+ tips: (_d = (_c = orderDetails.tips) === null || _c === void 0 ? void 0 : _c.map(function (tip) { return (__assign(__assign({}, (0, order_1.mapInputItemToOfferItem)(tip)), { recipient: tip.recipient })); })) !== null && _d !== void 0 ? _d : [],
689
+ extraData: (_e = orderDetails.extraData) !== null && _e !== void 0 ? _e : "0x",
690
+ offererBalancesAndApprovals: offerersBalancesAndApprovals[index],
691
+ offererOperator: allOffererOperators[index],
692
+ });
693
+ });
694
+ return [2 /*return*/, (0, fulfill_1.fulfillAvailableOrders)({
695
+ ordersMetadata: ordersMetadata,
696
+ seaportContract: this.contract,
697
+ fulfillerBalancesAndApprovals: fulfillerBalancesAndApprovals,
698
+ currentBlockTimestamp: currentBlock.timestamp,
699
+ ascendingAmountTimestampBuffer: this.config.ascendingAmountFulfillmentBuffer,
700
+ fulfillerOperator: fulfillerOperator,
701
+ signer: fulfiller,
702
+ conduitKey: conduitKey,
703
+ recipientAddress: recipientAddress,
704
+ })];
705
+ }
706
+ });
707
+ });
708
+ };
709
+ /**
710
+ * NOTE: Largely incomplete. Does NOT do any balance or approval checks.
711
+ * Just exposes the bare bones matchOrders where clients will have to supply
712
+ * their own overrides as needed.
713
+ * @param input
714
+ * @param input.orders the list of orders to match
715
+ * @param input.fulfillments the list of fulfillments to match offer and considerations
716
+ * @param input.overrides any overrides the client wants, will need to pass in value for matching orders with ETH.
717
+ * @param input.accountAddress Optional address for which to match the order with
718
+ * @returns set of transaction methods for matching orders
719
+ */
720
+ Seaport.prototype.matchOrders = function (_a) {
721
+ var orders = _a.orders, fulfillments = _a.fulfillments, overrides = _a.overrides, accountAddress = _a.accountAddress;
722
+ var signer = this._getSigner(accountAddress);
723
+ return (0, usecase_1.getTransactionMethods)(this.contract.connect(signer), "matchOrders", [
724
+ orders,
725
+ fulfillments,
726
+ overrides,
727
+ ]);
728
+ };
729
+ return Seaport;
730
+ }());
731
+ exports.Seaport = Seaport;
732
+ //# sourceMappingURL=seaport.js.map