Struct catenis_api_client::CatenisClient[][src]

pub struct CatenisClient { /* fields omitted */ }
Expand description

Represents a Catenis API client.

Implementations

Instantiate a new Catenis API client object with default option settings.

Note: if no virtual device credentials are passed, the resulting client object should only be used to call public API methods.

Instantiate a new Catenis API client object with alternative option settings.

Note: if no virtual device credentials are passed, the resulting client object should only be used to call public API methods.

Instantiate a new WebSocket notification channel object for a given Catenis notification event.

Example

use catenis_api_client::{
    CatenisClient, ClientOptions, Environment, Result,
    api::NotificationEvent,
};

let ctn_client = CatenisClient::new_with_options(
    Some((
        "drc3XdxNtzoucpw9xiRp",
        concat!(
            "4c1749c8e86f65e0a73e5fb19f2aa9e74a716bc22d7956bf3072b4bc3fbfe2a0",
            "d138ad0d4bcfee251e4e5f54d6e92b8fd4eb36958a7aeaeeb51e8d2fcc4552c3"
        ),
    ).into()),
    &[
        ClientOptions::Environment(Environment::Sandbox),
    ],
)?;

// Instantiate WebSocket notification channel object for New Message Received
//  notification event
let notify_channel = ctn_client.new_ws_notify_channel(NotificationEvent::NewMsgReceived);

Call Log Message API method.

Examples

Log a message in a single call:

use catenis_api_client::{
    api::*,
};

let result = ctn_client.log_message(
    Message::Whole(String::from("My message")),
    Some(LogMessageOptions {
        encoding: Some(Encoding::UTF8),
        encrypt: Some(true),
        off_chain: Some(true),
        storage: Some(Storage::Auto),
        async_: None,
    }),
)?;

println!("ID of logged message: {}", result.message_id.unwrap());

Log a message in chunks:

use catenis_api_client::{
    api::*,
};

let message = [
    "First part of message",
    "Second part of message",
    "Third and last part of message"
];

for idx in 0..message.len() {
    let mut continuation_token = None;

    let result = ctn_client.log_message(
        Message::Chunk(ChunkedMessage {
            data: Some(String::from(message[idx])),
            is_final: Some(idx < message.len() - 1),
            continuation_token: if let Some(token) = &continuation_token {
                Some(String::from(token))
            } else {
                None
            },
        }),
        Some(LogMessageOptions {
            encoding: Some(Encoding::UTF8),
            encrypt: Some(true),
            off_chain: Some(true),
            storage: Some(Storage::Auto),
            async_: None,
        }),
    )?;

    if let Some(token) = result.continuation_token {
        continuation_token = Some(token);
    } else {
        println!("ID of logged message: {}", result.message_id.unwrap());
    }
}

Call Send Message API method.

Examples

Send a message in a single call:

use catenis_api_client::{
    api::*,
};

let result = ctn_client.send_message(
    Message::Whole(String::from("My message")),
    DeviceId {
        id: String::from("d8YpQ7jgPBJEkBrnvp58"),
        is_prod_unique_id: None,
    },
    Some(SendMessageOptions {
        encoding: Some(Encoding::UTF8),
        encrypt: Some(true),
        off_chain: Some(true),
        storage: Some(Storage::Auto),
        read_confirmation: Some(true),
        async_: None,
    }),
)?;

println!("ID of sent message: {}", result.message_id.unwrap());

Send a message in chunks:

use catenis_api_client::{
    api::*,
};

let message = [
    "First part of message",
    "Second part of message",
    "Third and last part of message"
];

for idx in 0..message.len() {
    let mut continuation_token = None;

    let result = ctn_client.send_message(
        Message::Chunk(ChunkedMessage {
            data: Some(String::from(message[idx])),
            is_final: Some(idx < message.len() - 1),
            continuation_token: if let Some(token) = &continuation_token {
                Some(String::from(token))
            } else {
                None
            },
        }),
        DeviceId {
            id: String::from("d8YpQ7jgPBJEkBrnvp58"),
            is_prod_unique_id: None,
        },
        Some(SendMessageOptions {
            encoding: Some(Encoding::UTF8),
            encrypt: Some(true),
            off_chain: Some(true),
            storage: Some(Storage::Auto),
            read_confirmation: Some(true),
            async_: None,
        }),
    )?;

    if let Some(token) = result.continuation_token {
        continuation_token = Some(token);
    } else {
        println!("ID of sent message: {}", result.message_id.unwrap());
    }
}

Call Read Message API method.

Example

use catenis_api_client::{
    api::*,
};

let result = ctn_client.read_message(
    "o3muoTnnD6cXYyarYY38",
    Some(ReadMessageOptions {
        encoding: Some(Encoding::UTF8),
        continuation_token: None,
        data_chunk_size: None,
        async_: None,
    }),
)?;

println!("Read message: {}", result.msg_data.unwrap());

Call Retrieve Message Container API method.

Example

use catenis_api_client::{
    api::*,
};

let result = ctn_client.retrieve_message_container(
    "o3muoTnnD6cXYyarYY38",
)?;

if let Some(off_chain) = result.off_chain {
    println!("IPFS CID of Catenis off-chain message envelope: {}", off_chain.cid);
}

if let Some(blockchain) = result.blockchain {
    println!("ID of blockchain transaction containing the message: {}", blockchain.txid);
}

if let Some(external_storage) = result.external_storage {
    println!("IPFS reference to message: {}", external_storage.ipfs);
}

Call Retrieve Message Origin API method.

Note: this is a public API method.

Example

use catenis_api_client::{
    api::*,
};

let result = ctn_client.retrieve_message_origin(
    "o3muoTnnD6cXYyarYY38",
    Some("Any text to be signed"),
)?;

if let Some(tx) = result.tx {
    println!("Catenis message transaction info: {:?}", tx);
}

if let Some(off_chain_msg_env) = result.off_chain_msg_envelope {
    println!("Off-chain message envelope info: {:?}", off_chain_msg_env);
}

if let Some(proof) = result.proof {
    println!("Origin proof info: {:?}", proof);
}

Call Retrieve Message Progress API method.

Note: this method should be passed an ephemeral message ID: either a provisional message ID or a cached message ID.

Example

use catenis_api_client::{
    api::*,
};

let result = ctn_client.retrieve_message_progress(
    "pTZCgjKYEyHfu4rNPWct",
)?;

println!("Number of bytes processed so far: {}", result.progress.bytes_processed);

if result.progress.done {
    if let Some(true) = result.progress.success {
        // Get result
        println!("Asynchronous processing result: {:?}", result.result.unwrap());
    } else {
        // Process error
        let error = result.progress.error.unwrap();

        println!("Asynchronous processing error: [{}] - {}", error.code, error.message);
    }
} else {
    // Asynchronous processing not done yet. Continue pooling
}

Call List Messages API method.

Example

use catenis_api_client::{
    api::*,
};

let result = ctn_client.list_messages(
    Some(ListMessagesOptions {
        action: Some(MessageActionOption::Send),
        direction: Some(MessageDirectionOption::Inbound),
        from_devices: None,
        to_devices: None,
        read_state: Some(MessageReadStateOption::Unread),
        start_date: Some("2020-12-22T00:00:00Z".into()),
        end_date: None,
        limit: None,
        skip: None,
    }),
)?;

if result.msg_count > 0 {
    println!("Returned messages: {:?}", result.messages);

    if result.has_more {
        println!("Not all messages have been returned");
    }
}

Call Issue Asset API method.

Example

use catenis_api_client::{
    api::*,
};

let result = ctn_client.issue_asset(
    NewAssetInfo {
        name: String::from("XYZ001"),
        description: Some(String::from("My first test asset")),
        can_reissue: true,
        decimal_places: 2,
    },
    1_500.0,
    None,
)?;

println!("ID of newly issued asset: {}", result.asset_id);

Call Reissue Asset API method.

Example

use catenis_api_client::{
    api::*,
};

let result = ctn_client.reissue_asset(
    "aBy2ovnucyWaSB6Tro9x",
    650.25,
    Some(DeviceId {
        id: String::from("d8YpQ7jgPBJEkBrnvp58"),
        is_prod_unique_id: None,
    }),
)?;

println!("Total existent asset balance (after issuance): {}", result.total_existent_balance);

Call Transfer Asset API method.

Example

use catenis_api_client::{
    api::*,
};

let result = ctn_client.transfer_asset(
    "aBy2ovnucyWaSB6Tro9x",
    50.75,
    DeviceId {
        id: String::from("d8YpQ7jgPBJEkBrnvp58"),
        is_prod_unique_id: None,
    },
)?;

println!("Remaining asset balance: {}", result.remaining_balance);

Call Retrieve Asset Info API method.

Example

use catenis_api_client::{
    api::*,
};

let result = ctn_client.retrieve_asset_info(
    "aBy2ovnucyWaSB6Tro9x",
)?;

println!("Asset info: {:?}", result);

Call Get Asset Balance API method.

Example

use catenis_api_client::{
    api::*,
};

let result = ctn_client.get_asset_balance(
    "aBy2ovnucyWaSB6Tro9x",
)?;

println!("Current asset balance: {}", result.total);
println!("Amount not yet confirmed: {}", result.unconfirmed);

Call List Owned Assets API method.

Example

use catenis_api_client::{
    api::*,
};

let result = ctn_client.list_owned_assets(
    Some(200),
    Some(0),
)?;

for owned_asset in result.owned_assets {
    println!("Asset ID: {}", owned_asset.asset_id);
    println!(" - current asset balance: {}", owned_asset.balance.total);
    println!(" - amount not yet confirmed: {}\n", owned_asset.balance.unconfirmed);
}

if result.has_more {
    println!("Not all owned assets have been returned");
}

Call List Issued Assets API method.

Example

use catenis_api_client::{
    api::*,
};

let result = ctn_client.list_issued_assets(
    Some(200),
    Some(0),
)?;

for issued_asset in result.issued_assets {
    println!("Asset ID: {}", issued_asset.asset_id);
    println!(" - total existent balance: {}\n", issued_asset.total_existent_balance);
}

if result.has_more {
    println!("Not all issued assets have been returned");
}

Call Retrieve Asset Issuance History API method.

Example

use catenis_api_client::{
    api::*,
};

let result = ctn_client.retrieve_asset_issuance_history(
    "aBy2ovnucyWaSB6Tro9x",
    Some("2020-12-01T00:00:00Z".into()),
    None,
    Some(200),
    Some(0),
)?;

for issuance_events in result.issuance_events {
    println!("Issuance date: {}", issuance_events.date);
    println!(" - issued amount: {}", issuance_events.amount);
    println!(
        " - device to which issued amount had been assigned: {:?}\n",
        issuance_events.holding_device
    );
}

if result.has_more {
    println!("Not all asset issuance events have been returned");
}

Call List Asset Holders API method.

Example

use catenis_api_client::{
    api::*,
};

let result = ctn_client.list_asset_holders(
    "aBy2ovnucyWaSB6Tro9x",
    Some(200),
    Some(0),
)?;

for asset_holder in result.asset_holders {
    if let Some(holder) = asset_holder.holder {
        println!("Asset holder ID: {}", holder.device_id);
        println!(" - detailed holder info: {:?}", holder);
        println!(
            " - amount of asset currently held by device: {}",
            asset_holder.balance.total
        );
        println!(" - amount not yet confirmed: {}\n", asset_holder.balance.unconfirmed);
    } else {
        println!("Migrated asset:");
        println!(" - total migrated amount: {}", asset_holder.balance.total);
        println!(" - amount not yet confirmed: {}", asset_holder.balance.unconfirmed);
    }
}

if result.has_more {
    println!("Not all asset holders have been returned");
}

Call Export Asset API method.

Examples

Estimate export cost (in foregin blockchain’s native coin):

use catenis_api_client::{
    api::*,
};

let result = ctn_client.export_asset(
    "aH2AkrrL55GcThhPNa3J",
    ForeignBlockchain::Ethereum,
    NewForeignTokenInfo {
        name: String::from("Catenis test token #10"),
        symbol: String::from("CTK10"),
    },
    Some(ExportAssetOptions {
        consumption_profile: None,
        estimate_only: Some(true),
    }),
)?;

println!(
    "Estimated foreign blockchain transaction execution price: {}",
    result.estimated_price.unwrap()
);

Export asset:

use catenis_api_client::{
    api::*,
};

let result = ctn_client.export_asset(
    "aH2AkrrL55GcThhPNa3J",
    ForeignBlockchain::Ethereum,
    NewForeignTokenInfo {
        name: String::from("Catenis test token #10"),
        symbol: String::from("CTK10"),
    },
    None,
)?;

println!("Pending asset export: {:?}", result);

// Start polling for asset export outcome

Call Migrate Asset API method.

Examples

Estimate migration cost (in foreign blockchain’s native coin):

use catenis_api_client::{
    api::*,
};

let result = ctn_client.migrate_asset(
    "aH2AkrrL55GcThhPNa3J",
    ForeignBlockchain::Ethereum,
    AssetMigration::Info(AssetMigrationInfo {
        direction: AssetMigrationDirection::Outward,
        amount: 50.0,
        dest_address: Some(String::from("0xe247c9BfDb17e7D8Ae60a744843ffAd19C784943")),
    }),
    Some(MigrateAssetOptions {
        consumption_profile: None,
        estimate_only: Some(true),
    }),
)?;

println!(
    "Estimated foreign blockchain transaction execution price: {}",
    result.estimated_price.unwrap()
);

Migrate asset:

use catenis_api_client::{
    api::*,
};

let result = ctn_client.migrate_asset(
    "aH2AkrrL55GcThhPNa3J",
    ForeignBlockchain::Ethereum,
    AssetMigration::Info(AssetMigrationInfo {
        direction: AssetMigrationDirection::Outward,
        amount: 50.0,
        dest_address: Some(String::from("0xe247c9BfDb17e7D8Ae60a744843ffAd19C784943")),
    }),
    None,
)?;

println!("Pending asset migration: {:?}", result);

// Start polling for asset migration outcome

Reprocess a (failed) migration:

use catenis_api_client::{
    api::*,
};

let result = ctn_client.migrate_asset(
    "aH2AkrrL55GcThhPNa3J",
    ForeignBlockchain::Ethereum,
    AssetMigration::ID(String::from("gq8x3efLpEXTkGQchHTb")),
    None,
)?;

println!("Pending asset migration: {:?}", result);

// Start polling for asset migration outcome

Call Asset Export Outcome API method.

Example

use catenis_api_client::{
    api::*,
};

let result = ctn_client.asset_export_outcome(
    "aH2AkrrL55GcThhPNa3J",
    ForeignBlockchain::Ethereum,
)?;

match result.status {
    AssetExportStatus::Success => {
        // Asset successfully exported
        println!("Foreign token ID (address): {}", result.token.id.unwrap());
    },
    AssetExportStatus::Pending => {
        // Final asset export state not yet reached
    },
    AssetExportStatus::Error => {
        // Asset export has failed. Process error
        println!(
            "Error executing foreign blockchain transaction: {}",
            result.foreign_transaction.error.unwrap()
        );
    },
}

Call Asset Migration Outcome API method.

Example

use catenis_api_client::{
    api::*,
};

let result = ctn_client.asset_migration_outcome(
    "gq8x3efLpEXTkGQchHTb",
)?;

match result.status {
    AssetMigrationStatus::Success => {
        // Asset amount successfully migrated
        println!("Asset amount successfully migrated");
    },
    AssetMigrationStatus::Pending => {
        // Final asset migration state not yet reached
    },
    _ => {
        // Asset migration has failed. Process error
        if let Some(error) = result.catenis_service.error {
            println!("Error executing Catenis service: {}", error);
        }

        if let Some(error) = result.foreign_transaction.error {
            println!("Error executing foreign blockchain transaction: {}", error);
        }
    },
}

Call List Exported Assets API method.

Example

use catenis_api_client::{
    api::*,
};

let result = ctn_client.list_exported_assets(
    Some(ListExportedAssetsOptions {
        asset_id: None,
        foreign_blockchain: Some(ForeignBlockchain::Ethereum),
        token_symbol: None,
        status: Some(vec![AssetExportStatus::Success]),
        negate_status: None,
        start_date: Some("2021-08-01T00:00:00Z".into()),
        end_date: None,
        limit: Some(200),
        skip: Some(0),
    }),
)?;

if result.exported_assets.len() > 0 {
    println!("Returned asset exports: {:?}", result.exported_assets);

    if result.has_more {
        println!("Not all asset exports have been returned");
    }
}

Call List Asset Migrations API method.

Example

use catenis_api_client::{
    api::*,
};

let result = ctn_client.list_asset_migrations(
    Some(ListAssetMigrationsOptions {
        asset_id: None,
        foreign_blockchain: Some(ForeignBlockchain::Ethereum),
        direction: Some(AssetMigrationDirection::Outward),
        status: Some(vec![
            AssetMigrationStatus::Interrupted,
            AssetMigrationStatus::Error,
        ]),
        negate_status: None,
        start_date: Some("2021-08-01T00:00:00Z".into()),
        end_date: None,
        limit: Some(200),
        skip: Some(0),
    }),
)?;

if result.asset_migrations.len() > 0 {
    println!("Returned asset migrations: {:?}", result.asset_migrations);

    if result.has_more {
        println!("Not all asset migrations have been returned");
    }
}

Call List Permission Events API method.

Example

use catenis_api_client::{
    api::*,
};

let result = ctn_client.list_permission_events()?;

for (event, description) in result {
    println!("Permission event: {} - {}", event.to_string(), description);
}

Call Retrieve Permission Rights API method.

Example

use catenis_api_client::{
    api::*,
};

let result = ctn_client.retrieve_permission_rights(
    PermissionEvent::ReceiveMsg,
)?;

println!("Default (system) permission right: {:?}", result.system);

if let Some(rights_setting) = result.catenis_node {
    if let Some(catenis_node_idxs) = rights_setting.allow {
        println!(
            "Index of Catenis nodes to which permission is granted: {:?}",
            catenis_node_idxs
        );
    }

    if let Some(catenis_node_idxs) = rights_setting.deny {
        println!(
            "Index of Catenis nodes to which permission is not granted: {:?}",
            catenis_node_idxs
        );
    }
}

if let Some(rights_setting) = result.client {
    if let Some(client_ids) = rights_setting.allow {
        println!("ID of clients to which permission is granted: {:?}", client_ids);
    }

    if let Some(client_ids) = rights_setting.deny {
        println!("ID of clients to which permission is not granted: {:?}", client_ids);
    }
}

if let Some(rights_setting) = result.device {
    if let Some(devices) = rights_setting.allow {
        println!("Devices to which permission is granted: {:?}", devices);
    }

    if let Some(devices) = rights_setting.deny {
        println!("Devices to which permission is not granted: {:?}", devices);
    }
}

Call Set Permission Rights API method.

Example

use catenis_api_client::{
    api::*,
};

let result = ctn_client.set_permission_rights(
    PermissionEvent::ReceiveMsg,
    AllPermissionRightsUpdate {
        system: Some(PermissionRight::Deny),
        catenis_node: Some(PermissionRightsUpdate {
            allow: Some(vec![
                String::from("self"),
            ]),
            deny: None,
            none: None,
        }),
        client: Some(PermissionRightsUpdate {
            allow: Some(vec![
                String::from("self"),
                String::from("c3gBoX45xk3yAmenyDRD"),
            ]),
            deny: None,
            none: None,
        }),
        device: Some(DevicePermissionRightsUpdate {
            allow: None,
            deny: Some(vec![
                DeviceId {
                    id: String::from("self"),
                    is_prod_unique_id: None,
                },
                DeviceId {
                    id: String::from("ABCD001"),
                    is_prod_unique_id: Some(true),
                },
            ]),
            none: None,
        }),
    },
)?;

println!("Permission rights successfully set");

Call Check Effective Permission Right API method.

Example

use catenis_api_client::{
    api::*,
};

let result = ctn_client.check_effective_permission_right(
    PermissionEvent::ReceiveMsg,
    DeviceId {
        id: String::from("d8YpQ7jgPBJEkBrnvp58"),
        is_prod_unique_id: None,
    },
)?;

let (device_id, right) = result.iter().next().unwrap();

println!("Effective right for device {}: {:?}", device_id, right);

Call Retrieve Device Identification Info API method.

Example

use catenis_api_client::{
    api::*,
};

let result = ctn_client.retrieve_device_identification_info(
    DeviceId {
        id: String::from("self"),
        is_prod_unique_id: None,
    },
)?;

println!("Device's Catenis node ID info: {:?}", result.catenis_node);
println!("Device's client ID info: {:?}", result.client);
println!("Device's own ID info: {:?}", result.device);

Call List Notification Events API method.

Example

use catenis_api_client::{
    api::*,
};

let result = ctn_client.list_notification_events()?;

for (event, description) in result {
    println!("Notification event: {} - {}", event.to_string(), description);
}

Trait Implementations

Returns a copy of the value. Read more

Performs copy-assignment from source. Read more

Formats the value using the given formatter. Read more

Auto Trait Implementations

Blanket Implementations

Gets the TypeId of self. Read more

Immutably borrows from an owned value. Read more

Mutably borrows from an owned value. Read more

Performs the conversion.

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more

Instruments this type with the current Span, returning an Instrumented wrapper. Read more

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more

Instruments this type with the current Span, returning an Instrumented wrapper. Read more

Performs the conversion.

Should always be Self

The resulting type after obtaining ownership.

Creates owned data from borrowed data, usually by cloning. Read more

🔬 This is a nightly-only experimental API. (toowned_clone_into)

recently added

Uses borrowed data to replace owned data, usually by cloning. Read more

The type returned in the event of a conversion error.

Performs the conversion.

The type returned in the event of a conversion error.

Performs the conversion.