Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: show how to use mnemonic and storage #7

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
78 changes: 48 additions & 30 deletions create-wallet.js
Original file line number Diff line number Diff line change
@@ -1,34 +1,52 @@
"use strict";

require("dotenv").config({ path: ".env" });

// See https://dashplatform.readme.io/docs/tutorial-create-and-fund-a-wallet
const Dash = require('dash');

const clientOpts = {
network: 'testnet',
wallet: {
mnemonic: null, // this indicates that we want a new wallet to be generated
// if you want to get a new address for an existing wallet
// replace 'null' with an existing wallet mnemonic
offlineMode: true, // this indicates we don't want to sync the chain
// it can only be used when the mnemonic is set to 'null'
},
};

const client = new Dash.Client(clientOpts);

const createWallet = async () => {
const Dash = require("dash");

const Mnemonic = require("./lib/mnemonic.js");
const store = require("./lib/store.js").create({
filepath: "./db.json",
namespace: "dash",
});

async function main() {
const clientOpts = {
network: "testnet",
wallet: {
adapter: store,
// `null` would indicates that we want a new wallet to be generated
mnemonic: await Mnemonic.getOrCreate(process.env.MNEMONIC),
offlineMode: true, // this indicates we don't want to sync the chain
// it can only be used when the mnemonic is set to 'null'
},
};

const client = new Dash.Client(clientOpts);
// Handle wallet async errors
client.on("error", (error, context) => {
console.error(`Client error: ${error.name}`);
console.error(context);
});

let err = await createWallet(client).catch(function (e) {
return e;
});
client.disconnect();
if (err) {
throw err;
}
}

async function createWallet(client) {
const account = await client.getWalletAccount();

const mnemonic = client.wallet.exportWallet();
const address = account.getUnusedAddress();
console.log('Mnemonic:', mnemonic);
console.log('Unused address:', address.address);
};

createWallet()
.catch((e) => console.error('Something went wrong:\n', e))
.finally(() => client.disconnect());

// Handle wallet async errors
client.on('error', (error, context) => {
console.error(`Client error: ${error.name}`);
console.error(context);
});
console.log("Unused address:", address.address);
}

main().catch(function (err) {
console.error("Something went wrong:");
console.error(err.stack);
});
34 changes: 34 additions & 0 deletions lib/mnemonic.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
"use strict";

let Mnemonic = module.exports;

let Fs = require("fs").promises;
let CoreMnemonic = require("@dashevo/dashcore-lib/lib/mnemonic/");

/**
* @param {String} [mnemonic] - string of 12 whitespace-delimited words
* @returns {Promise<String>}
*/
Mnemonic.getOrCreate = async function (mnemonic) {
if (mnemonic) {
return mnemonic;
}

mnemonic = new CoreMnemonic().toString();

let txt = await Fs.readFile(".env", "utf8").catch(function (err) {
if ("ENOENT" !== err.code) {
throw err;
}
return "";
});

if (!txt.endsWith("\n")) {
txt += "\n";
}
txt += `MNEMONIC='${mnemonic}'\n`;
await Fs.writeFile(".env", txt, "utf8");
console.info("Wrote MNEMONIC='<mnemonic>' to .env");

return mnemonic;
};
45 changes: 45 additions & 0 deletions lib/store.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
"use strict";

let Store = module.exports;

let DomStorage = require("dom-storage");
let JsonStorage = require("json-storage").JsonStorage;

/**
* @typedef {Object} CoreStorage
* @property {CoreStorageGetItem} getItem
* @property {CoreStorageSetItem} setItem
*/

/**
* @typedef {Function} CoreStorageGetItem
* @param {String} key
*/

/**
* @typedef {Function} CoreStorageSetItem
* @param {String} key
* @param {any} value
*/

/**
* @param {Object} opts
* @param {String} opts.filepath - path of JSON db file
* @param {String} opts.namespace - namespace prefix for JSON storage
* @returns {CoreStorage}
*/
Store.create = function ({ filepath, namespace }) {
let myLocalStorage = new DomStorage(filepath, { strict: true, ws: " " });
/** @type {CoreStorage} */
//@ts-ignore
let store = JsonStorage.create(myLocalStorage, namespace, {
stringify: true,
});

//@ts-ignore
store.getItem = store.get;
//@ts-ignore
store.setItem = store.set;

return store;
};
30 changes: 29 additions & 1 deletion package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 3 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,9 @@
},
"homepage": "https://github.com/dashevo/platform-readme-tutorials#readme",
"dependencies": {
"dash": "^3.22.7"
"dash": "^3.22.7",
"dom-storage": "^2.1.0",
"json-storage": "^2.1.2"
},
"devDependencies": {
"dotenv": "^16.0.0",
Expand Down