UNPKG

@test-org122/hypernet-core

Version:

Hypernet Core. Represents the SDK for running the Hypernet Protocol.

287 lines 14.6 kB
"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()); }); }; Object.defineProperty(exports, "__esModule", { value: true }); exports.HypernetCore = void 0; const business_1 = require("@implementations/business"); const data_1 = require("@implementations/data"); const utilities_1 = require("@implementations/utilities"); const api_1 = require("@implementations/api"); const types_1 = require("@interfaces/types"); const rxjs_1 = require("rxjs"); const neverthrow_1 = require("neverthrow"); const utils_1 = require("@test-org122/utils"); const factory_1 = require("@implementations/utilities/factory"); const LocalStorageUtils_1 = require("./utilities/LocalStorageUtils"); const BrowserNodeFactory_1 = require("./utilities/factory/BrowserNodeFactory"); /** * The top-level class-definition for Hypernet Core. */ class HypernetCore { /** * Returns an instance of HypernetCore. * @param network the network to attach to * @param config optional config, defaults to localhost/dev config */ constructor(network = types_1.EBlockchainNetwork.Main, config, externalProvider) { this._inControl = false; this.onControlClaimed = new rxjs_1.Subject(); this.onControlYielded = new rxjs_1.Subject(); this.onPushPaymentProposed = new rxjs_1.Subject(); this.onPushPaymentUpdated = new rxjs_1.Subject(); this.onPushPaymentReceived = new rxjs_1.Subject(); this.onPullPaymentProposed = new rxjs_1.Subject(); this.onPullPaymentUpdated = new rxjs_1.Subject(); this.onPullPaymentApproved = new rxjs_1.Subject(); this.onBalancesChanged = new rxjs_1.Subject(); this.onMerchantAuthorized = new rxjs_1.Subject(); this.onAuthorizedMerchantUpdated = new rxjs_1.Subject(); this.onAuthorizedMerchantActivationFailed = new rxjs_1.Subject(); this.onControlClaimed.subscribe({ next: () => { this._inControl = true; }, }); this.onControlYielded.subscribe({ next: () => { this._inControl = false; }, }); this.logUtils = new utilities_1.LogUtils(); this.timeUtils = new utilities_1.TimeUtils(); this.localStorageUtils = new LocalStorageUtils_1.LocalStorageUtils(); this.contextProvider = new utilities_1.ContextProvider(this.onControlClaimed, this.onControlYielded, this.onPushPaymentProposed, this.onPullPaymentProposed, this.onPushPaymentReceived, this.onPullPaymentApproved, this.onPushPaymentUpdated, this.onPullPaymentUpdated, this.onBalancesChanged, this.onMerchantAuthorized, this.onAuthorizedMerchantUpdated, this.onAuthorizedMerchantActivationFailed); this.blockchainProvider = new utilities_1.EthersBlockchainProvider(externalProvider); this.paymentIdUtils = new utilities_1.PaymentIdUtils(); this.configProvider = new utilities_1.ConfigProvider(network, this.logUtils, config); this.linkUtils = new utilities_1.LinkUtils(this.contextProvider); this.merchantConnectorProxyFactory = new factory_1.MerchantConnectorProxyFactory(this.configProvider); this.browserNodeFactory = new BrowserNodeFactory_1.BrowserNodeFactory(this.configProvider, this.logUtils); this.browserNodeProvider = new utilities_1.BrowserNodeProvider(this.configProvider, this.contextProvider, this.blockchainProvider, this.logUtils, this.localStorageUtils, this.browserNodeFactory); this.vectorUtils = new utilities_1.VectorUtils(this.configProvider, this.contextProvider, this.browserNodeProvider, this.blockchainProvider, this.paymentIdUtils, this.logUtils, this.timeUtils); this.paymentUtils = new utilities_1.PaymentUtils(this.configProvider, this.logUtils, this.paymentIdUtils, this.vectorUtils, this.browserNodeProvider, this.timeUtils); this.ajaxUtils = new utils_1.AxiosAjaxUtils(); this.blockchainUtils = new utilities_1.EthersBlockchainUtils(this.blockchainProvider); this.accountRepository = new data_1.AccountsRepository(this.blockchainProvider, this.vectorUtils, this.browserNodeProvider, this.logUtils, this.blockchainUtils); this.paymentRepository = new data_1.PaymentRepository(this.browserNodeProvider, this.vectorUtils, this.configProvider, this.contextProvider, this.paymentUtils, this.logUtils, this.timeUtils); this.linkRepository = new data_1.VectorLinkRepository(this.browserNodeProvider, this.configProvider, this.contextProvider, this.vectorUtils, this.paymentUtils, this.linkUtils, this.timeUtils); this.merchantConnectorRepository = new data_1.MerchantConnectorRepository(this.blockchainProvider, this.ajaxUtils, this.configProvider, this.contextProvider, this.vectorUtils, this.localStorageUtils, this.merchantConnectorProxyFactory, this.blockchainUtils); this.paymentService = new business_1.PaymentService(this.linkRepository, this.accountRepository, this.contextProvider, this.configProvider, this.paymentRepository, this.merchantConnectorRepository, this.logUtils); this.accountService = new business_1.AccountService(this.accountRepository, this.contextProvider, this.logUtils); //this.controlService = new ControlService(this.contextProvider, this.threeboxMessagingRepository); this.linkService = new business_1.LinkService(this.linkRepository); this.developmentService = new business_1.DevelopmentService(this.accountRepository); this.merchantService = new business_1.MerchantService(this.merchantConnectorRepository, this.contextProvider); this.vectorAPIListener = new api_1.VectorAPIListener(this.browserNodeProvider, this.paymentService, this.vectorUtils, this.contextProvider, this.paymentUtils, this.logUtils); // This whole rigamarole is to make sure it can only be initialized a single time, and that you can call waitInitialized() // before the call to initialize() is made this._initializeResult = null; this._initializePromiseResolve = null; this._initialized = false; this._initializePromise = new Promise((resolve) => { this._initializePromiseResolve = resolve; }); } /** * Returns the initialized status of this instance of Hypernet Core. */ initialized() { return neverthrow_1.ok(this._initialized); } waitInitialized() { return neverthrow_1.ResultAsync.fromPromise(this._initializePromise, (e) => { return e; }); } /** * Whether or not this instance of Hypernet Core is currently the one in control. */ inControl() { return neverthrow_1.ok(this._inControl); } /** * Returns a list of Ethereum accounts associated with this instance of Hypernet Core. */ getEthereumAccounts() { return this.accountService.getAccounts(); } /** * Returns the (vector) pubId associated with this instance of HypernetCore. */ getPublicIdentifier() { return this.contextProvider.getInitializedContext().map((context) => { return context.publicIdentifier; }); } /** * Deposit funds into Hypernet Core. * @param assetAddress the Ethereum address of the token to deposit * @param amount the amount of the token to deposit */ depositFunds(assetAddress, amount) { // console.log(`HypernetCore:depositFunds:assetAddress:${assetAddress}`) return this.accountService.depositFunds(assetAddress, amount); } /** * Withdraw funds from Hypernet Core to a specified destination (Ethereum) address. * @param assetAddress the address of the token to withdraw * @param amount the amount of the token to withdraw * @param destinationAddress the (Ethereum) address to withdraw to */ withdrawFunds(assetAddress, amount, destinationAddress) { return this.accountService.withdrawFunds(assetAddress, amount, destinationAddress); } /** * Returns the current balances for this instance of Hypernet Core. */ getBalances() { return this.accountService.getBalances(); } /** * Return all Hypernet Links. */ getLinks() { return this.linkService.getLinks(); } /** * Return all *active* Hypernet Links. */ getActiveLinks() { return this.linkService.getLinks(); } /** * Returns all links with a specified counterparty. * @param counterPartyAccount */ getLinkByCounterparty(counterPartyAccount) { return __awaiter(this, void 0, void 0, function* () { throw new Error("Method not yet implemented."); }); } /** * Sends funds to a counterparty. * Internally, this is a three-step process. First, the consumer will notify the provider of the * proposed terms of the payment (amount, required stake, and payment token). If the provider * accepts these terms, they will create an insurance payment for the stake, and then the consumer * finishes by creating a parameterized payment for the amount. The provider can immediately finalize * the payment. * @param linkId * @param amount * @param requiredStake the amount of stake that the provider must put up as part of the insurancepayment * @param paymentToken * @param merchantURL the registered URL for the merchant that will resolve any disputes. */ sendFunds(counterPartyAccount, amount, expirationDate, requiredStake, paymentToken, merchantUrl) { // Send payment terms to provider & request provider make insurance payment return this.paymentService.sendFunds(counterPartyAccount, amount, expirationDate, requiredStake, paymentToken, merchantUrl); } /** * Accepts the terms of a push payment, and puts up the stake/insurance transfer. * @param paymentId */ acceptOffers(paymentIds) { return this.paymentService.acceptOffers(paymentIds); } /** * Authorizes funds to a specified counterparty, with an amount, rate, & expiration date. * @param counterPartyAccount the public identifier of the counterparty to authorize funds to * @param totalAuthorized the total amount the counterparty is allowed to "pull" * @param expirationDate the latest time in which the counterparty can pull funds * @param requiredStake the amount of stake the counterparyt must put up as insurance * @param paymentToken the (Ethereum) address of the payment token * @param merchantUrl the registered URL for the merchant that will resolve any disputes. */ authorizeFunds(counterPartyAccount, totalAuthorized, expirationDate, deltaAmount, deltaTime, requiredStake, paymentToken, merchantUrl) { return this.paymentService.authorizeFunds(counterPartyAccount, totalAuthorized, expirationDate, deltaAmount, deltaTime, requiredStake, paymentToken, merchantUrl); } /** * Pull funds for a given payment * @param paymentId the payment for which to pull funds from * @param amount the amount of funds to pull */ pullFunds(paymentId, amount) { return this.paymentService.pullFunds(paymentId, amount); } /** * Finalize a pull-payment. */ finalizePullPayment(paymentId, finalAmount) { return __awaiter(this, void 0, void 0, function* () { throw new Error("Method not yet implemented."); }); } /** * Initiate a dispute for a particular payment. * @param paymentId the payment for which to dispute * @param metadata the data provided to the dispute mediator about this dispute */ initiateDispute(paymentId) { return this.paymentService.initiateDispute(paymentId); } /** * Initialize this instance of Hypernet Core * @param account: the ethereum account to initialize with */ initialize(account) { if (this._initializeResult != null) { return this._initializeResult; } let context; this._initializeResult = this.contextProvider .getContext() .andThen((val) => { context = val; context.account = account; return this.contextProvider.setContext(context); }) .andThen(() => { return this.accountService.getPublicIdentifier(); }) .andThen((publicIdentifier) => { context.publicIdentifier = publicIdentifier; return this.contextProvider.setContext(context); }) .andThen(() => { // Initialize anything that wants an initialized context return utils_1.ResultUtils.combine([ this.vectorAPIListener.setup(), this.merchantService.activateAuthorizedMerchants(), ]); // , this.threeboxMessagingListener.initialize()]); }) // .andThen(() => { // // Claim control // return this.controlService.claimControl(); // }) .map(() => { if (this._initializePromiseResolve != null) { this._initializePromiseResolve(); } this._initialized = true; }); return this._initializeResult; } /** * Mints the test token to the Ethereum address associated with the Core account. * @param amount the amount of test token to mint */ mintTestToken(amount) { return this.contextProvider.getInitializedContext().andThen((context) => { return this.developmentService.mintTestToken(amount, context.account); }); } authorizeMerchant(merchantUrl) { return this.merchantService.authorizeMerchant(merchantUrl); } getAuthorizedMerchants() { return this.merchantService.getAuthorizedMerchants(); } } exports.HypernetCore = HypernetCore; //# sourceMappingURL=HypernetCore.js.map