Skip to content

Commit

Permalink
Add implicit account examples and fix some Python types (#2193)
Browse files Browse the repository at this point in the history
* Add implicit account examples and fix some Python types

* Use const

* Clean docs

* Rename to implicit_account_creation_address

---------

Co-authored-by: Thibault Martinez <[email protected]>
Co-authored-by: DaughterOfMars <[email protected]>
  • Loading branch information
3 people authored Mar 21, 2024
1 parent fe407ff commit 754eaee
Show file tree
Hide file tree
Showing 10 changed files with 158 additions and 36 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
// Copyright 2024 IOTA Stiftung
// SPDX-License-Identifier: Apache-2.0

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/wallet/create-wallet` example!
//
require('dotenv').config({ path: '.env' });

// Run with command:
// yarn run-example ./how_tos/account_output/implicit-account-creation-address.ts

// In this example we create an implicit account creation address.
async function run() {
initLogger();
for (const envVar of ['WALLET_DB_PATH']) {
if (!(envVar in process.env)) {
throw new Error(`.env ${envVar} is undefined, see .env.example`);
}
}

try {
// Create the wallet
const wallet = await Wallet.create({
storagePath: process.env.WALLET_DB_PATH,
});

// Get the implicit account address.
const implicitAccountCreationAddress =
await wallet.implicitAccountCreationAddress();
console.log(
`Implicit account creation address: ${implicitAccountCreationAddress}`,
);
} catch (error) {
console.log('Error: ', error);
}
process.exit(0);
}

void run().then(() => process.exit());
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
// Copyright 2024 IOTA Stiftung
// SPDX-License-Identifier: Apache-2.0

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/wallet/create-wallet` example!
//
require('dotenv').config({ path: '.env' });

// Run with command:
// yarn run-example ./how_tos/account_output/implicit-account-transition.ts

// In this example we transition an implicit account to an account.
async function run() {
initLogger();
for (const envVar of [
'WALLET_DB_PATH',
'STRONGHOLD_PASSWORD',
'EXPLORER_URL',
]) {
if (!(envVar in process.env)) {
throw new Error(`.env ${envVar} is undefined, see .env.example`);
}
}

try {
// Create the wallet
const wallet = await Wallet.create({
storagePath: process.env.WALLET_DB_PATH,
});

// Need to sync the wallet with implicit accounts option enabled.
let balance = await wallet.sync({ syncImplicitAccounts: true });

const implicitAccounts = await wallet.implicitAccounts();
if (implicitAccounts.length == 0) {
throw new Error(`No implicit account available`);
}

// To sign a transaction we need to unlock stronghold.
await wallet.setStrongholdPassword(
process.env.STRONGHOLD_PASSWORD as string,
);

console.log('Sending the transition transaction...');

// Transition to the account output.
const transaction = await wallet.implicitAccountTransition(
implicitAccounts[0].outputId,
);

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

await wallet.waitForTransactionAcceptance(transaction.transactionId);
console.log(
`Tx accepted: ${process.env.EXPLORER_URL}/transactions/${transaction.transactionId}`,
);

balance = await wallet.sync();
console.log(`Accounts:\n`, balance.accounts);
} catch (error) {
console.log('Error: ', error);
}
process.exit(0);
}

void run().then(() => process.exit());
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import os

from dotenv import load_dotenv
from iota_sdk import Wallet, WalletOptions, SyncOptions

# In this example we transition an implicit account to an account.

load_dotenv()

for env_var in ['WALLET_DB_PATH', 'STRONGHOLD_PASSWORD', 'EXPLORER_URL']:
if env_var not in os.environ:
raise Exception(f".env {env_var} is undefined, see .env.example")

# Need to sync the wallet with implicit accounts option enabled.
wallet = Wallet(WalletOptions(storage_path=os.environ.get('WALLET_DB_PATH')))

wallet.sync(SyncOptions(sync_implicit_accounts=True))

implicit_accounts = wallet.implicit_accounts()

wallet.set_stronghold_password(os.environ["STRONGHOLD_PASSWORD"])

# Transition to the account output.
transaction = wallet.implicit_account_transition(
implicit_accounts[0].output_id)
print(f'Transaction sent: {transaction.transaction_id}')

wallet.wait_for_transaction_acceptance(transaction.transaction_id)
print(
f'Tx accepted: {os.environ["EXPLORER_URL"]}/transactions/{transaction.transaction_id}')
19 changes: 1 addition & 18 deletions bindings/python/iota_sdk/types/address.py
Original file line number Diff line number Diff line change
Expand Up @@ -91,24 +91,7 @@ class ImplicitAccountCreationAddress:
"""
type: int = field(default_factory=lambda: int(
AddressType.IMPLICIT_ACCOUNT_CREATION), init=False)
address: Ed25519Address

def to_dict(self) -> dict:
"""Converts an implicit account creation address to the dictionary representation.
"""

return {
"type": self.type,
"pubKeyHash": self.address.pub_key_hash
}

@staticmethod
def from_dict(addr_dict: dict):
"""Creates an implicit account creation address from a dictionary representation.
"""

return ImplicitAccountCreationAddress(
Ed25519Address(addr_dict['pubKeyHash']))
pub_key_hash: HexStr


@json
Expand Down
10 changes: 3 additions & 7 deletions bindings/python/iota_sdk/types/output_data.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,11 @@

from __future__ import annotations
from dataclasses import dataclass
from typing import Optional
from iota_sdk.types.address import Address
from iota_sdk.types.common import json
from iota_sdk.types.output import Output
from iota_sdk.types.output_id import OutputId
from iota_sdk.types.output_id_proof import OutputIdProof
from iota_sdk.types.output_metadata import OutputMetadata
from iota_sdk.types.signature import Bip44


@json
Expand All @@ -21,15 +19,13 @@ class OutputData:
output_id: With the output data corresponding output ID.
metadata: With the output corresponding metadata.
output: The output object itself.
address: The address associated with the output.
output_id_proof: The output ID proof.
network_id: The network ID the output belongs to.
remainder: Whether the output represents a remainder amount.
chain: A list of chain state indexes.
"""
output_id: OutputId
metadata: OutputMetadata
output: Output
address: Address
output_id_proof: OutputIdProof
network_id: str
remainder: bool
chain: Optional[Bip44] = None
14 changes: 7 additions & 7 deletions bindings/python/iota_sdk/types/transaction_with_metadata.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,12 +23,12 @@ class InclusionState(str, Enum):
Conflicting: The transaction is conflicting.
UnknownPruned: The transaction is unknown or already pruned.
"""
Pending = 'pending'
Accepted = 'accepted'
Confirmed = 'confirmed'
Finalized = 'finalized'
Conflicting = 'conflicting'
UnknownPruned = 'unknownPruned'
Pending = 'Pending'
Accepted = 'Accepted'
Confirmed = 'Confirmed'
Finalized = 'Finalized'
Conflicting = 'Conflicting'
UnknownPruned = 'UnknownPruned'


@json
Expand All @@ -53,7 +53,7 @@ class TransactionWithMetadata:
transaction_id: TransactionId
network_id: int
incoming: bool
inputs = List[OutputWithMetadata]
inputs: List[OutputWithMetadata]
note: Optional[str] = None
block_id: Optional[BlockId] = None

Expand Down
2 changes: 1 addition & 1 deletion bindings/python/iota_sdk/wallet/wallet.py
Original file line number Diff line number Diff line change
Expand Up @@ -478,7 +478,7 @@ def prepare_implicit_account_transition(
"""Prepares to transition an implicit account to an account.
"""
prepared = PreparedTransactionData.from_dict(self._call_method(
'implicitAccountTransition', {
'prepareImplicitAccountTransition', {
'outputId': output_id
}
))
Expand Down
4 changes: 2 additions & 2 deletions sdk/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -348,8 +348,8 @@ path = "examples/how_tos/account_output/destroy.rs"
required-features = ["wallet", "stronghold"]

[[example]]
name = "implicit_account_creation"
path = "examples/how_tos/account_output/implicit_account_creation.rs"
name = "implicit_account_creation_address"
path = "examples/how_tos/account_output/implicit_account_creation_address.rs"
required-features = ["wallet", "storage"]

# Outputs
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
//!
//! Rename `.env.example` to `.env` first, then run the command:
//! ```sh
//! cargo run --release --all-features --example implicit_account_creation
//! cargo run --release --all-features --example implicit_account_creation_address
//! ```
use iota_sdk::{
Expand Down

0 comments on commit 754eaee

Please sign in to comment.