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

Nodejs update examples to single account wallet #1596

Merged
Show file tree
Hide file tree
Changes from 2 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
6 changes: 3 additions & 3 deletions bindings/nodejs/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -108,23 +108,23 @@ run().then(() => process.exit());
## Wallet Usage

The following example will create a
new [`Wallet`](https://wiki.iota.org/shimmer/iota-sdk/references/nodejs/classes/Wallet/) [`Account`](https://wiki.iota.org/shimmer/iota-sdk/references/nodejs/classes/Account/)
new [`Wallet`](https://wiki.iota.org/shimmer/iota-sdk/references/nodejs/classes/Wallet/)
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).

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

const walletOptions: WalletOptions = {
storagePath: `Alice`, // A name to associate with the created account.
storagePath: `Alice`, // A name to associate with the created wallet.
clientOptions: {
nodes: ['https://api.testnet.shimmer.network'], // The node to connect to.
},
coinType: CoinType.Shimmer,
secretManager: {
// Setup Stronghold secret manager
stronghold: {
snapshotPath: 'vault.stronghold', // The path to store the account snapshot.
snapshotPath: 'vault.stronghold', // The path to store the wallet snapshot.
password: 'a-secure-password', // A password to encrypt the stored data. WARNING: Never hardcode passwords in production code.
},
},
Expand Down
61 changes: 0 additions & 61 deletions bindings/nodejs/examples/exchange/1-create-account.ts

This file was deleted.

74 changes: 74 additions & 0 deletions bindings/nodejs/examples/exchange/1-create-wallet.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
// Copyright 2023 IOTA Stiftung
// SPDX-License-Identifier: Apache-2.0

// This example creates a new database and wallet.
// Run with command:
// yarn run-example ./exchange/1-create-wallet.ts

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

// This example uses secrets in environment variables for simplicity which should not be done in production.
require('dotenv').config({ path: '.env' });

async function run() {
try {
for (const envVar of [
'WALLET_DB_PATH',
'NODE_URL',
'STRONGHOLD_SNAPSHOT_PATH',
'STRONGHOLD_PASSWORD',
'MNEMONIC',
])
if (!(envVar in process.env)) {
throw new Error(
`.env ${envVar} is undefined, see .env.example`,
);
}

const strongholdSecretManager = {
stronghold: {
snapshotPath: process.env.STRONGHOLD_SNAPSHOT_PATH,
password: process.env.STRONGHOLD_PASSWORD,
},
};

const secretManager = new SecretManager(strongholdSecretManager);

// A mnemonic can be generated with `Utils.generateMnemonic()`.
// Store the mnemonic in the Stronghold snapshot, this needs to be done only the first time.
// The mnemonic can't be retrieved from the Stronghold file, so make a backup in a secure place!
await secretManager.storeMnemonic(process.env.MNEMONIC as string);

const walletAddress = await secretManager.generateEd25519Addresses({
coinType: CoinType.IOTA,
accountIndex: 0,
range: {
start: 0,
end: 1,
},
bech32Hrp: 'tst',
});

const walletOptions: WalletOptions = {
address: walletAddress[0],
storagePath: process.env.WALLET_DB_PATH,
clientOptions: {
nodes: [process.env.NODE_URL as string],
},
bipPath: {
coinType: CoinType.IOTA,
},
secretManager: strongholdSecretManager,
};

const wallet = new Wallet(walletOptions);

// Set syncOnlyMostBasicOutputs to true if not interested in outputs that are timelocked,
// have a storage deposit return, expiration or are nft/account/foundry outputs.
wallet.setDefaultSyncOptions({ syncOnlyMostBasicOutputs: true });
} catch (error) {
console.error(error);
}
}

run().then(() => process.exit());
40 changes: 0 additions & 40 deletions bindings/nodejs/examples/exchange/2-generate-address.ts

This file was deleted.

10 changes: 4 additions & 6 deletions bindings/nodejs/examples/exchange/3-check-balance.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
// Copyright 2023 IOTA Stiftung
// SPDX-License-Identifier: Apache-2.0

// This example gets the balance of an account.
// This example gets the balance of a wallet.
// Run with command:
// yarn run-example ./exchange/3-check-balance.ts

Expand All @@ -21,15 +21,13 @@ async function run() {
const wallet = new Wallet({
storagePath: process.env.WALLET_DB_PATH,
});
const address = await wallet.address();

const account = await wallet.getAccount('Alice');
const addresses = await account.addresses();

console.log('Addresses:', addresses);
console.log('Address:', address);

// Set syncOnlyMostBasicOutputs to true if not interested in outputs that are timelocked,
// have a storage deposit return, expiration or are nft/account/foundry outputs.
const balance = await account.sync({ syncOnlyMostBasicOutputs: true });
const balance = await wallet.sync({ syncOnlyMostBasicOutputs: true });

console.log('Balance', balance);

Expand Down
8 changes: 3 additions & 5 deletions bindings/nodejs/examples/exchange/4-listen-events.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,15 +33,13 @@ async function run() {
// Only interested in new outputs here.
await wallet.listen([WalletEventType.NewOutput], callback);

const account = await wallet.getAccount('Alice');

// Use the faucet to send testnet tokens to your address.
console.log(
'Fill your address with the faucet: https://faucet.testnet.shimmer.network/',
);

const addresses = await account.addresses();
console.log('Send funds to:', addresses[0].address);
const address = await wallet.address();
console.log('Send funds to:', address);

// Sync every 5 seconds until the faucet transaction gets confirmed.
for (let i = 0; i < 100; i++) {
Expand All @@ -50,7 +48,7 @@ async function run() {
// Sync to detect new outputs
// Set syncOnlyMostBasicOutputs to true if not interested in outputs that are timelocked,
// have a storage deposit return, expiration or are nft/account/foundry outputs.
await account.sync({ syncOnlyMostBasicOutputs: true });
await wallet.sync({ syncOnlyMostBasicOutputs: true });
}
} catch (error) {
console.error(error);
Expand Down
7 changes: 2 additions & 5 deletions bindings/nodejs/examples/exchange/5-send-amount.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,14 +31,11 @@ async function run() {
process.env.STRONGHOLD_PASSWORD as string,
);

const account = await wallet.getAccount('Alice');
console.log('Account:', account);

// Set syncOnlyMostBasicOutputs to true if not interested in outputs that are timelocked,
// have a storage deposit return, expiration or are nft/account/foundry outputs.
await account.sync({ syncOnlyMostBasicOutputs: true });
await wallet.sync({ syncOnlyMostBasicOutputs: true });

const response = await account.send(
const response = await wallet.send(
BigInt(1000000),
// Replace with the address of your choice!
'rms1qrrv7flg6lz5cssvzv2lsdt8c673khad060l4quev6q09tkm9mgtupgf0h0',
Expand Down
15 changes: 6 additions & 9 deletions bindings/nodejs/examples/how_tos/account_output/create.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import { Wallet, initLogger } from '@iota/sdk';
// This example uses secrets in environment variables for simplicity which should not be done in production.
//
// Make sure that `example.stronghold` and `example.walletdb` already exist by
// running the `how_tos/accounts_and_addresses/create-account` example!
// running the `how_tos/accounts_and_addresses/create-wallet` example!
//
require('dotenv').config({ path: '.env' });

Expand All @@ -31,11 +31,8 @@ async function run() {
storagePath: process.env.WALLET_DB_PATH,
});

// Get the account we generated with `01-create-wallet`
const account = await wallet.getAccount('Alice');

// May want to ensure the account is synced before sending a transaction.
let balance = await account.sync();
// May want to ensure the wallet is synced before sending a transaction.
let balance = await wallet.sync();

console.log(`Accounts BEFORE:\n`, balance.accounts);

Expand All @@ -47,19 +44,19 @@ async function run() {
console.log('Sending the create-account transaction...');

// Create an account output
const transaction = await account.createAccountOutput();
const transaction = await wallet.createAccountOutput();

console.log(`Transaction sent: ${transaction.transactionId}`);

// Wait for transaction to get included
const blockId = await account.reissueTransactionUntilIncluded(
const blockId = await wallet.reissueTransactionUntilIncluded(
transaction.transactionId,
);
console.log(
`Block included: ${process.env.EXPLORER_URL}/block/${blockId}`,
);

balance = await account.sync();
balance = await wallet.sync();
console.log(`Accounts AFTER:\n`, balance.accounts);
} catch (error) {
console.log('Error: ', error);
Expand Down
15 changes: 6 additions & 9 deletions bindings/nodejs/examples/how_tos/account_output/destroy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,17 +27,14 @@ async function run() {
storagePath: process.env.WALLET_DB_PATH,
});

// Get the account we generated with `01-create-wallet`
const account = await wallet.getAccount('Alice');

// May want to ensure the account is synced before sending a transaction.
let balance = await account.sync();
// May want to ensure the wallet is synced before sending a transaction.
let balance = await wallet.sync();

if (balance.accounts.length == 0) {
throw new Error(`No Account output available in account 'Alice'`);
}

// We try to destroy the first account output in the account
// We try to destroy the first account output in the wallet
const accountId = balance.accounts[0];

console.log(
Expand All @@ -53,22 +50,22 @@ async function run() {
console.log('Sending the destroy-account transaction...');

// Destroy an account output
const transaction = await account
const transaction = await wallet
.prepareDestroyAccount(accountId)
.then((prepared) => prepared.send());

console.log(`Transaction sent: ${transaction.transactionId}`);

// Wait for transaction to get included
const blockId = await account.reissueTransactionUntilIncluded(
const blockId = await wallet.reissueTransactionUntilIncluded(
transaction.transactionId,
);
console.log(
`Block included: ${process.env.EXPLORER_URL}/block/${blockId}`,
);
console.log(`Destroyed account output ${accountId}`);

balance = await account.sync();
balance = await wallet.sync();
console.log(
`Accounts AFTER destroying (${balance.accounts.length}):\n`,
balance.accounts,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import { Utils, Wallet, initLogger } from '@iota/sdk';
// This example uses secrets in environment variables for simplicity which should not be done in production.
//
// Make sure that `example.stronghold` and `example.walletdb` already exist by
// running the `how_tos/accounts_and_addresses/create-account` example!
// running the `how_tos/accounts_and_addresses/create-wallet` example!
//
require('dotenv').config({ path: '.env' });

Expand All @@ -27,10 +27,7 @@ async function run() {
storagePath: process.env.WALLET_DB_PATH,
});

// Get the account we generated with `create_wallet`
const account = await wallet.getAccount('Alice');

const balance = await account.sync();
const balance = await wallet.sync();

const totalBaseTokenBalance = balance.baseCoin.total;
console.log(
Expand All @@ -57,7 +54,7 @@ async function run() {
basicOutputs: true,
},
};
const totalBaseTokenBalanceAfter = (await account.sync(syncOptions))
const totalBaseTokenBalanceAfter = (await wallet.sync(syncOptions))
.baseCoin.total;
console.log(
`Balance after requesting funds on account address: ${totalBaseTokenBalanceAfter}`,
Expand Down
Loading
Loading