text: "use strict";
  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 __importDefault = (this && this.__importDefault) || function (mod) {
      return (mod && mod.__esModule) ? mod : { "default": mod };
  };
  Object.defineProperty(exports, "__esModule", { value: true });
  exports.BaseContract = void 0;
  var connect_1 = require("@stacks/connect");
  var transactions_1 = require("@stacks/transactions");
  var __1 = require("..");
  var bn_js_1 = __importDefault(require("bn.js"));
  var ReadOnlyResultVO_1 = require("../vo/ReadOnlyResultVO");
  var TransactionVO_1 = require("../vo/TransactionVO");
  var BaseContract = /** @class */ (function () {
      function BaseContract(config) {
          var _a;
          this.isMock = false;
          this.config = config;
          this.isMock = ((_a = this.config) === null || _a === void 0 ? void 0 : _a.mode) === __1.MODES.MOCK;
      }
      Object.defineProperty(BaseContract.prototype, "name", {
          get: function () {
              var _a;
              return (_a = this.template) === null || _a === void 0 ? void 0 : _a.name;
          },
          enumerable: false,
          configurable: true
      });
      BaseContract.prototype.init = function (template) {
          this.template = template;
          return this;
      };
      BaseContract.prototype.tokenAssetInfo = function (token) {
          var _a;
          return transactions_1.createAssetInfo((_a = this.template) === null || _a === void 0 ? void 0 : _a.address, token, token.replace("token-", ""));
      };
      BaseContract.prototype.ayTokenAssetInfo = function (token) {
          var _a;
          return transactions_1.createAssetInfo((_a = this.template) === null || _a === void 0 ? void 0 : _a.address, token, token);
      };
      BaseContract.prototype.toSFTYield = function (yTokenName) {
          var arr = yTokenName.split("-");
          var tokenName = arr.slice(0, 2).join("-");
          var expiry = Number(arr[2]);
          return { tokenName: tokenName, expiry: expiry, yTokenName: tokenName };
      };
      BaseContract.prototype.toSFTKey = function (kTokenName) {
          var arr = kTokenName.split("-");
          var tokenName = arr[0] + "-" + arr[1] + "-" + arr[3];
          var kExpiry = Number(arr[2]);
          return { kExpiry: kExpiry, kTokenName: tokenName };
      };
      BaseContract.prototype.toSFTYTP = function (ytpToken) {
          // ytp-yield-wbtc-34560-wbtc
          var arr = ytpToken.split("-");
          var ytpTokenName = arr[0] + "-" + arr[1] + "-" + arr[2];
          var ytpExpiry = Number(arr[3]);
          return { ytpExpiry: ytpExpiry, ytpTokenName: ytpTokenName };
      };
      BaseContract.prototype.getPCCode = function (code) {
          var pcCode = transactions_1.FungibleConditionCode.Equal;
          switch (code) {
              case "g":
                  pcCode = transactions_1.FungibleConditionCode.Greater;
                  break;
              case "ge":
                  pcCode = transactions_1.FungibleConditionCode.GreaterEqual;
                  break;
              case "l":
                  pcCode = transactions_1.FungibleConditionCode.Less;
                  break;
              case "le":
                  pcCode = transactions_1.FungibleConditionCode.LessEqual;
                  break;
          }
          return pcCode;
      };
      BaseContract.prototype.getSFPC = function (value, assets, type) {
          if (type === void 0) { type = "e"; }
          var code = this.getPCCode(type);
          return transactions_1.makeStandardFungiblePostCondition(this.config.senderAddress, code, new bn_js_1.default(value), assets);
      };
      BaseContract.prototype.getCFPC = function (value, contractName, assets, type) {
          var _a;
          if (type === void 0) { type = "ge"; }
          var code = this.getPCCode(type);
          return transactions_1.makeContractFungiblePostCondition((_a = this.template) === null || _a === void 0 ? void 0 : _a.address, contractName, code, new bn_js_1.default(value), assets);
      };
      BaseContract.prototype.callPublic = function (funcName, args, postConditions, postContitionsMode) {
          if (postContitionsMode === void 0) { postContitionsMode = transactions_1.PostConditionMode.Allow; }
          return __awaiter(this, void 0, void 0, function () {
              var _this = this;
              return __generator(this, function (_a) {
                  return [2 /*return*/, new Promise(function (resolve) { return __awaiter(_this, void 0, void 0, function () {
                          var txOptions, error_1;
                          var _this = this;
                          var _a, _b, _c;
                          return __generator(this, function (_d) {
                              switch (_d.label) {
                                  case 0:
                                      txOptions = {
                                          contractAddress: (_a = this.template) === null || _a === void 0 ? void 0 : _a.address,
                                          contractName: (_b = this.template) === null || _b === void 0 ? void 0 : _b.fullName,
                                          functionName: funcName,
                                          functionArgs: args,
                                          validateWithAbi: true,
                                          postConditionMode: postContitionsMode,
                                          network: (_c = this.config) === null || _c === void 0 ? void 0 : _c.network,
                                          anchorMode: transactions_1.AnchorMode.Any,
                                          postConditions: postConditions === undefined ? [] : postConditions,
                                          appDetails: {
                                              name: "Alex app",
                                              icon: "https://alexgo.io/wp-content/themes/alex/img/logo_tm.png",
                                          },
                                          onFinish: function (data) {
                                              var _a, _b;
                                              console.log("wallet call back", data);
                                              var result = new TransactionVO_1.TransactionVO(data);
                                              if (result.exeSuccess) {
                                                  (_b = (_a = _this.config) === null || _a === void 0 ? void 0 : _a.watcher) === null || _b === void 0 ? void 0 : _b.addTx(result);
                                              }
                                              resolve(result);
                                          },
                                          onCancel: function () {
                                              resolve(TransactionVO_1.TransactionVO.failVO({ msg: "cancelled" }));
                                          },
                                      };
                                      _d.label = 1;
                                  case 1:
                                      _d.trys.push([1, 3, , 4]);
                                      console.log("callPublic", txOptions);
                                      return [4 /*yield*/, connect_1.openContractCall(txOptions)];
                                  case 2:
                                      _d.sent();
                                      return [3 /*break*/, 4];
                                  case 3:
                                      error_1 = _d.sent();
                                      console.log(error_1);
                                      resolve(TransactionVO_1.TransactionVO.failVO(error_1));
                                      return [3 /*break*/, 4];
                                  case 4: return [2 /*return*/];
                              }
                          });
                      }); })];
              });
          });
      };
      BaseContract.prototype.callPublicAndEstimate = function (funcName, args, postConditions, postContitionsMode) {
          var _a, _b, _c, _d;
          if (postContitionsMode === void 0) { postContitionsMode = transactions_1.PostConditionMode.Allow; }
          return __awaiter(this, void 0, void 0, function () {
              var cost, publicKey, pk, txUnsignedOptions;
              return __generator(this, function (_e) {
                  cost = 0;
                  publicKey = "";
                  pk = (_a = this.config) === null || _a === void 0 ? void 0 : _a.userSession.loadUserData().appPrivateKey;
                  if (pk !== undefined) {
                      publicKey = pk;
                  }
                  txUnsignedOptions = {
                      contractAddress: (_b = this.template) === null || _b === void 0 ? void 0 : _b.address,
                      contractName: (_c = this.template) === null || _c === void 0 ? void 0 : _c.fullName,
                      functionName: funcName,
                      functionArgs: args,
                      validateWithAbi: true,
                      postConditionMode: postContitionsMode,
                      network: (_d = this.config) === null || _d === void 0 ? void 0 : _d.network,
                      anchorMode: transactions_1.AnchorMode.Any,
                      postConditions: postConditions,
                      publicKey: publicKey,
                  };
                  console.log("callPublicAndEstimate", txUnsignedOptions);
                  // try {
                  //   const tx = await makeUnsignedContractCall(txUnsignedOptions);
                  //   cost = (await estimateContractFunctionCall(tx)).toNumber();
                  //   cost = cost / 2500; // TODO: this is a magic number
                  //   console.log("cost", cost);
                  // } catch (error) {
                  //   console.log(error);
                  // }
                  return [2 /*return*/, 0];
              });
          });
      };
      BaseContract.prototype.callReadOnly = function (funcName, args, cacheParams) {
          var _a, _b, _c, _d;
          return __awaiter(this, void 0, void 0, function () {
              var options;
              var _this = this;
              return __generator(this, function (_e) {
                  options = {
                      contractAddress: (_a = this.template) === null || _a === void 0 ? void 0 : _a.address,
                      contractName: (_b = this.template) === null || _b === void 0 ? void 0 : _b.fullName,
                      functionName: funcName,
                      functionArgs: args,
                      network: (_c = this.config) === null || _c === void 0 ? void 0 : _c.network,
                      senderAddress: this.config.senderAddress,
                  };
                  if ((_d = this.config) === null || _d === void 0 ? void 0 : _d.logReadOnly) {
                      console.log("callReadOnly", options);
                  }
                  return [2 /*return*/, new Promise(function (resolve) { return __awaiter(_this, void 0, void 0, function () {
                          var cachedValue, result, rvo, error_2;
                          var _a, _b, _c, _d, _e;
                          return __generator(this, function (_f) {
                              switch (_f.label) {
                                  case 0:
                                      if (this.config.senderAddress === "") {
                                          resolve(ReadOnlyResultVO_1.ReadOnlyResultVO.failVO());
                                          return [2 /*return*/];
                                      }
                                      if (cacheParams !== undefined) {
                                          cachedValue = (_b = (_a = this.config) === null || _a === void 0 ? void 0 : _a.cacheManager) === null || _b === void 0 ? void 0 : _b.getCached(cacheParams.key, cacheParams.argsObj);
                                          if (cachedValue !== null && cachedValue !== undefined) {
                                              // console.log("[ALEX-JS]: hit", cacheParams.key);
                                              resolve(cachedValue);
                                              return [2 /*return*/];
                                          }
                                      }
                                      _f.label = 1;
                                  case 1:
                                      _f.trys.push([1, 3, , 4]);
                                      return [4 /*yield*/, transactions_1.callReadOnlyFunction(options)];
                                  case 2:
                                      result = _f.sent();
                                      if ((_c = this.config) === null || _c === void 0 ? void 0 : _c.logReadOnly) {
                                          console.log("ReadOnlyResultVO", result);
                                      }
                                      rvo = new ReadOnlyResultVO_1.ReadOnlyResultVO(result);
                                      if (cacheParams !== undefined) {
                                          (_e = (_d = this.config) === null || _d === void 0 ? void 0 : _d.cacheManager) === null || _e === void 0 ? void 0 : _e.cache(cacheParams.key, cacheParams.argsObj, rvo, cacheParams.expiry !== undefined ? cacheParams.expiry : 300000);
                                      }
                                      resolve(rvo);
                                      return [3 /*break*/, 4];
                                  case 3:
                                      error_2 = _f.sent();
                                      console.log(error_2);
                                      resolve(ReadOnlyResultVO_1.ReadOnlyResultVO.failVO());
                                      return [3 /*break*/, 4];
                                  case 4: return [2 /*return*/];
                              }
                          });
                      }); })];
              });
          });
      };
      BaseContract.prototype.decimalCacheParams = function () {
          var _a;
          return {
              key: "getDecimal",
              argsObj: { contract: (_a = this.template) === null || _a === void 0 ? void 0 : _a.name },
              expiry: 600000,
          };
      };
      BaseContract.prototype.getDecimals = function () {
          return __awaiter(this, void 0, void 0, function () {
              return __generator(this, function (_a) {
                  return [2 /*return*/, this.callReadOnly("get-decimals", [], this.decimalCacheParams())];
              });
          });
      };
      BaseContract.prototype.mockReadOnlyIntVO = function (value) {
          return new Promise(function (resolve) {
              resolve(ReadOnlyResultVO_1.ReadOnlyResultVO.mockUintVO(value));
          });
      };
      return BaseContract;
  }());
  exports.BaseContract = BaseContract;
  