Skip to content

Commit

Permalink
Update 'getting started' examples and link to them (iotaledger#1130)
Browse files Browse the repository at this point in the history
* Update getting started started examples and link to them

* Update wallet getting started

* snake_case

* Update sdk/examples/client/getting_started.rs

Co-authored-by: Thibault Martinez <[email protected]>

* consistency

* Fix comment

* Clean readmes

---------

Co-authored-by: Thibault Martinez <[email protected]>
Co-authored-by: Thibault Martinez <[email protected]>
  • Loading branch information
3 people authored Sep 6, 2023
1 parent 9f4fbbf commit 007c417
Show file tree
Hide file tree
Showing 10 changed files with 152 additions and 140 deletions.
76 changes: 6 additions & 70 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -117,79 +117,15 @@ iota-sdk = { git = "https://github.com/iotaledger/iota-sdk", branch = "develop"

## Client Usage

The following example creates a [`Client`](https://docs.rs/iota-sdk/latest/iota_sdk/client/core/struct.Client.html)
instance connected to
the [Shimmer Testnet](https://api.testnet.shimmer.network), and retrieves the node's information by
calling [`Client.get_info()`](https://docs.rs/iota-sdk/latest/iota_sdk/client/core/struct.Client.html#method.get_info),
and then print the node's information.

```rust
use iota_sdk::client::{Client, Result};

#[tokio::main]
async fn main() -> Result<()> {
let client = Client::builder()
.with_node("https://api.testnet.shimmer.network")? // Insert your node URL here
.finish()
.await?;

let info = client.get_info().await?;
println!("Node Info: {info:?}");

Ok(())
}
```
The following example creates a Client instance connected to the Shimmer Testnet, and retrieves the node's information by calling `Client.get_info()`, and then print the node's information.

[sdk/examples/client/getting_started.rs](sdk/examples/client/getting_started.rs)

## Wallet Usage

The following example will create a
new [`Wallet`](https://docs.rs/iota-sdk/latest/iota_sdk/wallet/core/struct.Wallet.html) [`Account`](https://docs.rs/iota-sdk/latest/iota_sdk/wallet/account/struct.Account.html)
that connects to the [Shimmer Testnet](https://api.testnet.shimmer.network) using the
[`StrongholdSecretManager`](https://docs.rs/iota-sdk/latest/iota_sdk/client/secret/stronghold/type.StrongholdSecretManager.html)
to store a mnemonic. For this `features = ["stronghold"]` is needed in the Cargo.toml import. To persist the wallet in a database, `"rocksdb"` can be added.

```rust
use iota_sdk::{
client::{
constants::SHIMMER_COIN_TYPE,
secret::{stronghold::StrongholdSecretManager, SecretManager},
},
wallet::{ClientOptions, Result, Wallet},
};

#[tokio::main]
async fn main() -> Result<()> {
// Setup Stronghold secret manager.
// WARNING: Never hardcode passwords in production code.
let secret_manager = StrongholdSecretManager::builder()
.password("password".to_owned()) // A password to encrypt the stored data.
.build("vault.stronghold")?; // The path to store the account snapshot.

let client_options = ClientOptions::new().with_node("https://api.testnet.shimmer.network")?;

// Set up and store the wallet.
let wallet = Wallet::builder()
.with_secret_manager(SecretManager::Stronghold(secret_manager))
.with_client_options(client_options)
.with_coin_type(SHIMMER_COIN_TYPE)
.finish()
.await?;

// Generate a mnemonic and store it in the Stronghold vault.
// INFO: It is best practice to back up the mnemonic somewhere secure.
let mnemonic = wallet.generate_mnemonic()?;
wallet.store_mnemonic(mnemonic).await?;

// Create an account.
let account = wallet
.create_account()
.with_alias("Alice") // A name to associate with the created account.
.finish()
.await?;

Ok(())
}
```
The following example will create a new Wallet Account using a StrongholdSecretManager. For this `features = ["stronghold"]` is needed in the Cargo.toml import. To persist the wallet in a database, `"rocksdb"` can be added.

[sdk/examples/wallet/getting_started.rs](sdk/examples/wallet/getting_started.rs)

## Examples

Expand Down
3 changes: 2 additions & 1 deletion bindings/nodejs-old/examples/getting-started.js
Original file line number Diff line number Diff line change
Expand Up @@ -34,9 +34,10 @@ async function main() {

const manager = new AccountManager(accountManagerOptions);

// Generate a mnemonic and store it in the Stronghold vault.
// Generate a mnemonic and store its seed in the Stronghold vault.
// INFO: It is best practice to back up the mnemonic somewhere secure.
const mnemonic = await manager.generateMnemonic();
console.log("Mnemonic:" + mnemonic);
await manager.storeMnemonic(mnemonic);

// Create an account.
Expand Down
23 changes: 23 additions & 0 deletions bindings/nodejs/examples/client/getting-started.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
// Copyright 2023 IOTA Stiftung
// SPDX-License-Identifier: Apache-2.0

import { Client } from '@iota/sdk';

// Run with command:
// yarn run-example ./client/getting-started.ts

// In this example we will get information about the node
async function run() {
const client = new Client({
nodes: ['https://api.testnet.shimmer.network'],
});

try {
const nodeInfo = (await client.getInfo()).nodeInfo;
console.log(nodeInfo);
} catch (error) {
console.error('Error: ', error);
}
}

run().then(() => process.exit());
60 changes: 60 additions & 0 deletions bindings/nodejs/examples/wallet/getting-started.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
// Copyright 2023 IOTA Stiftung
// SPDX-License-Identifier: Apache-2.0

import { Wallet, CoinType, WalletOptions, Utils } from '@iota/sdk';

// Run with command:
// yarn run-example ./wallet/getting-started.ts

// The database path.
const WALLET_DB_PATH = 'getting-started-db';

// A name to associate with the created account.
const ACCOUNT_ALIAS = 'Alice';

// The node to connect to.
const NODE_URL = 'https://api.testnet.shimmer.network';

// A password to encrypt the stored data.
// WARNING: Never hardcode passwords in production code.
const STRONGHOLD_PASSWORD = 'a-secure-password';

// The path to store the account snapshot.
const STRONGHOLD_SNAPSHOT_PATH = 'vault.stronghold';

async function main() {
const walletOptions: WalletOptions = {
storagePath: WALLET_DB_PATH,
clientOptions: {
nodes: [NODE_URL],
},
coinType: CoinType.Shimmer,
secretManager: {
stronghold: {
snapshotPath: STRONGHOLD_SNAPSHOT_PATH,
password: STRONGHOLD_PASSWORD,
},
},
};

const wallet = new Wallet(walletOptions);

// Generate a mnemonic and store its seed in the Stronghold vault.
// INFO: It is best practice to back up the mnemonic somewhere secure.
const mnemonic = Utils.generateMnemonic();
console.log('Mnemonic:' + mnemonic);
await wallet.storeMnemonic(mnemonic);

// Create an account.
const account = await wallet.createAccount({
alias: ACCOUNT_ALIAS,
});

// Get the first address and print it.
const address = (await account.addresses())[0];
console.log(`Address: ${address.address}\n`);

process.exit(0);
}

main();
44 changes: 4 additions & 40 deletions bindings/python/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -60,51 +60,15 @@ Python binding to the [iota-sdk library](/README.md).

## Client Usage

The following example creates a [`Client`](https://wiki.iota.org/shimmer/iota-sdk/references/python/iota_sdk/client/)
instance connected to
the [Shimmer Testnet](https://api.testnet.shimmer.network), and retrieves the node's information by
calling [`Client.get_info()`](https://wiki.iota.org/shimmer/iota-sdk/references/python/iota_sdk/client/_node_core_api/#get_info),
and then print the node's information.
The following example creates a Client instance connected to the Shimmer Testnet, and retrieves the node's information by calling `Client.get_info()`, and then print the node's information.

```python
from iota_sdk import Client
# Create a Client instance
client = Client(nodes=['https://api.testnet.shimmer.network'])
# Get the node info
node_info = client.get_info()
print(f'{node_info}')
```
[examples/client/getting_started.py](examples/client/getting_started.py)

## Wallet Usage

The following example will create a
new [`Wallet`](https://wiki.iota.org/shimmer/iota-sdk/references/python/iota_sdk/wallet/) [`Account`](https://wiki.iota.org/shimmer/iota-sdk/references/python/iota_sdk/wallet/account/)
that connects to the [Shimmer Testnet](https://api.testnet.shimmer.network) using the
[`StrongholdSecretManager`](https://wiki.iota.org/shimmer/iota-sdk/references/python/iota_sdk/secret_manager/#strongholdsecretmanager-objects)
to safely store a seed derived from a mnemonic, and then print the account's information.
```python
from iota_sdk import Wallet, StrongholdSecretManager, CoinType, ClientOptions
# This example creates a new database and account
The following example will create a new Wallet Account using a StrongholdSecretManager, and then print the account's information.
client_options = ClientOptions(nodes=['https://api.testnet.shimmer.network'])
secret_manager = StrongholdSecretManager(
"wallet.stronghold", "some_hopefully_secure_password")
wallet = Wallet('./alice-walletdb', client_options,
CoinType.SHIMMER, secret_manager)
# Store the mnemonic in the Stronghold snapshot. This only needs to be done once
account = wallet.store_mnemonic("flame fever pig forward exact dash body idea link scrub tennis minute " +
"surge unaware prosper over waste kitten ceiling human knife arch situate civil")
account = wallet.create_account('Alice')
print(account.get_metadata())
```
[examples/wallet/getting_started.py](examples/wallet/getting_started.py)
## Examples
Expand Down
8 changes: 8 additions & 0 deletions bindings/python/examples/client/getting_started.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
from iota_sdk import Client

# Create a Client instance
client = Client(nodes=['https://api.testnet.shimmer.network'])

# Get the node info
node_info = client.get_info()
print(f'{node_info}')
Original file line number Diff line number Diff line change
Expand Up @@ -34,9 +34,10 @@
secret_manager=secret_manager
)

# Generate a mnemonic and store it in the Stronghold vault.
# Generate a mnemonic and store its seed in the Stronghold vault.
# INFO: It is best practice to back up the mnemonic somewhere secure.
mnemonic = Utils.generate_mnemonic()
print(f'Mnemonic: {mnemonic}')
wallet.store_mnemonic(mnemonic)

# Create an account.
Expand Down
5 changes: 5 additions & 0 deletions sdk/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -624,6 +624,11 @@ name = "get_block"
path = "examples/client/get_block.rs"
required-features = ["client"]

[[example]]
name = "client_getting_started"
path = "examples/client/getting_started.rs"
required-features = ["client"]

[[example]]
name = "ledger_nano"
path = "examples/client/ledger_nano.rs"
Expand Down
23 changes: 23 additions & 0 deletions sdk/examples/client/getting_started.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
// Copyright 2023 IOTA Stiftung
// SPDX-License-Identifier: Apache-2.0

//! This examples shows how to get the node info.
//!
//! ```sh
//! cargo run --release --example client_getting_started
//! ```
use iota_sdk::client::{Client, Result};

#[tokio::main]
async fn main() -> Result<()> {
let client = Client::builder()
.with_node("https://api.testnet.shimmer.network")? // Insert your node URL here
.finish()
.await?;

let info = client.get_info().await?;
println!("Node Info: {info:?}");

Ok(())
}
47 changes: 19 additions & 28 deletions sdk/examples/wallet/getting_started.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,6 @@
//! In this example we will create a new wallet, a mnemonic, and an initial account. Then, we'll print the first address
//! of that account.
//!
//! Make sure there's no `STRONGHOLD_SNAPSHOT_PATH` file and no `WALLET_DB_PATH` folder yet!
//!
//! Rename `.env.example` to `.env` first, then run the command:
//! ```sh
//! cargo run --release --all-features --example wallet_getting_started
Expand All @@ -21,45 +19,38 @@ use iota_sdk::{

#[tokio::main]
async fn main() -> Result<()> {
// This example uses secrets in environment variables for simplicity which should not be done in production.
dotenvy::dotenv().ok();

// Setup Stronghold secret_manager
// Setup Stronghold secret manager.
// WARNING: Never hardcode passwords in production code.
let secret_manager = StrongholdSecretManager::builder()
.password(std::env::var("STRONGHOLD_PASSWORD").unwrap())
.build(std::env::var("STRONGHOLD_SNAPSHOT_PATH").unwrap())?;
.password("password".to_owned()) // A password to encrypt the stored data.
.build("vault.stronghold")?; // The path to store the account snapshot.

let client_options = ClientOptions::new().with_node(&std::env::var("NODE_URL").unwrap())?;
let client_options = ClientOptions::new().with_node("https://api.testnet.shimmer.network")?;

// Create the wallet
// Set up and store the wallet.
let wallet = Wallet::builder()
.with_secret_manager(SecretManager::Stronghold(secret_manager))
.with_storage_path(&std::env::var("WALLET_DB_PATH").unwrap())
.with_client_options(client_options)
.with_coin_type(SHIMMER_COIN_TYPE)
.with_storage_path("getting-started-db")
.finish()
.await?;

// Generate a mnemonic and store it in the Stronghold vault
// INFO: It is best practice to back up the mnemonic somewhere secure
// Generate a mnemonic and store its seed in the Stronghold vault.
// INFO: It is best practice to back up the mnemonic somewhere secure.
let mnemonic = wallet.generate_mnemonic()?;
wallet.store_mnemonic(mnemonic.clone()).await?;
println!("Created a wallet from the mnemonic:\n'{}'", mnemonic.as_ref());
println!("Mnemonic: {}", mnemonic.as_ref());
wallet.store_mnemonic(mnemonic).await?;

// Create an account
let alias = "Alice";
let account = wallet.create_account().with_alias(alias).finish().await?;
println!("Created account '{alias}'");
// Create an account.
let account = wallet
.create_account()
.with_alias("Alice") // A name to associate with the created account.
.finish()
.await?;

// Display the adresses in the account (only 1 for a new account)
let addresses = account.addresses().await?;
println!(
"{alias}'s addresses:\n{:#?}",
addresses
.iter()
.map(|addr| addr.address().to_string())
.collect::<Vec<_>>()
);
let first_address = &account.addresses().await?[0];
println!("{}", first_address.address());

Ok(())
}

0 comments on commit 007c417

Please sign in to comment.