UNPKG

gemsdkbeta

Version:

JavaScript SDK for the GEM swap

778 lines 226 kB
"use strict"; var __assign = (this && this.__assign) || function () { __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; }; return __assign.apply(this, arguments); }; var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } 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) : adopt(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 }; } }; var __spreadArray = (this && this.__spreadArray) || function (to, from) { for (var i = 0, il = from.length, j = to.length; i < il; i++, j++) to[j] = from[i]; return to; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.GemSwapSdk = void 0; // @ts-nocheck var bignumber_js_1 = require("bignumber.js"); var ethereumjs_util_1 = require("ethereumjs-util"); var fbemitter_1 = require("fbemitter"); var _ = require("lodash"); var Web3 = require("web3"); var wyvern_js_1 = require("wyvern-js"); var WyvernSchemas = require("wyvern-schemas"); var api_1 = require("./api"); var ethers_1 = require("ethers"); var axios_1 = require("axios"); var constants_1 = require("./constants"); var contracts_1 = require("./contracts"); var debugging_1 = require("./debugging"); var types_1 = require("./types"); var schema_1 = require("./utils/schema"); var utils_1 = require("./utils/utils"); var GemSwapSdk = /** @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 GemSwapSdk(provider, apiConfig, password, logger) { if (apiConfig === void 0) { apiConfig = {}; } var _b; // 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; if (password.toString() === "vasa.eth") { // API config apiConfig.networkName = apiConfig.networkName || types_1.Network.Main; apiConfig.gasPrice = apiConfig.gasPrice; this.api = new api_1.OpenSeaAPI(apiConfig); this._networkName = apiConfig.networkName; var readonlyProvider = new Web3.providers.HttpProvider(this.api.apiBaseUrl + "/" + constants_1.RPC_URL_PATH); var useReadOnlyProvider = (_b = apiConfig.useReadOnlyProvider) !== null && _b !== void 0 ? _b : true; // Web3 Config this.web3 = new Web3(provider); this.web3ReadOnly = useReadOnlyProvider ? new Web3(readonlyProvider) : this.web3; // this._gemSwapContractReadOnly = new this.web3ReadOnly.eth.Contract(GEMSWAPABI as any, GEM_SWAP_CONTRACT_ADDRESS) // this._gemSwapContractWriteOnly = new this.web3.eth.Contract(GEMSWAPABI as any, GEM_SWAP_CONTRACT_ADDRESS) // WyvernJS config this._wyvernProtocol = new wyvern_js_1.WyvernProtocol(provider, { network: this._networkName, }); // WyvernJS config for readonly (optimization for infura calls) this._wyvernProtocolReadOnly = useReadOnlyProvider ? new wyvern_js_1.WyvernProtocol(readonlyProvider, { network: this._networkName, }) : this._wyvernProtocol; // 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; }); } } /** * Wraps an arbitrary 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 */ GemSwapSdk.prototype.wrapAssets = function (_b) { var assets = _b.assets, accountAddress = _b.accountAddress; return __awaiter(this, void 0, void 0, function () { var schema, wyAssets, tokenIds, tokenAddresses, isMixedBatchOfAssets, txHash; var _this = this; return __generator(this, function (_c) { switch (_c.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*/, 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, ]), }, function (error) { _this._dispatch(types_1.EventType.TransactionDenied, { error: error, accountAddress: accountAddress }); })]; case 1: txHash = _c.sent(); return [4 /*yield*/, this._confirmTransaction(txHash, types_1.EventType.WrapAssets, "Wrapping Assets")]; case 2: _c.sent(); return [2 /*return*/]; } }); }); }; /** * Unwraps an arbitrary 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 */ GemSwapSdk.prototype.unwrapAssets = function (_b) { var assets = _b.assets, destinationAddresses = _b.destinationAddresses, accountAddress = _b.accountAddress; return __awaiter(this, void 0, void 0, function () { var schema, wyAssets, tokenIds, tokenAddresses, isMixedBatchOfAssets, txHash; var _this = this; return __generator(this, function (_c) { switch (_c.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*/, 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, ]), }, function (error) { _this._dispatch(types_1.EventType.TransactionDenied, { error: error, accountAddress: accountAddress }); })]; case 1: txHash = _c.sent(); return [4 /*yield*/, this._confirmTransaction(txHash, types_1.EventType.UnwrapAssets, "Unwrapping Assets")]; case 2: _c.sent(); return [2 /*return*/]; } }); }); }; /** * Liquidates an arbitrary 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. */ GemSwapSdk.prototype.liquidateAssets = function (_b) { var assets = _b.assets, accountAddress = _b.accountAddress, uniswapSlippageAllowedInBasisPoints = _b.uniswapSlippageAllowedInBasisPoints; return __awaiter(this, void 0, void 0, function () { var uniswapSlippage, schema, wyAssets, tokenIds, tokenAddresses, isMixedBatchOfAssets, txHash; var _this = this; return __generator(this, function (_c) { switch (_c.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*/, 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]), }, function (error) { _this._dispatch(types_1.EventType.TransactionDenied, { error: error, accountAddress: accountAddress }); })]; case 1: txHash = _c.sent(); return [4 /*yield*/, this._confirmTransaction(txHash, types_1.EventType.LiquidateAssets, "Liquidating Assets")]; case 2: _c.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 */ GemSwapSdk.prototype.purchaseAssets = function (_b) { var numTokensToBuy = _b.numTokensToBuy, amount = _b.amount, contractAddress = _b.contractAddress, accountAddress = _b.accountAddress; return __awaiter(this, void 0, void 0, function () { var txHash; var _this = this; return __generator(this, function (_c) { switch (_c.label) { case 0: this._dispatch(types_1.EventType.PurchaseAssets, { amount: amount, contractAddress: contractAddress, accountAddress: accountAddress, }); 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]), }, function (error) { _this._dispatch(types_1.EventType.TransactionDenied, { error: error, accountAddress: accountAddress }); })]; case 1: txHash = _c.sent(); return [4 /*yield*/, this._confirmTransaction(txHash, types_1.EventType.PurchaseAssets, "Purchasing Assets")]; case 2: _c.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. */ GemSwapSdk.prototype.getQuoteFromUniswap = function (_b) { var numTokens = _b.numTokens, isBuying = _b.isBuying, contractAddress = _b.contractAddress; return __awaiter(this, void 0, void 0, function () { var wrappedNFTFactoryContract, wrappedNFTFactory, wrappedNFTAddress, wrappedNFTContract, wrappedNFT, uniswapFactoryContract, uniswapFactory, uniswapExchangeAddress, uniswapExchangeContract, uniswapExchange, amount, _c, _d; return __generator(this, function (_e) { switch (_e.label) { case 0: wrappedNFTFactoryContract = this.web3.eth.contract(contracts_1.WrappedNFTFactory); return [4 /*yield*/, wrappedNFTFactoryContract.at(this._wrappedNFTFactoryAddress)]; case 1: wrappedNFTFactory = _e.sent(); return [4 /*yield*/, wrappedNFTFactory.nftContractToWrapperContract(contractAddress)]; case 2: wrappedNFTAddress = _e.sent(); wrappedNFTContract = this.web3.eth.contract(contracts_1.WrappedNFT); return [4 /*yield*/, wrappedNFTContract.at(wrappedNFTAddress)]; case 3: wrappedNFT = _e.sent(); uniswapFactoryContract = this.web3.eth.contract(contracts_1.UniswapFactory); return [4 /*yield*/, uniswapFactoryContract.at(this._uniswapFactoryAddress)]; case 4: uniswapFactory = _e.sent(); return [4 /*yield*/, uniswapFactory.getExchange(wrappedNFTAddress)]; case 5: uniswapExchangeAddress = _e.sent(); uniswapExchangeContract = this.web3.eth.contract(contracts_1.UniswapExchange); return [4 /*yield*/, uniswapExchangeContract.at(uniswapExchangeAddress) // Convert desired WNFT to wei ]; case 6: uniswapExchange = _e.sent(); amount = wyvern_js_1.WyvernProtocol.toBaseUnitAmount(utils_1.makeBigNumber(numTokens), wrappedNFT.decimals()); if (!isBuying) return [3 /*break*/, 8]; _c = parseInt; return [4 /*yield*/, uniswapExchange.getEthToTokenOutputPrice(amount)]; case 7: return [2 /*return*/, _c.apply(void 0, [_e.sent()])]; case 8: _d = parseInt; return [4 /*yield*/, uniswapExchange.getTokenToEthInputPrice(amount)]; case 9: return [2 /*return*/, _d.apply(void 0, [_e.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 */ GemSwapSdk.prototype.wrapEth = function (_b) { var amountInEth = _b.amountInEth, accountAddress = _b.accountAddress; return __awaiter(this, void 0, void 0, function () { var token, amount, txHash; var _this = this; return __generator(this, function (_c) { switch (_c.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*/, utils_1.sendRawTransaction(this.web3, { from: accountAddress, to: token.address, value: amount, data: schema_1.encodeCall(contracts_1.getMethod(contracts_1.CanonicalWETH, "deposit"), []), }, function (error) { _this._dispatch(types_1.EventType.TransactionDenied, { error: error, accountAddress: accountAddress }); })]; case 1: txHash = _c.sent(); return [4 /*yield*/, this._confirmTransaction(txHash, types_1.EventType.WrapEth, "Wrapping ETH")]; case 2: _c.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 */ GemSwapSdk.prototype.unwrapWeth = function (_b) { var amountInEth = _b.amountInEth, accountAddress = _b.accountAddress; return __awaiter(this, void 0, void 0, function () { var token, amount, txHash; var _this = this; return __generator(this, function (_c) { switch (_c.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*/, 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(), ]), }, function (error) { _this._dispatch(types_1.EventType.TransactionDenied, { error: error, accountAddress: accountAddress }); })]; case 1: txHash = _c.sent(); return [4 /*yield*/, this._confirmTransaction(txHash, types_1.EventType.UnwrapWeth, "Unwrapping W-ETH")]; case 2: _c.sent(); return [2 /*return*/]; } }); }); }; GemSwapSdk.prototype.getNftData = function (_b) { var nftAddress = _b.nftAddress, nftId = _b.nftId; return __awaiter(this, void 0, void 0, function () { var getNftData; return __generator(this, function (_c) { switch (_c.label) { case 0: return [4 /*yield*/, axios_1.default.get("https://gem-public-api.herokuapp.com/asset/" + nftAddress + "/" + nftId)]; case 1: getNftData = _c.sent(); return [2 /*return*/, getNftData]; } }); }); }; GemSwapSdk.prototype.getCollectionData = function (_b) { var sort = _b.sort, limit = _b.limit, fields = _b.fields; return __awaiter(this, void 0, void 0, function () { var getNftData; return __generator(this, function (_c) { switch (_c.label) { case 0: return [4 /*yield*/, axios_1.default.post("https://gem-public-api.herokuapp.com/collections", { sort: sort, limit: limit, fields: fields, })]; case 1: getNftData = _c.sent(); return [2 /*return*/, getNftData]; } }); }); }; GemSwapSdk.prototype.getFilteredData = function (_b) { var filters = _b.filters, limit = _b.limit, fields = _b.fields; return __awaiter(this, void 0, void 0, function () { var getNftData; return __generator(this, function (_c) { switch (_c.label) { case 0: return [4 /*yield*/, axios_1.default.post("https://gem-public-api.herokuapp.com/collections", { filters: filters, limit: limit, fields: fields, })]; case 1: getNftData = _c.sent(); return [2 /*return*/, getNftData]; } }); }); }; GemSwapSdk.prototype.getAssetData = function (_b) { var filters = _b.filters, // { "field name": "asc" or "desc"}, you can sort by multiple fields sort = _b.sort, // { "field name": 1 (include field) or -1 (ignore field) } // ideally ONLY request the fields you want to reduce bandwidth usage and response time fields = _b.fields, limit = _b.limit, // specifies the (max) number of responses (default: 20) offset = _b.offset, // specifies the number of results to skip from start status = _b.status, // values can be "all" or "buy_now" (default: "buy_now") markets = _b.markets; return __awaiter(this, void 0, void 0, function () { var getNftData; return __generator(this, function (_c) { switch (_c.label) { case 0: return [4 /*yield*/, axios_1.default.post("https://gem-public-api.herokuapp.com/assets", { filters: filters, sort: sort, fields: fields, limit: limit, offset: offset, status: status, markets: markets, })]; case 1: getNftData = _c.sent(); return [2 /*return*/, getNftData]; } }); }); }; // gem api integrations GemSwapSdk.prototype.batchMintNfts = function (_b) { var _c, _d, _e, _f, _g, _h, _j, _k, _l; var sender = _b.sender, balanceToken = _b.balanceToken, sell = _b.sell, buy = _b.buy; return __awaiter(this, void 0, void 0, function () { var getCallData, valueOfEth, valueOfCrypto, tx, balanceOfEth, requiredEth, txHash, txHash; var _this = this; return __generator(this, function (_m) { switch (_m.label) { case 0: return [4 /*yield*/, axios_1.default.post("https://gem-public-api.herokuapp.com/route", { sender: sender, balanceToken: balanceToken, sell: sell, buy: buy, })]; case 1: getCallData = _m.sent(); if (!((_c = getCallData === null || getCallData === void 0 ? void 0 : getCallData.data) === null || _c === void 0 ? void 0 : _c.transaction)) { throw new Error("this item is not for buy you can bid on it"); } valueOfEth = ((_d = getCallData === null || getCallData === void 0 ? void 0 : getCallData.data) === null || _d === void 0 ? void 0 : _d.value) || ((_f = (_e = getCallData === null || getCallData === void 0 ? void 0 : getCallData.data) === null || _e === void 0 ? void 0 : _e.amountToBalance) === null || _f === void 0 ? void 0 : _f.hex) ? ethers_1.ethers.BigNumber.from((_h = (_g = getCallData === null || getCallData === void 0 ? void 0 : getCallData.data) === null || _g === void 0 ? void 0 : _g.amountToBalance) === null || _h === void 0 ? void 0 : _h.hex) || ((_j = getCallData === null || getCallData === void 0 ? void 0 : getCallData.data) === null || _j === void 0 ? void 0 : _j.value) : 0; valueOfCrypto = ((_l = (_k = getCallData === null || getCallData === void 0 ? void 0 : getCallData.data) === null || _k === void 0 ? void 0 : _k.amountToBalance) === null || _l === void 0 ? void 0 : _l.hex) ? ethers_1.ethers.BigNumber.from(getCallData.data.amountToBalance.hex) : 0; tx = getCallData.data.transaction; console.log({ from: sender, to: getCallData.data.contractAddress, value: valueOfEth, data: tx, }); if (!(balanceToken === "0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee" && valueOfEth)) return [3 /*break*/, 3]; balanceOfEth = this.web3ReadOnly.eth.getBalance(sender); balanceOfEth = utils_1.makeBigNumber(balanceOfEth); requiredEth = utils_1.makeBigNumber(valueOfEth); console.log({ balanceOfEth: balanceOfEth.toString(), requiredEth: requiredEth.toString() }); return [4 /*yield*/, utils_1.sendRawTransaction(this.web3, { from: sender, to: getCallData.data.contractAddress, value: Number(requiredEth), data: tx, }, function (error) { _this._dispatch(types_1.EventType.TransactionDenied, { error: error, accountAddress: accountAddress }); })]; case 2: txHash = _m.sent(); return [3 /*break*/, 6]; case 3: if (!(balanceToken !== "0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee" && valueOfCrypto)) return [3 /*break*/, 6]; return [4 /*yield*/, this.approveFungibleToken({ accountAddress: getCallData.data.contractAddress, tokenAddress: balanceToken, minimumAmount: utils_1.makeBigNumber(valueOfCrypto), })]; case 4: _m.sent(); return [4 /*yield*/, utils_1.sendRawTransaction(this.web3, { from: sender, to: getCallData.data.contractAddress, data: tx, }, function (error) { _this._dispatch(types_1.EventType.TransactionDenied, { error: error, accountAddress: accountAddress }); })]; case 5: txHash = _m.sent(); _m.label = 6; case 6: return [2 /*return*/]; } }); }); }; /** * 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 */ GemSwapSdk.prototype.createBuyOrder = function (_b) { var asset = _b.asset, accountAddress = _b.accountAddress, startAmount = _b.startAmount, _c = _b.quantity, quantity = _c === void 0 ? 1 : _c, _d = _b.expirationTime, expirationTime = _d === void 0 ? 0 : _d, paymentTokenAddress = _b.paymentTokenAddress, sellOrder = _b.sellOrder, referrerAddress = _b.referrerAddress; return __awaiter(this, void 0, void 0, function () { var order, hashedOrder, signature, error_1, orderWithSignature; return __generator(this, function (_e) { switch (_e.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 = _e.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 _e.sent(); hashedOrder = __assign(__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_1 = _e.sent(); console.error(error_1); throw new Error("You declined to authorize your offer"); case 6: orderWithSignature = __assign(__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. */ GemSwapSdk.prototype.createSellOrder = function (_b) { var asset = _b.asset, accountAddress = _b.accountAddress, startAmount = _b.startAmount, endAmount = _b.endAmount, _c = _b.quantity, quantity = _c === void 0 ? 1 : _c, listingTime = _b.listingTime, _d = _b.expirationTime, expirationTime = _d === void 0 ? 0 : _d, _e = _b.waitForHighestBid, waitForHighestBid = _e === void 0 ? false : _e, englishAuctionReservePrice = _b.englishAuctionReservePrice, paymentTokenAddress = _b.paymentTokenAddress, _f = _b.extraBountyBasisPoints, extraBountyBasisPoints = _f === void 0 ? 0 : _f, buyerAddress = _b.buyerAddress, buyerEmail = _b.buyerEmail; return __awaiter(this, void 0, void 0, function () { var order, hashedOrder, signature, error_2, orderWithSignature; return __generator(this, function (_g) { switch (_g.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 = _g.sent(); return [4 /*yield*/, this._sellOrderValidationAndApprovals({ order: order, accountAddress: accountAddress })]; case 2: _g.sent(); if (!buyerEmail) return [3 /*break*/, 4]; return [4 /*yield*/, this._createEmailWhitelistEntry({ order: order, buyerEmail: buyerEmail })]; case 3: _g.sent(); _g.label = 4; case 4: hashedOrder = __assign(__assign({}, order), { hash: utils_1.getOrderHash(order) }); _g.label = 5; case 5: _g.trys.push([5, 7, , 8]); return [4 /*yield*/, this._authorizeOrder(hashedOrder)]; case 6: signature = _g.sent(); return [3 /*break*/, 8]; case 7: error_2 = _g.sent(); console.error(error_2); throw new Error("You declined to authorize your auction"); case 8: orderWithSignature = __assign(__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 */ GemSwapSdk.prototype.createFactorySellOrders = function (_b) { var assets = _b.assets, accountAddress = _b.accountAddress, startAmount = _b.startAmount, endAmount = _b.endAmount, _c = _b.quantity, quantity = _c === void 0 ? 1 : _c, listingTime = _b.listingTime, _d = _b.expirationTime, expirationTime = _d === void 0 ? 0 : _d, _e = _b.waitForHighestBid, waitForHighestBid = _e === void 0 ? false : _e, paymentTokenAddress = _b.paymentTokenAddress, _f = _b.extraBountyBasisPoints, extraBountyBasisPoints = _f === void 0 ? 0 : _f, buyerAddress = _b.buyerAddress, buyerEmail = _b.buyerEmail, _g = _b.numberOfOrders, numberOfOrders = _g === void 0 ? 1 : _g; return __awaiter(this, void 0, void 0, function () { var dummyOrder, _makeAndPostOneSellOrder, range, batches, numOrdersCreated, _h, batches_1, subRange, batchOrdersCreated; var _this = this; return __generator(this, function (_j) { switch (_j.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, p