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

Update 'getting started' examples and link to them #1130

Merged
merged 8 commits into from
Sep 6, 2023
Merged
Show file tree
Hide file tree
Changes from 7 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
60 changes: 2 additions & 58 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -123,22 +123,7 @@ the [Shimmer Testnet](https://api.testnet.shimmer.network), and retrieves the no
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(())
}
```
[sdk/examples/client/getting_started.rs](sdk/examples/client/getting_started.rs)
thibault-martinez marked this conversation as resolved.
Show resolved Hide resolved

## Wallet Usage

Expand All @@ -148,48 +133,7 @@ that connects to the [Shimmer Testnet](https://api.testnet.shimmer.network) usin
[`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(())
}
```
[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
thibault-martinez marked this conversation as resolved.
Show resolved Hide resolved
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
thibault-martinez marked this conversation as resolved.
Show resolved Hide resolved

// 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();
32 changes: 2 additions & 30 deletions bindings/python/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -66,16 +66,7 @@ the [Shimmer Testnet](https://api.testnet.shimmer.network), and retrieves the no
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.

```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)
Alex6323 marked this conversation as resolved.
Show resolved Hide resolved

## Wallet Usage
thibault-martinez marked this conversation as resolved.
Show resolved Hide resolved

Expand All @@ -85,26 +76,7 @@ that connects to the [Shimmer Testnet](https://api.testnet.shimmer.network) usin
[`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

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
thibault-martinez marked this conversation as resolved.
Show resolved Hide resolved

# 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"
thibault-martinez marked this conversation as resolved.
Show resolved Hide resolved
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(())
}
Loading