Просмотр исходного кода

book: Improve JSON-RPC documentation generation.

parazyd 4 лет назад
Родитель
Сommit
229a3d13cb
5 измененных файлов с 201 добавлено и 157 удалено
  1. 3 1
      book/Makefile
  2. 45 58
      book/build_jsonrpc.py
  3. 1 1
      book/src/SUMMARY.md
  4. 152 0
      book/src/clients/darkfid_jsonrpc.md
  5. 0 97
      book/src/clients/jsonrpc.md

+ 3 - 1
book/Makefile

@@ -1,7 +1,9 @@
 .POSIX:
 
 all:
-	python3 ./build_jsonrpc.py
+	echo "# darkfid JSON-RPC API" > src/clients/darkfid_jsonrpc.md
+	./build_jsonrpc.py ../bin/darkfid/src/main.rs \
+		>> src/clients/darkfid_jsonrpc.md
 	mdbook build
 
 github: all

+ 45 - 58
book/build_jsonrpc.py

@@ -1,72 +1,59 @@
+#!/usr/bin/env python3
+from sys import argv
 
-class Method:
-    def __init__(self, name, params):
-        self.name = name
-        self.params = params.replace(',', ', ');
-        self.result = ""
-        self.note = ""
 
+def main(path):
+    lines = []
 
-    def set_result(self, result):
-        self.result = result.replace(':', ': ');
-        self.result = result.replace(',', ', ');
+    f = open(path, "r")
+    read_lines = f.readlines()
+    for line in read_lines:
+        lines.append(line.strip())
 
-    def __str__(self):
-        method_str = '### ' + self.name + ': \n' \
-                + '`params`: ' +  self.params + '\n' \
-                + '\n' \
-                + '`result`: ' +  self.result + '\n' \
-                + '\n' \
+    parsing_method = False
 
-        if not self.note == "":
-            method_str += '> `note`: ' +  self.note + '\n' 
+    methods = []
+    method = ""
+    comment = ""
+    send = ""
+    recv = ""
 
-        return method_str
+    for i in lines:
+        if not i.startswith("//"):
+            continue
 
+        if i == ("// RPCAPI:"):
+            parsing_method = True
+            continue
 
-def main():
-    methods =  []
-    with open('../src/bin/darkfid.rs') as f:
-        lines = f.readlines()
-        for i in range(0, len(lines)):
-            line = lines[i]
+        if parsing_method:
+            if i.startswith("// --> "):
+                method = i.split()[3][1:-2]
+                recv = i[3:]
+                continue
 
-            if line.__contains__("RPCAPI"):
+            if i.startswith("// <-- "):
+                send = i[3:]
+                parsing_method = False
+                methods.append((method, comment.strip(), recv, send))
+                comment = ""
+                continue
 
-                line = lines[i + 1]
-                if line.__contains__(' --> '):
-                    line = line.strip()
-                    words = line.split(' ')
-                    method = words[3][1::][:-2:]
-                    params = words[5][:-1:]
-                    methods.append(Method(method, params))
+            comment += i[3:] + "\n"
 
-                line = lines[i + 2]
-                if line.__contains__(' <-- '):
-                    line = line.strip()
-                    words = line.split(' ')
-                    methods[-1].set_result(words[3][:-1:])
+    print("\n## Methods")
+    for i in methods:
+        print(f"* [`{i[0]}`](#{i[0]})")
 
-                line = lines[i + 3]
-                if line.__contains__("APINOTE"):
-                    methods[-1].note = line.strip().replace('// APINOTE:','')
-                    count = i + 4
-                    line = lines[count]
-                    while line.strip().startswith('//'):
-                        count += 1
-                        methods[-1].note += line[6::]
-                        line = lines[count]
+    print("\n")
+    for i in methods:
+        print(f"### `{i[0]}`\n")
+        print(f"{i[1]}")
+        print("\n```json")
+        print(i[2])
+        print(i[3])
+        print("```")
 
 
-
-    with open('src/clients/jsonrpc.md', 'w') as f:
-        f.write('# JSONRPC API \n')
-        f.write('## Methods \n')
-        for m in methods:
-            f.write('- [' + m.name + '](jsonrpc.md#' + m.name + ')\n')
-        for m in methods:
-            f.write(m.__str__())
-
-
-if __name__ == '__main__':
-    main()
+if __name__ == "__main__":
+    main(argv[1])

+ 1 - 1
book/src/SUMMARY.md

@@ -5,7 +5,7 @@
 - [Development](development.md)
 - [Tutorial](tutorial.md)
 - [Client](clients/clients.md)
-  - [JSONRPC API](clients/jsonrpc.md)
+  - [darkfid JSON-RPC API](clients/darkfid_jsonrpc.md)
 - [zkas](zkas/zkas.md)
   - [Bincode](zkas/bincode.md)
   - [Examples](zkas/examples.md)

+ 152 - 0
book/src/clients/darkfid_jsonrpc.md

@@ -0,0 +1,152 @@
+# darkfid JSON-RPC API
+
+## Methods
+* [`say_hello`](#say_hello)
+* [`create_wallet`](#create_wallet)
+* [`key_gen`](#key_gen)
+* [`get_key`](#get_key)
+* [`get_keys`](#get_keys)
+* [`import_keypair`](#import_keypair)
+* [`export_keypair`](#export_keypair)
+* [`set_default_address`](#set_default_address)
+* [`get_balances`](#get_balances)
+* [`get_token_id`](#get_token_id)
+* [`features`](#features)
+* [`deposit`](#deposit)
+* [`withdraw`](#withdraw)
+* [`transfer`](#transfer)
+
+
+### `say_hello`
+
+Returns a `helloworld` string.
+
+```json
+--> {"method": "say_hello", "params": []}
+<-- {"result": "helloworld"}
+```
+### `create_wallet`
+
+Attempts to initialize a wallet, and returns `true` upon success.
+
+```json
+--> {"method": "create_wallet", "params": []}
+<-- {"result": true}
+```
+### `key_gen`
+
+Attempts to generate a new keypair and returns `true` upon success.
+
+```json
+--> {"method": "key_gen", "params": []}
+<-- {"result": true}
+```
+### `get_key`
+
+Fetches the main keypair from the wallet and returns it
+in an encoded format.
+
+```json
+--> {"method": "get_key", "params": []}
+<-- {"result": "vdNS7oBj7KvsMWWmo9r96SV4SqATLrGsH2a3PGpCfJC"}
+```
+### `get_keys`
+
+Fetches all keypairs from the wallet and returns a list of them
+in an encoded format.
+The first one in the list is the default selected keypair.
+
+```json
+--> {"method": "get_keys", "params": []}
+<-- {"result": "[vdNS7oBj7KvsMWWmo9r96SV4SqATLrGsH2a3PGpCfJC,...]"}
+```
+### `import_keypair`
+
+Imports a keypair into the wallet with a given path on the filesystem.
+Returns `true` upon success.
+
+```json
+--> {"method": "import_keypair", "params": [path]}
+<-- {"result": true}
+```
+### `export_keypair`
+
+Exports the default selected keypair to a given path on the filesystem.
+Returns `true` upon success.
+
+```json
+--> {"method": "export_keypair", "params": [path]}
+<-- {"result": true}
+```
+### `set_default_address`
+
+Sets the default wallet address to the given parameter.
+Returns true upon success.
+
+```json
+--> {"method": "set_default_address", "params": [vdNS7oBj7KvsMWWmo9r96SV4SqATLrGsH2a3PGpCfJC]}
+<-- {"result": true}
+```
+### `get_balances`
+
+Fetches the known balances from the wallet.
+Returns a map of balances, indexed by `network`, and token ID.
+
+```json
+--> {"method": "get_balances", "params": []}
+<-- {"result": "[{"btc":(value,network)},...]"}
+```
+### `get_token_id`
+
+Generates the internal token ID for a given `network` and token ticker or address.
+Returns the internal representation of the token ID.
+
+```json
+--> {"method": "get_token_id", "params": [network,token]}
+<-- {"result": "Ht5G1RhkcKnpLVLMhqJc5aqZ4wYUEbxbtZwGCVbgU7DL"}
+```
+### `features`
+
+Asks the configured cashier for their supported features.
+Returns a map of features received from the requested cashier.
+
+```json
+--> {"method": "features", "params": []}
+<-- {"result": {"network":["btc","sol"]}}
+```
+### `deposit`
+
+Initializes a DarkFi deposit request for a given `network`, `token`,
+and `publickey`.
+The public key send here is used so the cashier can know where to send
+the newly minted tokens once the deposit is received.
+Returns an address to which the caller is supposed to deposit funds.
+
+```json
+--> {"method": "deposit", "params": [network,token,publickey]}
+<-- {"result": "Ht5G1RhkcKnpLVLMhqJc5aqZ4wYUEbxbtZwGCVbgU7DL"}
+```
+### `withdraw`
+
+Initializes a withdraw request for a given `network`, `token`, `publickey`,
+and `amount`.
+The publickey send here is the address where the caller wants to receive
+the tokens they plan to withdraw.
+On request, sends a request to a cashier to get a deposit address, and
+then transfers wrapped DarkFitokens to the cashier's wallet. Following that,
+the cashier should return a transaction ID of them sending the funds that
+are requested for withdrawal.
+
+```json
+--> {"method": "withdraw", "params": [network,token,publickey,amount]}
+<-- {"result": "txID"}
+```
+### `transfer`
+
+Transfer a given wrapped DarkFi token amount to the given address.
+Returns the transaction ID of the transfer.
+
+```json
+--> {"method": "transfer", "params": [network,dToken,address,amount]}
+<-- {"result": "txID"}
+```

+ 0 - 97
book/src/clients/jsonrpc.md

@@ -1,97 +0,0 @@
-# JSONRPC API 
-## Methods 
-- [say_hello](jsonrpc.md#say_hello)
-- [create_wallet](jsonrpc.md#create_wallet)
-- [key_gen](jsonrpc.md#key_gen)
-- [get_key](jsonrpc.md#get_key)
-- [get_keys](jsonrpc.md#get_keys)
-- [import_keypair](jsonrpc.md#import_keypair)
-- [export_keypair](jsonrpc.md#export_keypair)
-- [set_default_address](jsonrpc.md#set_default_address)
-- [get_balances](jsonrpc.md#get_balances)
-- [get_token_id](jsonrpc.md#get_token_id)
-- [features](jsonrpc.md#features)
-- [deposit](jsonrpc.md#deposit)
-- [withdraw](jsonrpc.md#withdraw)
-- [transfer](jsonrpc.md#transfer)
-### say_hello: 
-`params`: []
-
-`result`: "helloworld"
-
-### create_wallet: 
-`params`: []
-
-`result`: true
-
-### key_gen: 
-`params`: []
-
-`result`: true
-
-### get_key: 
-`params`: []
-
-`result`: "vdNS7oBj7KvsMWWmo9r96SV4SqATLrGsH2a3PGpCfJC"
-
-### get_keys: 
-`params`: []
-
-`result`: "[vdNS7oBj7KvsMWWmo9r96SV4SqATLrGsH2a3PGpCfJC, ...]"
-
-> `note`:  the first address in the returned vector is the default address
-
-### import_keypair: 
-`params`: [path]
-
-`result`: true
-
-### export_keypair: 
-`params`: [path]
-
-`result`: true
-
-### set_default_address: 
-`params`: [vdNS7oBj7KvsMWWmo9r96SV4SqATLrGsH2a3PGpCfJC]
-
-`result`: true
-
-### get_balances: 
-`params`: []
-
-`result`: "[{"btc":(value, network)}, ...]"
-
-### get_token_id: 
-`params`: [network, token]
-
-`result`: "Ht5G1RhkcKnpLVLMhqJc5aqZ4wYUEbxbtZwGCVbgU7DL"
-
-### features: 
-`params`: []
-
-`result`: {"network":["btc", "sol"]}
-
-### deposit: 
-`params`: [network, token, publickey]
-
-`result`: "Ht5G1RhkcKnpLVLMhqJc5aqZ4wYUEbxbtZwGCVbgU7DL"
-
-> `note`:  The publickey sent here is used so the cashier can know where to send
- tokens once the deposit is received.
-
-### withdraw: 
-`params`: [network, token, publickey, amount]
-
-`result`: "txID"
-
-> `note`:  The publickey sent here is the address where the caller wants to receive
- the tokens they plan to withdraw.
- On request, send request to cashier to get deposit address, and then transfer
- dark tokens to the cashier's wallet. Following that, the cashier should return
- a transaction ID of them sending the funds that are requested for withdrawal.
-
-### transfer: 
-`params`: [network, dToken, address, amount]
-
-`result`: "txID"
-