Skip to content

Commit

Permalink
subscribe alpha
Browse files Browse the repository at this point in the history
  • Loading branch information
lovelycs committed Mar 4, 2019
1 parent ceb04b2 commit 0cade88
Show file tree
Hide file tree
Showing 6 changed files with 92 additions and 29 deletions.
4 changes: 2 additions & 2 deletions src/Wallet/account.ts
Original file line number Diff line number Diff line change
Expand Up @@ -302,11 +302,11 @@ class Account {
}

async mintage({
spendType = 'fee', tokenName, isReIssuable, maxSupply, ownerBurnOnly, totalSupply, decimals, tokenSymbol
feeType = 'burn', tokenName, isReIssuable, maxSupply, ownerBurnOnly, totalSupply, decimals, tokenSymbol
}) {
const _callContractBlock = await this._client.buildinTxBlock.mintage({
accountAddress: this.address,
spendType, tokenName, isReIssuable, maxSupply, ownerBurnOnly, totalSupply, decimals, tokenSymbol
feeType, tokenName, isReIssuable, maxSupply, ownerBurnOnly, totalSupply, decimals, tokenSymbol
});
return this._client.buildinLedger.sendRawTx(_callContractBlock, this.privateKey);
}
Expand Down
27 changes: 27 additions & 0 deletions src/client/eventEmitter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,24 +4,51 @@ class EventEmitter {
id: string
callback: Function
client: client
timeLoop: any

constructor(subscription, client) {
this.id = subscription;
this.callback = null;
this.client = client;

this.timeLoop = null;
}

on(callback) {
this.callback = callback;
}

off() {
this.stopLoop();
this.client.unSubscribe(this);
}

emit(result) {
this.callback && this.callback(result);
}

startLoop(cb, time = 2000) {
let loop = () => {
this.timeLoop = setTimeout(() => {
this.client.subscribeFunc.getFilterChanges(this.id).then((data) => {
cb && cb(data);
loop();
}).catch(err => {
loop();
});
}, time);
}
loop();
}

stopLoop() {
if (!this.timeLoop) {
return;
}
clearTimeout(this.timeLoop);
this.timeLoop = null;
this.client.subscribeFunc.uninstallFilter(this.id);
}
}

export default EventEmitter;
56 changes: 36 additions & 20 deletions src/client/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ export default class client {
consensusGroup: _methods.consensusGroupFunc
ledger: _methods.ledgerFunc
tx: _methods.txFunc
subscribeFunc: _methods.subscribeFunc

subscriptionList: Array<eventEmitter>

Expand All @@ -41,6 +42,7 @@ export default class client {

setProvider(provider, firstConnect, abort) {
abort && this._provider.abort(abort);
this.clearSubscriptions();
this._provider = provider;

this.isConnected = false;
Expand Down Expand Up @@ -82,16 +84,18 @@ export default class client {
continue;
}

if (this[namespace]) {
let _namespace = namespace === 'subscribe' ? 'subscribeFunc' : namespace;

if (this[_namespace]) {
continue;
}

let spaceMethods = _methods[namespace];
this[namespace] = {};
this[_namespace] = {};

for (let methodName in spaceMethods) {
let name = spaceMethods[methodName]
this[namespace][methodName] = (...args: any[]) => {
this[_namespace][methodName] = (...args: any[]) => {
return this.request(name, ...args);
}
}
Expand All @@ -116,8 +120,10 @@ export default class client {
let _q = () => {
this[type](methods, ...args).then((data) => {
clearTimeout(_timeout);
this._offReq(_q);
res(data);
}).catch((err) => {
this._offReq(_q);
clearTimeout(_timeout);
rej(err);
});
Expand All @@ -139,7 +145,7 @@ export default class client {

const rep: RPCresponse = await this._provider.request(methods, args);
if (rep.error) {
throw rep.error
throw rep.error;
};
return rep.result;
}
Expand All @@ -165,45 +171,51 @@ export default class client {
}

private subscribeCallback(jsonEvent) {
if (!jsonEvent || !jsonEvent.method || jsonEvent.method !== 'subscribe_subscription') {
if (!jsonEvent) {
return;
}

let id = jsonEvent.params && jsonEvent.params.subscription ? jsonEvent.params.subscription : '';
let id = jsonEvent.params && jsonEvent.params.subscription ? jsonEvent.params.subscription : jsonEvent.id || '';
if (!id) {
return;
}

this.subscriptionList && this.subscriptionList.forEach((s) => {
if (s.id === id) {
s.emit(jsonEvent.params.result || null);
let result = jsonEvent.params && jsonEvent.params.result ? jsonEvent.params.result : jsonEvent;
s.emit(result || null);
}
});
}

async subscribe(methodName, ...args) {
if (!this._provider.subscribe) {
throw '[Error] Not supported subscribe.';
}
let subMethodName = this._provider.subscribe ? 'subscribe_subscribe' : `subscribe_${methodName}Filter`;
let params = this._provider.subscribe ? [methodName, ...args] : args;

let rep;
if (!this.isConnected) {
return this._onReq('request', 'subscribe_subscribe', [methodName, ...args]);
rep = await this._onReq('request', subMethodName, ...params);
} else {
rep = await this._provider.request(subMethodName, params);
rep = rep.result;
}

const rep: RPCresponse = await this._provider.request('subscribe_subscribe', [methodName, ...args]);
if (rep.error) {
throw rep.error;
};
const subscription = rep.result;

let subscription = rep;

if (!this.subscriptionList || !this.subscriptionList.length) {
this.subscriptionList = [];
this._provider.subscribe((jsonEvent) => {
this._provider.subscribe && this._provider.subscribe((jsonEvent) => {
this.subscribeCallback(jsonEvent);
});
}

let event = new eventEmitter(subscription, this);
if (!this._provider.subscribe) {
event.startLoop((jsonEvent) => {
this.subscribeCallback(jsonEvent);
});
}

this.subscriptionList.push(event);
return event;
}
Expand All @@ -221,15 +233,19 @@ export default class client {
return;
}

event && event.stopLoop();
this.subscriptionList.splice(i, 1);

if (!this.subscriptionList || !this.subscriptionList.length) {
this._provider.unSubscribe();
this._provider.unSubscribe && this._provider.unSubscribe();
}
}

clearSubscriptions() {
this.subscriptionList.forEach((s) => {
s.stopLoop();
});
this.subscriptionList = [];
this._provider.unSubscribe();
this._provider.unSubscribe && this._provider.unSubscribe();
}
}
11 changes: 6 additions & 5 deletions src/client/txBlock.ts
Original file line number Diff line number Diff line change
Expand Up @@ -356,13 +356,13 @@ export default class tx {
}

async mintage({
accountAddress, spendType = 'fee', tokenName, isReIssuable, maxSupply, ownerBurnOnly, totalSupply, decimals, tokenSymbol, height, prevHash, snapshotHash
accountAddress, feeType = 'burn', tokenName, isReIssuable, maxSupply, ownerBurnOnly, totalSupply, decimals, tokenSymbol, height, prevHash, snapshotHash
}: mintageBlock, requestType = 'async') {
let err = checkParams({ tokenName, isReIssuable, maxSupply, ownerBurnOnly, totalSupply, decimals, tokenSymbol, requestType, spendType},
let err = checkParams({ tokenName, isReIssuable, maxSupply, ownerBurnOnly, totalSupply, decimals, tokenSymbol, requestType, feeType},
['tokenName', 'isReIssuable', 'maxSupply', 'ownerBurnOnly', 'totalSupply', 'decimals', 'tokenSymbol'],
[{ name: 'requestType', func: validReqType },
{ name: 'spendType', func: (type) => {
return type === 'amount' || type === 'fee'
{ name: 'feeType', func: (type) => {
return type === 'burn' || type === 'stake'
}}
]);
if (err) {
Expand All @@ -371,11 +371,12 @@ export default class tx {

const spendAmount = '100000000000000000000000';
const spendFee = '1000000000000000000000';
feeType = feeType === 'burn' ? 'fee' : 'amount';

let requestBlock = {
blockType: 2, toAddress: Mintage_Addr, accountAddress, height, prevHash, snapshotHash
}
requestBlock[spendType] = spendType === 'fee' ? spendFee : spendAmount;
requestBlock[feeType] = feeType === 'fee' ? spendFee : spendAmount;
let block = requestType === 'async' ? await this.asyncAccountBlock(requestBlock) : _getAccountBlock(requestBlock);

let tokenId = await this._client.mintage.newTokenId({
Expand Down
21 changes: 20 additions & 1 deletion src/const/method.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import { type } from "os";

export const enum wallet {
listEntropyFilesInStandardDir = "wallet_listEntropyFilesInStandardDir",
listAllEntropyFiles = "wallet_listAllEntropyFiles",
Expand Down Expand Up @@ -78,6 +80,23 @@ export const enum ledger {
export const enum tx {
sendRawTx = "tx_sendRawTx"
}
export const enum subscribe {
newAccountBlocksFilter = 'subscribe_newAccountBlocksFilter',
newLogsFilter = 'subscribe_newLogsFilter',
uninstallFilter = 'subscribe_uninstallFilter',
getFilterChanges = 'subscribe_getFilterChanges',
newAccountBlocks = 'subscribe_newAccountBlocks',
newLogs = 'subscribe_newLogs'
}

export type subscribeFunc = {
newAccountBlocksFilter: Function
newLogsFilter: Function
uninstallFilter: Function
getFilterChanges: Function
newAccountBlocks: Function
newLogs: Function
}

export type walletFunc = {
listEntropyFilesInStandardDir: Function
Expand Down Expand Up @@ -160,6 +179,6 @@ export type txFunc = {
sendRawTx: Function
}

type methods = wallet | net | onroad | contract | pledge | contract | register | vote | mintage | consensusGroup | ledger | tx
type methods = subscribe | wallet | net | onroad | contract | pledge | contract | register | vote | mintage | consensusGroup | ledger | tx

export default methods;
2 changes: 1 addition & 1 deletion src/const/type.ts
Original file line number Diff line number Diff line change
Expand Up @@ -239,7 +239,7 @@ export declare type callContractBlock = {

export declare type mintageBlock = {
accountAddress: Address,
spendType: string,
feeType: string,
tokenName: string,
isReIssuable: boolean,
maxSupply: string,
Expand Down

0 comments on commit 0cade88

Please sign in to comment.