forked from ProjectOpenSea/opensea-js
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathseaport.js
3248 lines (3248 loc) · 206 KB
/
seaport.js
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
"use strict";
var __assign = (this && this.__assign) || Object.assign || function(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
t[p] = s[p];
}
return t;
};
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __generator = (this && this.__generator) || function (thisArg, body) {
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
function verb(n) { return function (v) { return step([n, v]); }; }
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while (_) try {
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;
if (y = 0, t) op = [op[0] & 2, t.value];
switch (op[0]) {
case 0: case 1: t = op; break;
case 4: _.label++; return { value: op[1], done: false };
case 5: _.label++; y = op[1]; op = [0]; continue;
case 7: op = _.ops.pop(); _.trys.pop(); continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
if (t[2]) _.ops.pop();
_.trys.pop(); continue;
}
op = body.call(thisArg, _);
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
}
};
Object.defineProperty(exports, "__esModule", { value: true });
var Web3 = require("web3");
var wyvern_js_1 = require("wyvern-js");
var WyvernSchemas = require("wyvern-schemas");
var _ = require("lodash");
var api_1 = require("./api");
var contracts_1 = require("./contracts");
var types_1 = require("./types");
var utils_1 = require("./utils/utils");
var schema_1 = require("./utils/schema");
var debugging_1 = require("./debugging");
var bignumber_js_1 = require("bignumber.js");
var fbemitter_1 = require("fbemitter");
var ethereumjs_util_1 = require("ethereumjs-util");
var constants_1 = require("./constants");
var OpenSeaPort = /** @class */ (function () {
/**
* Your very own seaport.
* Create a new instance of OpenSeaJS.
* @param provider Web3 Provider to use for transactions. For example:
* `const provider = new Web3.providers.HttpProvider('https://mainnet.infura.io')`
* @param apiConfig configuration options, including `networkName`
* @param logger logger, optional, a function that will be called with debugging
* information
*/
function OpenSeaPort(provider, apiConfig, logger) {
if (apiConfig === void 0) { apiConfig = {}; }
// Extra gwei to add to the mean gas price when making transactions
this.gasPriceAddition = new bignumber_js_1.BigNumber(3);
// Multiply gas estimate by this factor when making transactions
this.gasIncreaseFactor = constants_1.DEFAULT_GAS_INCREASE_FACTOR;
// API config
apiConfig.networkName = apiConfig.networkName || types_1.Network.Main;
apiConfig.gasPrice = apiConfig.gasPrice || utils_1.makeBigNumber(300000);
this.api = new api_1.OpenSeaAPI(apiConfig);
this._networkName = apiConfig.networkName;
var readonlyProvider = new Web3.providers.HttpProvider(this._networkName == types_1.Network.Main ? constants_1.MAINNET_PROVIDER_URL : constants_1.RINKEBY_PROVIDER_URL);
// Web3 Config
this.web3 = new Web3(provider);
this.web3ReadOnly = new Web3(readonlyProvider);
// WyvernJS config
this._wyvernProtocol = new wyvern_js_1.WyvernProtocol(provider, {
network: this._networkName,
gasPrice: apiConfig.gasPrice,
});
// WyvernJS config for readonly (optimization for infura calls)
this._wyvernProtocolReadOnly = new wyvern_js_1.WyvernProtocol(readonlyProvider, {
network: this._networkName,
gasPrice: apiConfig.gasPrice,
});
// WrappedNFTLiquidationProxy Config
this._wrappedNFTFactoryAddress = this._networkName == types_1.Network.Main ? constants_1.WRAPPED_NFT_FACTORY_ADDRESS_MAINNET : constants_1.WRAPPED_NFT_FACTORY_ADDRESS_RINKEBY;
this._wrappedNFTLiquidationProxyAddress = this._networkName == types_1.Network.Main ? constants_1.WRAPPED_NFT_LIQUIDATION_PROXY_ADDRESS_MAINNET : constants_1.WRAPPED_NFT_LIQUIDATION_PROXY_ADDRESS_RINKEBY;
this._uniswapFactoryAddress = this._networkName == types_1.Network.Main ? constants_1.UNISWAP_FACTORY_ADDRESS_MAINNET : constants_1.UNISWAP_FACTORY_ADDRESS_RINKEBY;
// Emit events
this._emitter = new fbemitter_1.EventEmitter();
// Debugging: default to nothing
this.logger = logger || (function (arg) { return arg; });
}
/**
* Add a listener to a marketplace event
* @param event An event to listen for
* @param listener A callback that will accept an object with event data
* @param once Whether the listener should only be called once
*/
OpenSeaPort.prototype.addListener = function (event, listener, once) {
if (once === void 0) { once = false; }
var subscription = once
? this._emitter.once(event, listener)
: this._emitter.addListener(event, listener);
return subscription;
};
/**
* Remove an event listener, included here for completeness.
* Simply calls `.remove()` on a subscription
* @param subscription The event subscription returned from `addListener`
*/
OpenSeaPort.prototype.removeListener = function (subscription) {
subscription.remove();
};
/**
* Remove all event listeners. Good idea to call this when you're unmounting
* a component that listens to events to make UI updates
* @param event Optional EventType to remove listeners for
*/
OpenSeaPort.prototype.removeAllListeners = function (event) {
this._emitter.removeAllListeners(event);
};
/**
* Wraps an arbirary group of NFTs into their corresponding WrappedNFT ERC20 tokens.
* Emits the `WrapAssets` event when the transaction is prompted.
* @param param0 __namedParameters Object
* @param assets An array of objects with the tokenId and tokenAddress of each of the assets to bundle together.
* @param accountAddress Address of the user's wallet
*/
OpenSeaPort.prototype.wrapAssets = function (_a) {
var assets = _a.assets, accountAddress = _a.accountAddress;
return __awaiter(this, void 0, void 0, function () {
var schema, wyAssets, tokenIds, tokenAddresses, isMixedBatchOfAssets, gasPrice, txHash;
var _this = this;
return __generator(this, function (_b) {
switch (_b.label) {
case 0:
schema = this._getSchema(types_1.WyvernSchemaName.ERC721);
wyAssets = assets.map(function (a) { return utils_1.getWyvernAsset(schema, a); });
tokenIds = wyAssets.map(function (a) { return a.id; });
tokenAddresses = wyAssets.map(function (a) { return a.address; });
isMixedBatchOfAssets = !tokenAddresses.every(function (val, i, arr) { return val === arr[0]; });
this._dispatch(types_1.EventType.WrapAssets, { assets: wyAssets, accountAddress: accountAddress });
return [4 /*yield*/, this._computeGasPrice()];
case 1:
gasPrice = _b.sent();
return [4 /*yield*/, utils_1.sendRawTransaction(this.web3, {
from: accountAddress,
to: this._wrappedNFTLiquidationProxyAddress,
value: 0,
data: schema_1.encodeCall(contracts_1.getMethod(contracts_1.WrappedNFTLiquidationProxy, 'wrapNFTs'), [tokenIds, tokenAddresses, isMixedBatchOfAssets]),
gasPrice: gasPrice
}, function (error) {
_this._dispatch(types_1.EventType.TransactionDenied, { error: error, accountAddress: accountAddress });
})];
case 2:
txHash = _b.sent();
return [4 /*yield*/, this._confirmTransaction(txHash, types_1.EventType.WrapAssets, "Wrapping Assets")];
case 3:
_b.sent();
return [2 /*return*/];
}
});
});
};
/**
* Unwraps an arbirary group of NFTs from their corresponding WrappedNFT ERC20 tokens back into ERC721 tokens.
* Emits the `UnwrapAssets` event when the transaction is prompted.
* @param param0 __namedParameters Object
* @param assets An array of objects with the tokenId and tokenAddress of each of the assets to bundle together.
* @param destinationAddresses Addresses that each resulting ERC721 token will be sent to. Must be the same length as `tokenIds`. Each address corresponds with its respective token ID in the `tokenIds` array.
* @param accountAddress Address of the user's wallet
*/
OpenSeaPort.prototype.unwrapAssets = function (_a) {
var assets = _a.assets, destinationAddresses = _a.destinationAddresses, accountAddress = _a.accountAddress;
return __awaiter(this, void 0, void 0, function () {
var schema, wyAssets, tokenIds, tokenAddresses, isMixedBatchOfAssets, gasPrice, txHash;
var _this = this;
return __generator(this, function (_b) {
switch (_b.label) {
case 0:
if (!assets || !destinationAddresses || assets.length != destinationAddresses.length) {
throw new Error("The 'assets' and 'destinationAddresses' arrays must exist and have the same length.");
}
schema = this._getSchema(types_1.WyvernSchemaName.ERC721);
wyAssets = assets.map(function (a) { return utils_1.getWyvernAsset(schema, a); });
tokenIds = wyAssets.map(function (a) { return a.id; });
tokenAddresses = wyAssets.map(function (a) { return a.address; });
isMixedBatchOfAssets = !tokenAddresses.every(function (val, i, arr) { return val === arr[0]; });
this._dispatch(types_1.EventType.UnwrapAssets, { assets: wyAssets, accountAddress: accountAddress });
return [4 /*yield*/, this._computeGasPrice()];
case 1:
gasPrice = _b.sent();
return [4 /*yield*/, utils_1.sendRawTransaction(this.web3, {
from: accountAddress,
to: this._wrappedNFTLiquidationProxyAddress,
value: 0,
data: schema_1.encodeCall(contracts_1.getMethod(contracts_1.WrappedNFTLiquidationProxy, 'unwrapNFTs'), [tokenIds, tokenAddresses, destinationAddresses, isMixedBatchOfAssets]),
gasPrice: gasPrice
}, function (error) {
_this._dispatch(types_1.EventType.TransactionDenied, { error: error, accountAddress: accountAddress });
})];
case 2:
txHash = _b.sent();
return [4 /*yield*/, this._confirmTransaction(txHash, types_1.EventType.UnwrapAssets, "Unwrapping Assets")];
case 3:
_b.sent();
return [2 /*return*/];
}
});
});
};
/**
* Liquidates an arbirary group of NFTs by atomically wrapping them into their
* corresponding WrappedNFT ERC20 tokens, and then immediately selling those
* ERC20 tokens on their corresponding Uniswap exchange.
* Emits the `LiquidateAssets` event when the transaction is prompted.
* @param param0 __namedParameters Object
* @param assets An array of objects with the tokenId and tokenAddress of each of the assets to bundle together.
* @param accountAddress Address of the user's wallet
* @param uniswapSlippageAllowedInBasisPoints The amount of slippage that a user will tolerate in their Uniswap trade; if Uniswap cannot fulfill the order without more slippage, the whole function will revert.
*/
OpenSeaPort.prototype.liquidateAssets = function (_a) {
var assets = _a.assets, accountAddress = _a.accountAddress, uniswapSlippageAllowedInBasisPoints = _a.uniswapSlippageAllowedInBasisPoints;
return __awaiter(this, void 0, void 0, function () {
var uniswapSlippage, schema, wyAssets, tokenIds, tokenAddresses, isMixedBatchOfAssets, gasPrice, txHash;
var _this = this;
return __generator(this, function (_b) {
switch (_b.label) {
case 0:
uniswapSlippage = uniswapSlippageAllowedInBasisPoints === 0 ? constants_1.DEFAULT_WRAPPED_NFT_LIQUIDATION_UNISWAP_SLIPPAGE_IN_BASIS_POINTS : uniswapSlippageAllowedInBasisPoints;
schema = this._getSchema(types_1.WyvernSchemaName.ERC721);
wyAssets = assets.map(function (a) { return utils_1.getWyvernAsset(schema, a); });
tokenIds = wyAssets.map(function (a) { return a.id; });
tokenAddresses = wyAssets.map(function (a) { return a.address; });
isMixedBatchOfAssets = !tokenAddresses.every(function (val, i, arr) { return val === arr[0]; });
this._dispatch(types_1.EventType.LiquidateAssets, { assets: wyAssets, accountAddress: accountAddress });
return [4 /*yield*/, this._computeGasPrice()];
case 1:
gasPrice = _b.sent();
return [4 /*yield*/, utils_1.sendRawTransaction(this.web3, {
from: accountAddress,
to: this._wrappedNFTLiquidationProxyAddress,
value: 0,
data: schema_1.encodeCall(contracts_1.getMethod(contracts_1.WrappedNFTLiquidationProxy, 'liquidateNFTs'), [tokenIds, tokenAddresses, isMixedBatchOfAssets, uniswapSlippage]),
gasPrice: gasPrice
}, function (error) {
_this._dispatch(types_1.EventType.TransactionDenied, { error: error, accountAddress: accountAddress });
})];
case 2:
txHash = _b.sent();
return [4 /*yield*/, this._confirmTransaction(txHash, types_1.EventType.LiquidateAssets, "Liquidating Assets")];
case 3:
_b.sent();
return [2 /*return*/];
}
});
});
};
/**
* Purchases a bundle of WrappedNFT tokens from Uniswap and then unwraps them into ERC721 tokens.
* Emits the `PurchaseAssets` event when the transaction is prompted.
* @param param0 __namedParameters Object
* @param numTokensToBuy The number of WrappedNFT tokens to purchase and unwrap
* @param amount The estimated cost in wei for tokens (probably some ratio above the minimum amount to avoid the transaction failing due to frontrunning, minimum amount is found by calling UniswapExchange(uniswapAddress).getEthToTokenOutputPrice(numTokensToBuy.mul(10**18));
* @param contractAddress Address of the corresponding NFT core contract for these NFTs.
* @param accountAddress Address of the user's wallet
*/
OpenSeaPort.prototype.purchaseAssets = function (_a) {
var numTokensToBuy = _a.numTokensToBuy, amount = _a.amount, contractAddress = _a.contractAddress, accountAddress = _a.accountAddress;
return __awaiter(this, void 0, void 0, function () {
var token, gasPrice, txHash;
var _this = this;
return __generator(this, function (_b) {
switch (_b.label) {
case 0:
token = WyvernSchemas.tokens[this._networkName].canonicalWrappedEther;
this._dispatch(types_1.EventType.PurchaseAssets, { amount: amount, contractAddress: contractAddress, accountAddress: accountAddress });
return [4 /*yield*/, this._computeGasPrice()];
case 1:
gasPrice = _b.sent();
return [4 /*yield*/, utils_1.sendRawTransaction(this.web3, {
from: accountAddress,
to: this._wrappedNFTLiquidationProxyAddress,
value: amount,
data: schema_1.encodeCall(contracts_1.getMethod(contracts_1.WrappedNFTLiquidationProxy, 'purchaseNFTs'), [numTokensToBuy, contractAddress]),
gasPrice: gasPrice
}, function (error) {
_this._dispatch(types_1.EventType.TransactionDenied, { error: error, accountAddress: accountAddress });
})];
case 2:
txHash = _b.sent();
return [4 /*yield*/, this._confirmTransaction(txHash, types_1.EventType.PurchaseAssets, "Purchasing Assets")];
case 3:
_b.sent();
return [2 /*return*/];
}
});
});
};
/**
* Gets the estimated cost or payout of either buying or selling NFTs to Uniswap using either purchaseAssts() or liquidateAssets()
* @param param0 __namedParameters Object
* @param numTokens The number of WrappedNFT tokens to either purchase or sell
* @param isBuying A bool for whether the user is buying or selling
* @param contractAddress Address of the corresponding NFT core contract for these NFTs.
*/
OpenSeaPort.prototype.getQuoteFromUniswap = function (_a) {
var numTokens = _a.numTokens, isBuying = _a.isBuying, contractAddress = _a.contractAddress;
return __awaiter(this, void 0, void 0, function () {
var wrappedNFTFactoryContract, wrappedNFTFactory, wrappedNFTAddress, wrappedNFTContract, wrappedNFT, uniswapFactoryContract, uniswapFactory, uniswapExchangeAddress, uniswapExchangeContract, uniswapExchange, amount, _b, _c;
return __generator(this, function (_d) {
switch (_d.label) {
case 0:
wrappedNFTFactoryContract = this.web3.eth.contract(contracts_1.WrappedNFTFactory);
return [4 /*yield*/, wrappedNFTFactoryContract.at(this._wrappedNFTFactoryAddress)];
case 1:
wrappedNFTFactory = _d.sent();
return [4 /*yield*/, wrappedNFTFactory.nftContractToWrapperContract(contractAddress)];
case 2:
wrappedNFTAddress = _d.sent();
wrappedNFTContract = this.web3.eth.contract(contracts_1.WrappedNFT);
return [4 /*yield*/, wrappedNFTContract.at(wrappedNFTAddress)];
case 3:
wrappedNFT = _d.sent();
uniswapFactoryContract = this.web3.eth.contract(contracts_1.UniswapFactory);
return [4 /*yield*/, uniswapFactoryContract.at(this._uniswapFactoryAddress)];
case 4:
uniswapFactory = _d.sent();
return [4 /*yield*/, uniswapFactory.getExchange(wrappedNFTAddress)];
case 5:
uniswapExchangeAddress = _d.sent();
uniswapExchangeContract = this.web3.eth.contract(contracts_1.UniswapExchange);
return [4 /*yield*/, uniswapExchangeContract.at(uniswapExchangeAddress)
// Convert desired WNFT to wei
];
case 6:
uniswapExchange = _d.sent();
amount = wyvern_js_1.WyvernProtocol.toBaseUnitAmount(utils_1.makeBigNumber(numTokens), wrappedNFT.decimals());
if (!isBuying) return [3 /*break*/, 8];
_b = parseInt;
return [4 /*yield*/, uniswapExchange.getEthToTokenOutputPrice(amount)];
case 7: return [2 /*return*/, _b.apply(void 0, [_d.sent()])];
case 8:
_c = parseInt;
return [4 /*yield*/, uniswapExchange.getTokenToEthInputPrice(amount)];
case 9: return [2 /*return*/, _c.apply(void 0, [_d.sent()])];
}
});
});
};
/**
* Wrap ETH into W-ETH.
* W-ETH is needed for placing buy orders (making offers).
* Emits the `WrapEth` event when the transaction is prompted.
* @param param0 __namedParameters Object
* @param amountInEth How much ether to wrap
* @param accountAddress Address of the user's wallet containing the ether
*/
OpenSeaPort.prototype.wrapEth = function (_a) {
var amountInEth = _a.amountInEth, accountAddress = _a.accountAddress;
return __awaiter(this, void 0, void 0, function () {
var token, amount, gasPrice, txHash;
var _this = this;
return __generator(this, function (_b) {
switch (_b.label) {
case 0:
token = WyvernSchemas.tokens[this._networkName].canonicalWrappedEther;
amount = wyvern_js_1.WyvernProtocol.toBaseUnitAmount(utils_1.makeBigNumber(amountInEth), token.decimals);
this._dispatch(types_1.EventType.WrapEth, { accountAddress: accountAddress, amount: amount });
return [4 /*yield*/, this._computeGasPrice()];
case 1:
gasPrice = _b.sent();
return [4 /*yield*/, utils_1.sendRawTransaction(this.web3, {
from: accountAddress,
to: token.address,
value: amount,
data: schema_1.encodeCall(contracts_1.getMethod(contracts_1.CanonicalWETH, 'deposit'), []),
gasPrice: gasPrice
}, function (error) {
_this._dispatch(types_1.EventType.TransactionDenied, { error: error, accountAddress: accountAddress });
})];
case 2:
txHash = _b.sent();
return [4 /*yield*/, this._confirmTransaction(txHash, types_1.EventType.WrapEth, "Wrapping ETH")];
case 3:
_b.sent();
return [2 /*return*/];
}
});
});
};
/**
* Unwrap W-ETH into ETH.
* Emits the `UnwrapWeth` event when the transaction is prompted.
* @param param0 __namedParameters Object
* @param amountInEth How much W-ETH to unwrap
* @param accountAddress Address of the user's wallet containing the W-ETH
*/
OpenSeaPort.prototype.unwrapWeth = function (_a) {
var amountInEth = _a.amountInEth, accountAddress = _a.accountAddress;
return __awaiter(this, void 0, void 0, function () {
var token, amount, gasPrice, txHash;
var _this = this;
return __generator(this, function (_b) {
switch (_b.label) {
case 0:
token = WyvernSchemas.tokens[this._networkName].canonicalWrappedEther;
amount = wyvern_js_1.WyvernProtocol.toBaseUnitAmount(utils_1.makeBigNumber(amountInEth), token.decimals);
this._dispatch(types_1.EventType.UnwrapWeth, { accountAddress: accountAddress, amount: amount });
return [4 /*yield*/, this._computeGasPrice()];
case 1:
gasPrice = _b.sent();
return [4 /*yield*/, utils_1.sendRawTransaction(this.web3, {
from: accountAddress,
to: token.address,
value: 0,
data: schema_1.encodeCall(contracts_1.getMethod(contracts_1.CanonicalWETH, 'withdraw'), [amount.toString()]),
gasPrice: gasPrice
}, function (error) {
_this._dispatch(types_1.EventType.TransactionDenied, { error: error, accountAddress: accountAddress });
})];
case 2:
txHash = _b.sent();
return [4 /*yield*/, this._confirmTransaction(txHash, types_1.EventType.UnwrapWeth, "Unwrapping W-ETH")];
case 3:
_b.sent();
return [2 /*return*/];
}
});
});
};
/**
* Create a buy order to make an offer on a bundle or group of assets.
* Will throw an 'Insufficient balance' error if the maker doesn't have enough W-ETH to make the offer.
* If the user hasn't approved W-ETH access yet, this will emit `ApproveCurrency` before asking for approval.
* @param param0 __namedParameters Object
* @param assets Array of Asset objects to bid on
* @param collection Optional collection for computing fees, required only if all assets belong to the same collection
* @param quantities The quantity of each asset to sell. Defaults to 1 for each.
* @param accountAddress Address of the maker's wallet
* @param startAmount Value of the offer, in units of the payment token (or wrapped ETH if no payment token address specified)
* @param expirationTime Expiration time for the order, in seconds. An expiration time of 0 means "never expire"
* @param paymentTokenAddress Optional address for using an ERC-20 token in the order. If unspecified, defaults to W-ETH
* @param sellOrder Optional sell order (like an English auction) to ensure fee and schema compatibility
* @param referrerAddress The optional address that referred the order
*/
OpenSeaPort.prototype.createBundleBuyOrder = function (_a) {
var assets = _a.assets, collection = _a.collection, quantities = _a.quantities, accountAddress = _a.accountAddress, startAmount = _a.startAmount, _b = _a.expirationTime, expirationTime = _b === void 0 ? 0 : _b, paymentTokenAddress = _a.paymentTokenAddress, sellOrder = _a.sellOrder, referrerAddress = _a.referrerAddress;
return __awaiter(this, void 0, void 0, function () {
var order, hashedOrder, signature, error_1, orderWithSignature;
return __generator(this, function (_c) {
switch (_c.label) {
case 0:
// Default to 1 of each asset
quantities = quantities || assets.map(function (a) { return 1; });
paymentTokenAddress = paymentTokenAddress || WyvernSchemas.tokens[this._networkName].canonicalWrappedEther.address;
return [4 /*yield*/, this._makeBundleBuyOrder({
assets: assets,
collection: collection,
quantities: quantities,
accountAddress: accountAddress,
startAmount: startAmount,
expirationTime: expirationTime,
paymentTokenAddress: paymentTokenAddress,
extraBountyBasisPoints: 0,
sellOrder: sellOrder,
referrerAddress: referrerAddress
})
// NOTE not in Wyvern exchange code:
// frontend checks to make sure
// token is approved and sufficiently available
];
case 1:
order = _c.sent();
// NOTE not in Wyvern exchange code:
// frontend checks to make sure
// token is approved and sufficiently available
return [4 /*yield*/, this._buyOrderValidationAndApprovals({ order: order, accountAddress: accountAddress })];
case 2:
// NOTE not in Wyvern exchange code:
// frontend checks to make sure
// token is approved and sufficiently available
_c.sent();
hashedOrder = __assign({}, order, { hash: utils_1.getOrderHash(order) });
_c.label = 3;
case 3:
_c.trys.push([3, 5, , 6]);
return [4 /*yield*/, this._authorizeOrder(hashedOrder)];
case 4:
signature = _c.sent();
return [3 /*break*/, 6];
case 5:
error_1 = _c.sent();
console.error(error_1);
throw new Error("You declined to authorize your offer");
case 6:
orderWithSignature = __assign({}, hashedOrder, signature);
return [2 /*return*/, this.validateAndPostOrder(orderWithSignature)];
}
});
});
};
/**
* Create a buy order to make an offer on an asset.
* Will throw an 'Insufficient balance' error if the maker doesn't have enough W-ETH to make the offer.
* If the user hasn't approved W-ETH access yet, this will emit `ApproveCurrency` before asking for approval.
* @param param0 __namedParameters Object
* @param asset The asset to trade
* @param accountAddress Address of the maker's wallet
* @param startAmount Value of the offer, in units of the payment token (or wrapped ETH if no payment token address specified)
* @param quantity The number of assets to bid for (if fungible or semi-fungible). Defaults to 1. In units, not base units, e.g. not wei.
* @param expirationTime Expiration time for the order, in seconds. An expiration time of 0 means "never expire"
* @param paymentTokenAddress Optional address for using an ERC-20 token in the order. If unspecified, defaults to W-ETH
* @param sellOrder Optional sell order (like an English auction) to ensure fee and schema compatibility
* @param referrerAddress The optional address that referred the order
*/
OpenSeaPort.prototype.createBuyOrder = function (_a) {
var asset = _a.asset, accountAddress = _a.accountAddress, startAmount = _a.startAmount, _b = _a.quantity, quantity = _b === void 0 ? 1 : _b, _c = _a.expirationTime, expirationTime = _c === void 0 ? 0 : _c, paymentTokenAddress = _a.paymentTokenAddress, sellOrder = _a.sellOrder, referrerAddress = _a.referrerAddress;
return __awaiter(this, void 0, void 0, function () {
var order, hashedOrder, signature, error_2, orderWithSignature;
return __generator(this, function (_d) {
switch (_d.label) {
case 0:
paymentTokenAddress = paymentTokenAddress || WyvernSchemas.tokens[this._networkName].canonicalWrappedEther.address;
return [4 /*yield*/, this._makeBuyOrder({
asset: asset,
quantity: quantity,
accountAddress: accountAddress,
startAmount: startAmount,
expirationTime: expirationTime,
paymentTokenAddress: paymentTokenAddress,
extraBountyBasisPoints: 0,
sellOrder: sellOrder,
referrerAddress: referrerAddress
})
// NOTE not in Wyvern exchange code:
// frontend checks to make sure
// token is approved and sufficiently available
];
case 1:
order = _d.sent();
// NOTE not in Wyvern exchange code:
// frontend checks to make sure
// token is approved and sufficiently available
return [4 /*yield*/, this._buyOrderValidationAndApprovals({ order: order, accountAddress: accountAddress })];
case 2:
// NOTE not in Wyvern exchange code:
// frontend checks to make sure
// token is approved and sufficiently available
_d.sent();
hashedOrder = __assign({}, order, { hash: utils_1.getOrderHash(order) });
_d.label = 3;
case 3:
_d.trys.push([3, 5, , 6]);
return [4 /*yield*/, this._authorizeOrder(hashedOrder)];
case 4:
signature = _d.sent();
return [3 /*break*/, 6];
case 5:
error_2 = _d.sent();
console.error(error_2);
throw new Error("You declined to authorize your offer");
case 6:
orderWithSignature = __assign({}, hashedOrder, signature);
return [2 /*return*/, this.validateAndPostOrder(orderWithSignature)];
}
});
});
};
/**
* Create a sell order to auction an asset.
* Will throw a 'You do not own enough of this asset' error if the maker doesn't have the asset or not enough of it to sell the specific `quantity`.
* If the user hasn't approved access to the token yet, this will emit `ApproveAllAssets` (or `ApproveAsset` if the contract doesn't support approve-all) before asking for approval.
* @param param0 __namedParameters Object
* @param tokenId DEPRECATED: Token ID. Use `asset` instead.
* @param tokenAddress DEPRECATED: Address of the token's contract. Use `asset` instead.
* @param asset The asset to trade
* @param accountAddress Address of the maker's wallet
* @param startAmount Price of the asset at the start of the auction. Units are in the amount of a token above the token's decimal places (integer part). For example, for ether, expected units are in ETH, not wei.
* @param endAmount Optional price of the asset at the end of its expiration time. Units are in the amount of a token above the token's decimal places (integer part). For example, for ether, expected units are in ETH, not wei.
* @param quantity The number of assets to sell (if fungible or semi-fungible). Defaults to 1. In units, not base units, e.g. not wei.
* @param listingTime Optional time when the order will become fulfillable, in UTC seconds. Undefined means it will start now.
* @param expirationTime Expiration time for the order, in UTC seconds. An expiration time of 0 means "never expire."
* @param waitForHighestBid If set to true, this becomes an English auction that increases in price for every bid. The highest bid wins when the auction expires, as long as it's at least `startAmount`. `expirationTime` must be > 0.
* @param englishAuctionReservePrice Optional price level, below which orders may be placed but will not be matched. Orders below the reserve can be manually accepted but will not be automatically matched.
* @param paymentTokenAddress Address of the ERC-20 token to accept in return. If undefined or null, uses Ether.
* @param extraBountyBasisPoints Optional basis points (1/100th of a percent) to reward someone for referring the fulfillment of this order
* @param buyerAddress Optional address that's allowed to purchase this item. If specified, no other address will be able to take the order, unless its value is the null address.
* @param buyerEmail Optional email of the user that's allowed to purchase this item. If specified, a user will have to verify this email before being able to take the order.
*/
OpenSeaPort.prototype.createSellOrder = function (_a) {
var asset = _a.asset, accountAddress = _a.accountAddress, startAmount = _a.startAmount, endAmount = _a.endAmount, _b = _a.quantity, quantity = _b === void 0 ? 1 : _b, listingTime = _a.listingTime, _c = _a.expirationTime, expirationTime = _c === void 0 ? 0 : _c, _d = _a.waitForHighestBid, waitForHighestBid = _d === void 0 ? false : _d, englishAuctionReservePrice = _a.englishAuctionReservePrice, paymentTokenAddress = _a.paymentTokenAddress, _e = _a.extraBountyBasisPoints, extraBountyBasisPoints = _e === void 0 ? 0 : _e, buyerAddress = _a.buyerAddress, buyerEmail = _a.buyerEmail;
return __awaiter(this, void 0, void 0, function () {
var order, hashedOrder, signature, error_3, orderWithSignature;
return __generator(this, function (_f) {
switch (_f.label) {
case 0: return [4 /*yield*/, this._makeSellOrder({
asset: asset,
quantity: quantity,
accountAddress: accountAddress,
startAmount: startAmount,
endAmount: endAmount,
listingTime: listingTime,
expirationTime: expirationTime,
waitForHighestBid: waitForHighestBid,
englishAuctionReservePrice: englishAuctionReservePrice,
paymentTokenAddress: paymentTokenAddress || constants_1.NULL_ADDRESS,
extraBountyBasisPoints: extraBountyBasisPoints,
buyerAddress: buyerAddress || constants_1.NULL_ADDRESS
})];
case 1:
order = _f.sent();
return [4 /*yield*/, this._sellOrderValidationAndApprovals({ order: order, accountAddress: accountAddress })];
case 2:
_f.sent();
if (!buyerEmail) return [3 /*break*/, 4];
return [4 /*yield*/, this._createEmailWhitelistEntry({ order: order, buyerEmail: buyerEmail })];
case 3:
_f.sent();
_f.label = 4;
case 4:
hashedOrder = __assign({}, order, { hash: utils_1.getOrderHash(order) });
_f.label = 5;
case 5:
_f.trys.push([5, 7, , 8]);
return [4 /*yield*/, this._authorizeOrder(hashedOrder)];
case 6:
signature = _f.sent();
return [3 /*break*/, 8];
case 7:
error_3 = _f.sent();
console.error(error_3);
throw new Error("You declined to authorize your auction");
case 8:
orderWithSignature = __assign({}, hashedOrder, signature);
return [2 /*return*/, this.validateAndPostOrder(orderWithSignature)];
}
});
});
};
/**
* Create multiple sell orders in bulk to auction assets out of an asset factory.
* Will throw a 'You do not own this asset' error if the maker doesn't own the factory.
* Items will mint to users' wallets only when they buy them. See https://docs.opensea.io/docs/opensea-initial-item-sale-tutorial for more info.
* If the user hasn't approved access to the token yet, this will emit `ApproveAllAssets` (or `ApproveAsset` if the contract doesn't support approve-all) before asking for approval.
* @param param0 __namedParameters Object
* @param assets Which assets you want to post orders for. Use the tokenAddress of your factory contract
* @param accountAddress Address of the factory owner's wallet
* @param startAmount Price of the asset at the start of the auction, or minimum acceptable bid if it's an English auction. Units are in the amount of a token above the token's decimal places (integer part). For example, for ether, expected units are in ETH, not wei.
* @param endAmount Optional price of the asset at the end of its expiration time. If not specified, will be set to `startAmount`. Units are in the amount of a token above the token's decimal places (integer part). For example, for ether, expected units are in ETH, not wei.
* @param quantity The number of assets to sell at one time (if fungible or semi-fungible). Defaults to 1. In units, not base units, e.g. not wei.
* @param listingTime Optional time when the order will become fulfillable, in UTC seconds. Undefined means it will start now.
* @param expirationTime Expiration time for the order, in seconds. An expiration time of 0 means "never expire."
* @param waitForHighestBid If set to true, this becomes an English auction that increases in price for every bid. The highest bid wins when the auction expires, as long as it's at least `startAmount`. `expirationTime` must be > 0.
* @param paymentTokenAddress Address of the ERC-20 token to accept in return. If undefined or null, uses Ether.
* @param extraBountyBasisPoints Optional basis points (1/100th of a percent) to reward someone for referring the fulfillment of each order
* @param buyerAddress Optional address that's allowed to purchase each item. If specified, no other address will be able to take each order.
* @param buyerEmail Optional email of the user that's allowed to purchase each item. If specified, a user will have to verify this email before being able to take each order.
* @param numberOfOrders Number of times to repeat creating the same order for each asset. If greater than 5, creates them in batches of 5. Requires an `apiKey` to be set during seaport initialization in order to not be throttled by the API.
* @returns The number of orders created in total
*/
OpenSeaPort.prototype.createFactorySellOrders = function (_a) {
var assets = _a.assets, accountAddress = _a.accountAddress, startAmount = _a.startAmount, endAmount = _a.endAmount, _b = _a.quantity, quantity = _b === void 0 ? 1 : _b, listingTime = _a.listingTime, _c = _a.expirationTime, expirationTime = _c === void 0 ? 0 : _c, _d = _a.waitForHighestBid, waitForHighestBid = _d === void 0 ? false : _d, paymentTokenAddress = _a.paymentTokenAddress, _e = _a.extraBountyBasisPoints, extraBountyBasisPoints = _e === void 0 ? 0 : _e, buyerAddress = _a.buyerAddress, buyerEmail = _a.buyerEmail, _f = _a.numberOfOrders, numberOfOrders = _f === void 0 ? 1 : _f;
return __awaiter(this, void 0, void 0, function () {
var dummyOrder, _makeAndPostOneSellOrder, range, batches, numOrdersCreated, _i, batches_1, subRange, batchOrdersCreated;
var _this = this;
return __generator(this, function (_g) {
switch (_g.label) {
case 0:
if (numberOfOrders < 1) {
throw new Error('Need to make at least one sell order');
}
if (!assets || !assets.length) {
throw new Error('Need at least one asset to create orders for');
}
if (_.uniqBy(assets, function (a) { return a.tokenAddress; }).length !== 1) {
throw new Error('All assets must be on the same factory contract address');
}
return [4 /*yield*/, this._makeSellOrder({
asset: assets[0],
quantity: quantity,
accountAddress: accountAddress,
startAmount: startAmount,
endAmount: endAmount,
listingTime: listingTime,
expirationTime: expirationTime,
waitForHighestBid: waitForHighestBid,
paymentTokenAddress: paymentTokenAddress || constants_1.NULL_ADDRESS,
extraBountyBasisPoints: extraBountyBasisPoints,
buyerAddress: buyerAddress || constants_1.NULL_ADDRESS
})];
case 1:
dummyOrder = _g.sent();
return [4 /*yield*/, this._sellOrderValidationAndApprovals({ order: dummyOrder, accountAddress: accountAddress })];
case 2:
_g.sent();
_makeAndPostOneSellOrder = function (asset) { return __awaiter(_this, void 0, void 0, function () {
var order, hashedOrder, signature, error_4, orderWithSignature;
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, this._makeSellOrder({
asset: asset,
quantity: quantity,
accountAddress: accountAddress,
startAmount: startAmount,
endAmount: endAmount,
listingTime: listingTime,
expirationTime: expirationTime,
waitForHighestBid: waitForHighestBid,
paymentTokenAddress: paymentTokenAddress || constants_1.NULL_ADDRESS,
extraBountyBasisPoints: extraBountyBasisPoints,
buyerAddress: buyerAddress || constants_1.NULL_ADDRESS
})];
case 1:
order = _a.sent();
if (!buyerEmail) return [3 /*break*/, 3];
return [4 /*yield*/, this._createEmailWhitelistEntry({ order: order, buyerEmail: buyerEmail })];
case 2:
_a.sent();
_a.label = 3;
case 3:
hashedOrder = __assign({}, order, { hash: utils_1.getOrderHash(order) });
_a.label = 4;
case 4:
_a.trys.push([4, 6, , 7]);
return [4 /*yield*/, this._authorizeOrder(hashedOrder)];
case 5:
signature = _a.sent();
return [3 /*break*/, 7];
case 6:
error_4 = _a.sent();
console.error(error_4);
throw new Error("You declined to authorize your auction, or your web3 provider can't sign using personal_sign. Try 'web3-provider-engine' and make sure a mnemonic is set. Just a reminder: there's no gas needed anymore to mint tokens!");
case 7:
orderWithSignature = __assign({}, hashedOrder, signature);
return [2 /*return*/, this.validateAndPostOrder(orderWithSignature)];
}
});
}); };
range = _.range(numberOfOrders * assets.length);
batches = _.chunk(range, constants_1.SELL_ORDER_BATCH_SIZE);
numOrdersCreated = 0;
_i = 0, batches_1 = batches;
_g.label = 3;
case 3:
if (!(_i < batches_1.length)) return [3 /*break*/, 7];
subRange = batches_1[_i];
return [4 /*yield*/, Promise.all(subRange.map(function (assetOrderIndex) { return __awaiter(_this, void 0, void 0, function () {
var assetIndex;
return __generator(this, function (_a) {
assetIndex = Math.floor(assetOrderIndex / numberOfOrders);
return [2 /*return*/, _makeAndPostOneSellOrder(assets[assetIndex])];
});
}); }))];
case 4:
batchOrdersCreated = _g.sent();
this.logger("Created and posted a batch of " + batchOrdersCreated.length + " orders in parallel.");
numOrdersCreated += batchOrdersCreated.length;
// Don't overwhelm router
return [4 /*yield*/, utils_1.delay(500)];
case 5:
// Don't overwhelm router
_g.sent();
_g.label = 6;
case 6:
_i++;
return [3 /*break*/, 3];
case 7: return [2 /*return*/, numOrdersCreated];
}
});
});
};
/**
* Create a sell order to auction a bundle of assets.
* Will throw a 'You do not own this asset' error if the maker doesn't have one of the assets.
* If the user hasn't approved access to any of the assets yet, this will emit `ApproveAllAssets` (or `ApproveAsset` if the contract doesn't support approve-all) before asking for approval for each asset.
* @param param0 __namedParameters Object
* @param bundleName Name of the bundle
* @param bundleDescription Optional description of the bundle. Markdown is allowed.
* @param bundleExternalLink Optional link to a page that adds context to the bundle.
* @param assets An array of objects with the tokenId and tokenAddress of each of the assets to bundle together.
* @param collection Optional collection for computing fees, required only if all assets belong to the same collection
* @param quantities The quantity of each asset to sell. Defaults to 1 for each.
* @param accountAddress The address of the maker of the bundle and the owner of all the assets.
* @param startAmount Price of the asset at the start of the auction, or minimum acceptable bid if it's an English auction.
* @param endAmount Optional price of the asset at the end of its expiration time. If not specified, will be set to `startAmount`.
* @param listingTime Optional time when the order will become fulfillable, in UTC seconds. Undefined means it will start now.
* @param expirationTime Expiration time for the order, in seconds. An expiration time of 0 means "never expire."
* @param waitForHighestBid If set to true, this becomes an English auction that increases in price for every bid. The highest bid wins when the auction expires, as long as it's at least `startAmount`. `expirationTime` must be > 0.
* @param englishAuctionReservePrice Optional price level, below which orders may be placed but will not be matched. Orders below the reserve can be manually accepted but will not be automatically matched.
* @param paymentTokenAddress Address of the ERC-20 token to accept in return. If undefined or null, uses Ether.
* @param extraBountyBasisPoints Optional basis points (1/100th of a percent) to reward someone for referring the fulfillment of this order
* @param buyerAddress Optional address that's allowed to purchase this bundle. If specified, no other address will be able to take the order, unless it's the null address.
*/
OpenSeaPort.prototype.createBundleSellOrder = function (_a) {
var bundleName = _a.bundleName, bundleDescription = _a.bundleDescription, bundleExternalLink = _a.bundleExternalLink, assets = _a.assets, collection = _a.collection, quantities = _a.quantities, accountAddress = _a.accountAddress, startAmount = _a.startAmount, endAmount = _a.endAmount, _b = _a.expirationTime, expirationTime = _b === void 0 ? 0 : _b, listingTime = _a.listingTime, _c = _a.waitForHighestBid, waitForHighestBid = _c === void 0 ? false : _c, englishAuctionReservePrice = _a.englishAuctionReservePrice, paymentTokenAddress = _a.paymentTokenAddress, _d = _a.extraBountyBasisPoints, extraBountyBasisPoints = _d === void 0 ? 0 : _d, buyerAddress = _a.buyerAddress;
return __awaiter(this, void 0, void 0, function () {
var order, hashedOrder, signature, error_5, orderWithSignature;
return __generator(this, function (_e) {
switch (_e.label) {
case 0:
// Default to one of each asset
quantities = quantities || assets.map(function (a) { return 1; });
return [4 /*yield*/, this._makeBundleSellOrder({
bundleName: bundleName,
bundleDescription: bundleDescription,
bundleExternalLink: bundleExternalLink,
assets: assets,
collection: collection,
quantities: quantities,
accountAddress: accountAddress,
startAmount: startAmount,
endAmount: endAmount,
listingTime: listingTime,
expirationTime: expirationTime,
waitForHighestBid: waitForHighestBid,
englishAuctionReservePrice: englishAuctionReservePrice,
paymentTokenAddress: paymentTokenAddress || constants_1.NULL_ADDRESS,
extraBountyBasisPoints: extraBountyBasisPoints,
buyerAddress: buyerAddress || constants_1.NULL_ADDRESS,
})];
case 1:
order = _e.sent();
return [4 /*yield*/, this._sellOrderValidationAndApprovals({ order: order, accountAddress: accountAddress })];
case 2:
_e.sent();
hashedOrder = __assign({}, order, { hash: utils_1.getOrderHash(order) });
_e.label = 3;
case 3:
_e.trys.push([3, 5, , 6]);
return [4 /*yield*/, this._authorizeOrder(hashedOrder)];
case 4:
signature = _e.sent();
return [3 /*break*/, 6];
case 5:
error_5 = _e.sent();
console.error(error_5);
throw new Error("You declined to authorize your auction");
case 6:
orderWithSignature = __assign({}, hashedOrder, signature);
return [2 /*return*/, this.validateAndPostOrder(orderWithSignature)];
}
});
});
};
/**
* Fullfill or "take" an order for an asset, either a buy or sell order
* @param param0 __namedParamaters Object
* @param order The order to fulfill, a.k.a. "take"
* @param accountAddress The taker's wallet address
* @param recipientAddress The optional address to receive the order's item(s) or curriencies. If not specified, defaults to accountAddress.
* @param referrerAddress The optional address that referred the order
* @returns Transaction hash for fulfilling the order
*/
OpenSeaPort.prototype.fulfillOrder = function (_a) {
var order = _a.order, accountAddress = _a.accountAddress, recipientAddress = _a.recipientAddress, referrerAddress = _a.referrerAddress;
return __awaiter(this, void 0, void 0, function () {
var matchingOrder, _b, buy, sell, metadata, transactionHash;
var _this = this;
return __generator(this, function (_c) {
switch (_c.label) {
case 0:
matchingOrder = this._makeMatchingOrder({
order: order,
accountAddress: accountAddress,
recipientAddress: recipientAddress || accountAddress
});
_b = utils_1.assignOrdersToSides(order, matchingOrder), buy = _b.buy, sell = _b.sell;
metadata = this._getMetadata(order, referrerAddress);
return [4 /*yield*/, this._atomicMatch({ buy: buy, sell: sell, accountAddress: accountAddress, metadata: metadata })];
case 1:
transactionHash = _c.sent();
return [4 /*yield*/, this._confirmTransaction(transactionHash, types_1.EventType.MatchOrders, "Fulfilling order", function () { return __awaiter(_this, void 0, void 0, function () {
var isOpen;
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, this._validateOrder(order)];
case 1:
isOpen = _a.sent();
return [2 /*return*/, !isOpen];
}
});
}); })];
case 2:
_c.sent();
return [2 /*return*/, transactionHash];
}
});
});
};
/**
* Cancel an order on-chain, preventing it from ever being fulfilled.
* @param param0 __namedParameters Object
* @param order The order to cancel
* @param accountAddress The order maker's wallet address
*/
OpenSeaPort.prototype.cancelOrder = function (_a) {
var order = _a.order, accountAddress = _a.accountAddress;
return __awaiter(this, void 0, void 0, function () {
var gasPrice, transactionHash;
var _this = this;
return __generator(this, function (_b) {
switch (_b.label) {
case 0:
this._dispatch(types_1.EventType.CancelOrder, { order: order, accountAddress: accountAddress });
return [4 /*yield*/, this._computeGasPrice()];
case 1:
gasPrice = _b.sent();
return [4 /*yield*/, this._wyvernProtocol.wyvernExchange.cancelOrder_.sendTransactionAsync([order.exchange, order.maker, order.taker, order.feeRecipient, order.target, order.staticTarget, order.paymentToken], [order.makerRelayerFee, order.takerRelayerFee, order.makerProtocolFee, order.takerProtocolFee, order.basePrice, order.extra, order.listingTime, order.expirationTime, order.salt], order.feeMethod, order.side, order.saleKind, order.howToCall, order.calldata, order.replacementPattern, order.staticExtradata, order.v || 0, order.r || constants_1.NULL_BLOCK_HASH, order.s || constants_1.NULL_BLOCK_HASH, { from: accountAddress, gasPrice: gasPrice })];
case 2:
transactionHash = _b.sent();
return [4 /*yield*/, this._confirmTransaction(transactionHash.toString(), types_1.EventType.CancelOrder, "Cancelling order", function () { return __awaiter(_this, void 0, void 0, function () {
var isOpen;
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, this._validateOrder(order)];
case 1:
isOpen = _a.sent();
return [2 /*return*/, !isOpen];
}
});
}); })];
case 3:
_b.sent();
return [2 /*return*/];
}
});
});
};
/**
* Approve a non-fungible token for use in trades.
* Requires an account to be initialized first.
* Called internally, but exposed for dev flexibility.
* Checks to see if already approved, first. Then tries different approval methods from best to worst.
* @param param0 __namedParamters Object
* @param tokenId Token id to approve, but only used if approve-all isn't
* supported by the token contract
* @param tokenAddress The contract address of the token being approved
* @param accountAddress The user's wallet address
* @param proxyAddress Address of the user's proxy contract. If not provided,
* will attempt to fetch it from Wyvern.
* @param tokenAbi ABI of the token's contract. Defaults to a flexible ERC-721
* contract.
* @param skipApproveAllIfTokenAddressIn an optional list of token addresses that, if a token is approve-all type, will skip approval
* @param schemaName The Wyvern schema name corresponding to the asset type
* @returns Transaction hash if a new transaction was created, otherwise null
*/
OpenSeaPort.prototype.approveSemiOrNonFungibleToken = function (_a) {
var tokenId = _a.tokenId, tokenAddress = _a.tokenAddress, accountAddress = _a.accountAddress, proxyAddress = _a.proxyAddress, _b = _a.tokenAbi, tokenAbi = _b === void 0 ? contracts_1.ERC721 : _b, _c = _a.skipApproveAllIfTokenAddressIn, skipApproveAllIfTokenAddressIn = _c === void 0 ? new Set() : _c, _d = _a.schemaName, schemaName = _d === void 0 ? types_1.WyvernSchemaName.ERC721 : _d;
return __awaiter(this, void 0, void 0, function () {
var schema, tokenContract, contract, approvalAllCheck, isApprovedForAll, gasPrice, txHash, error_6, approvalOneCheck, isApprovedForOne, gasPrice, txHash, error_7;
var _this = this;
return __generator(this, function (_e) {
switch (_e.label) {
case 0:
schema = this._getSchema(schemaName);
tokenContract = this.web3.eth.contract(tokenAbi);
return [4 /*yield*/, tokenContract.at(tokenAddress)];
case 1:
contract = _e.sent();
if (!!proxyAddress) return [3 /*break*/, 3];
return [4 /*yield*/, this._getProxy(accountAddress)];
case 2:
proxyAddress = (_e.sent()) || undefined;
if (!proxyAddress) {
throw new Error('Uninitialized account');
}
_e.label = 3;
case 3:
approvalAllCheck = function () { return __awaiter(_this, void 0, void 0, function () {
var isApprovedForAllRaw;
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, utils_1.rawCall(this.web3ReadOnly, {
from: accountAddress,
to: contract.address,
data: contract.isApprovedForAll.getData(accountAddress, proxyAddress)
})];
case 1:
isApprovedForAllRaw = _a.sent();
return [2 /*return*/, parseInt(isApprovedForAllRaw)];
}
});
}); };
return [4 /*yield*/, approvalAllCheck()];
case 4:
isApprovedForAll = _e.sent();
if (isApprovedForAll == 1) {
// Supports ApproveAll