@gotake/gotake-sdk
Version:
SDK for interacting with GoTake blockchain contracts
630 lines (629 loc) • 30.2 kB
JavaScript
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __exportStar = (this && this.__exportStar) || function(m, exports) {
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
};
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 = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype);
return g.next = verb(0), g["throw"] = verb(1), g["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 (g && (g = 0, op[0] && (_ = 0)), _) 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 });
exports.VideoStatus = exports.getNetworkByName = exports.getNetworkById = exports.NetworkId = exports.GoTakeSDK = void 0;
var ethers_1 = require("ethers");
var providers_1 = require("@ethersproject/providers");
var utils_1 = require("./utils");
var environment_1 = require("./utils/environment");
var api_1 = require("./api");
var types_1 = require("./types");
var statusTracker_1 = require("./utils/statusTracker");
/**
* GoTake SDK - Main SDK class for interacting with GoTake contracts and services
*/
var GoTakeSDK = /** @class */ (function () {
/**
* Create SDK instance
* @param options Initialization options
*/
function GoTakeSDK(options) {
if (options === void 0) { options = {}; }
// Determine network
this._networkConfig = this._resolveNetwork(options.network);
this._networkId = this._networkConfig.id;
// Set up Provider
this._provider = this._resolveProvider(options.provider, this._networkConfig);
// Set up Signer (synchronous fallback)
this._signer = this._resolveSigner(options.signer);
// Set up API config
this._apiConfig = {
endpoint: options.apiEndpoint || 'https://api.goodtake.io', // Default API endpoint
headers: {
'Authorization': "Bearer ".concat(options.apiKey || '') // JWT token if provided
}
};
// Initialize APIs
this.account = new api_1.AccountApi(this._provider, this._signer);
this.ipnft = new api_1.IPNFTApi(this._provider, this._signer);
this.video = new api_1.VideoApi(this._apiConfig);
this.videoPayment = new api_1.VideoPaymentApi(this._provider, this._signer);
// Initialize status tracker
this._statusTracker = statusTracker_1.StatusTracker.getInstance();
}
Object.defineProperty(GoTakeSDK.prototype, "networkId", {
/**
* Get current network ID
*/
get: function () {
return this._networkId;
},
enumerable: false,
configurable: true
});
Object.defineProperty(GoTakeSDK.prototype, "provider", {
/**
* Get Provider
*/
get: function () {
return this._provider;
},
enumerable: false,
configurable: true
});
Object.defineProperty(GoTakeSDK.prototype, "signer", {
/**
* Get Signer
*/
get: function () {
return this._signer;
},
enumerable: false,
configurable: true
});
/**
* Get current user address
*/
GoTakeSDK.prototype.getAddress = function () {
return __awaiter(this, void 0, void 0, function () {
return __generator(this, function (_a) {
return [2 /*return*/, this._signer.getAddress()];
});
});
};
/**
* Check if user has a TBA and create one if not exists
* @param options Transaction options
* @returns Promise resolving to TBA address and whether it was newly created
*/
GoTakeSDK.prototype.checkAndCreateTBA = function (options) {
return __awaiter(this, void 0, void 0, function () {
var salt, tokenId, tokenContract, tbaAddress, code, exists, result, error_1;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
_a.trys.push([0, 5, , 6]);
salt = "0x0000000000000000000000000000000000000000000000000000000000000000";
tokenId = 0;
tokenContract = "0xE71014657C0AC1bF1Bbc3a85E0b21087A83411f4";
return [4 /*yield*/, this.account.computeTBAAddress({
tokenContract: tokenContract,
tokenId: tokenId,
salt: salt
})];
case 1:
tbaAddress = _a.sent();
return [4 /*yield*/, this.account.provider.getCode(tbaAddress)];
case 2:
code = _a.sent();
exists = code !== '0x';
if (!!exists) return [3 /*break*/, 4];
return [4 /*yield*/, this.account.createTBA({
tokenContract: tokenContract,
tokenId: tokenId,
salt: salt
}, options)];
case 3:
result = _a.sent();
return [2 /*return*/, {
tbaAddress: result.tbaAddress,
isNew: true
}];
case 4: return [2 /*return*/, {
tbaAddress: tbaAddress,
isNew: false
}];
case 5:
error_1 = _a.sent();
console.error('Error checking/creating TBA:', error_1);
throw error_1;
case 6: return [2 /*return*/];
}
});
});
};
/**
* Upload video to the platform
* @param file Video file to upload
* @param metadata Video metadata
* @returns Promise resolving to video ID
*/
GoTakeSDK.prototype.uploadVideo = function (file, metadata) {
return __awaiter(this, void 0, void 0, function () {
return __generator(this, function (_a) {
return [2 /*return*/, this.video.uploadVideo(file, metadata)];
});
});
};
/**
* Get video status
* @param videoId Video ID
* @returns Promise resolving to video status information
*/
GoTakeSDK.prototype.getVideoStatus = function (videoId) {
return __awaiter(this, void 0, void 0, function () {
return __generator(this, function (_a) {
return [2 /*return*/, this.video.getVideoInfo(videoId)];
});
});
};
/**
* Subscribe to video status updates
* @param videoId Video ID
* @param callback Function to be called when status updates
* @returns Subscription object
*/
GoTakeSDK.prototype.subscribeToVideoStatus = function (videoId, callback) {
return this._statusTracker.subscribe(videoId, callback);
};
/**
* Poll video status at regular intervals
* @param videoId Video ID
* @param options Poll options
* @returns Poll controller
*/
GoTakeSDK.prototype.pollVideoStatus = function (videoId, options) {
var _this = this;
return this._statusTracker.startPolling(videoId, function () { return _this.getVideoStatus(videoId); }, options);
};
/**
* Mint IP NFT for a video
* @param videoId Video ID
* @param options Transaction options
* @returns Promise resolving to mint result
*/
GoTakeSDK.prototype.mintIPNFT = function (videoId, options) {
return __awaiter(this, void 0, void 0, function () {
var status_1, tbaAddress, uri, title, description, userAddress, result, nftDetails, mintResult, error_2;
var _a, _b;
return __generator(this, function (_c) {
switch (_c.label) {
case 0:
_c.trys.push([0, 6, , 7]);
return [4 /*yield*/, this.getVideoStatus(videoId)];
case 1:
status_1 = _c.sent();
// Check if video is ready for minting
if (status_1.status !== types_1.VideoStatus.READY && status_1.status !== types_1.VideoStatus.MINT_READY) {
throw new Error("Video not ready for minting. Current status: ".concat(status_1.status));
}
return [4 /*yield*/, this.checkAndCreateTBA(options)];
case 2:
tbaAddress = (_c.sent()).tbaAddress;
// Update status
this._statusTracker.updateStatus(videoId, {
status: types_1.VideoStatus.MINTING
});
uri = ((_a = status_1.assetInfo) === null || _a === void 0 ? void 0 : _a.playbackUrl) || "video://".concat(videoId);
title = ((_b = status_1.assetInfo) === null || _b === void 0 ? void 0 : _b.assetId) || "Video ".concat(videoId);
description = status_1.message || '';
return [4 /*yield*/, this.account.getAddress()];
case 3:
userAddress = _c.sent();
return [4 /*yield*/, this.ipnft.mint(tbaAddress, {
title: title,
description: description,
thumbnailUrl: uri,
creator: userAddress
}, options)];
case 4:
result = _c.sent();
return [4 /*yield*/, this.ipnft.getNFTDetails(result.tokenId)];
case 5:
nftDetails = _c.sent();
mintResult = {
tokenId: result.tokenId.toString(),
transactionHash: result.tx.hash,
owner: nftDetails.owner,
metadata: {
seriesTitle: nftDetails.seriesTitle,
description: nftDetails.description,
totalSeasons: nftDetails.totalSeasons,
totalEpisodes: nftDetails.totalEpisodes,
genres: nftDetails.genres,
creators: nftDetails.creators,
createdAt: nftDetails.createdAt,
posterUri: nftDetails.posterUri
}
};
// Update status
this._statusTracker.updateStatus(videoId, {
status: types_1.VideoStatus.COMPLETED,
mintInfo: {
tokenId: mintResult.tokenId,
transactionHash: mintResult.transactionHash
}
});
return [2 /*return*/, mintResult];
case 6:
error_2 = _c.sent();
// Update status with error
this._statusTracker.updateStatus(videoId, {
status: types_1.VideoStatus.ERROR,
error: {
code: 'MINT_ERROR',
message: error_2 instanceof Error ? error_2.message : 'Unknown minting error'
}
});
throw error_2;
case 7: return [2 /*return*/];
}
});
});
};
/**
* Upload video and mint NFT when ready
* @param file Video file to upload
* @param metadata Video metadata
* @param options Options including status callback and auto-mint flag
* @returns Promise resolving to video ID
*/
GoTakeSDK.prototype.uploadAndMintWhenReady = function (file, metadata, options) {
return __awaiter(this, void 0, void 0, function () {
var videoId;
var _this = this;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
// Check TBA
return [4 /*yield*/, this.checkAndCreateTBA(options === null || options === void 0 ? void 0 : options.transactionOptions)];
case 1:
// Check TBA
_a.sent();
return [4 /*yield*/, this.uploadVideo(file, metadata)];
case 2:
videoId = _a.sent();
// Set up status callback
if (options === null || options === void 0 ? void 0 : options.statusCallback) {
this.subscribeToVideoStatus(videoId, options.statusCallback);
}
// Auto-mint if requested
if (options === null || options === void 0 ? void 0 : options.autoMint) {
this.pollVideoStatus(videoId, {
interval: 5000,
stopCondition: function (status) {
return status.status === types_1.VideoStatus.READY ||
status.status === types_1.VideoStatus.ERROR;
},
callback: function (status) { return __awaiter(_this, void 0, void 0, function () {
var error_3;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
if (!(status.status === types_1.VideoStatus.READY)) return [3 /*break*/, 4];
_a.label = 1;
case 1:
_a.trys.push([1, 3, , 4]);
return [4 /*yield*/, this.mintIPNFT(videoId, options.transactionOptions)];
case 2:
_a.sent();
return [3 /*break*/, 4];
case 3:
error_3 = _a.sent();
console.error('Auto-mint failed:', error_3);
return [3 /*break*/, 4];
case 4: return [2 /*return*/];
}
});
}); }
});
}
return [2 /*return*/, videoId];
}
});
});
};
// VideoPayment Convenience Methods
/**
* Purchase content with simplified interface
* @param contentId Content ID to purchase
* @param paymentMethod Payment method (ETH or ERC20)
* @param tokenAddress Token address (required for ERC20 payments)
* @param options Transaction options
* @returns Purchase result
*/
GoTakeSDK.prototype.purchaseContent = function (contentId, paymentMethod, tokenAddress, options) {
return __awaiter(this, void 0, void 0, function () {
return __generator(this, function (_a) {
return [2 /*return*/, this.videoPayment.purchaseContent(contentId, paymentMethod, tokenAddress, options)];
});
});
};
/**
* Check if current user has view permission for content
* @param contentId Content ID
* @returns True if user has valid view permission
*/
GoTakeSDK.prototype.hasViewPermission = function (contentId) {
return __awaiter(this, void 0, void 0, function () {
return __generator(this, function (_a) {
return [2 /*return*/, this.videoPayment.hasViewPermission(contentId)];
});
});
};
/**
* Get current user's permission details for content
* @param contentId Content ID
* @returns View permission details
*/
GoTakeSDK.prototype.getMyPermissions = function (contentId) {
return __awaiter(this, void 0, void 0, function () {
return __generator(this, function (_a) {
return [2 /*return*/, this.videoPayment.getMyPermissions(contentId)];
});
});
};
/**
* Get content information including pricing
* @param contentId Content ID
* @returns Content information
*/
GoTakeSDK.prototype.getContentInfo = function (contentId) {
return __awaiter(this, void 0, void 0, function () {
return __generator(this, function (_a) {
return [2 /*return*/, this.videoPayment.getContentInfo(contentId)];
});
});
};
/**
* Switch network
* @param network Network ID or name
*/
GoTakeSDK.prototype.switchNetwork = function (network) {
return __awaiter(this, void 0, void 0, function () {
var newNetworkConfig;
return __generator(this, function (_a) {
newNetworkConfig = this._resolveNetwork(network);
this._networkId = newNetworkConfig.id;
this._networkConfig = newNetworkConfig;
// Update Provider
this._provider = new providers_1.JsonRpcProvider(newNetworkConfig.rpcUrl);
// Update Signer's Provider
if (this._signer instanceof ethers_1.ethers.Wallet) {
this._signer = this._signer.connect(this._provider);
}
// Update API connections
this.account.updateConnection(this._provider, this._signer);
this.ipnft.updateConnection(this._provider, this._signer);
return [2 /*return*/];
});
});
};
/**
* Resolve network configuration
* @param network Network ID or name
* @returns Network configuration
*/
GoTakeSDK.prototype._resolveNetwork = function (network) {
if (!network) {
// Default to Base Sepolia
return (0, utils_1.getNetworkById)(utils_1.NetworkId.BASE_SEPOLIA);
}
if (typeof network === 'number' || !isNaN(Number(network))) {
// Look up by ID
var networkId = typeof network === 'number' ? network : Number(network);
var config = (0, utils_1.getNetworkById)(networkId);
if (!config) {
throw new Error("Network ID ".concat(networkId, " not supported"));
}
return config;
}
else {
// Look up by name
var config = (0, utils_1.getNetworkByName)(network);
if (!config) {
throw new Error("Network \"".concat(network, "\" not supported"));
}
return config;
}
};
/**
* Resolve Provider
* @param provider Provider or RPC URL
* @param networkConfig Network configuration
* @returns Provider instance
*/
GoTakeSDK.prototype._resolveProvider = function (provider, networkConfig) {
if (!provider) {
// Use network config's RPC URL
return new providers_1.JsonRpcProvider(networkConfig.rpcUrl);
}
if (typeof provider === 'string') {
// Assume it's an RPC URL
return new providers_1.JsonRpcProvider(provider);
}
// Already a Provider instance
return provider;
};
/**
* Resolve Signer
* @param signer Signer, private key, or environment variable name
* @returns Signer instance
*/
GoTakeSDK.prototype._resolveSigner = function (signer) {
if (!signer) {
// Check if we're in Node.js environment and can use environment variables
if ((0, environment_1.hasEnvironmentVariables)()) {
var privateKey = (0, environment_1.getEnvironmentVariable)('PRIVATE_KEY');
if (privateKey) {
return new ethers_1.ethers.Wallet(privateKey, this._provider);
}
else {
throw new Error("No signer provided and no PRIVATE_KEY environment variable found. In Node.js, set PRIVATE_KEY in .env file. In browser, provide signer explicitly.");
}
}
else {
throw new Error("No signer provided. In browser environment, you must provide a signer (e.g., from MetaMask, WalletConnect, etc.)");
}
}
if (typeof signer === 'string') {
// Could be private key or environment variable name
if (signer.startsWith('0x')) {
// Assume it's a private key
return new ethers_1.ethers.Wallet(signer, this._provider);
}
else {
// Assume it's an environment variable name (only works in Node.js)
if ((0, environment_1.hasEnvironmentVariables)()) {
var privateKey = (0, environment_1.getEnvironmentVariable)(signer);
if (privateKey) {
return new ethers_1.ethers.Wallet(privateKey, this._provider);
}
else {
throw new Error("Failed to load private key from environment variable ".concat(signer));
}
}
else {
throw new Error("Environment variables not available in browser. Please provide private key directly.");
}
}
}
// Already a Signer instance
return signer;
};
/**
* Get current gas price recommendations
* @param options Optional configuration
* @returns Gas price data including maxFeePerGas and maxPriorityFeePerGas
*/
GoTakeSDK.prototype.getGasPrice = function (options) {
return __awaiter(this, void 0, void 0, function () {
var gasPriceMultiplier, priorityFeeMultiplier, latestBlock, baseFeePerGas, maxPriorityFeePerGas, networkDefaultPriorityFee, feeData, e_1, adjustedPriorityFee, adjustedMaxFee, gasPrice, adjustedGasPrice, error_4, gasPrice;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
_a.trys.push([0, 10, , 12]);
gasPriceMultiplier = (options === null || options === void 0 ? void 0 : options.multiplier) || 1.2;
priorityFeeMultiplier = (options === null || options === void 0 ? void 0 : options.priorityMultiplier) || 1.5;
return [4 /*yield*/, this._provider.getBlock('latest')];
case 1:
latestBlock = _a.sent();
if (!latestBlock.baseFeePerGas) return [3 /*break*/, 7];
baseFeePerGas = latestBlock.baseFeePerGas;
maxPriorityFeePerGas = void 0;
_a.label = 2;
case 2:
_a.trys.push([2, 5, , 6]);
networkDefaultPriorityFee = this._networkConfig.maxPriorityFeePerGas;
// Use the network's configured priority fee instead of feeData
maxPriorityFeePerGas = ethers_1.ethers.utils.parseUnits(networkDefaultPriorityFee, "gwei");
if (!maxPriorityFeePerGas.isZero()) return [3 /*break*/, 4];
return [4 /*yield*/, this._provider.getFeeData()];
case 3:
feeData = _a.sent();
maxPriorityFeePerGas = feeData.maxPriorityFeePerGas || ethers_1.ethers.utils.parseUnits("0", "gwei");
_a.label = 4;
case 4: return [3 /*break*/, 6];
case 5:
e_1 = _a.sent();
// Default priority fee if not available - use 0 as default fallback
maxPriorityFeePerGas = ethers_1.ethers.utils.parseUnits("0", "gwei");
return [3 /*break*/, 6];
case 6:
adjustedPriorityFee = maxPriorityFeePerGas.mul(Math.floor(priorityFeeMultiplier * 100)).div(100);
adjustedMaxFee = baseFeePerGas
.mul(Math.floor(gasPriceMultiplier * 100))
.div(100)
.add(adjustedPriorityFee);
return [2 /*return*/, {
baseFeePerGas: baseFeePerGas,
maxFeePerGas: adjustedMaxFee,
maxPriorityFeePerGas: adjustedPriorityFee
}];
case 7: return [4 /*yield*/, this._provider.getGasPrice()];
case 8:
gasPrice = _a.sent();
adjustedGasPrice = gasPrice.mul(Math.floor(gasPriceMultiplier * 100)).div(100);
return [2 /*return*/, {
maxFeePerGas: adjustedGasPrice,
gasPrice: adjustedGasPrice
}];
case 9: return [3 /*break*/, 12];
case 10:
error_4 = _a.sent();
console.warn("Failed to get gas price data:", error_4);
return [4 /*yield*/, this._provider.getGasPrice()];
case 11:
gasPrice = _a.sent();
return [2 /*return*/, {
maxFeePerGas: gasPrice,
gasPrice: gasPrice
}];
case 12: return [2 /*return*/];
}
});
});
};
return GoTakeSDK;
}());
exports.GoTakeSDK = GoTakeSDK;
// Export types and utilities
var utils_2 = require("./utils");
Object.defineProperty(exports, "NetworkId", { enumerable: true, get: function () { return utils_2.NetworkId; } });
Object.defineProperty(exports, "getNetworkById", { enumerable: true, get: function () { return utils_2.getNetworkById; } });
Object.defineProperty(exports, "getNetworkByName", { enumerable: true, get: function () { return utils_2.getNetworkByName; } });
// Export types
var types_2 = require("./types");
Object.defineProperty(exports, "VideoStatus", { enumerable: true, get: function () { return types_2.VideoStatus; } });
// Export these modules fully
__exportStar(require("./api"), exports);
__exportStar(require("./wrappers"), exports);