forked from ProjectOpenSea/seaport-js
-
Notifications
You must be signed in to change notification settings - Fork 0
/
seaport.ts
1150 lines (1035 loc) · 37.5 KB
/
seaport.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { providers as multicallProviders } from "@0xsequence/multicall";
import {
BigNumber,
BigNumberish,
Contract,
ethers,
PayableOverrides,
providers,
} from "ethers";
import { _TypedDataEncoder } from "ethers/lib/utils";
import { DomainRegistryABI } from "./abi/DomainRegistry";
import { SeaportABIv14 } from "./abi/Seaport_v1_4";
import {
SEAPORT_CONTRACT_NAME,
SEAPORT_CONTRACT_VERSION_V1_4,
SEAPORT_CONTRACT_VERSION_V1_5,
EIP_712_ORDER_TYPE,
KNOWN_CONDUIT_KEYS_TO_CONDUIT,
MAX_INT,
NO_CONDUIT,
OPENSEA_CONDUIT_KEY,
OrderType,
DOMAIN_REGISTRY_ADDRESS,
CROSS_CHAIN_SEAPORT_V1_4_ADDRESS,
CROSS_CHAIN_SEAPORT_V1_5_ADDRESS,
} from "./constants";
import type {
SeaportConfig,
CreateOrderAction,
CreateOrderInput,
DomainRegistryContract,
ExchangeAction,
InputCriteria,
Order,
OrderComponents,
OrderStatus,
OrderUseCase,
OrderWithCounter,
TipInputItem,
TransactionMethods,
ContractMethodReturnType,
MatchOrdersFulfillment,
SeaportContract,
Signer,
ApprovalAction,
CreateBulkOrdersAction,
} from "./types";
import { getApprovalActions } from "./utils/approval";
import {
getBalancesAndApprovals,
validateOfferBalancesAndApprovals,
} from "./utils/balanceAndApprovalCheck";
import { getBulkOrderTree } from "./utils/eip712/bulk-orders";
import {
fulfillAvailableOrders,
fulfillBasicOrder,
FulfillOrdersMetadata,
fulfillStandardOrder,
shouldUseBasicFulfill,
validateAndSanitizeFromOrderStatus,
} from "./utils/fulfill";
import { getMaximumSizeForOrder, isCurrencyItem } from "./utils/item";
import {
areAllCurrenciesSame,
deductFees,
feeToConsiderationItem,
generateRandomSalt,
mapInputItemToOfferItem,
totalItemsAmount,
} from "./utils/order";
import { executeAllActions, getTransactionMethods } from "./utils/usecase";
export class Seaport {
// Provides the raw interface to the contract for flexibility
public contract: SeaportContract;
public domainRegistry: DomainRegistryContract;
private provider: providers.Provider;
private signer?: Signer;
// Use the multicall provider for reads for batching and performance optimisations
// NOTE: Do NOT await between sequential requests if you're intending to batch
// instead, use Promise.all() and map to fetch data in parallel
// https://www.npmjs.com/package/@0xsequence/multicall
private multicallProvider: multicallProviders.MulticallProvider;
private config: Required<Omit<SeaportConfig, "overrides">>;
private defaultConduitKey: string;
readonly OPENSEA_CONDUIT_KEY: string = OPENSEA_CONDUIT_KEY;
/**
* @param providerOrSigner - The provider or signer to use for web3-related calls
* @param considerationConfig - A config to provide flexibility in the usage of Seaport
*/
public constructor(
providerOrSigner: providers.JsonRpcProvider | Signer,
{
overrides,
// Five minute buffer
ascendingAmountFulfillmentBuffer = 300,
balanceAndApprovalChecksOnOrderCreation = true,
conduitKeyToConduit,
seaportVersion = "1.5",
}: SeaportConfig = {}
) {
const provider =
providerOrSigner instanceof providers.Provider
? providerOrSigner
: providerOrSigner.provider;
this.signer = (providerOrSigner as Signer)._isSigner
? (providerOrSigner as Signer)
: undefined;
if (!provider) {
throw new Error(
"Either a provider or custom signer with provider must be provided"
);
}
this.provider = provider;
this.multicallProvider = new multicallProviders.MulticallProvider(
this.provider
);
this.contract = new Contract(
overrides?.contractAddress ??
(seaportVersion === "1.5"
? CROSS_CHAIN_SEAPORT_V1_5_ADDRESS
: CROSS_CHAIN_SEAPORT_V1_4_ADDRESS),
SeaportABIv14,
this.multicallProvider
) as SeaportContract;
this.domainRegistry = new Contract(
overrides?.domainRegistryAddress ?? DOMAIN_REGISTRY_ADDRESS,
DomainRegistryABI,
this.multicallProvider
) as DomainRegistryContract;
this.config = {
ascendingAmountFulfillmentBuffer,
balanceAndApprovalChecksOnOrderCreation,
conduitKeyToConduit: {
...KNOWN_CONDUIT_KEYS_TO_CONDUIT,
[NO_CONDUIT]: this.contract.address,
...conduitKeyToConduit,
},
seaportVersion,
};
this.defaultConduitKey = overrides?.defaultConduitKey ?? NO_CONDUIT;
}
/**
* Returns a use case that will create an order.
* The use case will contain the list of actions necessary to finish creating an order.
* The list of actions will either be an approval if approvals are necessary
* or a signature request that will then be supplied into the final Order struct, ready to be fulfilled.
*
* @param input
* @param input.conduitKey The conduitKey key to derive where to source your approvals from. Defaults to 0 which refers to the Seaport contract.
* Another special value is address(1) will refer to the legacy proxy. All other must derive to the specified address.
* @param input.zone The zone of the order. Defaults to the zero address.
* @param input.startTime The start time of the order. Defaults to the current unix time.
* @param input.endTime The end time of the order. Defaults to "never end".
* It is HIGHLY recommended to pass in an explicit end time
* @param input.offer The items you are willing to offer. This is a condensed version of the Seaport struct OfferItem for convenience
* @param input.consideration The items that will go to their respective recipients upon receiving your offer.
* @param input.counter The counter from which to create the order with. Automatically fetched from the contract if not provided
* @param input.allowPartialFills Whether to allow the order to be partially filled
* @param input.restrictedByZone Whether the order should be restricted by zone
* @param input.fees Convenience array to apply fees onto the order. The fees will be deducted from the
* existing consideration items and then tacked on as new consideration items
* @param input.domain An optional domain to be hashed and included in the first four bytes of the random salt.
* @param input.salt Arbitrary salt. If not passed in, a random salt will be generated with the first four bytes being the domain hash or empty.
* @param input.offerer The order's creator address. Defaults to the first address on the provider.
* @param accountAddress Optional address for which to create the order with
* @param exactApproval optional boolean to indicate whether the approval should be exact or not
* @returns a use case containing the list of actions needed to be performed in order to create the order
*/
public async createOrder(
input: CreateOrderInput,
accountAddress?: string,
exactApproval?: boolean
): Promise<OrderUseCase<CreateOrderAction>> {
const signer = this._getSigner(accountAddress);
const offerer = accountAddress ?? (await signer.getAddress());
const { orderComponents, approvalActions } = await this._formatOrder(
signer,
offerer,
Boolean(exactApproval),
input
);
const createOrderAction = {
type: "create",
getMessageToSign: () => {
return this._getMessageToSign(orderComponents);
},
createOrder: async () => {
const signature = await this.signOrder(orderComponents, offerer);
return {
parameters: orderComponents,
signature,
};
},
} as const;
const actions = [...approvalActions, createOrderAction] as const;
return {
actions,
executeAllActions: () =>
executeAllActions(actions) as Promise<OrderWithCounter>,
};
}
/**
* Returns a use case that will create bulk orders.
* The use case will contain the list of actions necessary to finish creating the orders.
* The list of actions will either be an approval if approvals are necessary
* or a signature request that will then be supplied into the final orders, ready to be fulfilled.
*
* @param input See {@link createOrder} for more details about the input parameters.
* @param exactApproval optional boolean to indicate whether the approval should be exact or not
* @returns a use case containing the list of actions needed to be performed in order to create the orders
*/
public async createBulkOrders(
createOrderInput: CreateOrderInput[],
accountAddress?: string,
exactApproval?: boolean
): Promise<OrderUseCase<CreateBulkOrdersAction>> {
const signer = this._getSigner(accountAddress);
const offerer = await signer.getAddress();
const offererCounter = await this.getCounter(offerer);
const allApprovalActions: ApprovalAction[] = [];
const allOrderComponents: OrderComponents[] = [];
for (const input of createOrderInput) {
input.counter ??= offererCounter;
const { orderComponents, approvalActions } = await this._formatOrder(
signer,
offerer,
Boolean(exactApproval),
input
);
allOrderComponents.push(orderComponents);
// Dedupe approvals by token address
for (const approval of approvalActions) {
if (
allApprovalActions.find((a) => a.token === approval.token) ===
undefined
) {
allApprovalActions.push(approval);
}
}
}
const createBulkOrdersAction = {
type: "createBulk",
getMessageToSign: () => {
return this._getBulkMessageToSign(allOrderComponents);
},
createBulkOrders: async () => {
const orders = await this.signBulkOrder(allOrderComponents, offerer);
return orders;
},
} as const;
const actions = [...allApprovalActions, createBulkOrdersAction] as const;
return {
actions,
executeAllActions: () =>
executeAllActions(actions) as Promise<OrderWithCounter[]>,
};
}
/**
* Formats an order for creation.
*/
private async _formatOrder(
signer: Signer,
offerer: string,
exactApproval: boolean,
{
conduitKey = this.defaultConduitKey,
zone = ethers.constants.AddressZero,
startTime = Math.floor(Date.now() / 1000).toString(),
endTime = MAX_INT.toString(),
offer,
consideration,
counter,
allowPartialFills,
restrictedByZone,
fees,
domain,
salt,
}: CreateOrderInput
) {
const offerItems = offer.map(mapInputItemToOfferItem);
const considerationItems = [
...consideration.map((consideration) => ({
...mapInputItemToOfferItem(consideration),
recipient: consideration.recipient ?? offerer,
})),
];
if (
fees?.length &&
!areAllCurrenciesSame({
offer: offerItems,
consideration: considerationItems,
})
) {
throw new Error(
"All currency tokens in the order must be the same token when applying fees"
);
}
const currencies = [...offerItems, ...considerationItems].filter(
isCurrencyItem
);
const totalCurrencyAmount = totalItemsAmount(currencies);
const operator = this.config.conduitKeyToConduit[conduitKey];
const orderType = this._getOrderTypeFromOrderOptions({
allowPartialFills,
restrictedByZone,
});
const considerationItemsWithFees = [
...deductFees(considerationItems, fees),
...(currencies.length
? fees?.map((fee) =>
feeToConsiderationItem({
fee,
token: currencies[0].token,
baseAmount: totalCurrencyAmount.startAmount,
baseEndAmount: totalCurrencyAmount.endAmount,
})
) ?? []
: []),
];
const saltFollowingConditional =
salt !== undefined
? `0x${BigNumber.from(salt).toHexString().slice(2).padStart(64, "0")}`
: generateRandomSalt(domain);
const orderComponents: OrderComponents = {
offerer,
zone,
zoneHash: ethers.constants.HashZero,
startTime,
endTime,
orderType,
offer: offerItems,
consideration: considerationItemsWithFees,
totalOriginalConsiderationItems: considerationItemsWithFees.length,
salt: saltFollowingConditional,
conduitKey,
counter: (counter ?? (await this.getCounter(offerer))).toString(),
};
const approvalActions: ApprovalAction[] = [];
if (this.config.balanceAndApprovalChecksOnOrderCreation) {
const balancesAndApprovals = await getBalancesAndApprovals({
owner: offerer,
items: offerItems,
criterias: [],
multicallProvider: this.multicallProvider,
operator,
});
const insufficientApprovals = validateOfferBalancesAndApprovals({
offer: offerItems,
criterias: [],
balancesAndApprovals,
throwOnInsufficientBalances: true,
operator,
});
const approvals = getApprovalActions(
insufficientApprovals,
exactApproval,
signer
);
approvalActions.push(...approvals);
}
return { orderComponents, approvalActions };
}
private _getSigner(accountAddress?: string): Signer {
if (this.signer) {
return this.signer;
}
if (!(this.provider instanceof providers.JsonRpcProvider)) {
throw new Error("Either signer or a JsonRpcProvider must be provided");
}
return this.provider.getSigner(accountAddress);
}
/**
* Returns the corresponding order type based on whether it allows partial fills and is restricted by zone
*
* @param input
* @param input.allowPartialFills Whether or not the order can be partially filled
* @param input.restrictedByZone Whether or not the order can only be filled/cancelled by the zone
* @returns the order type
*/
private _getOrderTypeFromOrderOptions({
allowPartialFills,
restrictedByZone,
}: Pick<CreateOrderInput, "allowPartialFills" | "restrictedByZone">) {
if (allowPartialFills) {
return restrictedByZone
? OrderType.PARTIAL_RESTRICTED
: OrderType.PARTIAL_OPEN;
}
return restrictedByZone ? OrderType.FULL_RESTRICTED : OrderType.FULL_OPEN;
}
/**
* Returns the domain data used when signing typed data
* @returns domain data
*/
private async _getDomainData() {
const { chainId } = await this.provider.getNetwork();
return {
name: SEAPORT_CONTRACT_NAME,
version:
this.config.seaportVersion === "1.5"
? SEAPORT_CONTRACT_VERSION_V1_5
: SEAPORT_CONTRACT_VERSION_V1_4,
chainId,
verifyingContract: this.contract.address,
};
}
/**
* Returns a raw message to be signed using EIP-712
* @param orderParameters order parameter struct
* @returns JSON string of the message to be signed
*/
private async _getMessageToSign(orderComponents: OrderComponents) {
const domainData = await this._getDomainData();
return JSON.stringify(
_TypedDataEncoder.getPayload(
domainData,
EIP_712_ORDER_TYPE,
orderComponents
)
);
}
/**
* Returns a raw bulk order message to be signed using EIP-712
* @param orderParameters order parameter struct
* @param counter counter of the order
* @returns JSON string of the message to be signed
*/
private async _getBulkMessageToSign(orderComponents: OrderComponents[]) {
const domainData = await this._getDomainData();
const tree = getBulkOrderTree(orderComponents);
const bulkOrderType = tree.types;
const chunks = tree.getDataToSign();
return JSON.stringify(
_TypedDataEncoder.getPayload(domainData, bulkOrderType, { tree: chunks })
);
}
/**
* Submits a request to your provider to sign the order. Signed orders are used for off-chain order books.
* @param orderComponents standard order parameter struct
* @param accountAddress optional account address from which to sign the order with.
* @returns the order signature
*/
public async signOrder(
orderComponents: OrderComponents,
accountAddress?: string
): Promise<string> {
const signer = this._getSigner(accountAddress);
const domainData = await this._getDomainData();
const signature = await signer._signTypedData(
domainData,
EIP_712_ORDER_TYPE,
orderComponents
);
// Use EIP-2098 compact signatures to save gas.
return ethers.utils.splitSignature(signature).compact;
}
/**
* Submits a request to your provider to sign the bulk order. Signed orders are used for off-chain order books.
* @param orderComponents standard order components struct
* @param accountAddress optional account address from which to sign the order with.
* @returns the orders with their signatures
*/
public async signBulkOrder(
orderComponents: OrderComponents[],
accountAddress?: string
): Promise<OrderWithCounter[]> {
const signer = this._getSigner(accountAddress);
const domainData = await this._getDomainData();
const tree = getBulkOrderTree(orderComponents);
const bulkOrderType = tree.types;
const chunks = tree.getDataToSign();
const value = { tree: chunks };
let signature = await signer._signTypedData(
domainData,
bulkOrderType,
value
);
// Use EIP-2098 compact signatures to save gas.
signature = ethers.utils.splitSignature(signature).compact;
const orders: OrderWithCounter[] = orderComponents.map((parameters, i) => ({
parameters,
signature: tree.getEncodedProofAndSignature(i, signature),
}));
return orders;
}
/**
* Cancels a list of orders so that they are no longer fulfillable.
*
* @param orders list of order components
* @param accountAddress optional account address from which to cancel the orders from.
* @param domain optional domain to be hashed and appended to calldata
* @returns the set of transaction methods that can be used
*/
public cancelOrders(
orders: OrderComponents[],
accountAddress?: string,
domain?: string
): TransactionMethods<ContractMethodReturnType<SeaportContract, "cancel">> {
const signer = this._getSigner(accountAddress);
return getTransactionMethods(
this.contract.connect(signer),
"cancel",
[orders],
domain
);
}
/**
* Bulk cancels all existing orders for a given account
* @param offerer the account to bulk cancel orders on
* @param domain optional domain to be hashed and appended to calldata
* @returns the set of transaction methods that can be used
*/
public bulkCancelOrders(
offerer?: string,
domain?: string
): TransactionMethods<
ContractMethodReturnType<SeaportContract, "incrementCounter">
> {
const signer = this._getSigner(offerer);
return getTransactionMethods(
this.contract.connect(signer),
"incrementCounter",
[],
domain
);
}
/**
* Approves a list of orders on-chain. This allows accounts to fulfill the order without requiring
* a signature. Can also check if an order is valid using `callStatic`
* @param orders list of order structs
* @param accountAddress optional account address to approve orders.
* @param domain optional domain to be hashed and appended to calldata
* @returns the set of transaction methods that can be used
*/
public validate(
orders: Order[],
accountAddress?: string,
domain?: string
): TransactionMethods<ContractMethodReturnType<SeaportContract, "validate">> {
const signer = this._getSigner(accountAddress);
return getTransactionMethods(
this.contract.connect(signer),
"validate",
[orders],
domain
);
}
/**
* Returns the order status given an order hash
* @param orderHash the hash of the order
* @returns an order status struct
*/
public getOrderStatus(orderHash: string): Promise<OrderStatus> {
return this.contract.getOrderStatus(orderHash);
}
/**
* Gets the counter of a given offerer
* @param offerer the offerer to get the counter of
* @returns counter as a number
*/
public getCounter(offerer: string): Promise<BigNumber> {
return this.contract.getCounter(offerer);
}
/**
* Calculates the order hash of order components so we can forgo executing a request to the contract
* This saves us RPC calls and latency.
*/
public getOrderHash = (orderComponents: OrderComponents): string => {
const offerItemTypeString =
"OfferItem(uint8 itemType,address token,uint256 identifierOrCriteria,uint256 startAmount,uint256 endAmount)";
const considerationItemTypeString =
"ConsiderationItem(uint8 itemType,address token,uint256 identifierOrCriteria,uint256 startAmount,uint256 endAmount,address recipient)";
const orderComponentsPartialTypeString =
"OrderComponents(address offerer,address zone,OfferItem[] offer,ConsiderationItem[] consideration,uint8 orderType,uint256 startTime,uint256 endTime,bytes32 zoneHash,uint256 salt,bytes32 conduitKey,uint256 counter)";
const orderTypeString = `${orderComponentsPartialTypeString}${considerationItemTypeString}${offerItemTypeString}`;
const offerItemTypeHash = ethers.utils.keccak256(
ethers.utils.toUtf8Bytes(offerItemTypeString)
);
const considerationItemTypeHash = ethers.utils.keccak256(
ethers.utils.toUtf8Bytes(considerationItemTypeString)
);
const orderTypeHash = ethers.utils.keccak256(
ethers.utils.toUtf8Bytes(orderTypeString)
);
const offerHash = ethers.utils.keccak256(
"0x" +
orderComponents.offer
.map((offerItem) => {
return ethers.utils
.keccak256(
"0x" +
[
offerItemTypeHash.slice(2),
offerItem.itemType.toString().padStart(64, "0"),
offerItem.token.slice(2).padStart(64, "0"),
ethers.BigNumber.from(offerItem.identifierOrCriteria)
.toHexString()
.slice(2)
.padStart(64, "0"),
ethers.BigNumber.from(offerItem.startAmount)
.toHexString()
.slice(2)
.padStart(64, "0"),
ethers.BigNumber.from(offerItem.endAmount)
.toHexString()
.slice(2)
.padStart(64, "0"),
].join("")
)
.slice(2);
})
.join("")
);
const considerationHash = ethers.utils.keccak256(
"0x" +
orderComponents.consideration
.map((considerationItem) => {
return ethers.utils
.keccak256(
"0x" +
[
considerationItemTypeHash.slice(2),
considerationItem.itemType.toString().padStart(64, "0"),
considerationItem.token.slice(2).padStart(64, "0"),
ethers.BigNumber.from(
considerationItem.identifierOrCriteria
)
.toHexString()
.slice(2)
.padStart(64, "0"),
ethers.BigNumber.from(considerationItem.startAmount)
.toHexString()
.slice(2)
.padStart(64, "0"),
ethers.BigNumber.from(considerationItem.endAmount)
.toHexString()
.slice(2)
.padStart(64, "0"),
considerationItem.recipient.slice(2).padStart(64, "0"),
].join("")
)
.slice(2);
})
.join("")
);
const derivedOrderHash = ethers.utils.keccak256(
"0x" +
[
orderTypeHash.slice(2),
orderComponents.offerer.slice(2).padStart(64, "0"),
orderComponents.zone.slice(2).padStart(64, "0"),
offerHash.slice(2),
considerationHash.slice(2),
orderComponents.orderType.toString().padStart(64, "0"),
ethers.BigNumber.from(orderComponents.startTime)
.toHexString()
.slice(2)
.padStart(64, "0"),
ethers.BigNumber.from(orderComponents.endTime)
.toHexString()
.slice(2)
.padStart(64, "0"),
orderComponents.zoneHash.slice(2),
BigNumber.from(orderComponents.salt)
.toHexString()
.slice(2)
.padStart(64, "0"),
orderComponents.conduitKey.slice(2).padStart(64, "0"),
ethers.BigNumber.from(orderComponents.counter)
.toHexString()
.slice(2)
.padStart(64, "0"),
].join("")
);
return derivedOrderHash;
};
/**
* Fulfills an order through either the basic method or the standard method
* Units to fill are denominated by the max possible size of the order, which is the greatest common denominator (GCD).
* We expose a helper to get this: getMaximumSizeForOrder
* i.e. If the maximum size of an order is 4, supplying 2 as the units to fulfill will fill half of the order: ;
* @param input
* @param input.order The standard order struct
* @param input.unitsToFill the number of units to fill for the given order. Only used if you wish to partially fill an order
* @param input.offerCriteria an array of criteria with length equal to the number of offer criteria items
* @param input.considerationCriteria an array of criteria with length equal to the number of consideration criteria items
* @param input.tips an array of optional condensed consideration items to be added onto a fulfillment
* @param input.extraData extra data supplied to the order
* @param input.accountAddress optional address from which to fulfill the order from
* @param input.conduitKey the conduitKey to source approvals from
* @param input.recipientAddress optional recipient to forward the offer to as opposed to the fulfiller.
* Defaults to the zero address which means the offer goes to the fulfiller
* @param input.domain optional domain to be hashed and appended to calldata
* @param input.exactApproval optional boolean to indicate whether the approval should be exact or not
* @returns a use case containing the set of approval actions and fulfillment action
*/
public async fulfillOrder({
order,
unitsToFill,
offerCriteria = [],
considerationCriteria = [],
tips = [],
extraData = "0x",
accountAddress,
conduitKey = this.defaultConduitKey,
recipientAddress = ethers.constants.AddressZero,
domain,
exactApproval = false,
}: {
order: OrderWithCounter;
unitsToFill?: BigNumberish;
offerCriteria?: InputCriteria[];
considerationCriteria?: InputCriteria[];
tips?: TipInputItem[];
extraData?: string;
accountAddress?: string;
conduitKey?: string;
recipientAddress?: string;
domain?: string;
exactApproval?: boolean;
}): Promise<
OrderUseCase<
ExchangeAction<
ContractMethodReturnType<
SeaportContract,
"fulfillBasicOrder" | "fulfillOrder" | "fulfillAdvancedOrder"
>
>
>
> {
if (!order.signature) {
throw new Error("Order is missing signature");
}
const { parameters: orderParameters } = order;
const { offerer, offer, consideration } = orderParameters;
const fulfiller = this._getSigner(accountAddress);
const fulfillerAddress = await fulfiller.getAddress();
const offererOperator =
this.config.conduitKeyToConduit[orderParameters.conduitKey];
const fulfillerOperator = this.config.conduitKeyToConduit[conduitKey];
const [
offererBalancesAndApprovals,
fulfillerBalancesAndApprovals,
currentBlock,
orderStatus,
] = await Promise.all([
getBalancesAndApprovals({
owner: offerer,
items: offer,
criterias: offerCriteria,
multicallProvider: this.multicallProvider,
operator: offererOperator,
}),
// Get fulfiller balances and approvals of all items in the set, as offer items
// may be received by the fulfiller for standard fulfills
getBalancesAndApprovals({
owner: fulfillerAddress,
items: [...offer, ...consideration],
criterias: [...offerCriteria, ...considerationCriteria],
multicallProvider: this.multicallProvider,
operator: fulfillerOperator,
}),
this.multicallProvider.getBlock("latest"),
this.getOrderStatus(this.getOrderHash(orderParameters)),
]);
const currentBlockTimestamp = currentBlock.timestamp;
const { totalFilled, totalSize } = orderStatus;
const sanitizedOrder = validateAndSanitizeFromOrderStatus(
order,
orderStatus
);
const timeBasedItemParams = {
startTime: sanitizedOrder.parameters.startTime,
endTime: sanitizedOrder.parameters.endTime,
currentBlockTimestamp,
ascendingAmountTimestampBuffer:
this.config.ascendingAmountFulfillmentBuffer,
};
const tipConsiderationItems = tips.map((tip) => ({
...mapInputItemToOfferItem(tip),
recipient: tip.recipient,
}));
const isRecipientSelf = recipientAddress === ethers.constants.AddressZero;
// We use basic fulfills as they are more optimal for simple and "hot" use cases
// We cannot use basic fulfill if user is trying to partially fill though.
if (
!unitsToFill &&
isRecipientSelf &&
shouldUseBasicFulfill(sanitizedOrder.parameters, totalFilled)
) {
// TODO: Use fulfiller proxy if there are approvals needed directly, but none needed for proxy
return fulfillBasicOrder(
{
order: sanitizedOrder,
seaportContract: this.contract,
offererBalancesAndApprovals,
fulfillerBalancesAndApprovals,
timeBasedItemParams,
conduitKey,
offererOperator,
fulfillerOperator,
signer: fulfiller,
tips: tipConsiderationItems,
domain,
},
exactApproval
);
}
// Else, we fallback to the standard fulfill order
return fulfillStandardOrder(
{
order: sanitizedOrder,
unitsToFill,
totalFilled,
totalSize: totalSize.eq(0)
? getMaximumSizeForOrder(sanitizedOrder)
: totalSize,
offerCriteria,
considerationCriteria,
tips: tipConsiderationItems,
extraData,
seaportContract: this.contract,
offererBalancesAndApprovals,
fulfillerBalancesAndApprovals,
timeBasedItemParams,
conduitKey,
signer: fulfiller,
offererOperator,
fulfillerOperator,
recipientAddress,
domain,
},
exactApproval
);
}
/**
* Fulfills an order through best-effort fashion. Orders that fail will not revert the whole transaction
* unless there's an issue with approvals or balance checks
* @param input
* @param input.fulfillOrderDetails list of helper order details
* @param input.accountAddress the account to fulfill orders on
* @param input.conduitKey the key from which to source approvals from
* @param input.recipientAddress optional recipient to forward the offer to as opposed to the fulfiller.
* Defaults to the zero address which means the offer goes to the fulfiller
* @param input.domain optional domain to be hashed and appended to calldata
* @param input.exactApproval optional boolean to indicate whether the approval should be exact or not
* @returns a use case containing the set of approval actions and fulfillment action
*/
public async fulfillOrders({
fulfillOrderDetails,
accountAddress,
conduitKey = this.defaultConduitKey,
recipientAddress = ethers.constants.AddressZero,
domain,
exactApproval = false,
}: {
fulfillOrderDetails: {
order: OrderWithCounter;
unitsToFill?: BigNumberish;
offerCriteria?: InputCriteria[];
considerationCriteria?: InputCriteria[];
tips?: TipInputItem[];
extraData?: string;
}[];
accountAddress?: string;
conduitKey?: string;
recipientAddress?: string;
domain?: string;
exactApproval?: boolean;
}) {
if (
fulfillOrderDetails.some((orderDetails) => !orderDetails.order.signature)
) {
throw new Error("All orders must include signatures");
}
const fulfiller = this._getSigner(accountAddress);
const fulfillerAddress = await fulfiller.getAddress();
const allOffererOperators = fulfillOrderDetails.map(
({ order }) =>
this.config.conduitKeyToConduit[order.parameters.conduitKey]
);
const fulfillerOperator = this.config.conduitKeyToConduit[conduitKey];
const allOfferItems = fulfillOrderDetails.flatMap(
({ order }) => order.parameters.offer
);
const allConsiderationItems = fulfillOrderDetails.flatMap(
({ order }) => order.parameters.consideration
);
const allOfferCriteria = fulfillOrderDetails.flatMap(
({ offerCriteria = [] }) => offerCriteria
);
const allConsiderationCriteria = fulfillOrderDetails.flatMap(
({ considerationCriteria = [] }) => considerationCriteria
);
const [
offerersBalancesAndApprovals,
fulfillerBalancesAndApprovals,