Skip to content

Commit

Permalink
Add AddressToBech32 utils (#2069)
Browse files Browse the repository at this point in the history
* Add AddressToBech32

* python bindings

* Add comments

* nodejs bindings
  • Loading branch information
thibault-martinez authored Feb 26, 2024
1 parent c09702b commit d9cbd61
Show file tree
Hide file tree
Showing 15 changed files with 128 additions and 13 deletions.
5 changes: 4 additions & 1 deletion bindings/core/src/method/client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ use iota_sdk::{
node_manager::node::NodeAuth,
},
types::block::{
address::{Bech32Address, Hrp},
address::{Address, Bech32Address, Hrp},
output::{
feature::Feature, unlock_condition::UnlockCondition, AccountId, AnchorId, DelegationId, FoundryId, NftId,
Output, OutputId, TokenScheme,
Expand Down Expand Up @@ -417,6 +417,9 @@ pub enum ClientMethod {
/// Human readable part
bech32_hrp: Option<Hrp>,
},
/// Converts an address to its bech32 representation
#[serde(rename_all = "camelCase")]
AddressToBech32 { address: Address, bech32_hrp: Option<Hrp> },
/// Transforms an account id to a bech32 encoded address
#[serde(rename_all = "camelCase")]
AccountIdToBech32 {
Expand Down
8 changes: 7 additions & 1 deletion bindings/core/src/method/utils.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ use derivative::Derivative;
use iota_sdk::{
client::secret::types::InputSigningData,
types::block::{
address::{Bech32Address, Hrp},
address::{Address, Bech32Address, Hrp},
output::{AccountId, AnchorId, NftId, Output, OutputId, StorageScoreParameters},
payload::signed_transaction::{
dto::{SignedTransactionPayloadDto, TransactionDto},
Expand Down Expand Up @@ -41,6 +41,12 @@ pub enum UtilsMethod {
hex: String,
bech32_hrp: Hrp,
},
/// Converts an address to its bech32 representation
#[serde(rename_all = "camelCase")]
AddressToBech32 {
address: Address,
bech32_hrp: Hrp,
},
/// Transforms an account id to a bech32 encoded address
#[serde(rename_all = "camelCase")]
AccountIdToBech32 {
Expand Down
3 changes: 3 additions & 0 deletions bindings/core/src/method_handler/client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -326,6 +326,9 @@ pub(crate) async fn call_client_method_internal(client: &Client, method: ClientM
ClientMethod::HexToBech32 { hex, bech32_hrp } => {
Response::Bech32Address(client.hex_to_bech32(&hex, bech32_hrp).await?)
}
ClientMethod::AddressToBech32 { address, bech32_hrp } => {
Response::Bech32Address(client.address_to_bech32(address, bech32_hrp).await?)
}
ClientMethod::AccountIdToBech32 { account_id, bech32_hrp } => {
Response::Bech32Address(client.account_id_to_bech32(account_id, bech32_hrp).await?)
}
Expand Down
1 change: 1 addition & 0 deletions bindings/core/src/method_handler/utils.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ pub(crate) fn call_utils_method_internal(method: UtilsMethod) -> Result<Response
let response = match method {
UtilsMethod::Bech32ToHex { bech32 } => Response::Bech32ToHex(Client::bech32_to_hex(bech32)?),
UtilsMethod::HexToBech32 { hex, bech32_hrp } => Response::Bech32Address(hex_to_bech32(&hex, bech32_hrp)?),
UtilsMethod::AddressToBech32 { address, bech32_hrp } => Response::Bech32Address(address.to_bech32(bech32_hrp)),
UtilsMethod::AccountIdToBech32 { account_id, bech32_hrp } => {
Response::Bech32Address(account_id.to_bech32(bech32_hrp))
}
Expand Down
2 changes: 2 additions & 0 deletions bindings/core/src/response.rs
Original file line number Diff line number Diff line change
Expand Up @@ -246,6 +246,8 @@ pub enum Response {
/// - [`PrepareOutput`](crate::method::WalletMethod::PrepareOutput)
Output(Output),
/// Response for:
/// - [`AddressToBech32`](crate::method::ClientMethod::AddressToBech32)
/// - [`AddressToBech32`](crate::method::UtilsMethod::AddressToBech32)
/// - [`AccountIdToBech32`](crate::method::ClientMethod::AccountIdToBech32)
/// - [`AccountIdToBech32`](crate::method::UtilsMethod::AccountIdToBech32)
/// - [`AnchorIdToBech32`](crate::method::ClientMethod::AnchorIdToBech32)
Expand Down
23 changes: 23 additions & 0 deletions bindings/nodejs/lib/client/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@ import {
SlotIndex,
SlotCommitmentId,
SlotCommitment,
Address,
} from '../types/block';
import { HexEncodedString } from '../utils';
import {
Expand Down Expand Up @@ -690,6 +691,28 @@ export class Client {
return JSON.parse(response).payload;
}

/**
* Converts an address to its bech32 representation
*
* @param address An address.
* @param bech32Hrp The Bech32 HRP (human readable part) to be used.
* @returns The corresponding Bech32 address.
*/
async addressToBech32(
address: Address,
bech32Hrp?: string,
): Promise<Bech32Address> {
const response = await this.methodHandler.callMethod({
name: 'addressToBech32',
data: {
address,
bech32Hrp,
},
});

return JSON.parse(response).payload;
}

/**
* Transforms an account id to a bech32 encoded address.
*
Expand Down
9 changes: 9 additions & 0 deletions bindings/nodejs/lib/types/client/bridge/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ import type {
Payload,
SlotIndex,
SlotCommitmentId,
Address,
} from '../../block';
import type { PreparedTransactionData } from '../prepared-transaction-data';
import type {
Expand Down Expand Up @@ -271,6 +272,14 @@ export interface __HexToBech32Method__ {
};
}

export interface __AddressToBech32Method__ {
name: 'addressToBech32';
data: {
address: Address;
bech32Hrp?: string;
};
}

export interface __AccountIdToBech32Method__ {
name: 'accountIdToBech32';
data: {
Expand Down
2 changes: 2 additions & 0 deletions bindings/nodejs/lib/types/client/bridge/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ import type {
__GetUtxoChangesByIndexMethod__,
__GetUtxoChangesFullByIndexMethod__,
__HexToBech32Method__,
__AddressToBech32Method__,
__AccountIdToBech32Method__,
__AnchorIdToBech32Method__,
__NftIdToBech32Method__,
Expand Down Expand Up @@ -105,6 +106,7 @@ export type __ClientMethods__ =
| __GetUtxoChangesByIndexMethod__
| __GetUtxoChangesFullByIndexMethod__
| __HexToBech32Method__
| __AddressToBech32Method__
| __AccountIdToBech32Method__
| __AnchorIdToBech32Method__
| __NftIdToBech32Method__
Expand Down
2 changes: 2 additions & 0 deletions bindings/nodejs/lib/types/utils/bridge/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import type {
__TransactionIdMethod__,
__Bech32ToHexMethod__,
__HexToBech32Method__,
__AddressToBech32Method__,
__AccountIdToBech32Method__,
__AnchorIdToBech32Method__,
__NftIdToBech32Method__,
Expand Down Expand Up @@ -50,6 +51,7 @@ export type __UtilsMethods__ =
| __TransactionIdMethod__
| __Bech32ToHexMethod__
| __HexToBech32Method__
| __AddressToBech32Method__
| __AccountIdToBech32Method__
| __AnchorIdToBech32Method__
| __NftIdToBech32Method__
Expand Down
17 changes: 13 additions & 4 deletions bindings/nodejs/lib/types/utils/bridge/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import {
NftId,
Bech32Address,
Unlock,
Address,
} from '../../';
import { AccountId, AnchorId } from '../../block/id';
import { SlotCommitment } from '../../block/slot';
Expand Down Expand Up @@ -111,15 +112,23 @@ export interface __HexToBech32Method__ {
name: 'hexToBech32';
data: {
hex: HexEncodedString;
bech32Hrp?: string;
bech32Hrp: string;
};
}

export interface __AddressToBech32Method__ {
name: 'addressToBech32';
data: {
address: Address;
bech32Hrp: string;
};
}

export interface __AccountIdToBech32Method__ {
name: 'accountIdToBech32';
data: {
accountId: AccountId;
bech32Hrp?: string;
bech32Hrp: string;
};
}

Expand All @@ -135,15 +144,15 @@ export interface __NftIdToBech32Method__ {
name: 'nftIdToBech32';
data: {
nftId: NftId;
bech32Hrp?: string;
bech32Hrp: string;
};
}

export interface __HexPublicKeyToBech32AddressMethod__ {
name: 'hexPublicKeyToBech32Address';
data: {
hex: HexEncodedString;
bech32Hrp?: string;
bech32Hrp: string;
};
}

Expand Down
17 changes: 17 additions & 0 deletions bindings/nodejs/lib/utils/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -294,6 +294,23 @@ export class Utils {
});
}

/**
* Converts an address to its bech32 representation.
*
* @param address An address.
* @param bech32Hrp The Bech32 HRP (human readable part) to use.
* @returns The Bech32-encoded address string.
*/
static addressToBech32(address: Address, bech32Hrp: string): Bech32Address {
return callUtilsMethod({
name: 'addressToBech32',
data: {
address,
bech32Hrp,
},
});
}

/**
* Transforms an account id to a bech32 encoded address.
*
Expand Down
22 changes: 18 additions & 4 deletions bindings/python/iota_sdk/client/_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
from typing import Optional
from abc import ABCMeta, abstractmethod

from iota_sdk.types.address import Address
from iota_sdk.types.block.block import Block
from iota_sdk.types.block.id import BlockId
from iota_sdk.types.common import HexStr
Expand Down Expand Up @@ -36,31 +37,44 @@ def _call_method(self, name, data=None):
"""

# pylint: disable=redefined-builtin
def hex_to_bech32(self, hex_str: HexStr, bech32_hrp: Optional[str] = None) -> str:
def hex_to_bech32(self, hex_str: HexStr,
bech32_hrp: Optional[str] = None) -> str:
"""Transforms a hex encoded address to a bech32 encoded address.
"""
return self._call_method('hexToBech32', {
'hex': hex_str,
'bech32Hrp': bech32_hrp
})

def account_id_to_bech32(self, account_id: HexStr, bech32_hrp: Optional[str] = None) -> str:
def address_to_bech32(self, address: Address,
bech32_hrp: Optional[str] = None) -> str:
"""Converts an address to its bech32 representation.
"""
return self._call_method('addressToBech32', {
'address': address,
'bech32Hrp': bech32_hrp
})

def account_id_to_bech32(self, account_id: HexStr,
bech32_hrp: Optional[str] = None) -> str:
"""Transforms an account id to a bech32 encoded address.
"""
return self._call_method('accountIdToBech32', {
'accountId': account_id,
'bech32Hrp': bech32_hrp
})

def anchor_id_to_bech32(self, anchor_id: HexStr, bech32_hrp: Optional[str] = None) -> str:
def anchor_id_to_bech32(self, anchor_id: HexStr,
bech32_hrp: Optional[str] = None) -> str:
"""Transforms an anchor id to a bech32 encoded address.
"""
return self._call_method('anchorIdToBech32', {
'anchorId': anchor_id,
'bech32Hrp': bech32_hrp
})

def nft_id_to_bech32(self, nft_id: HexStr, bech32_hrp: Optional[str] = None) -> str:
def nft_id_to_bech32(self, nft_id: HexStr,
bech32_hrp: Optional[str] = None) -> str:
"""Transforms an nft id to a bech32 encoded address.
"""
return self._call_method('nftIdToBech32', {
Expand Down
3 changes: 2 additions & 1 deletion bindings/python/iota_sdk/types/output_id.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,8 @@ def __new__(cls, output_id: str):
return instance

@classmethod
def from_transaction_id_and_output_index(cls, transaction_id: TransactionId, output_index: int):
def from_transaction_id_and_output_index(
cls, transaction_id: TransactionId, output_index: int):
"""Creates an `OutputId` instance from its transaction id and output index.
Args:
Expand Down
15 changes: 13 additions & 2 deletions bindings/python/iota_sdk/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,15 @@ def hex_to_bech32(hex_str: HexStr, bech32_hrp: str) -> str:
'bech32Hrp': bech32_hrp
})

@staticmethod
def address_to_bech32(address: Address, bech32_hrp: str) -> str:
"""Convert an address to its bech32 representation.
"""
return _call_method('addressToBech32', {
'address': address,
'bech32Hrp': bech32_hrp
})

@staticmethod
def account_id_to_bech32(account_id: HexStr, bech32_hrp: str) -> str:
"""Convert an account id to a Bech32 encoded address.
Expand Down Expand Up @@ -307,13 +316,15 @@ def block_bytes(
def iota_mainnet_protocol_parameters() -> ProtocolParameters:
"""Returns sample protocol parameters for IOTA mainnet.
"""
return ProtocolParameters.from_dict(_call_method('iotaMainnetProtocolParameters'))
return ProtocolParameters.from_dict(
_call_method('iotaMainnetProtocolParameters'))

@staticmethod
def shimmer_mainnet_protocol_parameters() -> ProtocolParameters:
"""Returns sample protocol parameters for Shimmer mainnet.
"""
return ProtocolParameters.from_dict(_call_method('shimmerMainnetProtocolParameters'))
return ProtocolParameters.from_dict(
_call_method('shimmerMainnetProtocolParameters'))


class UtilsError(Exception):
Expand Down
12 changes: 12 additions & 0 deletions sdk/src/client/utils.rs
Original file line number Diff line number Diff line change
Expand Up @@ -117,6 +117,18 @@ impl Client {
}
}

/// Converts an address to its bech32 representation
pub async fn address_to_bech32(
&self,
address: Address,
bech32_hrp: Option<impl ConvertTo<Hrp>>,
) -> crate::client::Result<Bech32Address> {
match bech32_hrp {
Some(hrp) => Ok(address.to_bech32(hrp.convert()?)),
None => Ok(address.to_bech32(self.get_bech32_hrp().await?)),
}
}

/// Transforms an account id to a bech32 encoded address
pub async fn account_id_to_bech32(
&self,
Expand Down

0 comments on commit d9cbd61

Please sign in to comment.