tryflop 0.0.1 → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/wallet.js ADDED
@@ -0,0 +1,123 @@
1
+ // tryflop's ONE wallet on this computer (SPEC.md "tryflop"): the agent's own Flop account. It claims the faucet's
2
+ // grant itself and pays miners as the channel's agent (no session key, no transfer between wallets, ever). Made from
3
+ // 12 recovery words, exactly as the Try Flop browser app makes its wallet (sr25519 from the words, SS58 42), so the
4
+ // same words restore it there, in Talisman, SubWallet or Polkadot.js, or with `tryflop restore` on a new computer.
5
+ // The words sit in <wallet folder>/wallet.json (0600, like ~/.ssh): the daily run must sign with no human present, so
6
+ // they cannot be locked behind a passphrase. No function here returns them except walletWords (for `tryflop backup`,
7
+ // which shows them only to a person at a terminal), and no error message ever quotes the file.
8
+ import { readFileSync } from 'node:fs';
9
+ import { Keyring } from '@polkadot/keyring';
10
+ import { cryptoWaitReady, mnemonicGenerate, mnemonicValidate } from '@polkadot/util-crypto';
11
+ import { assertPrivateFile, createPrivateFileOnce, ensurePrivateDir, HomeError, SS58_PREFIX } from './home.js';
12
+
13
+ export class WalletError extends Error {
14
+ /** @param {'EXISTS'|'MISSING'|'WRONG_NETWORK'|'DAMAGED'|'BAD_WORDS'} code @param {string} message */
15
+ constructor(code, message) {
16
+ super(message);
17
+ this.name = 'WalletError';
18
+ this.code = code;
19
+ }
20
+ }
21
+
22
+ const keyring = () => new Keyring({ type: 'sr25519', ss58Format: SS58_PREFIX });
23
+
24
+ /**
25
+ * The words in the one form they are stored and derived from: lower case, single spaces. Null unless they are 12
26
+ * valid BIP39 words (the browser app's rule).
27
+ * @param {string} text @returns {string | null}
28
+ */
29
+ export function normalWords(text) {
30
+ const words = String(text ?? '').trim().toLowerCase().split(/\s+/).filter(Boolean).join(' ');
31
+ return words.split(' ').length === 12 && mnemonicValidate(words) ? words : null;
32
+ }
33
+
34
+ /** @param {string} words */
35
+ const pairOf = (words) => keyring().addFromMnemonic(words, { name: 'Try Flop agent wallet' });
36
+
37
+ /**
38
+ * @param {import('./home.js').WalletHome} home @param {{ genesis: string }} network @param {string} words already normalised
39
+ * @returns {{ address: string }}
40
+ */
41
+ function writeWallet(home, { genesis }, words) {
42
+ ensurePrivateDir(home.dir);
43
+ const { address } = pairOf(words);
44
+ const file = { version: 1, kind: 'tryflop-wallet', network: home.network, genesis, address, words, createdAt: new Date().toISOString() };
45
+ if (!createPrivateFileOnce(home.walletFile, `${JSON.stringify(file, null, 2)}\n`)) {
46
+ throw new WalletError('EXISTS', `This computer already has a Try Flop wallet for ${home.network}; it was left unchanged (one wallet per person).`);
47
+ }
48
+ return { address };
49
+ }
50
+
51
+ /**
52
+ * Make the wallet: 12 new words from the operating system's random source. Refuses (EXISTS) when one exists: a
53
+ * second wallet would split one person's activity, and replacing one would strand its FLOP.
54
+ * @param {import('./home.js').WalletHome} home @param {{ genesis: string }} network
55
+ * @returns {Promise<{ address: string }>} never the words
56
+ */
57
+ export async function createWallet(home, network) {
58
+ await cryptoWaitReady();
59
+ return writeWallet(home, network, mnemonicGenerate(12));
60
+ }
61
+
62
+ /**
63
+ * Put a wallet the person already has on this computer, from its 12 words (typed by them: `tryflop restore`). Refuses
64
+ * (EXISTS) when this computer already has one, and (BAD_WORDS) for anything but 12 valid words.
65
+ * @param {import('./home.js').WalletHome} home @param {{ genesis: string }} network @param {string} typed
66
+ * @returns {Promise<{ address: string }>}
67
+ */
68
+ export async function restoreWallet(home, network, typed) {
69
+ await cryptoWaitReady();
70
+ const words = normalWords(typed);
71
+ if (!words) throw new WalletError('BAD_WORDS', 'Those are not 12 valid recovery words. Check each word and their order; nothing was saved.');
72
+ return writeWallet(home, network, words);
73
+ }
74
+
75
+ /** @param {import('./home.js').WalletHome} home @param {{ genesis: string }} network */
76
+ function readWalletFile(home, { genesis }) {
77
+ try {
78
+ assertPrivateFile(home.walletFile);
79
+ } catch (error) {
80
+ if (error instanceof HomeError && error.code === 'MISSING') {
81
+ throw new WalletError('MISSING', `There is no Try Flop wallet for ${home.network} on this computer yet. Set it up with: tryflop setup`);
82
+ }
83
+ throw error;
84
+ }
85
+ let file;
86
+ try {
87
+ file = JSON.parse(readFileSync(home.walletFile, 'utf8'));
88
+ } catch {
89
+ throw new WalletError('DAMAGED', `${home.walletFile} is damaged (not valid JSON).`);
90
+ }
91
+ if (!file || file.version !== 1 || file.kind !== 'tryflop-wallet' || typeof file.address !== 'string' || typeof file.words !== 'string' || normalWords(file.words) !== file.words) {
92
+ throw new WalletError('DAMAGED', `${home.walletFile} is damaged (missing or malformed fields).`);
93
+ }
94
+ if (file.network !== home.network || file.genesis !== genesis) {
95
+ throw new WalletError('WRONG_NETWORK', `${home.walletFile} belongs to another Flop network than ${home.network}.`);
96
+ }
97
+ return file;
98
+ }
99
+
100
+ /**
101
+ * Load the wallet to sign with.
102
+ * @param {import('./home.js').WalletHome} home @param {{ genesis: string }} network
103
+ * @returns {Promise<{ address: string, pair: import('@polkadot/keyring/types').KeyringPair }>}
104
+ */
105
+ export async function loadWallet(home, network) {
106
+ await cryptoWaitReady();
107
+ const file = readWalletFile(home, network);
108
+ const pair = pairOf(file.words);
109
+ if (pair.address !== file.address) throw new WalletError('DAMAGED', `${home.walletFile} is damaged (its address does not match its words).`);
110
+ return { address: pair.address, pair };
111
+ }
112
+
113
+ /**
114
+ * The wallet's address without its key (status, setup's "already set up"). @param {import('./home.js').WalletHome} home
115
+ * @param {{ genesis: string }} network @returns {string}
116
+ */
117
+ export const walletAddress = (home, network) => readWalletFile(home, network).address;
118
+
119
+ /**
120
+ * The 12 words, for `tryflop backup` only: it shows them to a person at a terminal and to nobody else.
121
+ * @param {import('./home.js').WalletHome} home @param {{ genesis: string }} network @returns {string}
122
+ */
123
+ export const walletWords = (home, network) => readWalletFile(home, network).words;
package/bin/tryflop.js DELETED
@@ -1,5 +0,0 @@
1
- #!/usr/bin/env node
2
- // Placeholder: the real Try Flop agent tool is not released yet.
3
- console.log("Try Flop's agent tool isn't released yet. See https://tryflop.com for the current way to start.");
4
- console.log('Independent app, not made by Flop Labs. There is no FLOP token yet: ignore anyone selling one.');
5
- process.exitCode = 1;