Skip to content

Commit 6d1d4b1

Browse files
committed
Typescript SDK support for zk-nyms
1 parent 3f6de8b commit 6d1d4b1

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

77 files changed

+3375
-82
lines changed

.gitignore

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -48,4 +48,6 @@ foxyfox.env
4848

4949
.next
5050
ppa-private-key.b64
51-
ppa-private-key.asc
51+
ppa-private-key.asc
52+
53+
yarn-error.log

Cargo.lock

Lines changed: 28 additions & 2 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

Cargo.toml

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -125,7 +125,8 @@ members = [
125125
# "wasm/full-nym-wasm", # If we uncomment this again, remember to also uncomment the profile settings below
126126
"wasm/mix-fetch",
127127
"wasm/node-tester",
128-
"wasm/zknym-lib",
128+
"wasm/zk-nym-lib",
129+
"wasm/zk-nym-faucet-lib",
129130
"tools/internal/testnet-manager",
130131
"tools/internal/testnet-manager/dkg-bypass-contract",
131132
]

Makefile

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -104,7 +104,8 @@ sdk-wasm-build:
104104
$(MAKE) -C wasm/client
105105
$(MAKE) -C wasm/node-tester
106106
$(MAKE) -C wasm/mix-fetch
107-
$(MAKE) -C wasm/zknym-lib
107+
$(MAKE) -C wasm/zk-nym-lib
108+
$(MAKE) -C wasm/zk-nym-faucet-lib
108109
#$(MAKE) -C wasm/full-nym-wasm
109110

110111
# run this from npm/yarn to ensure tools are in the path, e.g. yarn build:sdk from root of repo

common/client-libs/validator-client/src/nyxd/error.rs

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -50,7 +50,7 @@ pub enum NyxdError {
5050
#[error("{0} is not a valid tx hash")]
5151
InvalidTxHash(String),
5252

53-
#[error("Tendermint RPC request failed - {0}")]
53+
#[error("Tendermint RPC request failed: {0}")]
5454
TendermintErrorRpc(#[from] TendermintRpcError),
5555

5656
#[error("tendermint library failure: {0}")]
@@ -62,22 +62,22 @@ pub enum NyxdError {
6262
#[error("Failed when attempting to deserialize data ({0})")]
6363
DeserializationError(String),
6464

65-
#[error("Failed when attempting to encode our protobuf data - {0}")]
65+
#[error("Failed when attempting to encode our protobuf data: {0}")]
6666
ProtobufEncodingError(#[from] prost::EncodeError),
6767

68-
#[error("Failed to decode our protobuf data - {0}")]
68+
#[error("Failed to decode our protobuf data: {0}")]
6969
ProtobufDecodingError(#[from] prost::DecodeError),
7070

71-
#[error("Account {0} does not exist on the chain")]
71+
#[error("Account '{0}' does not exist on the chain")]
7272
NonExistentAccountError(AccountId),
7373

74-
#[error("Failed on json serialization/deserialization - {0}")]
74+
#[error("Failed on json serialization/deserialization: {0}")]
7575
SerdeJsonError(#[from] serde_json::Error),
7676

77-
#[error("Account {0} is not a valid account address")]
77+
#[error("Account '{0}' is not a valid account address")]
7878
MalformedAccountAddress(String),
7979

80-
#[error("Account {0} has an invalid associated public key")]
80+
#[error("Account '{0}' has an invalid associated public key")]
8181
InvalidPublicKey(AccountId),
8282

8383
#[error("Queried contract (code_id: {0}) did not have any code information attached")]
@@ -92,7 +92,7 @@ pub enum NyxdError {
9292
#[error("Block has an invalid height (either negative or larger than i64::MAX")]
9393
InvalidHeight,
9494

95-
#[error("Failed to compress provided wasm code - {0}")]
95+
#[error("Failed to compress provided wasm code: {0}")]
9696
WasmCompressionError(io::Error),
9797

9898
#[error("Logs returned from the validator were malformed")]

common/client-libs/validator-client/src/rpc/reqwest.rs

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -109,7 +109,8 @@ trait TendermintRpcErrorMap {
109109

110110
impl TendermintRpcErrorMap for reqwest::Error {
111111
fn into_rpc_err(self) -> Error {
112-
todo!()
112+
// that's not the best error converion, but it's better than a panic
113+
Error::client_internal(self.to_string())
113114
}
114115
}
115116

common/network-defaults/Cargo.toml

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -14,10 +14,12 @@ schemars = { workspace = true, features = ["preserve_order"], optional = true }
1414
serde = { workspace = true, features = ["derive"], optional = true }
1515
url = { workspace = true, optional = true }
1616

17-
# please be extremely careful when adding new dependencies because this crate is imported by the ecash contract,
18-
# so if anything new is added, consider feature-locking it and then just adding it to default feature
17+
# 'wasm-serde-types' feature
18+
tsify = { workspace = true, features = ["js"], optional = true }
19+
wasm-bindgen = { workspace = true, optional = true }
1920

2021
[features]
22+
wasm-serde-types = ["tsify", "wasm-bindgen"]
2123
default = ["env", "network"]
2224
env = ["dotenvy", "log"]
2325
network = ["schemars", "serde", "url"]

common/wasm/client-core/Cargo.toml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -44,4 +44,4 @@ wasm-storage = { path = "../storage" }
4444
console_error_panic_hook = { workspace = true, optional = true }
4545

4646
[features]
47-
default = ["console_error_panic_hook"]
47+
default = ["wasm-utils/console_error_panic_hook"]

common/wasm/utils/Cargo.toml

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,10 @@ gloo-utils = { workspace = true }
1717
gloo-net = { workspace = true, features = ["websocket"], optional = true }
1818
#gloo-net = { path = "../../../../gloo/crates/net", features = ["websocket"], optional = true }
1919

20+
# The `console_error_panic_hook` crate provides better debugging of panics by
21+
# logging them with `console.error`. This is great for development, but requires
22+
# all the `std::fmt` and `std::panicking` infrastructure, so isn't great for
23+
# code size when deploying.
2024
console_error_panic_hook = { workspace = true, optional = true }
2125

2226
# we don't want entire tokio-tungstenite, tungstenite itself is just fine - we just want message and error enums

package.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -54,4 +54,4 @@
5454
"node-gyp": "^9.3.1",
5555
"tslog": "3.3.3"
5656
}
57-
}
57+
}
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
# Nym credential generation Usage Example
2+
3+
This is a simple project to show you how to use nym credential generation.
4+
5+
```ts
6+
import { mixFetch } from '@nymproject/mix-fetch';
7+
8+
// HTTP GET
9+
const response = await mixFetch('https://nymtech.net');
10+
const html = await response.text();
11+
12+
// HTTP POST
13+
const apiResponse = await mixFetch('https://api.example.com', {
14+
method: 'POST',
15+
body: JSON.stringify({ foo: 'bar' }),
16+
headers: { [`Content-Type`]: 'application/json', Authorization: `Bearer ${AUTH_TOKEN}` }
17+
});
18+
```
19+
20+
## Running the example
21+
22+
```
23+
npm install
24+
npm run start
25+
```
26+
27+
Open a browser at http://localhost:1234 and as the example loads, a connection will be made to the Nym Mixnet
28+
and a text file and image will be downloaded and displayed in the browser.
Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
{
2+
"name": "@nymproject/nym-sdk-zk-nyms-example-parcel",
3+
"version": "1.3.0-rc.0",
4+
"license": "Apache-2.0",
5+
"scripts": {
6+
"build": "parcel build --no-cache --no-content-hash",
7+
"serve": "serve dist",
8+
"start": "parcel --no-cache"
9+
},
10+
"dependencies": {
11+
"@nymproject/sdk": "1.3.0-rc.0",
12+
"parcel": "^2.9.3"
13+
},
14+
"private": false,
15+
"source": "src/index.html"
16+
}
Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
<!DOCTYPE html>
2+
<html lang="en">
3+
4+
<head>
5+
<meta charset="UTF-8">
6+
<meta name="viewport" content="width=device-width, initial-scale=1.0">
7+
<title>Internal Credential Tester</title>
8+
<script type="module" src="./index.ts"></script>
9+
<style>
10+
body {
11+
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol";
12+
padding: 2rem;
13+
}
14+
</style>
15+
</head>
16+
17+
<body>
18+
<div>
19+
<h1>Credential</h1>
20+
<input id="mnemonic" placeholder="mnemonic"></input>
21+
<input id="coin" placeholder="amount" value="1unym"></input>
22+
<button id="button">Get Credential</button>
23+
<div id="credential"></div>
24+
</div>
25+
</body>
26+
27+
</html>
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
import { createNymCredentialsClient } from '@nymproject/sdk';
2+
import { appendOutput } from './utils';
3+
4+
async function main() {
5+
const mnemonic = document.getElementById('mnemonic') as HTMLInputElement;
6+
if (process.env.MNEMONIC) {
7+
mnemonic.defaultValue = process.env.MNEMONIC;
8+
}
9+
const coin = document.getElementById('coin') as HTMLInputElement;
10+
const button = document.getElementById('button') as HTMLButtonElement;
11+
12+
const client = await createNymCredentialsClient();
13+
14+
const generateCredential = async () => {
15+
const amount = coin.value;
16+
const mnemonicString = mnemonic.value;
17+
console.log({ amount, mnemonicString });
18+
try {
19+
appendOutput('About to get a credential... 🥁');
20+
const credential = await client.comlink.acquireCredential(amount, mnemonicString, { useSandbox: true }); // options: {useSandbox?: boolean; networkDetails?: {}}
21+
appendOutput('Success! 🎉');
22+
appendOutput(JSON.stringify(credential, null, 2));
23+
} catch (e) {
24+
console.error('Failed to get credential', e);
25+
appendOutput((e as any).message);
26+
}
27+
};
28+
29+
if (button) {
30+
button.addEventListener('click', () => generateCredential());
31+
}
32+
}
33+
34+
// wait for the html to load
35+
window.addEventListener('DOMContentLoaded', () => {
36+
// let's do this!
37+
main();
38+
});
Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
export function appendOutput(value: string) {
2+
const el = document.getElementById('credential') as HTMLPreElement;
3+
const text = document.createTextNode(`${value}\n`);
4+
el.appendChild(text);
5+
}
6+
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,4 @@
11
src/mixnet/wasm/worker.js
2+
src/zk-nym/worker.js
3+
src/zk-nym-faucet/worker.js
24
docs/

sdk/typescript/packages/sdk/package.json

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,8 @@
1313
"scripts": {
1414
"build": "scripts/build-prod.sh",
1515
"build:dev": "scripts/build.sh",
16-
"build:dev:esm": "scripts/build-dev-esm.sh",
16+
"build:dev:esm": "SDK_DEV_MODE=true scripts/build-dev-esm.sh",
17+
"build:dev:esm:no-inline": "scripts/build-dev-esm.sh",
1718
"build:worker": "rollup -c rollup-worker.config.mjs",
1819
"clean": "rimraf dist",
1920
"docs:dev": "run-p docs:watch docs:serve ",
@@ -32,6 +33,8 @@
3233
},
3334
"dependencies": {
3435
"@nymproject/nym-client-wasm": ">=1.2.4-rc.2 || ^1",
36+
"@nymproject/zk-nym-faucet-lib": ">=1.3.0-rc.0 || ^1",
37+
"@nymproject/zk-nym-lib": ">=1.3.0-rc.0 || ^1",
3538
"comlink": "^4.3.1"
3639
},
3740
"devDependencies": {

sdk/typescript/packages/sdk/rollup-esm.config.mjs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,6 @@ import { getConfig } from './rollup/esm.mjs';
22

33
export default {
44
...getConfig({
5-
inline: false,
5+
inline: process.env.SDK_DEV_MODE === 'true',
66
}),
77
};
Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
import { getConfig } from './rollup/worker.mjs';
2+
3+
export default {
4+
...getConfig('src/mixnet/wasm/worker.ts', 'nym_client_wasm_bg.wasm', {
5+
inlineWasm: true,
6+
format: 'cjs',
7+
}),
8+
};
Lines changed: 4 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -1,26 +1,7 @@
1-
import typescript from '@rollup/plugin-typescript';
2-
import resolve from '@rollup/plugin-node-resolve';
3-
import { wasm } from '@rollup/plugin-wasm';
4-
import replace from '@rollup/plugin-replace';
5-
6-
const extensions = ['.js', '.jsx', '.ts', '.tsx'];
1+
import { getConfig } from './rollup/worker.mjs';
72

83
export default {
9-
input: 'src/mixnet/wasm/worker.ts',
10-
output: {
11-
dir: 'dist',
12-
format: 'cjs',
13-
},
14-
plugins: [
15-
resolve({ extensions }),
16-
// this is some nasty monkey patching that removes the WASM URL (because it is handled by the `wasm` plugin)
17-
replace({
18-
values: { "input = new URL('nym_client_wasm_bg.wasm', import.meta.url);": 'input = undefined;' },
19-
delimiters: ['', ''],
20-
preventAssignment: true,
21-
}),
22-
// force the wasm plugin to embed the wasm bundle - this means no downstream bundlers have to worry about handling it
23-
wasm({ maxFileSize: 10000000, targetEnv: 'browser' }),
24-
typescript({ compilerOptions: { declaration: false, target: 'es5' } }),
25-
],
4+
...getConfig('src/mixnet/wasm/worker.ts', 'nym_client_wasm_bg.wasm', {
5+
inlineWasm: process.env.SDK_DEV_MODE === 'true',
6+
}),
267
};
Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
import { getConfig } from './rollup/worker.mjs';
2+
3+
export default {
4+
...getConfig('src/zk-nym-faucet/worker.ts', 'zk_nym_faucet_lib_bg.wasm'),
5+
inlineWasm: true,
6+
format: 'cjs',
7+
};
Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
import { getConfig } from './rollup/worker.mjs';
2+
3+
export default {
4+
...getConfig('src/zk-nym-faucet/worker.ts', 'zk_nym_faucet_lib_bg.wasm', {
5+
inlineWasm: process.env.SDK_DEV_MODE === 'true',
6+
}),
7+
};
Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
import { getConfig } from './rollup/worker.mjs';
2+
3+
export default {
4+
...getConfig('src/zk-nym/worker.ts', 'nym_credential_client_wasm_bg.wasm'),
5+
inlineWasm: true,
6+
format: 'cjs',
7+
};

0 commit comments

Comments
 (0)