Skip to content

Commit

Permalink
Merge branch '2.0' into bindings/add-protocol-parameters-test
Browse files Browse the repository at this point in the history
  • Loading branch information
thibault-martinez committed Nov 15, 2023
2 parents 6ea6d21 + 010d70a commit d07e216
Show file tree
Hide file tree
Showing 158 changed files with 1,738 additions and 1,638 deletions.
14 changes: 7 additions & 7 deletions bindings/core/src/method/client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ pub enum ClientMethod {
#[allow(missing_docs)]
#[serde(rename_all = "camelCase")]
BuildAccountOutput {
// If not provided, minimum storage deposit will be used
// If not provided, minimum amount will be used
#[serde(default, with = "option_string")]
amount: Option<u64>,
// TODO: Determine if `default` is wanted here
Expand All @@ -55,7 +55,7 @@ pub enum ClientMethod {
#[allow(missing_docs)]
#[serde(rename_all = "camelCase")]
BuildBasicOutput {
// If not provided, minimum storage deposit will be used
// If not provided, minimum amount will be used
#[serde(default, with = "option_string")]
amount: Option<u64>,
// TODO: Determine if `default` is wanted here
Expand All @@ -70,7 +70,7 @@ pub enum ClientMethod {
#[allow(missing_docs)]
#[serde(rename_all = "camelCase")]
BuildFoundryOutput {
// If not provided, minimum storage deposit will be used
// If not provided, minimum amount will be used
#[serde(default, with = "option_string")]
amount: Option<u64>,
native_tokens: Option<Vec<NativeToken>>,
Expand All @@ -85,7 +85,7 @@ pub enum ClientMethod {
#[allow(missing_docs)]
#[serde(rename_all = "camelCase")]
BuildNftOutput {
// If not provided, minimum storage deposit will be used
// If not provided, minimum amount will be used
#[serde(default, with = "option_string")]
amount: Option<u64>,
// TODO: Determine if `default` is wanted here
Expand Down Expand Up @@ -351,10 +351,10 @@ pub enum ClientMethod {
/// Human readable part
bech32_hrp: Option<Hrp>,
},
/// Calculate the minimum required storage deposit for an output.
/// Calculate the minimum required amount for an output.
/// Expected response:
/// [`MinimumRequiredStorageDeposit`](crate::Response::MinimumRequiredStorageDeposit)
MinimumRequiredStorageDeposit { output: OutputDto },
/// [`OutputAmount`](crate::Response::OutputAmount)
ComputeMinimumOutputAmount { output: OutputDto },
/// Requests funds for a given address from the faucet, for example `https://faucet.testnet.shimmer.network/api/enqueue` or `http://localhost:8091/api/enqueue`.
RequestFundsFromFaucet {
/// Faucet URL
Expand Down
10 changes: 7 additions & 3 deletions bindings/core/src/method/utils.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
use derivative::Derivative;
use iota_sdk::types::block::{
address::{Bech32Address, Hrp},
output::{dto::OutputDto, AccountId, NftId, OutputId, RentStructure},
output::{dto::OutputDto, AccountId, NftId, OutputId, StorageScoreParameters},
payload::signed_transaction::{
dto::{SignedTransactionPayloadDto, TransactionDto},
TransactionId,
Expand Down Expand Up @@ -128,8 +128,12 @@ pub enum UtilsMethod {
/// The transaction.
transaction: TransactionDto,
},
/// Computes the required storage deposit of an output.
ComputeStorageDeposit { output: OutputDto, rent: RentStructure },
/// Computes the minimum required amount of an output.
#[serde(rename_all = "camelCase")]
ComputeMinimumOutputAmount {
output: OutputDto,
storage_score_parameters: StorageScoreParameters,
},
/// Checks if the given mnemonic is valid.
/// Expected response: [`Ok`](crate::Response::Ok)
VerifyMnemonic {
Expand Down
19 changes: 9 additions & 10 deletions bindings/core/src/method_handler/client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,8 @@ use iota_sdk::{
api::core::OutputWithMetadataResponse,
block::{
output::{
dto::OutputDto, AccountOutput, BasicOutput, FoundryOutput, NftOutput, Output, OutputBuilderAmount, Rent,
dto::OutputDto, AccountOutput, BasicOutput, FoundryOutput, MinimumOutputAmount, NftOutput, Output,
OutputBuilderAmount,
},
payload::Payload,
SignedBlock, SignedBlockDto, UnsignedBlockDto,
Expand Down Expand Up @@ -69,7 +70,7 @@ pub(crate) async fn call_client_method_internal(client: &Client, method: ClientM
if let Some(amount) = amount {
OutputBuilderAmount::Amount(amount)
} else {
OutputBuilderAmount::MinimumStorageDeposit(client.get_rent_structure().await?)
OutputBuilderAmount::MinimumAmount(client.get_storage_score_parameters().await?)
},
mana,
native_tokens,
Expand All @@ -94,7 +95,7 @@ pub(crate) async fn call_client_method_internal(client: &Client, method: ClientM
if let Some(amount) = amount {
OutputBuilderAmount::Amount(amount)
} else {
OutputBuilderAmount::MinimumStorageDeposit(client.get_rent_structure().await?)
OutputBuilderAmount::MinimumAmount(client.get_storage_score_parameters().await?)
},
mana,
native_tokens,
Expand All @@ -118,7 +119,7 @@ pub(crate) async fn call_client_method_internal(client: &Client, method: ClientM
if let Some(amount) = amount {
OutputBuilderAmount::Amount(amount)
} else {
OutputBuilderAmount::MinimumStorageDeposit(client.get_rent_structure().await?)
OutputBuilderAmount::MinimumAmount(client.get_storage_score_parameters().await?)
},
native_tokens,
serial_number,
Expand All @@ -144,7 +145,7 @@ pub(crate) async fn call_client_method_internal(client: &Client, method: ClientM
if let Some(amount) = amount {
OutputBuilderAmount::Amount(amount)
} else {
OutputBuilderAmount::MinimumStorageDeposit(client.get_rent_structure().await?)
OutputBuilderAmount::MinimumAmount(client.get_storage_score_parameters().await?)
},
mana,
native_tokens,
Expand Down Expand Up @@ -294,13 +295,11 @@ pub(crate) async fn call_client_method_internal(client: &Client, method: ClientM
ClientMethod::HexPublicKeyToBech32Address { hex, bech32_hrp } => {
Response::Bech32Address(client.hex_public_key_to_bech32_address(&hex, bech32_hrp).await?)
}
ClientMethod::MinimumRequiredStorageDeposit { output } => {
ClientMethod::ComputeMinimumOutputAmount { output } => {
let output = Output::try_from_dto_with_params(output, client.get_token_supply().await?)?;
let rent_structure = client.get_rent_structure().await?;
let storage_score_params = client.get_storage_score_parameters().await?;

let minimum_storage_deposit = output.rent_cost(rent_structure);

Response::MinimumRequiredStorageDeposit(minimum_storage_deposit.to_string())
Response::OutputAmount(output.minimum_amount(storage_score_params))
}
ClientMethod::RequestFundsFromFaucet { url, address } => {
Response::Faucet(request_funds_from_faucet(&url, &address).await?)
Expand Down
9 changes: 6 additions & 3 deletions bindings/core/src/method_handler/utils.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ use iota_sdk::{
block::{
address::{AccountAddress, Address, ToBech32Ext},
input::UtxoInput,
output::{AccountId, FoundryId, NftId, Output, OutputId, Rent, TokenId},
output::{AccountId, FoundryId, MinimumOutputAmount, NftId, Output, OutputId, TokenId},
payload::{signed_transaction::Transaction, SignedTransactionPayload},
SignedBlock,
},
Expand Down Expand Up @@ -72,9 +72,12 @@ pub(crate) fn call_utils_method_internal(method: UtilsMethod) -> Result<Response
UtilsMethod::TransactionSigningHash { transaction } => {
Response::Hash(Transaction::try_from_dto(transaction)?.signing_hash().to_string())
}
UtilsMethod::ComputeStorageDeposit { output, rent } => {
UtilsMethod::ComputeMinimumOutputAmount {
output,
storage_score_parameters: storage_params,
} => {
let out = Output::try_from_dto(output)?;
Response::MinimumRequiredStorageDeposit(out.rent_cost(rent).to_string())
Response::OutputAmount(out.minimum_amount(storage_params))
}
UtilsMethod::VerifyMnemonic { mnemonic } => {
let mnemonic = Mnemonic::from(mnemonic);
Expand Down
7 changes: 4 additions & 3 deletions bindings/core/src/response.rs
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ use iota_sdk::{
BlockId, SignedBlockDto, UnsignedBlockDto,
},
},
utils::serde::string,
wallet::{
types::{Balance, OutputDataDto, TransactionWithMetadataDto},
PreparedCreateNativeTokenTransactionDto,
Expand Down Expand Up @@ -256,9 +257,9 @@ pub enum Response {
/// - [`GetAddress`](crate::method::WalletMethod::GetAddress)
Address(Bech32Address),
/// Response for:
/// - [`MinimumRequiredStorageDeposit`](crate::method::ClientMethod::MinimumRequiredStorageDeposit)
/// - [`ComputeStorageDeposit`](crate::method::UtilsMethod::ComputeStorageDeposit)
MinimumRequiredStorageDeposit(String),
/// - [`ClientMethod::ComputeMinimumOutputAmount`](crate::method::ClientMethod::ComputeMinimumOutputAmount)
/// - [`UtilsMethod::ComputeMinimumOutputAmount`](crate::method::UtilsMethod::ComputeMinimumOutputAmount)
OutputAmount(#[serde(with = "string")] u64),
/// Response for:
/// - [`ClaimableOutputs`](crate::method::WalletMethod::ClaimableOutputs)
OutputIds(Vec<OutputId>),
Expand Down
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.

Loading

0 comments on commit d07e216

Please sign in to comment.