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

Feat: node merge part 2 #639

Merged
merged 49 commits into from
Jul 5, 2023
Merged
Show file tree
Hide file tree
Changes from 40 commits
Commits
Show all changes
49 commits
Select commit Hold shift + click to select a range
42ca3eb
added input/output
Jun 15, 2023
770e32e
typo, issuer and unit-utils
Jun 16, 2023
2147783
utils added
Jun 17, 2023
fcac2d8
renamed response to Hash
Jun 19, 2023
49642b9
Merge branch 'develop' into feat/node-merge2
Jun 19, 2023
f2b1780
added compute to some methods
Jun 19, 2023
aed6c52
renamed and added to python
Jun 19, 2023
5d887e9
added conflict reason strings and format
Jun 19, 2023
c65306b
added plugin_fetch
Jun 19, 2023
57fbc09
added to js client
Jun 20, 2023
e19dc39
lint
Jun 20, 2023
654eba9
format
Jun 20, 2023
4762399
lint again :D
Jun 20, 2023
00f46f2
removed declare
Jun 21, 2023
4e91fcf
Merge branch 'develop' into feat/node-merge2
Jun 22, 2023
e9283fd
fixes and mqtt examplue update
Jun 23, 2023
a23915a
format and yarn lock
Jun 23, 2023
95b3bfb
Merge branch 'develop' into feat/node-merge2
Jun 26, 2023
99c2f4b
updated python version req
Jun 26, 2023
159e3dc
Merge branch 'develop' into feat/node-merge2
Jun 29, 2023
0c1d086
const
Jun 29, 2023
bb504c2
review
Jun 29, 2023
f8b801c
moved some stuff
Jun 30, 2023
a12e9a5
update
Jun 30, 2023
5388ca4
review
Jun 30, 2023
9053e5b
format
Jun 30, 2023
65414f0
changelog and review
Jun 30, 2023
269180a
custom_plugin_call
Jul 3, 2023
920db2f
Merge branch 'develop' into feat/node-merge2
Jul 3, 2023
0c2aabc
changelog
Jul 3, 2023
353719b
Merge branch 'develop' into feat/node-merge2
Jul 3, 2023
1b33e44
updated test
Jul 3, 2023
f63345c
Merge branch 'feat/node-merge2' of https://github.com/kwek20/iota-sdk…
Jul 3, 2023
e4580c1
lint
Jul 3, 2023
533299e
typo
Jul 3, 2023
b1bd101
review
Jul 4, 2023
58364d9
review 2
Jul 4, 2023
1ea66e3
review 3
Jul 4, 2023
9ba4062
review 4
Jul 4, 2023
66a4998
just send serde:value
Jul 4, 2023
fb104ba
added missing block transforms
Jul 4, 2023
9a34719
align comput5e, update test
Jul 4, 2023
ef8e7be
fmt
Jul 4, 2023
9866d21
made node health ignore actually happen
Jul 5, 2023
269dd89
Merge branch 'develop' into feat/node-merge2
Jul 5, 2023
739edb2
arghhh
Jul 5, 2023
7b5b52f
Merge branch 'feat/node-merge2' of https://github.com/kwek20/iota-sdk…
Jul 5, 2023
802f7ec
now without starting /
Jul 5, 2023
0db1794
method_path -> endpoint
Jul 5, 2023
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
9 changes: 9 additions & 0 deletions bindings/core/src/method/client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -125,6 +125,15 @@ pub enum ClientMethod {
/// Returns the unhealthy nodes.
#[cfg(not(target_family = "wasm"))]
UnhealthyNodes,
/// Extension method which provides request methods for plugins.
#[serde(rename_all = "camelCase")]
CallPluginRoute {
base_plugin_path: String,
method: String,
method_path: String,
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think this is a bit confusing given we also have method, maybe endpoint instead? Or something else

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

but its also basePluginPath. base_plugin_endpoint as well?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't have a strong opinion, I just don't like method_path :trollface:

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Are we changing it then?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

sure ill change method_path to endpoint

query_params: Vec<String>,
request_object: Option<String>,
},
/// Prepare a transaction for signing
#[serde(rename_all = "camelCase")]
PrepareTransaction {
Expand Down
38 changes: 27 additions & 11 deletions bindings/core/src/method/utils.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,14 @@

use derivative::Derivative;
use iota_sdk::types::block::{
address::{AliasAddress, Bech32Address, Hrp},
output::{AliasId, NftId, OutputId},
address::{Bech32Address, Hrp},
output::{dto::OutputDto, AliasId, NftId, OutputId, RentStructure, TokenScheme},
payload::{
dto::MilestonePayloadDto,
transaction::dto::{TransactionEssenceDto, TransactionPayloadDto},
transaction::{
dto::{TransactionEssenceDto, TransactionPayloadDto},
TransactionId,
},
},
signature::dto::Ed25519SignatureDto,
BlockDto,
Expand Down Expand Up @@ -97,27 +100,40 @@ pub enum UtilsMethod {
/// Output ID
output_id: OutputId,
},
/// Computes the Foundry ID
#[serde(rename_all = "camelCase")]
ComputeFoundryId {
/// Alias id
alias_id: AliasId,
/// Serial number
serial_number: u32,
/// Token scheme kind
token_scheme_kind: u8,
},
/// Computes the NFT ID
#[serde(rename_all = "camelCase")]
ComputeNftId {
/// Output ID
output_id: OutputId,
},
/// Computes the Foundry ID
/// Computes the output ID from transaction id and output index
ComputeOutputId { id: TransactionId, index: u16 },
/// Computes a tokenId from the aliasId, serial number and token scheme type.
#[serde(rename_all = "camelCase")]
ComputeFoundryId {
/// Alias address
alias_address: AliasAddress,
/// Serial number
ComputeTokenId {
alias_id: AliasId,
serial_number: u32,
/// Token scheme kind
token_scheme_kind: u8,
token_scheme_type: TokenScheme,
},
/// Compute the hash of a transaction essence.
/// Computes the hash of a transaction essence.
HashTransactionEssence {
/// The transaction essence
essence: TransactionEssenceDto,
},
/// Computes the input commitment from the output objects that are used as inputs to fund the transaction.
ComputeInputsCommitment { inputs: Vec<OutputDto> },
/// Computes the required storage deposit of an output.
ComputeStorageDeposit { output: OutputDto, rent: RentStructure },
/// Checks if the given mnemonic is valid.
/// Expected response: [`Ok`](crate::Response::Ok)
VerifyMnemonic {
Expand Down
18 changes: 15 additions & 3 deletions bindings/core/src/method_handler/client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -304,7 +304,7 @@ pub(crate) async fn call_client_method_internal(client: &Client, method: ClientM
ClientMethod::GetBlockMetadata { block_id } => {
Response::BlockMetadata(client.get_block_metadata(&block_id).await?)
}
ClientMethod::GetBlockRaw { block_id } => Response::BlockRaw(client.get_block_raw(&block_id).await?),
ClientMethod::GetBlockRaw { block_id } => Response::Raw(client.get_block_raw(&block_id).await?),
ClientMethod::GetOutput { output_id } => Response::OutputWithMetadataResponse(
client
.get_output(&output_id)
Expand All @@ -318,13 +318,13 @@ pub(crate) async fn call_client_method_internal(client: &Client, method: ClientM
&client.get_milestone_by_id(&milestone_id).await?,
)),
ClientMethod::GetMilestoneByIdRaw { milestone_id } => {
Response::MilestoneRaw(client.get_milestone_by_id_raw(&milestone_id).await?)
Response::Raw(client.get_milestone_by_id_raw(&milestone_id).await?)
}
ClientMethod::GetMilestoneByIndex { index } => {
Response::Milestone(MilestonePayloadDto::from(&client.get_milestone_by_index(index).await?))
}
ClientMethod::GetMilestoneByIndexRaw { index } => {
Response::MilestoneRaw(client.get_milestone_by_index_raw(index).await?)
Response::Raw(client.get_milestone_by_index_raw(index).await?)
}
ClientMethod::GetUtxoChangesById { milestone_id } => {
Response::MilestoneUtxoChanges(client.get_utxo_changes_by_id(&milestone_id).await?)
Expand Down Expand Up @@ -459,6 +459,18 @@ pub(crate) async fn call_client_method_internal(client: &Client, method: ClientM
ClientMethod::RequestFundsFromFaucet { url, address } => {
Response::Faucet(request_funds_from_faucet(&url, &address).await?)
}
ClientMethod::CallPluginRoute {
base_plugin_path,
method,
method_path,
query_params,
request_object,
} => {
let data: serde_json::Value = client
.call_plugin_route(&base_plugin_path, &method, &method_path, query_params, request_object)
.await?;
Response::CustomJson(data)
}
};
Ok(response)
}
36 changes: 30 additions & 6 deletions bindings/core/src/method_handler/utils.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,8 @@
use iota_sdk::{
client::{hex_public_key_to_bech32_address, hex_to_bech32, verify_mnemonic, Client},
types::block::{
address::{dto::AddressDto, Address, ToBech32Ext},
output::{AliasId, FoundryId, NftId},
address::{dto::AddressDto, Address, AliasAddress, ToBech32Ext},
output::{AliasId, FoundryId, InputsCommitment, NftId, Output, OutputId, Rent, TokenId},
payload::{transaction::TransactionEssence, MilestonePayload, TransactionPayload},
signature::Ed25519Signature,
Block,
Expand Down Expand Up @@ -48,15 +48,39 @@ pub(crate) fn call_utils_method_internal(method: UtilsMethod) -> Result<Response
Response::TransactionId(payload.id())
}
UtilsMethod::ComputeAliasId { output_id } => Response::AliasId(AliasId::from(&output_id)),
UtilsMethod::ComputeNftId { output_id } => Response::NftId(NftId::from(&output_id)),
UtilsMethod::ComputeFoundryId {
alias_address,
alias_id,
serial_number,
token_scheme_kind,
} => Response::FoundryId(FoundryId::build(
&AliasAddress::new(alias_id),
serial_number,
token_scheme_kind,
} => Response::FoundryId(FoundryId::build(&alias_address, serial_number, token_scheme_kind)),
UtilsMethod::HashTransactionEssence { essence } => Response::TransactionEssenceHash(prefix_hex::encode(
)),
UtilsMethod::ComputeNftId { output_id } => Response::NftId(NftId::from(&output_id)),
UtilsMethod::ComputeOutputId { id, index } => Response::OutputId(OutputId::new(id, index)?),
UtilsMethod::ComputeTokenId {
alias_id,
serial_number,
token_scheme_type,
} => {
let foundry_id = FoundryId::build(&AliasAddress::new(alias_id), serial_number, token_scheme_type.kind());
Response::TokenId(TokenId::from(foundry_id))
}
UtilsMethod::HashTransactionEssence { essence } => Response::Hash(prefix_hex::encode(
TransactionEssence::try_from_dto_unverified(essence)?.hash(),
)),
UtilsMethod::ComputeInputsCommitment { inputs } => {
let inputs = inputs
.into_iter()
.map(|o| Ok(Output::try_from_dto_unverified(o)?))
.collect::<Result<Vec<Output>>>()?;
Response::Hash(InputsCommitment::new(inputs.iter()).to_string())
}
UtilsMethod::ComputeStorageDeposit { output, rent } => {
let out = Output::try_from_dto_unverified(output)?;
Response::MinimumRequiredStorageDeposit(out.rent_cost(&rent).to_string())
}
UtilsMethod::VerifyMnemonic { mut mnemonic } => {
verify_mnemonic(&mnemonic)?;
mnemonic.zeroize();
Expand Down
19 changes: 12 additions & 7 deletions bindings/core/src/response.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ use iota_sdk::{
input::dto::UtxoInputDto,
output::{
dto::{OutputDto, OutputMetadataDto},
AliasId, FoundryId, NftId, OutputId,
AliasId, FoundryId, NftId, OutputId, TokenId,
},
payload::{
dto::{MilestonePayloadDto, PayloadDto},
Expand Down Expand Up @@ -135,7 +135,9 @@ pub enum Response {
BlockMetadata(BlockMetadataResponse),
/// Response for:
/// - [`GetBlockRaw`](crate::method::ClientMethod::GetBlockRaw)
BlockRaw(Vec<u8>),
/// - [`GetMilestoneByIdRaw`](crate::method::ClientMethod::GetMilestoneByIdRaw)
/// - [`GetMilestoneByIndexRaw`](crate::method::ClientMethod::GetMilestoneByIndexRaw)
Raw(Vec<u8>),
/// Response for:
/// - [`GetOutput`](crate::method::ClientMethod::GetOutput)
OutputWithMetadataResponse(OutputWithMetadataResponse),
Expand All @@ -152,10 +154,6 @@ pub enum Response {
/// - [`GetMilestoneByIndex`](crate::method::ClientMethod::GetMilestoneByIndex)
Milestone(MilestonePayloadDto),
/// Response for:
/// - [`GetMilestoneByIdRaw`](crate::method::ClientMethod::GetMilestoneByIdRaw)
/// - [`GetMilestoneByIndexRaw`](crate::method::ClientMethod::GetMilestoneByIndexRaw)
MilestoneRaw(Vec<u8>),
/// Response for:
/// - [`GetUtxoChangesById`](crate::method::ClientMethod::GetUtxoChangesById)
/// - [`GetUtxoChangesByIndex`](crate::method::ClientMethod::GetUtxoChangesByIndex)
MilestoneUtxoChanges(MilestoneUTXOChanges),
Expand Down Expand Up @@ -210,6 +208,9 @@ pub enum Response {
/// - [`MilestoneId`](crate::method::UtilsMethod::MilestoneId)
MilestoneId(MilestoneId),
/// Response for:
/// - [`TokenId`](crate::method::UtilsMethod::TokenId)
TokenId(TokenId),
/// Response for:
/// - [`TransactionId`](crate::method::UtilsMethod::TransactionId)
TransactionId(TransactionId),
/// Response for:
Expand All @@ -223,11 +224,14 @@ pub enum Response {
FoundryId(FoundryId),
/// Response for:
/// - [`HashTransactionEssence`](crate::method::UtilsMethod::HashTransactionEssence)
TransactionEssenceHash(String),
/// - [`ComputeInputsCommitment`](crate::method::UtilsMethod::ComputeInputsCommitment)
Hash(String),
/// Response for [`GetNodeInfo`](crate::method::ClientMethod::GetNodeInfo)
NodeInfoWrapper(NodeInfoWrapper),
/// Response for [`Bech32ToHex`](crate::method::UtilsMethod::Bech32ToHex)
HexAddress(String),
/// Response for [`CallPluginRoute`](crate::method::ClientMethod::CallPluginRoute)
CustomJson(serde_json::Value),

// Responses in client and wallet
/// Response for:
Expand Down Expand Up @@ -308,6 +312,7 @@ pub enum Response {
AddressesWithUnspentOutputs(Vec<AddressWithUnspentOutputs>),
/// Response for:
/// - [`MinimumRequiredStorageDeposit`](crate::method::AccountMethod::MinimumRequiredStorageDeposit)
/// - [`ComputeStorageDeposit`](crate::method::UtilsMethod::ComputeStorageDeposit)
MinimumRequiredStorageDeposit(String),
thibault-martinez marked this conversation as resolved.
Show resolved Hide resolved
/// Response for:
/// - [`ClaimableOutputs`](crate::method::AccountMethod::ClaimableOutputs)
Expand Down
7 changes: 7 additions & 0 deletions bindings/nodejs/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -23,19 +23,26 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

### Added

thibault-martinez marked this conversation as resolved.
Show resolved Hide resolved
- `callPluginRoute` to Client to fetch data from custom node plugins;
- `computeTokenId `, `computeOutputId`, `computeInputsCommitment` and `computeStorageDeposit` to Utils;
- Type alias for Ids which were previously just `HexEncodedString`;
- List of `ConfictReason` explanations matching the enum;
- `units-helper` class for IOTA units conversion;
- `Client::destroy` to close an open handle;

### Changed

- Rename `Account::prepareMintNativeToken` to `prepareCreateNativeToken`, `Account::prepareIncreaseNativeTokenSupply` to `prepareMintNativeToken`, `Account::prepareDecreaseNativeTokenSupply` to `prepareMeltNativeToken`;
- Rename `MintNativeTokenParams` to `CreateNativeTokenParams`;
- Rename `MintTokenTransaction` to `CreateNativeTokenTransaction` and `PreparedMintTokenTransaction` to `PreparedCreateNativeTokenTransaction` (including their corresponding `Data` types);
- Renamed `Response::MilestoneRaw` to `Raw`;

### Fixed

- Moved `internal` field from `IGenerateAddressesOptions` to `IGenerateAddressOptions`;
- Error handling in `Client`, `SecretManager` and `Wallet` constructors;
- Deadlock in .sync() with incoming transactions;
- Renamed `Output.getNntId` to `Output.getNftId`;

## 1.0.0-rc.1 - 2023-06-19

Expand Down
35 changes: 32 additions & 3 deletions bindings/nodejs/examples/client/10-mqtt.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,15 @@
// Copyright 2021-2023 IOTA Stiftung
// SPDX-License-Identifier: Apache-2.0

import { Client, initLogger } from '@iota/sdk';
import {
Block,
Client,
initLogger,
MilestonePayload,
parsePayload,
} from '@iota/sdk';
import { plainToInstance } from 'class-transformer';

require('dotenv').config({ path: '.env' });

// Run with command:
Expand All @@ -24,14 +32,35 @@ async function run() {
const topics = ['blocks'];

const callback = function (error: Error, data: string) {
console.log(JSON.parse(data));
if (error != null) {
console.log(error);
return;
}

const parsed = JSON.parse(data);
if (parsed.topic == 'milestone') {
const payload = parsePayload(
JSON.parse(parsed.payload),
) as MilestonePayload;
const index = payload.index;
const previousMilestone = payload.previousMilestoneId;
console.log(
'New milestone index' +
index +
', previous ID: ' +
previousMilestone,
);
} else if (parsed.topic == 'blocks') {
const block = plainToInstance(Block, JSON.parse(parsed.payload));
console.log('payload:', block.payload);
}
};

await client.listen(topics, callback);

// Clear listener after 10 seconds
setTimeout(async () => {
await client.clearListeners(['blocks']);
await client.clearListeners(topics);
console.log('Listener cleared');
// Exit the process
setTimeout(async () => process.exit(0), 2000);
Expand Down
43 changes: 43 additions & 0 deletions bindings/nodejs/examples/client/16-custom-plugin.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
// Copyright 2021-2023 IOTA Stiftung
// SPDX-License-Identifier: Apache-2.0

import { Client, initLogger } from '@iota/sdk';
require('dotenv').config({ path: '.env' });

// Run with command:
// yarn run-example ./client/16-custom-plugin.ts

// In this example we will get output from a known nft by calling the node endpoint using a "custom plugin" call.
async function run() {
initLogger();
if (!process.env.NODE_URL) {
throw new Error('.env NODE_URL is undefined, see .env.example');
}

const client = new Client({
// Insert your node URL in the .env.
nodes: [process.env.NODE_URL],
localPow: true,
});

try {
// Get an NFT id from ./how_tos/nfts/mint_nft.ts
const nftId =
'0x0000000000000000000000000000000000000000000000000000000000000000';
Thoralf-M marked this conversation as resolved.
Show resolved Hide resolved
const route = 'outputs/nft/' + nftId;

// Call our "custom" indexer plugin
const outputId = await client.callPluginRoute(
'api/indexer/v1/',
'GET',
route,
undefined,
undefined,
);
console.log('Output id: ', outputId);
} catch (error) {
console.error('Error: ', error);
}
}

run().then(() => process.exit());
1 change: 1 addition & 0 deletions bindings/nodejs/examples/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
},
"dependencies": {
"@iota/sdk": "link:../",
"class-transformer": "^0.5.1",
"dotenv": "^16.0.0",
"ts-node": "^10.9.1"
},
Expand Down
Loading