@newcoin-foundation/newcoin-sdk
Version:
SDK for Newcoin blockchain
1,108 lines (1,086 loc) • 98.7 kB
JavaScript
'use strict';
Object.defineProperty(exports, '__esModule', { value: true });
var eosjs = require('eosjs');
var eosjsJssig = require('eosjs/dist/eosjs-jssig');
var hyperion = require('@eoscafe/hyperion');
var newcoin_poolsJs = require('@newcoin-foundation/newcoin.pools-js');
var newcoin_poolJs = require('@newcoin-foundation/newcoin.pool-js');
var newcoin_daosJs = require('@newcoin-foundation/newcoin.daos-js');
var fetch = require('cross-fetch');
function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
var fetch__default = /*#__PURE__*/_interopDefaultLegacy(fetch);
/******************************************************************************
Copyright (c) Microsoft Corporation.
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
***************************************************************************** */
var __assign = function() {
__assign = Object.assign || function __assign(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);
};
function __awaiter(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());
});
}
function __generator(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 };
}
}
function __spreadArray(to, from, pack) {
if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
if (ar || !(i in from)) {
if (!ar) ar = Array.prototype.slice.call(from, 0, i);
ar[i] = from[i];
}
}
return to.concat(ar || Array.prototype.slice.call(from));
}
var ActionGenerator = /** @class */ (function () {
function ActionGenerator(contract, token_contract) {
this.contract = contract;
this.token_contract = token_contract;
this.newaccount = function (new_name, payer, newacc_public_active_key, newacc_public_owner_key) { return ({
account: 'eosio',
name: 'newaccount',
authorization: [{
actor: payer,
permission: 'active',
}],
data: {
creator: payer,
name: new_name,
owner: {
threshold: 1,
keys: [{
key: newacc_public_owner_key,
weight: 1
}],
accounts: [],
waits: []
},
active: {
threshold: 1,
keys: [{
key: newacc_public_active_key,
weight: 1
}],
accounts: [],
waits: []
},
}
}); };
this.buyrambytes = function (receiver, payer, amt) {
if (payer === void 0) { payer = 'io'; }
if (amt === void 0) { amt = 8192; }
return ({
account: 'eosio',
name: 'buyrambytes',
authorization: [{ actor: payer, permission: 'active' }],
data: {
payer: payer,
receiver: receiver,
bytes: amt,
},
});
};
this.delegateBw = function (receiver, payer, net_amount, cpu_amount, trfer) {
if (payer === void 0) { payer = 'io'; }
if (net_amount === void 0) { net_amount = '100.0000 NCO'; }
if (cpu_amount === void 0) { cpu_amount = '100.0000 NCO'; }
if (trfer === void 0) { trfer = true; }
return ({
account: 'eosio',
name: 'delegatebw',
authorization: [{
actor: payer,
permission: 'active',
}],
data: {
from: payer,
receiver: receiver,
stake_net_quantity: net_amount,
stake_cpu_quantity: cpu_amount,
transfer: trfer,
}
});
};
/*createUser = async (
newUser: string,
payer: string,
public_active_key: string,
public_owner_key: string
) => {
let newacc_action = this._newaccount(newUser, payer, public_active_key, public_owner_key);
let buyram_action = this._buyrambytes(newUser, payer);
let delegatebw_action = this._delegateBw(newUser, payer);
return [newacc_action, buyram_action, delegatebw_action]
};
createAccount(
authorization: EosioAuthorizationObject[],
owner: string,
symbol: string,
payer: string
) {
return this._pack(this.contract, authorization, "open", {
owner,
symbol,
payer
});
}*/
this.createCollection = function (author, collection_name, authorized_accounts, notify_accounts, market_fee, allow_notify) {
if (notify_accounts === void 0) { notify_accounts = []; }
var action = {
account: 'atomicassets',
name: 'createcol',
data: {
author: author,
collection_name: collection_name,
allow_notify: allow_notify,
authorized_accounts: authorized_accounts,
notify_accounts: notify_accounts,
market_fee: market_fee,
data: []
},
authorization: [
{ actor: author, permission: 'active' }
]
};
return action;
};
this.createSchema = function (author, collection_name, schema_name, sch) {
var action = {
account: 'atomicassets',
name: 'createschema',
data: {
authorized_creator: author,
collection_name: collection_name,
schema_name: schema_name,
schema_format: sch
},
authorization: [
{ actor: author, permission: 'active' }
]
};
return action;
};
this.createTemplate = function (author, collection_name, schema_name, xferable, burnable, template_fields) {
var action = {
account: 'atomicassets',
name: 'createtempl',
data: {
authorized_creator: author,
collection_name: collection_name,
schema_name: schema_name,
transferable: xferable,
burnable: burnable,
max_supply: 0xffffff,
immutable_data: template_fields //{key: 'name', value: ['string', 'default'] } ]
},
authorization: [
{ actor: author, permission: 'active' }
]
};
return action;
};
this.createPermission = function (author, perm_name, perm_key) {
var authorization_object = {
threshold: 1,
accounts: [{ permission: { actor: author, permission: 'active' }, weight: 1 }],
keys: [{ key: perm_key, weight: 1 }],
waits: []
};
var updateauth_input = {
account: author,
permission: perm_name,
parent: 'active',
auth: authorization_object
};
var action = {
account: 'eosio',
name: 'updateauth',
data: updateauth_input,
authorization: [
{ actor: author, permission: 'active' }
]
};
return action;
};
this.mintAsset = function (author, col_name, sch_name, tmpl_id, immutable_data, mutable_data) {
var action = {
account: 'atomicassets',
name: 'mintasset',
data: {
authorized_minter: author,
collection_name: col_name,
schema_name: sch_name,
template_id: tmpl_id,
new_asset_owner: author,
immutable_data: immutable_data,
mutable_data: mutable_data,
tokens_to_back: [] //tokens to back
},
authorization: [
{ actor: author, permission: 'active' }
]
};
return action;
};
this.createPool = function (creator, ticker, is_inflatable, is_deflatable, is_treasury, descr) {
var action = {
account: 'pools2.nco',
name: 'createpool',
data: {
owner: creator,
ticker: ticker,
description: descr,
is_inflatable: is_inflatable,
is_deflatable: is_deflatable,
is_treasury: is_treasury
},
authorization: [
{ actor: creator, permission: 'active' }
]
};
return action;
};
this.txNcoBalance = function (from, to, amt, memo) {
var action = {
account: 'eosio.token',
name: 'transfer',
data: {
from: from,
to: to,
quantity: amt,
memo: memo //''
},
authorization: [
{ 'actor': from, 'permission': 'active' }
]
};
return action;
};
this.txBalance = function (contract, from, to, amt, memo) {
var action = {
account: contract,
name: 'transfer',
data: {
from: from,
to: to,
quantity: amt,
memo: memo //''
},
authorization: [
{ 'actor': from, 'permission': 'active' }
]
};
return action;
};
}
ActionGenerator.prototype._pack = function (account, authorization, name, data) {
return [{ account: account, name: name, authorization: authorization, data: data }];
};
return ActionGenerator;
}());
var default_schema = [
{ name: 'name', type: "string" },
{ name: 'description', type: "string" },
{ name: 'image', type: 'string' },
{ name: 'external_url', type: 'string' },
{ name: 'content_type', type: 'string' },
{ name: 'content', type: 'string' },
{ name: 'license', type: 'string' }
];
var SBT_NFT_schema = [
{ name: 'name', type: "string" },
{ name: 'description', type: "string" },
{ name: 'image', type: 'string' },
{ name: 'type', type: 'string' },
{ name: 'issuer', type: 'string' },
{ name: 'recipient', type: 'string' },
{ name: 'quantifiers', type: 'string' },
{ name: 'signature', type: 'string' },
{ name: 'content', type: 'string' },
{ name: 'version', type: 'string' }
];
// https://docs.opensea.io/docs/metadata-standards
// export const OpenSea_schema = [
//]
var normalizeUsername = function (username, r) {
return username.replace(/\./g, r + r.repeat(12 - username.length));
};
var AuctionType;
(function (AuctionType) {
AuctionType["standard"] = "standard";
AuctionType["dutch"] = "dutch";
})(AuctionType || (AuctionType = {}));
var CreateActionName;
(function (CreateActionName) {
CreateActionName["standard"] = "createenauct";
CreateActionName["dutch"] = "createduauct";
})(CreateActionName || (CreateActionName = {}));
var getNameForTransaction = function (name) {
return name.toLowerCase().trim();
};
var priceForCurrency = function (price, currency, decimals) {
return "".concat(price.toFixed(decimals), " ").concat(currency);
};
function getTransferTokensActions(params) {
var accountName = params.accountName, _a = params.requestPermission, requestPermission = _a === void 0 ? "active" : _a, to = params.to, currency = params.currency, contract = params.contract, amount = params.amount, decimals = params.decimals, memo = params.memo;
if (!accountName || !to || !currency || !contract) {
throw new Error("Missing required params");
}
return [
{
account: contract,
name: "transfer",
authorization: [
{
actor: getNameForTransaction(accountName),
permission: requestPermission,
},
],
data: {
from: getNameForTransaction(accountName),
to: getNameForTransaction(to),
quantity: priceForCurrency(amount, currency, decimals),
memo: memo || "",
},
},
];
}
var getCreateAuctionActions = function (params) {
var _a;
var accountName = params.accountName, collection = params.collection, assetIds = params.assetIds, minPrice = params.minPrice, priceToken = params.priceToken, precision = params.precision, startDateMs = params.startDateMs, endDateMs = params.endDateMs, buyNowPrice = params.buyNowPrice, marketplace = params.marketplace, discountInterval = params.discountInterval, discountRate = params.discountRate, neftymarketContract = params.neftymarketContract, atomicassetsContract = params.atomicassetsContract;
var requestPermission = (_a = params.requestPermission) !== null && _a !== void 0 ? _a : "active";
var createAuctionData = {
seller: getNameForTransaction(accountName),
collection_name: getNameForTransaction(collection),
asset_ids: assetIds,
min_price: priceForCurrency(minPrice, priceToken, precision),
start_time: Math.floor(startDateMs / 1000),
end_time: Math.floor(endDateMs / 1000),
buy_now_price: priceForCurrency(buyNowPrice || 0, priceToken, precision),
security_id: 0,
marketplace: marketplace !== null && marketplace !== void 0 ? marketplace : "",
};
if (params.auctionType === AuctionType.dutch) {
createAuctionData["discount_rate"] = (discountRate !== null && discountRate !== void 0 ? discountRate : 0) / 100;
createAuctionData["discount_interval"] = discountInterval !== null && discountInterval !== void 0 ? discountInterval : 0;
}
return [
{
account: neftymarketContract,
name: "openinv",
authorization: [
{
actor: params.accountName,
permission: requestPermission,
},
],
data: {
owner: params.accountName,
count: params.assetIds.length,
},
},
{
account: atomicassetsContract,
name: "transfer",
authorization: [
{
actor: params.accountName,
permission: requestPermission,
},
],
data: {
from: params.accountName,
to: neftymarketContract,
asset_ids: params.assetIds || [],
memo: "deposit",
},
},
{
account: neftymarketContract,
name: params.auctionType === AuctionType.dutch
? CreateActionName.dutch
: CreateActionName.standard,
authorization: [
{
actor: params.accountName,
permission: requestPermission,
},
],
data: createAuctionData,
},
];
};
var getPlaceBidActions = function (params) {
var accountName = params.accountName, _a = params.requestPermission, requestPermission = _a === void 0 ? "active" : _a, decimals = params.decimals, symbol = params.symbol, amount = params.amount, auctionId = params.auctionId, marketplace = params.marketplace, neftymarketContract = params.neftymarketContract, atomicassetsContract = params.atomicassetsContract;
return __spreadArray(__spreadArray([
{
account: neftymarketContract,
name: "openbal",
authorization: [
{
actor: getNameForTransaction(accountName),
permission: requestPermission,
},
],
data: {
owner: getNameForTransaction(accountName),
token_symbol: "".concat(decimals, ",").concat(symbol),
},
}
], getTransferTokensActions({
amount: amount,
to: neftymarketContract,
contract: atomicassetsContract,
currency: symbol,
decimals: decimals,
accountName: accountName,
requestPermission: requestPermission,
memo: "deposit",
atomicassetsContract: atomicassetsContract,
neftymarketContract: neftymarketContract,
}), true), [
{
account: neftymarketContract,
name: "bid",
authorization: [
{
actor: getNameForTransaction(accountName),
permission: requestPermission,
},
],
data: {
bidder: getNameForTransaction(accountName),
auction_id: auctionId,
bid_amount: priceForCurrency(amount, symbol, decimals),
marketplace: marketplace !== null && marketplace !== void 0 ? marketplace : "",
},
},
], false);
};
var getClaimNftsActions = function (params) {
var accountName = params.accountName, _a = params.requestPermission, requestPermission = _a === void 0 ? "active" : _a, auctionId = params.auctionId, neftymarketContract = params.neftymarketContract;
return [
{
account: neftymarketContract,
name: "claimassets",
authorization: [
{
actor: getNameForTransaction(accountName),
permission: requestPermission,
},
],
data: {
auction_id: getNameForTransaction(auctionId),
},
},
];
};
var getClaimWinBidActions = function (params) {
var accountName = params.accountName, _a = params.requestPermission, requestPermission = _a === void 0 ? "active" : _a, auctionId = params.auctionId, neftymarketContract = params.neftymarketContract;
return [
{
account: neftymarketContract,
name: "claimwinbid",
authorization: [
{
actor: getNameForTransaction(accountName),
permission: requestPermission,
},
],
data: {
auction_id: getNameForTransaction(auctionId),
},
},
];
};
var getEraseAuctionActions = function (params) {
var accountName = params.accountName, _a = params.requestPermission, requestPermission = _a === void 0 ? "active" : _a, auctionId = params.auctionId, neftymarketContract = params.neftymarketContract;
return [
{
account: neftymarketContract,
name: "eraseauct",
authorization: [
{
actor: getNameForTransaction(accountName),
permission: requestPermission,
},
],
data: {
auction_id: getNameForTransaction(auctionId),
},
},
];
};
var getEditAuctionActions = function (params) {
var accountName = params.accountName, requestPermission = params.requestPermission, auctionId = params.auctionId, neftymarketContract = params.neftymarketContract, atomicassetsContract = params.atomicassetsContract;
if (!auctionId) {
throw new Error("Missing required params");
}
return __spreadArray(__spreadArray([], getEraseAuctionActions({
auctionId: auctionId,
accountName: accountName,
requestPermission: requestPermission,
neftymarketContract: neftymarketContract,
atomicassetsContract: atomicassetsContract,
}), true), getCreateAuctionActions(params), true);
};
var ecc = require("eosjs-ecc-priveos");
var CREATE_ACCOUNT_DEFAULTS = {
ram_amt: 8192,
cpu_amount: '100.0000 NCO',
net_amount: '100.0000 NCO',
xfer: false,
};
var devnet_urls = {
nodeos_url: "https://nodeos-dev.newcoin.org",
hyperion_url: "https://hyperion-dev.newcoin.org",
atomicassets_url: "https://atomic-dev.newcoin.org/"
};
var devnet_services = {
eosio_contract: "eosio",
token_contract: "eosio.token",
maindao_contract: "pool.nco",
staking_contract: "pools2.nco",
daos_contract: "daos.nco",
neftymarket_contract: "market.nefty",
atomicassets_contract: "atomicassets"
};
/**
* The primary tool to interact with [https://newcoin.org](newcoin.org).
*
* This is an early alpha.
*
* See [https://docs.newcoin.org/](https://docs.newcoin.org/) for an overview of the newcoin ecosystem.
*/
var NCO_BlockchainAPI = /** @class */ (function () {
/**
* Init the api
* @name newcoin-api
* @param urls
* @param services
* @returns a Newcoin API instance
*/
function NCO_BlockchainAPI(urls, services, debug) {
if (debug === void 0) { debug = false; }
this.debug = false;
this.debug = debug;
this.urls = urls;
if (this.debug)
console.log("Init URLS " + JSON.stringify(urls));
//this.aa_api = new ExplorerApi(this.urls.atomicassets_url, "atomicassets", { fetch: node_fetch });
this.nodeos_rpc = new eosjs.JsonRpc(this.urls.nodeos_url, { fetch: fetch__default["default"] });
this.hrpc = new hyperion.JsonRpc(this.urls.hyperion_url, { fetch: fetch__default["default"] });
this.cApi = new newcoin_daosJs.ChainApi(this.urls.nodeos_url, services.daos_contract, fetch__default["default"]);
this.poolsRpcApi = new newcoin_poolsJs.RpcApi(this.urls.nodeos_url, services.staking_contract, fetch__default["default"]);
// this.poolRpcApi = new PoolRpcApi(this.urls.nodeos_url, services.maindao_contract, fetch)
this.aGen = new newcoin_daosJs.ActionGenerator(services.daos_contract, services.staking_contract);
this.mGen = new newcoin_poolJs.ActionGenerator(services.maindao_contract, services.token_contract);
this.pGen = new newcoin_poolsJs.ActionGenerator(services.staking_contract, services.maindao_contract);
this.sdkGen = new ActionGenerator(services.eosio_contract, services.token_contract);
this.services = services;
}
// Native EOS services
/**
* Create a key pair assuming a secure environment (not frontend)
* @params none
* @returns An EOS key pair
*/
NCO_BlockchainAPI.prototype.createKeyPair = function () {
return __awaiter(this, void 0, void 0, function () {
var opts, p, t;
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, ecc.initialize()];
case 1:
_a.sent();
opts = { secureEnv: true };
return [4 /*yield*/, ecc.randomKey(0, opts)];
case 2:
p = _a.sent();
t = { prv_key: p, pub_key: ecc.privateToPublic(p) };
return [2 /*return*/, t];
}
});
});
};
/**
* Create a user - multistage operation creating new user account,
* defailt collection, schema and template for the account
* @param NCCreateUser
* @returns NCReturnTxs
*/
NCO_BlockchainAPI.prototype.createUser = function (inpt) {
return __awaiter(this, void 0, void 0, function () {
var _a, newUser, newacc_pub_active_key, newacc_pub_owner_key, payer, payer_prv_key, ram_amt, net_amount, cpu_amount, xfer, res, newacc_action, buyram_action, delegatebw_action, tres;
return __generator(this, function (_b) {
switch (_b.label) {
case 0:
_a = __assign(__assign({}, CREATE_ACCOUNT_DEFAULTS), inpt), newUser = _a.newUser, newacc_pub_active_key = _a.newacc_pub_active_key, newacc_pub_owner_key = _a.newacc_pub_owner_key, payer = _a.payer, payer_prv_key = _a.payer_prv_key, ram_amt = _a.ram_amt, net_amount = _a.net_amount, cpu_amount = _a.cpu_amount, xfer = _a.xfer;
res = {};
newacc_action = this.sdkGen.newaccount(newUser, payer, newacc_pub_active_key, newacc_pub_owner_key);
buyram_action = this.sdkGen.buyrambytes(newUser, payer, ram_amt);
delegatebw_action = this.sdkGen.delegateBw(newUser, payer, net_amount, cpu_amount, xfer);
if (this.debug)
console.log("before create account transaction");
return [4 /*yield*/, this.SubmitTx([newacc_action, buyram_action, delegatebw_action], [ecc.privateToPublic(payer_prv_key)], [payer_prv_key])];
case 1:
tres = _b.sent();
res.TxID_createAcc = tres.transaction_id;
if (this.debug)
console.log("createuser transaction complete");
return [2 /*return*/, res];
}
});
});
};
NCO_BlockchainAPI.prototype.buyRam = function (inpt) {
return __awaiter(this, void 0, void 0, function () {
var buyram_action, tres;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
buyram_action = this.sdkGen.buyrambytes(inpt.user, inpt.payer, inpt.ram_amt);
return [4 /*yield*/, this.SubmitTx([buyram_action], [ecc.privateToPublic(inpt.payer_prv_key)], [inpt.payer_prv_key])];
case 1:
tres = _a.sent();
return [2 /*return*/, { TxID_createAcc: tres.transaction_id }];
}
});
});
};
/**
* Create default collection for the account
* @param NCCreateCollection
* @returns Create Collection and template transactions' ids
*/
NCO_BlockchainAPI.prototype.createCollection = function (inpt) {
return __awaiter(this, void 0, void 0, function () {
var t, res, tres, sbt_sch_name, user_public_active_key, mkt_fee, allow_notify, schema_fields, t1, template, xferable, burnable;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
res = {};
if (inpt.collection_name == undefined)
inpt.collection_name = normalizeUsername(inpt.user, "z");
if (inpt.schema_name == undefined)
inpt.schema_name = normalizeUsername(inpt.user, "w");
sbt_sch_name = normalizeUsername(inpt.user, "s");
user_public_active_key = ecc.privateToPublic(inpt.user_prv_active_key);
mkt_fee = inpt.mkt_fee ? inpt.mkt_fee : 0.05;
allow_notify = inpt.allow_notify ? inpt.allow_notify : true;
t = this.sdkGen.createCollection(inpt.user, inpt.collection_name, [inpt.user], [inpt.user], mkt_fee, allow_notify);
if (this.debug)
console.log(t);
if (this.debug)
console.log("createcol transaction");
return [4 /*yield*/, this.SubmitTx([t], [user_public_active_key], [inpt.user_prv_active_key])];
case 1:
tres = (_a.sent());
res.TxID_createCol = tres.transaction_id;
if (this.debug)
console.log(tres);
if (this.debug)
console.log("creating default schema ");
schema_fields = inpt.schema_fields ? inpt.schema_fields : default_schema;
t = this.sdkGen.createSchema(inpt.user, inpt.collection_name, inpt.schema_name, schema_fields);
if (this.debug)
console.log(t);
if (this.debug)
console.log("createsch transaction");
return [4 /*yield*/, this.SubmitTx([t], [user_public_active_key], [inpt.user_prv_active_key])];
case 2:
tres = (_a.sent());
res.TxID_createSch = tres.transaction_id;
if (this.debug)
console.log(tres);
if (this.debug)
console.log("creating SBT schema");
t1 = this.sdkGen.createSchema(inpt.user, inpt.collection_name, sbt_sch_name, SBT_NFT_schema);
if (this.debug)
console.log(t1);
if (this.debug)
console.log("createsch SBT transaction");
return [4 /*yield*/, this.SubmitTx([t1], [user_public_active_key], [inpt.user_prv_active_key])];
case 3:
tres = (_a.sent());
res.TxID_createSch = tres.transaction_id;
if (this.debug)
console.log(tres);
if (this.debug)
console.log("creating template");
template = inpt.template_fields ? inpt.template_fields : [];
xferable = inpt.xferable ? inpt.xferable : true;
burnable = inpt.burnable ? inpt.burnable : true;
t = this.sdkGen.createTemplate(inpt.user, inpt.collection_name, inpt.schema_name, xferable, burnable, template);
if (this.debug)
console.log(t);
if (this.debug)
console.log("creating template transaction");
return [4 /*yield*/, this.SubmitTx([t], [user_public_active_key], [inpt.user_prv_active_key])];
case 4:
tres = (_a.sent());
res.TxID_createTpl = res.TxID_createTpl;
if (this.debug)
console.log(tres);
return [2 /*return*/, res];
}
});
});
};
/**
* Create a new permission subordinate to the Active permission.
* (future optional: allow under owner, TBD)
* @param NCCreatePermission
* @returns Create permission transaction id
*/
NCO_BlockchainAPI.prototype.createPermission = function (inpt) {
return __awaiter(this, void 0, void 0, function () {
var t, res, r;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
t = this.sdkGen.createPermission(inpt.author, inpt.perm_name, inpt.perm_pub_key);
return [4 /*yield*/, this.SubmitTx([t], [ecc.privateToPublic(inpt.author_prv_active_key)], [inpt.author_prv_active_key])];
case 1:
res = _a.sent();
r = {};
r.TxID_createPerm = res.transaction_id;
return [2 /*return*/, r];
}
});
});
};
/**
* Link a permission to a specific action of a specific contract.
* @param NCLinkPerm
* author: the permission's owner to be linked
* code: the owner of the action to be linked
* type: the action to be linked
* 'active', 'owner' ...
* @returns Link permission transaction id
*/
NCO_BlockchainAPI.prototype.linkPermission = function (inpt) {
return __awaiter(this, void 0, void 0, function () {
var linkauth_input, action, res, r;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
linkauth_input = {
account: inpt.author,
code: inpt.action_owner,
type: inpt.action_to_link,
requirement: inpt.perm_to_link, //
};
action = {
account: 'eosio',
name: 'linkauth',
data: linkauth_input,
authorization: [{
actor: inpt.author,
permission: 'active'
}]
};
return [4 /*yield*/, this.SubmitTx([action], [ecc.privateToPublic(inpt.author_prv_active_key)], [inpt.author_prv_active_key])];
case 1:
res = _a.sent();
r = {};
r.TxID_linkPerm = res.transaction_id;
return [2 /*return*/, r];
}
});
});
};
/* =====================================================================================
* Main DAO service: common staking pool transfrming NCO (external convertible currency)
* into internal GNCO currency.
*
* Staked amount is subject to a staking fee, redemption delay and/or
* instant unstaking fee.
* @param NCStakeMainDao
* @returns NCReturnTxs
*/
NCO_BlockchainAPI.prototype.stakeMainDAO = function (inpt) {
return __awaiter(this, void 0, void 0, function () {
var r, stakeTx, res;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
r = {};
return [4 /*yield*/, this.mGen.stake([{ actor: inpt.payer, permission: "active" }], inpt.payer, inpt.amt)];
case 1:
stakeTx = _a.sent();
if (this.debug)
console.log("action: " + JSON.stringify(stakeTx));
return [4 /*yield*/, this.SubmitTx(stakeTx, [ecc.privateToPublic(inpt.payer_prv_key)], [inpt.payer_prv_key])];
case 2:
res = _a.sent();
r.TxID_stakeMainDAO = res.transaction_id;
return [2 /*return*/, r];
}
});
});
};
/**
* Instant UnStake mainDAO with penalty
* @param NCStakeMainDao
* @returns NCReturnTxs
*/
NCO_BlockchainAPI.prototype.instUnstakeMainDAO = function (inpt) {
return __awaiter(this, void 0, void 0, function () {
var r, stakeTx, res;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
r = {};
return [4 /*yield*/, this.mGen.instunstake([{ actor: inpt.payer, permission: "active" }], inpt.payer, inpt.amt)];
case 1:
stakeTx = _a.sent();
if (this.debug)
console.log("action: " + JSON.stringify(stakeTx));
return [4 /*yield*/, this.SubmitTx(stakeTx, [ecc.privateToPublic(inpt.payer_prv_key)], [inpt.payer_prv_key])];
case 2:
res = _a.sent();
r.TxID_unstakeMainDAO = res.transaction_id;
return [2 /*return*/, r];
}
});
});
};
/**
* Delayed UnStake mainDAO delay without penalty
* @param NCStakeMainDao
* @returns NCReturnTxs
*/
NCO_BlockchainAPI.prototype.dldUnstakeMainDAO = function (inpt) {
return __awaiter(this, void 0, void 0, function () {
var r, stakeTx, res;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
r = {};
return [4 /*yield*/, this.mGen.dldunstake([{ actor: inpt.payer, permission: "active" }], inpt.payer, inpt.amt)];
case 1:
stakeTx = _a.sent();
if (this.debug)
console.log("action: " + JSON.stringify(stakeTx));
return [4 /*yield*/, this.SubmitTx(stakeTx, [ecc.privateToPublic(inpt.payer_prv_key)], [inpt.payer_prv_key])];
case 2:
res = _a.sent();
r.TxID_unstakeMainDAO = res.transaction_id;
return [2 /*return*/, r];
}
});
});
};
// ========================================================================
/** Staking pools service, issuing social tokens
*
* Create a staking pool for an account.
* Selection of ticker and inflation/deflation optionality
* @param NCCreatePool
* @returns Create Pool transaction id
*/
NCO_BlockchainAPI.prototype.createPool = function (inpt) {
var _a, _b, _c;
return __awaiter(this, void 0, void 0, function () {
var t, res, r;
return __generator(this, function (_d) {
switch (_d.label) {
case 0:
inpt.ticker = (inpt.ticker || inpt.owner.substring(0, 5)).toUpperCase();
(_a = inpt.is_inflatable) !== null && _a !== void 0 ? _a : (inpt.is_inflatable = true);
(_b = inpt.is_deflatable) !== null && _b !== void 0 ? _b : (inpt.is_deflatable = true);
(_c = inpt.is_treasury) !== null && _c !== void 0 ? _c : (inpt.is_treasury = false);
if (this.debug)
console.log("Creating pool: " + JSON.stringify(inpt));
t = this.sdkGen.createPool(inpt.owner, inpt.ticker, inpt.is_inflatable, inpt.is_deflatable, inpt.is_treasury, "test pool for " + inpt.owner);
return [4 /*yield*/, this.SubmitTx([t], [ecc.privateToPublic(inpt.owner_prv_active_key)], [inpt.owner_prv_active_key])];
case 1:
res = _d.sent();
r = {};
r.TxID_createPool = res.transaction_id;
return [2 /*return*/, r];
}
});
});
};
/**
* Stake to creator pool
* @param
* @returns Create Pool transaction id
*/
NCO_BlockchainAPI.prototype.stakePool = function (inpt) {
return __awaiter(this, void 0, void 0, function () {
var p, r, q, t, pool_id, pool_code, stakeTx, res;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
p = { owner: inpt.owner };
r = {};
if (this.debug)
console.log("Get poolbyowner: ", JSON.stringify(p));
return [4 /*yield*/, this.poolsRpcApi.getPoolByOwner(p)];
case 1:
q = _a.sent();
return [4 /*yield*/, q.json()];
case 2:
t = _a.sent();
pool_id = t.rows[0].id;
pool_code = t.rows[0].code;
if (this.debug)
console.log("pool:" + JSON.stringify(t));
return [4 /*yield*/, this.pGen.stakeToPool([{ actor: inpt.payer, permission: "active" }], inpt.payer, inpt.amt, pool_id)];
case 3:
stakeTx = _a.sent();
if (this.debug)
console.log("action: " + JSON.stringify(stakeTx));
return [4 /*yield*/, this.SubmitTx(stakeTx, [ecc.privateToPublic(inpt.payer_prv_key)], [inpt.payer_prv_key])];
case 4:
res = _a.sent();
r.TxID_stakePool = res.transaction_id;
r.pool_id = pool_id;
r.pool_code = pool_code;
return [2 /*return*/, r];
}
});
});
};
// DAO functionality
/**
* Unstake creator pool
* @param NCUnstakePool
* @returns Create Pool transaction id
*/
NCO_BlockchainAPI.prototype.unstakePool = function (inpt) {
return __awaiter(this, void 0, void 0, function () {
var t, res, r;
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, this.pGen.withdrawFromPool([{ actor: inpt.payer, permission: "active" }], //{ actor: "io", permission: "active"}
inpt.payer, inpt.amt)];
case 1:
t = _a.sent();
if (this.debug)
console.log("action: " + JSON.stringify(t));
return [4 /*yield*/, this.SubmitTx(t, [ecc.privateToPublic(inpt.payer_prv_key)], [inpt.payer_prv_key])];
case 2:
res = _a.sent();
r = {};
r.TxID_unstakePool = res.transaction_id;
return [2 /*return*/, r];
}
});
});
};
/**
* DAO creation. One per account.
* @param inpt : NCCreateDao
* @returns NCReturnTxs.TxID_createDao, NCReturnTxs.dao_id
*/
NCO_BlockchainAPI.prototype.createDao = function (inpt) {
return __awaiter(this, void 0, void 0, function () {
var t, res, p, q, w, r;
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, this.aGen.createDao([{ actor: inpt.author, permission: "active" }], inpt.author, inpt.descr)];
case 1:
t = _a.sent();
return [4 /*yield*/, this.SubmitTx(t, [ecc.privateToPublic(inpt.author_prv_key)], [inpt.author_prv_key])];
case 2:
res = _a.sent();
p = { owner: inpt.author };
if (this.debug)
console.log("Get dao by owner: ", JSON.stringify(p));
return [4 /*yield*/, this.cApi.getDAOByOwner(p)];
case 3:
q = _a.sent();
return [4 /*yield*/, q.json()];
case 4:
w = _a.sent();
if (this.debug)
console.log("received from getDaoByOwner" + JSON.stringify(w));
r = {};
r.TxID_createDao = res.transaction_id;
r.dao_id = w.rows[0].id.toString();
// r.dao_id = r.dao_id.toString() ;
return [2 /*return*/, r];
}
});
});
};
/**
*
* @param inpt : NCCreateDaoProposal
* @returns NCReturnTxs.TxID_createDaoProposal, NCReturnTxs.proposal_id
*/
NCO_BlockchainAPI.prototype.createDaoProposal = function (inpt) {
return __awaiter(this, void 0, void 0, function () {
var dao_id, _a, t, res, r, ps;
return __generator(this, function (_b) {
switch (_b.label) {
case 0:
_a = inpt.dao_id;
if (_a) return [3 /*break*/, 2];
return [4 /*yield*/, this.getDaoIdByOwner(inpt.dao_owner)];
case 1:
_a = (_b.sent());
_b.label = 2;
case 2:
dao_id = _a;
return [4 /*yield*/, this.aGen.createProposal([{ actor: inpt.proposer, permission: "active" }], inpt.proposer, Number(dao_id), inpt.title, inpt.summary, inpt.url, inpt.vote_start, inpt.vote_end)];
case 3:
t = _b.sent();
return [4 /*yield*/, this.SubmitTx(t, [ecc.privateToPublic(inpt.proposer_prv_key)], [inpt.proposer_prv_key])];
case 4:
res = _b.sent();
r = {};
r.TxID_createDaoProposal = res.transaction_id;
r.dao_id = dao_id;
return [4 /*yield*/, this.getDaoProposals(__assign(__assign({}, inpt), { dao_id: dao_id }))];
case 5:
ps = _b.sent();
r.proposal_id = ps.rows[ps.rows.l