How do I generate private keys for ThunderCore from a 12-word mnemonic seed phrase exported from TrustWallet or Metamask? - metamask

I got a 12-word mnemonic seed phrase exported from TrustWallet, however, I need it as a thunderCore private key. How do I generate the thunderCore private key from it? What if the seed phrase is export from Metamask?

To generate private keys from 12-word mnemonic phrases, you need a derivation path (a string) as specified in BIP-0049.
Derivation paths used in the field:
m/44'/1001'/0'/0: uses the correct coin type for ThunderCore (1001) as registered in SLIP-0044, used by TrustWallet
"m/44'/60'/0'/0: is the derivation path used for Ethereum mainnet, used by MetaMask
Here's a self-contained example to generate private keys from the 12-word mnemonic using the ethereum-hdwallet library:
hdwallet.js
const EthereumHDWallet = require('ethereum-hdwallet')
// https://github.com/bitcoin/bips/blob/master/bip-0049.mediawiki
// https://github.com/satoshilabs/slips/blob/master/slip-0044.md
const TrustWalletHdPath = "m/44'/1001'/0'/0" // coin_type 1001 is ThunderCore, this is the recommended path
const MetaMaskHdPath = "m/44'/60'/0'/0" // coin_type 60 is really Ethereum, but MetaMask use it for all EVM compatible chains
class HdWallet {
constructor(mnemonic) {
this.mnemonic = this.mnemonic
this.w = EthereumHDWallet.fromMnemonic(mnemonic)
}
deriveUsingTrustWalletPath() {
return this.w.derive(TrustWalletHdPath)
}
deriveUsingMetaMaskPath() {
return this.w.derive(MetaMaskHdPath)
}
metaMaskAddress(index /*: number */) /*: string */ {
return '0x' + this.deriveUsingMetaMaskPath().derive(index).getAddress().toString('hex')
}
trustWalletAddress(index /*: number */) /*: string */ {
return '0x' + this.deriveUsingTrustWalletPath().derive(index).getAddress().toString('hex')
}
metaMaskPrivateKey(index /*: number */) /*: string */ {
return this.deriveUsingMetaMaskPath().derive(index).getPrivateKey().toString('hex')
}
trustWalletPrivateKey(index /*: number */) /*: string */ {
return this.deriveUsingTrustWalletPath().derive(index).getPrivateKey().toString('hex')
}
}
const fromMnemonic = (s /*: string or buffer */) => {
return new HdWallet(s)
}
module.exports = {
fromMnemonic: fromMnemonic,
}
testHdWallet.js
const assert = require('assert');
const HdWallet = require('../src/hdwallet');
const mnemonic = 'feel pulp crunch segment buzz turn organ broccoli elder ask phone limit';
describe('fromMnemonic', () => {
it('trustWalletAddress', async() => {
const w = HdWallet.fromMnemonic(mnemonic);
console.log('TrustWallet:', w.trustWalletAddress(0));
assert('0x2323Beb990514446bA4c073C2e1A4BDC0ECf06Af'.toLowerCase() ===
w.trustWalletAddress(0).toLowerCase());
});
it('metaMaskAddress', async() => {
const w = HdWallet.fromMnemonic(mnemonic);
console.log('MetaMask:', w.metaMaskAddress(0));
assert('0x9A7be7ae9a2779167bc5b64d1cC672cc5b2593e4'.toLowerCase() ===
w.metaMaskAddress(0).toLowerCase());
});
it('trustWalletPrivateKey', async() => {
const w = HdWallet.fromMnemonic(mnemonic);
console.log('TrustWallet sk:', w.trustWalletPrivateKey(0));
assert('6d7bf444545ce47d7fda9df58275f5f4dd5eb911494ab66d81f76f1aca2b763e'.toLowerCase() ===
w.trustWalletPrivateKey(0).toLowerCase());
});
it('metaMaskPrivateKey', async() => {
const w = HdWallet.fromMnemonic(mnemonic);
console.log('MetaMask sk:', w.metaMaskPrivateKey(0));
assert('6aad31c479c44230721b470570c12bd3f41e71b79d8f27ca08b913cbaeac25af'.toLowerCase() ===
w.metaMaskPrivateKey(0).toLowerCase());
});
})
See a complete project in the hdwallet branch of the field-support repo.

Make sure you have Node.js and NPM installed.
Open up a terminal and execute the following, assuming you hav
npx mnemonic-to-private-key "paste your 12 word phrase here".
Do NOT use online sites as you never know if they will store your phrase. In fact, even the above repository of "mnemonic-to-private-key" could be compromised, as the "Great Suspender" was. So it's best to use version pinning with npm.

Related

Why is the public key in `.near-credentials` keypairs seemingly irrelevant?

Let's say I create an account foo.near on NEAR with a single full access public key ed25519:publiccc which is matched to a private key ed25519:secrettt and stored locally in the .near-credentials/mainnet/foo.near.json file.
I can now send myself 1 NEAR using near send foo.near foo.near 1 to verify the keys work. If I modify the private key in that keypair at all, the send fails. Good.
Then I replace the public key in that keypair with a nonsense string like ed25519:giggle.
I can still send myself 1 NEAR using the same command. Why?
It appears the public key is totally irrelevant in this keypair. You can use a nonsense string or a public key that's supposed to have limited access only and the private key gives full access to transfer funds.
Good question! I had to do some digging. So let's start with what the CLI is doing behind the scenes. The code is found here:
exports.sendMoney = async function (options) {
await checkCredentials(options.sender, options.networkId, options.keyStore);
console.log(`Sending ${options.amount} NEAR to ${options.receiver} from ${options.sender}`);
const near = await connect(options);
const account = await near.account(options.sender);
const result = await account.sendMoney(options.receiver, utils.format.parseNearAmount(options.amount));
inspectResponse.prettyPrintResponse(result, options);
};
Essentially it connects to the network, creates an account object, and then calls the sendMoney method for that account object which is through near-api-js. The way it's instantiated is through near.account() which behind the scenes does the following (found here):
async account(accountId: string): Promise<Account> {
const account = new Account(this.connection, accountId);
return account;
}
This is just calling the class' constructor passing in the connection and account ID. Up until this point, we have no reference to the private or public key other than the connection which has a keystore indicating WHERE the keypair will be found. Ok moving on.
After the account class is initialized, the sendMoney method is called and the only action is a simple transfer with the amount. The code for this method can be seen here.
async sendMoney(receiverId: string, amount: BN): Promise<FinalExecutionOutcome> {
return this.signAndSendTransaction({
receiverId,
actions: [transfer(amount)]
});
}
You'll notice that it calls the signAndSendTransaction method that is part of the Account Class (found here).
async signAndSendTransaction({ receiverId, actions, returnError }: SignAndSendTransactionOptions): Promise<FinalExecutionOutcome> {
let txHash, signedTx;
// TODO: TX_NONCE (different constants for different uses of exponentialBackoff?)
const result = await exponentialBackoff(TX_NONCE_RETRY_WAIT, TX_NONCE_RETRY_NUMBER, TX_NONCE_RETRY_WAIT_BACKOFF, async () => {
[txHash, signedTx] = await this.signTransaction(receiverId, actions);
const publicKey = signedTx.transaction.publicKey;
try {
return await this.connection.provider.sendTransaction(signedTx);
}
...
...
Out of this method, the important thing is this.signTransaction whose method is found here:
protected async signTransaction(receiverId: string, actions: Action[]): Promise<[Uint8Array, SignedTransaction]> {
const accessKeyInfo = await this.findAccessKey(receiverId, actions);
if (!accessKeyInfo) {
throw new TypedError(`Can not sign transactions for account ${this.accountId} on network ${this.connection.networkId}, no matching key pair exists for this account`, 'KeyNotFound');
}
const { accessKey } = accessKeyInfo;
const block = await this.connection.provider.block({ finality: 'final' });
const blockHash = block.header.hash;
const nonce = accessKey.nonce.add(new BN(1));
return await signTransaction(
receiverId, nonce, actions, baseDecode(blockHash), this.connection.signer, this.accountId, this.connection.networkId
);
}
In this method, there's a sneaky this.findAccessKey being done whose code can be found here.
async findAccessKey(receiverId: string, actions: Action[]): Promise<{ publicKey: PublicKey; accessKey: AccessKeyView }> {
// TODO: Find matching access key based on transaction (i.e. receiverId and actions)
const publicKey = await this.connection.signer.getPublicKey(this.accountId, this.connection.networkId);
if (!publicKey) {
throw new TypedError(`no matching key pair found in ${this.connection.signer}`, 'PublicKeyNotFound');
}
const cachedAccessKey = this.accessKeyByPublicKeyCache[publicKey.toString()];
if (cachedAccessKey !== undefined) {
return { publicKey, accessKey: cachedAccessKey };
}
try {
const rawAccessKey = await this.connection.provider.query<AccessKeyViewRaw>({
request_type: 'view_access_key',
account_id: this.accountId,
public_key: publicKey.toString(),
finality: 'optimistic'
});
// store nonce as BN to preserve precision on big number
const accessKey = {
...rawAccessKey,
nonce: new BN(rawAccessKey.nonce),
};
// this function can be called multiple times and retrieve the same access key
// this checks to see if the access key was already retrieved and cached while
// the above network call was in flight. To keep nonce values in line, we return
// the cached access key.
if (this.accessKeyByPublicKeyCache[publicKey.toString()]) {
return { publicKey, accessKey: this.accessKeyByPublicKeyCache[publicKey.toString()] };
}
this.accessKeyByPublicKeyCache[publicKey.toString()] = accessKey;
return { publicKey, accessKey };
} catch (e) {
if (e.type == 'AccessKeyDoesNotExist') {
return null;
}
throw e;
}
}
If you take a look at this code, you'll notice a really important line:
const publicKey = await this.connection.signer.getPublicKey(this.accountId, this.connection.networkId);
What is this returning? The short answer is that if you're using the NEAR-CLI, the connection.signer comes from UnencryptedFileSystemKeyStore since your keys are stored in .near-credentials. Now let's look at this getPublicKey method found here:
async getPublicKey(accountId?: string, networkId?: string): Promise<PublicKey> {
const keyPair = await this.keyStore.getKey(networkId, accountId);
if (keyPair === null) {
return null;
}
return keyPair.getPublicKey();
}
It does this.keyStore.getKey where the keyStore is the UnencryptedFileSystemKeyStore I mentioned earlier. The getKey method is then found here:
async getKey(networkId: string, accountId: string): Promise<KeyPair> {
// Find key / account id.
if (!await exists(this.getKeyFilePath(networkId, accountId))) {
return null;
}
const accountKeyPair = await readKeyFile(this.getKeyFilePath(networkId, accountId));
return accountKeyPair[1];
}
In this function, the final culprit is the readKeyFile where it returns the key pair (both public and private). This can be found here:
export async function readKeyFile(filename: string): Promise<[string, KeyPair]> {
const accountInfo = await loadJsonFile(filename);
// The private key might be in private_key or secret_key field.
let privateKey = accountInfo.private_key;
if (!privateKey && accountInfo.secret_key) {
privateKey = accountInfo.secret_key;
}
return [accountInfo.account_id, KeyPair.fromString(privateKey)];
}
Notice that it returns a KeyPair that is generated from the private key. This means that no matter what the public key is, it will overwrite it. I did a quick test where I console logged the accountInfo and it indeed returned the incorrect public key that I had set manually but when it generates the KeyPair from the private key, that information is overwritten.
TLDR:
When the your account signs a transaction, the public key is re-generated based on the private key. It doesn't matter what public key you have in your .near-credentials since it is overwritten when the KeyPair is created based on the private key.

Ckeditor5 error with undoing multiline paste operation

I have a plugin for my ckeditor build which should convert pasted content with formulas,
separated by '(' ')', '$$' etc. into math-formulas from ckeditor5-math (https://github.com/isaul32/ckeditor5-math). I changed the AutoMath Plugin so that it supports text with the separators.
I have run into a problem where undoing (ctrl-z) the operation works fine for single-line content, but not for multiline content.
To reproduce the issue, I have built a similar plugin which does not require the math plugin. This plugin converts text enclosed by '&' to bold text.
To reproduce this issue with an editor instance it is required to have the cursor inside a word (not after or before the end of the text, I don't know why that doesn't work, if you know why, help is appreciated^^) and paste it from the clipboard. The content will inside the '&' will be marked bold, however if you undo this operation twice, an model-position-path-incorrect-format error will be thrown.
example to paste:
aa &bb& cc
dd
ee &ff& gg
Undoing the operation twice results in this error:
Uncaught CKEditorError: model-position-path-incorrect-format {"path":[]}
Read more: https://ckeditor.com/docs/ckeditor5/latest/support/error-codes.html#error-model-position-path-incorrect-form
Unfortunately, I haven't found a way to fix this issue, and have not found a similar issue.
I know it has to do with the batches that are operated, and that maybe the position parent has to do something with it, that I should cache the position of the parent. However, I do not know how.
Below my code for an example to reproduce:
import Plugin from '#ckeditor/ckeditor5-core/src/plugin';
import Undo from '#ckeditor/ckeditor5-undo/src/undo';
import LiveRange from '#ckeditor/ckeditor5-engine/src/model/liverange';
import LivePosition from '#ckeditor/ckeditor5-engine/src/model/liveposition';
import global from '#ckeditor/ckeditor5-utils/src/dom/global';
export default class Test extends Plugin {
static get requires() {
return [Undo];
}
static get pluginName() {
return 'Test';
}
constructor(editor) {
super(editor);
this._timeoutId = null;
this._positionToInsert = null;
}
init() {
const editor = this.editor;
const modelDocument = editor.model.document;
const view = editor.editing.view;
//change < Clipboard > to < 'ClipboardPipeline' > because in version upgrade from 26 to 27
//the usage of this call changed
this.listenTo(editor.plugins.get('ClipboardPipeline'), 'inputTransformation', (evt, data) => {
const firstRange = modelDocument.selection.getFirstRange();
const leftLivePosition = LivePosition.fromPosition(firstRange.start);
leftLivePosition.stickiness = 'toPrevious';
const rightLivePosition = LivePosition.fromPosition(firstRange.end);
rightLivePosition.stickiness = 'toNext';
modelDocument.once('change:data', () => {
this._boldBetweenPositions(leftLivePosition, rightLivePosition);
leftLivePosition.detach();
rightLivePosition.detach();
}, {priority: 'high'});
});
editor.commands.get('undo').on('execute', () => {
if (this._timeoutId) {
global.window.clearTimeout(this._timeoutId);
this._timeoutId = null;
}
}, {priority: 'high'});
}
_boldBetweenPositions(leftPosition, rightPosition) {
const editor = this.editor;
const equationRange = new LiveRange(leftPosition, rightPosition);
// With timeout user can undo conversation if wants to use plain text
this._timeoutId = global.window.setTimeout(() => {
this._timeoutId = null;
let walker = equationRange.getWalker({ignoreElementEnd: true});
let nodeArray = [];
for (const node of walker) { // remember nodes, because when they are changed model-textproxy-wrong-length error occurs
nodeArray.push(node);
}
editor.model.change(writer => {
for (let node of nodeArray) {
let text = node.item.data;
if (node.item.is('$textProxy') && text !== undefined && text.match(/&/g)) {
let finishedFormulas = this._split(text);
const realRange = writer.createRange(node.previousPosition, node.nextPosition);
writer.remove(realRange);
for (let i = finishedFormulas.length - 1; i >= 0; i--) {
if (i % 2 === 0) {
writer.insertText(finishedFormulas[i], node.previousPosition);
} else {
writer.insertText(finishedFormulas[i], {bold: true}, node.previousPosition);
}
}
}
}
});
}, 100);
}
_split(text) {
let mathFormsAndText = text.split(/(&)/g);
let mathTextArray = [];
for (let i = 0; i < mathFormsAndText.length; i++) {
if (i % 4 === 0) {
mathTextArray.push(mathFormsAndText[i]);
} else if (i % 2 === 0) {
mathTextArray.push(mathFormsAndText[i]);
}
}
return mathTextArray;
}
}
Let me know if I can clarify anything.

ACE editor adding special characters

The use case is to display server logs in the UI built using Angular9.
I am using ACE editor to display text content received from server upon a http call and the server responds with recent 1000 lines of logs
To verify the content i did console.log() to view the text content in the chrome dev tool.
Console output received from server
While loading the same content to editor I notice special characters
Ace editor content while using in text mode
Attached 2 screenshot to compare
HTML Content
<div ace-editor #codeEditor style="min-height: 550px; width:100%; overflow: auto;"></div>
Typescript
import { Component, ViewChild, ElementRef, Input, SimpleChanges } from '#angular/core';
import * as ace from 'ace-builds';
import 'ace-builds/src-noconflict/mode-json';
import 'ace-builds/src-noconflict/theme-github';
import 'ace-builds/src-noconflict/ext-beautify';
const THEME = 'ace/theme/github';
const LANG = 'ace/mode/text';
#Component({
selector: 'app-text-editor',
templateUrl: './text-editor.component.html',
styleUrls: ['./text-editor.component.css']
})
export class TextEditorComponent {
#ViewChild('codeEditor') codeEditorElmRef: ElementRef;
private codeEditor: ace.Ace.Editor;
#Input() textObject;
#Input() readMode;
data: any;
mode: any;
constructor() { }
ngOnChanges(changes: SimpleChanges) {
for (const properties of Object.keys(changes)) {
if (properties == 'textObject') {
const currentJSONObject = changes[properties];
if (currentJSONObject.currentValue && currentJSONObject.firstChange == false)
this.codeEditor.setValue(currentJSONObject.currentValue, -1);
else
this.data = currentJSONObject.currentValue
}
if (properties == 'readMode') {
const currentReadMode = changes[properties];
if (currentReadMode.firstChange == false)
this.codeEditor.setReadOnly(currentReadMode.currentValue);
else
this.mode = currentReadMode.currentValue
}
}
}
ngAfterViewInit() {
const element = this.codeEditorElmRef.nativeElement;
const editorOptions: Partial<ace.Ace.EditorOptions> = {
highlightActiveLine: true,
displayIndentGuides: true,
highlightSelectedWord: true,
};
this.codeEditor = ace.edit(element, editorOptions);
this.codeEditor.setTheme(THEME);
this.codeEditor.getSession().setMode(LANG);
this.codeEditor.setShowFoldWidgets(true);
this.codeEditor.setHighlightActiveLine(true);
this.codeEditor.setShowPrintMargin(false);
this.codeEditor.setReadOnly(this.readMode);
this.codeEditor.navigateFileEnd();
if (this.data)
this.codeEditor.setValue(this.data, - 1);
if (this.mode)
this.codeEditor.setReadOnly(this.mode);
}
}
This are not characters added by ace, but color control characters sent by the terminal. If you do not want to display colors, and only want the text use the following function
var CSIRegexp;
function getCSIRegexp() {
if (CSIRegexp) return CSIRegexp;
// http://www.inwap.com/pdp10/ansicode.txt
var classes = {
C0 : "\\x00-\\x1F", //
SPACE : "\\x20\\xA0" , // Always and everywhere a blank space
G0 : "\\x21-\\x7E", //
Intermediate : "\\x20-\\x2F", // !"#$%&'()*+,-./
Parameters : "\\x30-\\x3F", // 0123456789:;<=>?
Uppercase : "\\x40-\\x5F", // #ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_
Lowercase : "\\x60-\\x7E", // `abcdefghijlkmnopqrstuvwxyz{|}~
Alphabetic : "\\x40-\\x7E", // (all of upper and lower case)
Delete : "\\x7F" , // Always and everywhere ignored
C1 : "\\x80-\\x9F", // 32 additional control characters
G1 : "\\xA1-\\xFE", // 94 additional displayable characters
Special : "\\xA0\\xFF" , // Same as SPACE and DELETE
ESC : "\\x1b" , //
Ignore : "\\x7F\\x00-\\x1F\\x80-\\x9F" // Delete|C0|C1
};
var g = /:ESC:(\[:Parameters:*:Intermediate:?:Alphabetic:?|:Intermediate:+:Parameters:|:Parameters:|:Lowercase:|)|[:Ignore:]/;
var inBrackets = false;
var source = g.source.replace(/(\\.)|([\[\]])|:(\w*):/g, function(_, esc, b, cls) {
if (esc) return esc;
if (b) {
inBrackets = b == "[";
return b;
}
if (!cls) return ":";
var r = classes[cls];
if (!/ESC|Delete|C0|C1/.test(cls)) {
r += classes.Ignore;
}
if (!inBrackets && cls != "ESC")
r = "[" + r + "]";
return r;
});
return CSIRegexp = new RegExp(source, "g");
}
to remove control character before setting data to the editor
this.codeEditor.setValue(this.data.replace(getCSIRegexp(), ""), - 1);
You can test it with the following call:
"\x1b[1mreal text\x1b[10m".replace(getCSIRegexp(), "")

BotBuilder type error :Cannot read property 'listen' of undefined

I'm following the official quick start of Microsoft Bot Builder(SDK v3) for NodeJs: Create a bot with the Bot Builder SDK for Node.js
1- I made a new project with
npm init
2- then
npm install --save botbuilder#3.13.1
3- then I created a new file "app.js"
var builder = require('botbuilder');
var connector = new builder.ConsoleConnector().listen();
var bot = new builder.UniversalBot(connector, function (session) {
session.send("You said: %s", session.message.text);
});
But when I run node app.js the following error is thrown:
var connector=builder.ConsoleConnector().listen(); TypeError:
Cannot read property 'listen' of undefined
You haven't assigned a storage option to your bot. The simplest option (for development only) is to use in memory storage. You're code should look like this:
var builder = require('botbuilder');
// Bot Storage: Here we register the state storage for your bot.
// Default store: volatile in-memory store - Only for prototyping!
var inMemoryStorage = new builder.MemoryBotStorage();
var connector = new builder.ConsoleConnector().listen();
var bot = new builder.UniversalBot(connector, function(session) {
session.send("You said: %s", session.message.text);
}).set('storage', inMemoryStorage); // Register in memory storage
That being said, please be aware that the v3 SDK is going to be DEPRECATED in the near future. It is advised that you start your development using the v4 Node SDK, instead. To get started, you can reference the docs here and review sample code here.
In short, in v4, you will utilize three files: index.js, bot.js, and consoleAdapter.js.
The index.js file essentially builds the server, api's, etc.
const path = require('path');
const {
ConsoleAdapter
} = require('./consoleAdapter');
// load environment variables from .env file.
const ENV_FILE = path.join(__dirname, '.env');
require('dotenv').config({
path: ENV_FILE
});
// Create the bot adapter, which is responsible for sending and receiving messages.
// We are using the ConsoleAdapter, which enables a bot you can chat with from within your terminal window.
const adapter = new ConsoleAdapter();
// Import our bot class.
const {
EchoBot
} = require('./bot');
const bot = new EchoBot();
// A call to adapter.listen tells the adapter to start listening for incoming messages and events, known as "activities."
// Activities are received as TurnContext objects by the handler function.
adapter.listen(async(context) => {
bot.onTurn(context);
});
// Emit a startup message with some instructions.
console.log('> Console EchoBot is online. I will repeat any message you send me!');
console.log('> Say "quit" to end.');
console.log(''); // Leave a blank line after instructions.
The bot.js file, generally, handles your bot's on[ActivityType] actions (e.g. onMessage()). In more complex bots, dialogs are extrapolated into their own files.
class EchoBot {
async onTurn(context) {
// Check to see if this activity is an incoming message.
// (It could theoretically be another type of activity.)
if(context.activity.type === 'message' && context.activity.text) {
// Check to see if the user sent a simple "quit" message.
if(context.activity.text.toLowerCase() === 'quit') {
// Send a reply.
context.sendActivity(`Bye!`);
process.exit();
} else {
// Echo the message text back to the user.
return context.sendActivity(`I heard you say "${ context.activity.text }"`);
}
}
}
}
module.exports.EchoBot = EchoBot;
Lastly, the consoleAdapter.js file is tasked with capturing the console activity and translating that to the bot.
'use strict';
var __importStar = (this && this.__importStar) || function(mod) {
if(mod && mod.__esModule) return mod;
var result = {};
if(mod != null)
for(var k in mod)
if(Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
result['default'] = mod;
return result;
};
Object.defineProperty(exports, '__esModule', {
value: true
});
const botbuilderCore = require('botbuilder-core');
const readline = __importStar(require('readline'));
const console = require('console');
/**
* Lets a user communicate with a bot from a console window.
*
*/
class ConsoleAdapter extends botbuilderCore.BotAdapter {
/**
* Creates a new ConsoleAdapter instance.
* #param reference (Optional) reference used to customize the address information of activities sent from the adapter.
*/
constructor(reference) {
super();
this.nextId = 0;
this.reference = Object.assign({
channelId: 'console',
user: {
id: 'user',
name: 'User1'
},
bot: {
id: 'bot',
name: 'Bot'
},
conversation: {
id: 'convo1',
name: '',
isGroup: false
},
serviceUrl: ''
}, reference);
}
/**
* Begins listening to console input. A function will be returned that can be used to stop the
* bot listening and therefore end the process.
*
* #param logic Function which will be called each time a message is input by the user.
*/
listen(logic) {
const rl = this.createInterface({
input: process.stdin,
output: process.stdout,
terminal: false
});
rl.on('line', (line) => {
// Initialize activity
const activity = botbuilderCore.TurnContext.applyConversationReference({
type: botbuilderCore.ActivityTypes.Message,
id: (this.nextId++).toString(),
timestamp: new Date(),
text: line
}, this.reference, true);
// Create context and run middleware pipe
const context = new botbuilderCore.TurnContext(this, activity);
this.runMiddleware(context, logic)
.catch((err) => {
this.printError(err.toString());
});
});
return() => {
rl.close();
};
}
/**
* Lets a bot proactively message the user.
*
* #param reference A `ConversationReference` saved during a previous message from a user. This can be calculated for any incoming activity using `TurnContext.getConversationReference(context.activity)`.
* #param logic A function handler that will be called to perform the bots logic after the the adapters middleware has been run.
*/
continueConversation(reference, logic) {
// Create context and run middleware pipe
const activity = botbuilderCore.TurnContext.applyConversationReference({}, reference, true);
const context = new botbuilderCore.TurnContext(this, activity);
return this.runMiddleware(context, logic)
.catch((err) => {
this.printError(err.toString());
});
}
/**
* Logs a set of activities to the console.
*
* #param context Context for the current turn of conversation with the user.
* #param activities List of activities to send.
*/
sendActivities(context, activities) {
const that = this;
// tslint:disable-next-line:promise-must-complete
return new Promise((resolve, reject) => {
const responses = [];
function next(i) {
if(i < activities.length) {
responses.push({});
const a = activities[i];
switch(a.type) {
case 'delay':
setTimeout(() => next(i + 1), a.value);
break;
case botbuilderCore.ActivityTypes.Message:
if(a.attachments && a.attachments.length > 0) {
const append = a.attachments.length === 1 ?
`(1 attachment)` : `(${ a.attachments.length } attachments)`;
that.print(`${ a.text } ${ append }`);
} else {
that.print(a.text || '');
}
next(i + 1);
break;
default:
that.print(`[${ a.type }]`);
next(i + 1);
break;
}
} else {
resolve(responses);
}
}
next(0);
});
}
/**
* Not supported for the ConsoleAdapter. Calling this method or `TurnContext.updateActivity()`
* will result an error being returned.
*/
updateActivity(context, activity) {
return Promise.reject(new Error(`ConsoleAdapter.updateActivity(): not supported.`));
}
/**
* Not supported for the ConsoleAdapter. Calling this method or `TurnContext.deleteActivity()`
* will result an error being returned.
*/
deleteActivity(context, reference) {
return Promise.reject(new Error(`ConsoleAdapter.deleteActivity(): not supported.`));
}
/**
* Allows for mocking of the console interface in unit tests.
* #param options Console interface options.
*/
createInterface(options) {
return readline.createInterface(options);
}
/**
* Logs text to the console.
* #param line Text to print.
*/
print(line) {
console.log(line);
}
/**
* Logs an error to the console.
* #param line Error text to print.
*/
printError(line) {
console.error(line);
}
}
exports.ConsoleAdapter = ConsoleAdapter;
The above code is taken from the 01.console-echo sample of the Botbuilder-Samples repo. I removed some inline commentary. Please refer to the project for the complete code/files and associated remarks.
Hope of help!

Angular6 - Variable won't update

I'm sorry I'm sure this is one of the most frequently asked questions about angular, and I found a ton but nothing's helping me here. I got a simple Observable - subscribe relationship with a variable.
my Service:
activeRoom: number = 0; // we're starting in room 0
/* get the roomnumber from open-rooms to chat-window */
getActiveRoom(): Observable<number> {
return of(this.activeRoom);
}
my component:
constructor(
private activeRoomService: ActiveRoomService){}
ngOnInit() {
/* Observe if we're changing rooms */
this.activeRoomService.getActiveRoom().subscribe(newActiveRoom => {
this.activeRoomChat = []; // clear the message board
this.activeRoom = newActiveRoom;
});
}
click(){
console.log("the following line doesn't work");
console.log(this.activeRoom);
console.log("the following line does work")
console.log(this.activeRoomService.activeRoom);
}
I obviously can't update my component with a click every time, so option b is no option :D
What's the blatantly obvious thing I'm missing here?
Here's a working example.
Service:
private userArray: User[] = [];
getUserArray(): Observable<User[]>{
return of(this.userArray);
}
component:
constructor(private backend: BackendService) {}
ngOnInit() {
this.backend.getUserArray().subscribe(user => {
this.userlist = user;
// console.log(user);
});
Can someone please point a really really big red arrow to the thing I'm missing here?
Changed
activeRoom: number = 0;
getActiveRoom(): Observable<number> {
return of(this.activeRoom);
}
setActiveRoom(roomID): void {
this.activeRoom = roomID;
}
to:
activeRoom: Subject<number> = new Subject;
public getActiveRoom(): Observable<number> {
return this.activeRoom.asObservable();
}
public setActiveRoom(roomID): void {
this.activeRoom.next(roomID);
}
and it works. To be honest, I have no idea why or what changed, but I'm happy it works :D

Resources