pub struct ApiClient { /* private fields */ }Implementations§
Source§impl ApiClient
impl ApiClient
Sourcepub async fn new() -> Result<Self, Error>
pub async fn new() -> Result<Self, Error>
Creates a new API client with the base URL from environment variables.
Automatically selects the appropriate token strategy based on environment detection:
- Mock strategy for mock environments (no persistence, isolated tokens)
- Live strategy for live environments (full token management with persistence)
§Errors
Returns an error if:
- The
AMP_API_BASE_URLenvironment variable contains an invalid URL - Token strategy initialization fails
§Examples
// Create a new client - automatically detects environment
let client = ApiClient::new().await?;
// Client is ready to use
let assets = client.get_assets().await?;
println!("Found {} assets", assets.len());Sourcepub async fn with_base_url(base_url: Url) -> Result<Self, Error>
pub async fn with_base_url(base_url: Url) -> Result<Self, Error>
Creates a new API client with the specified base URL.
Automatically selects the appropriate token strategy based on environment detection.
§Errors
Returns an error if token strategy initialization fails.
§Examples
let base_url = Url::parse("https://amp-test.blockstream.com/api")?;
let client = ApiClient::with_base_url(base_url).await?;
// Client is ready to use with the specified URL
let assets = client.get_assets().await?;Sourcepub fn with_token_strategy(
token_strategy: Box<dyn TokenStrategy>,
) -> Result<Self, Error>
pub fn with_token_strategy( token_strategy: Box<dyn TokenStrategy>, ) -> Result<Self, Error>
Creates a new API client with a custom token strategy (useful for testing).
§Errors
Returns an error if the base URL cannot be obtained from environment variables.
Sourcepub fn with_token_manager(
token_manager: Arc<TokenManager>,
) -> Result<Self, Error>
pub fn with_token_manager( token_manager: Arc<TokenManager>, ) -> Result<Self, Error>
Creates a new API client with a custom token manager (useful for testing).
§Errors
Returns an error if the base URL cannot be obtained from environment variables.
Sourcepub fn with_mock_token(base_url: Url, mock_token: String) -> Result<Self, Error>
pub fn with_mock_token(base_url: Url, mock_token: String) -> Result<Self, Error>
Creates a new API client for testing with a mock token strategy that always returns a fixed token. This bypasses all token acquisition and management logic and uses complete isolation.
§Errors
This method is infallible but returns Result for API consistency.
§Examples
let base_url = Url::parse("http://localhost:8080/api")?;
let client = ApiClient::with_mock_token(base_url, "test_token".to_string())?;
// Client will always use "test_token" for authentication
let token = client.get_token().await?;
assert_eq!(token, "test_token");Sourcepub async fn obtain_amp_token(&self) -> Result<String, Error>
👎Deprecated: Use get_token() instead - it provides automatic token management
pub async fn obtain_amp_token(&self) -> Result<String, Error>
Use get_token() instead - it provides automatic token management
Obtains a new authentication token from the AMP API.
Note: This method is deprecated in favor of the automatic token management
provided by get_token(). The TokenManager handles token acquisition internally
with enhanced retry logic and error handling.
§Errors
Returns an error if:
- The
AMP_USERNAMEorAMP_PASSWORDenvironment variables are not set - The HTTP request fails
- The token request is rejected by the server
- The response cannot be parsed
Sourcepub async fn get_token_info(&self) -> Result<Option<TokenInfo>, Error>
pub async fn get_token_info(&self) -> Result<Option<TokenInfo>, Error>
Gets current token information for debugging and monitoring.
Returns detailed information about the current token including:
- Expiry time and remaining duration
- Token age since acquisition
- Expiry status flags
Note: Mock strategies may return limited or no token information.
§Returns
Some(TokenInfo) if a token exists, None if no token is stored or strategy doesn’t support info
§Errors
Returns an error if token information retrieval fails
§Examples
let client = ApiClient::new().await?;
if let Some(token_info) = client.get_token_info().await? {
println!("Token expires at: {}", token_info.expires_at);
println!("Token is expired: {}", token_info.is_expired);
} else {
println!("No token stored or mock strategy in use");
}Sourcepub async fn clear_token(&self) -> Result<(), Error>
pub async fn clear_token(&self) -> Result<(), Error>
Clears the stored token (useful for testing scenarios).
This method removes the current token from storage, forcing the next
get_token() call to obtain a fresh token.
§Errors
Returns an error if token clearing fails
§Examples
let client = ApiClient::new().await?;
// Clear any existing token
client.clear_token().await?;
// Next get_token() call will obtain a fresh token
let token = client.get_token().await?;Sourcepub async fn force_refresh(&self) -> Result<String, Error>
pub async fn force_refresh(&self) -> Result<String, Error>
Forces a token refresh regardless of current token status.
This method bypasses the normal proactive refresh logic and immediately attempts to refresh the current token. If no token exists or refresh fails, it falls back to obtaining a new token.
§Errors
Returns an error if both refresh and obtain operations fail
Sourcepub async fn reset_global_token_manager() -> Result<(), Error>
pub async fn reset_global_token_manager() -> Result<(), Error>
Resets the global TokenManager singleton (useful for testing).
This method clears the token from the global TokenManager instance.
Primarily intended for test scenarios where a clean token state is needed.
§Errors
Returns an error if the reset operation fails
Sourcepub async fn get_token(&self) -> Result<String, Error>
pub async fn get_token(&self) -> Result<String, Error>
Gets a valid authentication token with automatic token management.
This method uses the integrated TokenManager to handle:
- Proactive token refresh (5 minutes before expiry)
- Automatic fallback from refresh to obtain on failure
- Retry logic with exponential backoff
- Thread-safe token storage
§Errors
Returns an error if token acquisition or refresh fails after all retries.
§Examples
let client = ApiClient::new().await?;
// Get a valid token - automatically handles refresh if needed
let token = client.get_token().await?;
println!("Got token: {}", &token[..10]); // Print first 10 charsSourcepub fn get_strategy_type(&self) -> &'static str
pub fn get_strategy_type(&self) -> &'static str
Returns the type of token strategy currently in use
This is useful for debugging and testing to verify the correct strategy is selected.
§Returns
A string indicating the strategy type: “mock” or “live”
Sourcepub fn should_persist_tokens(&self) -> bool
pub fn should_persist_tokens(&self) -> bool
Returns whether the current strategy persists tokens
This is useful for understanding the token management behavior.
§Returns
true if tokens are persisted to disk, false for in-memory only
Sourcepub async fn force_cleanup_token_files() -> Result<(), Error>
pub async fn force_cleanup_token_files() -> Result<(), Error>
Force cleanup of token files (for test cleanup)
This is a static method that can be used to cleanup token files
without needing an ApiClient instance. Useful for test teardown.
§Errors
Returns an error if token file cleanup fails
Sourcepub async fn get_changelog(&self) -> Result<Value, Error>
pub async fn get_changelog(&self) -> Result<Value, Error>
Gets the API changelog.
§Errors
Returns an error if:
- Authentication fails
- The HTTP request fails
- The server returns an error status
- The response cannot be parsed as JSON
Sourcepub async fn user_change_password(
&self,
password: Secret<String>,
) -> Result<ChangePasswordResponse, Error>
pub async fn user_change_password( &self, password: Secret<String>, ) -> Result<ChangePasswordResponse, Error>
Changes the user’s password.
§Errors
Returns an error if:
- Authentication fails
- The HTTP request fails
- The server rejects the password change
- The response cannot be parsed
Sourcepub async fn get_assets(&self) -> Result<Vec<Asset>, Error>
pub async fn get_assets(&self) -> Result<Vec<Asset>, Error>
Gets a list of all assets.
§Errors
Returns an error if:
- Authentication fails
- The HTTP request fails
- The server returns an error status
- The response cannot be parsed
§Examples
let client = ApiClient::new().await?;
let assets = client.get_assets().await?;
for asset in assets {
println!("Asset: {} ({})", asset.name, asset.ticker.unwrap_or_default());
}Sourcepub async fn get_asset(&self, asset_uuid: &str) -> Result<Asset, Error>
pub async fn get_asset(&self, asset_uuid: &str) -> Result<Asset, Error>
Gets a specific asset by UUID.
§Errors
Returns an error if:
- Authentication fails
- The HTTP request fails
- The asset does not exist
- The response cannot be parsed
§Examples
let client = ApiClient::new().await?;
let asset_uuid = "550e8400-e29b-41d4-a716-446655440000";
let asset = client.get_asset(asset_uuid).await?;
println!("Asset: {} ({})", asset.name, asset.ticker.unwrap_or_default());
println!("Registered: {}, Locked: {}", asset.is_registered, asset.is_locked);Sourcepub async fn issue_asset(
&self,
issuance_request: &IssuanceRequest,
) -> Result<IssuanceResponse, Error>
pub async fn issue_asset( &self, issuance_request: &IssuanceRequest, ) -> Result<IssuanceResponse, Error>
Issues a new asset.
§Errors
Returns an error if:
- Authentication fails
- The HTTP request fails
- The issuance request is invalid
- The response cannot be parsed
§Examples
let client = ApiClient::new().await?;
let issuance_request = IssuanceRequest {
name: "My Token".to_string(),
amount: 1000000,
destination_address: "vjU2i2EM2viGEzSywpStMPkTX9U9QSDsLSN63kJJYVpxKJZuxaph8v5r5Jf11aqnfBVdjSbrvcJ2pw26".to_string(),
domain: "example.com".to_string(),
ticker: "MYTKN".to_string(),
pubkey: "0279be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798".to_string(),
precision: Some(8),
is_confidential: Some(true),
is_reissuable: Some(false),
reissuance_amount: None,
reissuance_address: None,
transfer_restricted: Some(false),
};
let response = client.issue_asset(&issuance_request).await?;
println!("Issued asset with UUID: {}", response.asset_uuid);Sourcepub async fn edit_asset(
&self,
asset_uuid: &str,
edit_asset_request: &EditAssetRequest,
) -> Result<Asset, Error>
pub async fn edit_asset( &self, asset_uuid: &str, edit_asset_request: &EditAssetRequest, ) -> Result<Asset, Error>
Edits an existing asset.
§Errors
Returns an error if:
- Authentication fails
- The HTTP request fails
- The asset does not exist
- The edit request is invalid
- The response cannot be parsed
Sourcepub async fn register_asset(
&self,
asset_uuid: &str,
) -> Result<RegisterAssetResponse, Error>
pub async fn register_asset( &self, asset_uuid: &str, ) -> Result<RegisterAssetResponse, Error>
Registers an asset with the Blockstream Asset Registry.
This method publishes an asset to the public registry, making it discoverable and verifiable by other users and applications. The asset must already exist in the AMP system before it can be registered.
§Arguments
asset_uuid- The unique identifier of the asset to register
§Returns
Returns a RegisterAssetResponse containing:
success: Boolean indicating whether the registration was successfulmessage: Optional status message from the APIasset_id: The registered asset identifier (hex string)
§Errors
Returns an error if:
- The asset does not exist or cannot be found (404)
- Authentication fails or token is invalid (401)
- The asset is already registered (returns success with appropriate message)
- Network connectivity issues occur
- The server returns an error status (5xx)
- The response cannot be parsed
§Examples
let client = ApiClient::new().await?;
let asset_uuid = "550e8400-e29b-41d4-a716-446655440000";
let response = client.register_asset(asset_uuid).await?;
if response.success {
println!("Asset registered successfully!");
if let Some(asset) = response.asset_data {
println!("Asset ID: {}", asset.asset_id);
}
if let Some(message) = response.message {
println!("Message: {}", message);
}
}Sourcepub async fn delete_asset(&self, asset_uuid: &str) -> Result<(), Error>
pub async fn delete_asset(&self, asset_uuid: &str) -> Result<(), Error>
§Errors
Returns an error if:
- The asset does not exist or cannot be found
- Authentication fails or token is invalid
- Network connectivity issues occur
- The server returns an error status
Sourcepub async fn get_broadcast_status(
&self,
txid: &str,
) -> Result<BroadcastResponse, Error>
pub async fn get_broadcast_status( &self, txid: &str, ) -> Result<BroadcastResponse, Error>
§Errors
Returns an error if:
- The transaction ID is invalid or not found
- Authentication fails or token is invalid
- Network connectivity issues occur
- The server returns an error status
- The response cannot be parsed
Sourcepub async fn broadcast_transaction(
&self,
tx_hex: &str,
) -> Result<BroadcastResponse, Error>
pub async fn broadcast_transaction( &self, tx_hex: &str, ) -> Result<BroadcastResponse, Error>
§Errors
Returns an error if:
- The transaction hex is invalid or malformed
- The transaction is rejected by the network
- Authentication fails or token is invalid
- Network connectivity issues occur
- The server returns an error status
- The response cannot be parsed
§Errors
Returns an error if:
- The asset UUID is invalid or not found
- The user lacks authorization to register the asset
- The asset is already registered
- Authentication fails or token is invalid
- Network connectivity issues occur
- The server returns an error status
- The response cannot be parsed
Sourcepub async fn lock_asset(&self, asset_uuid: &str) -> Result<Asset, Error>
pub async fn lock_asset(&self, asset_uuid: &str) -> Result<Asset, Error>
§Errors
Returns an error if:
- The asset UUID is invalid or not found
- The asset is already locked
- The user lacks permission to lock the asset
- Authentication fails or token is invalid
- Network connectivity issues occur
- The server returns an error status
- The response cannot be parsed
Sourcepub async fn unlock_asset(&self, asset_uuid: &str) -> Result<Asset, Error>
pub async fn unlock_asset(&self, asset_uuid: &str) -> Result<Asset, Error>
§Errors
Returns an error if:
- The asset UUID is invalid or not found
- The asset is not currently locked
- The user lacks permission to unlock the asset
- Authentication fails or token is invalid
- Network connectivity issues occur
- The server returns an error status
- The response cannot be parsed
Sourcepub async fn get_asset_activities(
&self,
asset_uuid: &str,
params: &AssetActivityParams,
) -> Result<Vec<Activity>, Error>
pub async fn get_asset_activities( &self, asset_uuid: &str, params: &AssetActivityParams, ) -> Result<Vec<Activity>, Error>
§Errors
Returns an error if:
- The asset UUID is invalid or not found
- The activity parameters are invalid
- Authentication fails or token is invalid
- Network connectivity issues occur
- The server returns an error status
- The response cannot be parsed
Sourcepub async fn get_asset_ownerships(
&self,
asset_uuid: &str,
height: Option<i64>,
) -> Result<Vec<Ownership>, Error>
pub async fn get_asset_ownerships( &self, asset_uuid: &str, height: Option<i64>, ) -> Result<Vec<Ownership>, Error>
§Errors
Returns an error if:
- The asset UUID is invalid or not found
- The specified height is invalid or out of range
- Authentication fails or token is invalid
- Network connectivity issues occur
- The server returns an error status
- The response cannot be parsed
Sourcepub async fn get_asset_balance(
&self,
asset_uuid: &str,
) -> Result<Balance, Error>
pub async fn get_asset_balance( &self, asset_uuid: &str, ) -> Result<Balance, Error>
§Errors
Returns an error if:
- The asset UUID is invalid or not found
- Authentication fails or token is invalid
- Network connectivity issues occur
- The server returns an error status
- The response cannot be parsed
Sourcepub async fn get_asset_summary(
&self,
asset_uuid: &str,
) -> Result<AssetSummary, Error>
pub async fn get_asset_summary( &self, asset_uuid: &str, ) -> Result<AssetSummary, Error>
§Errors
Returns an error if:
- The asset UUID is invalid or not found
- Authentication fails or token is invalid
- Network connectivity issues occur
- The server returns an error status
- The response cannot be parsed
Sourcepub async fn get_asset_utxos(
&self,
asset_uuid: &str,
) -> Result<Vec<Utxo>, Error>
pub async fn get_asset_utxos( &self, asset_uuid: &str, ) -> Result<Vec<Utxo>, Error>
§Errors
Returns an error if:
- The asset UUID is invalid or not found
- Authentication fails or token is invalid
- Network connectivity issues occur
- The server returns an error status
- The response cannot be parsed
Sourcepub async fn get_asset_memo(&self, asset_uuid: &str) -> Result<String, Error>
pub async fn get_asset_memo(&self, asset_uuid: &str) -> Result<String, Error>
Gets the memo for a specific asset.
§Arguments
asset_uuid- The UUID of the asset to retrieve the memo for
§Returns
The memo string associated with the asset
§Errors
Returns an error if:
- Authentication fails
- The HTTP request fails
- The server returns an error status
- The asset does not exist
- The response cannot be parsed
Sourcepub async fn set_asset_memo(
&self,
asset_uuid: &str,
memo: &str,
) -> Result<(), Error>
pub async fn set_asset_memo( &self, asset_uuid: &str, memo: &str, ) -> Result<(), Error>
Sets a memo for the specified asset.
§Arguments
asset_uuid- The UUID of the asset to set the memo formemo- The memo string to associate with the asset
§Returns
Returns Ok(()) on success.
§Errors
Returns an error if:
- Authentication fails
- The HTTP request fails
- The server returns an error status
- The asset does not exist
- The memo cannot be set due to validation errors
§Example
let client = ApiClient::new().await?;
client.set_asset_memo("asset-uuid-123", "This is a memo for the asset").await?;Sourcepub async fn blacklist_asset_utxos(
&self,
asset_uuid: &str,
utxos: &[Outpoint],
) -> Result<Vec<Utxo>, Error>
pub async fn blacklist_asset_utxos( &self, asset_uuid: &str, utxos: &[Outpoint], ) -> Result<Vec<Utxo>, Error>
Blacklists specific UTXOs for an asset to prevent them from being used in transactions.
This method adds the specified UTXOs to the asset’s blacklist, preventing them from being used in future transactions. This is typically used for security purposes when UTXOs are suspected to be compromised or need to be temporarily disabled.
§Arguments
asset_uuid- The UUID of the asset to blacklist UTXOs forutxos- A slice ofOutpointstructs representing the UTXOs to blacklist
§Returns
Returns a vector of Utxo structs representing the blacklisted UTXOs with their updated status.
§Errors
Returns an error if:
- Authentication fails or insufficient permissions
- The asset UUID is invalid or does not exist
- One or more UTXOs are invalid or already blacklisted
- The HTTP request fails
- The server returns an error status
- The response cannot be parsed
§Examples
let client = ApiClient::new().await?;
let asset_uuid = "550e8400-e29b-41d4-a716-446655440000";
let utxos = vec![
Outpoint {
txid: "abc123...".to_string(),
vout: 0,
},
Outpoint {
txid: "def456...".to_string(),
vout: 1,
},
];
let blacklisted_utxos = client.blacklist_asset_utxos(asset_uuid, &utxos).await?;
println!("Blacklisted {} UTXOs", blacklisted_utxos.len());§Related Methods
whitelist_asset_utxos- Remove UTXOs from blacklistget_asset- Get asset information including UTXO status
Sourcepub async fn whitelist_asset_utxos(
&self,
asset_uuid: &str,
utxos: &[Outpoint],
) -> Result<Vec<Utxo>, Error>
pub async fn whitelist_asset_utxos( &self, asset_uuid: &str, utxos: &[Outpoint], ) -> Result<Vec<Utxo>, Error>
Removes UTXOs from the asset’s blacklist, allowing them to be used in transactions again.
This method removes the specified UTXOs from the asset’s blacklist, restoring their ability to be used in transactions. This is the reverse operation of blacklisting UTXOs.
§Arguments
asset_uuid- The UUID of the asset to whitelist UTXOs forutxos- A slice ofOutpointstructs representing the UTXOs to remove from blacklist
§Returns
Returns a vector of Utxo structs representing the whitelisted UTXOs with their updated status.
§Errors
Returns an error if:
- Authentication fails or insufficient permissions
- The asset UUID is invalid or does not exist
- One or more UTXOs are invalid or not currently blacklisted
- The HTTP request fails
- The server returns an error status
- The response cannot be parsed
§Examples
let client = ApiClient::new().await?;
let asset_uuid = "550e8400-e29b-41d4-a716-446655440000";
let utxos = vec![
Outpoint {
txid: "abc123...".to_string(),
vout: 0,
},
];
let whitelisted_utxos = client.whitelist_asset_utxos(asset_uuid, &utxos).await?;
println!("Whitelisted {} UTXOs", whitelisted_utxos.len());§Related Methods
blacklist_asset_utxos- Add UTXOs to blacklistget_asset- Get asset information including UTXO status
Sourcepub async fn get_asset_treasury_addresses(
&self,
asset_uuid: &str,
) -> Result<Vec<String>, Error>
pub async fn get_asset_treasury_addresses( &self, asset_uuid: &str, ) -> Result<Vec<String>, Error>
Sourcepub async fn add_asset_treasury_addresses(
&self,
asset_uuid: &str,
addresses: &[String],
) -> Result<(), Error>
pub async fn add_asset_treasury_addresses( &self, asset_uuid: &str, addresses: &[String], ) -> Result<(), Error>
Adds treasury addresses to a specific asset
§Arguments
asset_uuid- The UUID of the asset to add treasury addresses toaddresses- A slice of address strings to add as treasury addresses
§Returns
Returns Ok(()) on success
§Errors
Returns an error if:
- The asset does not exist
- The addresses are invalid
- The request fails
- Insufficient permissions
Sourcepub async fn delete_asset_treasury_addresses(
&self,
asset_uuid: &str,
addresses: &[String],
) -> Result<(), Error>
pub async fn delete_asset_treasury_addresses( &self, asset_uuid: &str, addresses: &[String], ) -> Result<(), Error>
Removes treasury addresses from a specific asset.
This method removes the specified addresses from the asset’s treasury address list. Treasury addresses are special addresses that can be used for asset management operations such as reissuance and burning.
§Arguments
asset_uuid- The UUID of the asset to remove treasury addresses fromaddresses- A slice of address strings to remove from the treasury addresses
§Returns
Returns Ok(()) on successful removal.
§Errors
Returns an error if:
- Authentication fails or insufficient permissions
- The asset UUID is invalid or does not exist
- One or more addresses are invalid or not currently treasury addresses
- The HTTP request fails
- The server returns an error status
- Attempting to remove the last treasury address (if not allowed)
§Examples
let client = ApiClient::new().await?;
let asset_uuid = "550e8400-e29b-41d4-a716-446655440000";
let addresses = vec![
"bc1qxy2kgdygjrsqtzq2n0yrf2493p83kkfjhx0wlh".to_string(),
"bc1qw508d6qejxtdg4y5r3zarvary0c5xw7kv8f3t4".to_string(),
];
client.delete_asset_treasury_addresses(asset_uuid, &addresses).await?;
println!("Removed {} treasury addresses", addresses.len());§Related Methods
add_asset_treasury_addresses- Add treasury addressesget_asset_treasury_addresses- Get current treasury addressesreissue_asset- Reissue assets using treasury addresses
Sourcepub async fn get_registered_users(
&self,
) -> Result<Vec<RegisteredUserResponse>, Error>
pub async fn get_registered_users( &self, ) -> Result<Vec<RegisteredUserResponse>, Error>
Gets a list of all registered users.
§Errors
Returns an error if:
- Authentication fails
- The HTTP request fails
- The server returns an error status
- The response cannot be parsed
§Examples
let client = ApiClient::new().await?;
let users = client.get_registered_users().await?;
for user in users {
println!("User: {} (ID: {})", user.name, user.id);
}Sourcepub async fn get_registered_user(
&self,
user_id: i64,
) -> Result<RegisteredUserResponse, Error>
pub async fn get_registered_user( &self, user_id: i64, ) -> Result<RegisteredUserResponse, Error>
Gets a specific registered user by ID.
§Arguments
user_id- The ID of the registered user to retrieve
§Errors
Returns an error if:
- Authentication fails
- The HTTP request fails
- The user ID does not exist
- The response cannot be parsed
§Examples
let client = ApiClient::new().await?;
let user = client.get_registered_user(1).await?;
println!("User: {} (ID: {})", user.name, user.id);Sourcepub async fn add_registered_user(
&self,
new_user: &RegisteredUserAdd,
) -> Result<RegisteredUserResponse, Error>
pub async fn add_registered_user( &self, new_user: &RegisteredUserAdd, ) -> Result<RegisteredUserResponse, Error>
Creates a new registered user in the AMP system.
This method creates a new registered user with the provided information. Registered users can be associated with GAIDs, assigned to categories, and receive asset assignments.
§Arguments
new_user- ARegisteredUserAddstruct containing the user information to create
§Returns
Returns a RegisteredUserResponse containing the created user’s information including
the assigned user ID.
§Errors
Returns an error if:
- Authentication fails or insufficient permissions
- The user data is invalid (e.g., missing required fields, invalid email format)
- A user with the same identifier already exists
- The HTTP request fails
- The server returns an error status
- The response cannot be parsed
§Examples
let client = ApiClient::new().await?;
let new_user = RegisteredUserAdd {
name: "John Doe".to_string(),
gaid: Some("GAbYScu6jkWUND2jo3L4KJxyvo55d".to_string()),
is_company: false,
};
let created_user = client.add_registered_user(&new_user).await?;
println!("Created user: {} with ID {}", created_user.name, created_user.id);§Related Methods
get_registered_users- List all registered usersedit_registered_user- Update user informationdelete_registered_user- Remove a user
Sourcepub async fn delete_registered_user(&self, user_id: i64) -> Result<(), Error>
pub async fn delete_registered_user(&self, user_id: i64) -> Result<(), Error>
Removes a registered user from the AMP system.
This method permanently deletes a registered user and all associated data. This operation cannot be undone. Any GAIDs associated with the user will be disassociated, and any pending assignments may be affected.
§Arguments
user_id- The ID of the registered user to delete
§Returns
Returns Ok(()) on successful deletion.
§Errors
Returns an error if:
- Authentication fails or insufficient permissions
- The user ID is invalid or does not exist
- The user has active assignments that prevent deletion
- The HTTP request fails
- The server returns an error status
§Examples
let client = ApiClient::new().await?;
let user_id = 123;
client.delete_registered_user(user_id).await?;
println!("Successfully deleted user with ID {}", user_id);§Related Methods
get_registered_user- Get user information before deletionadd_registered_user- Create a new userget_registered_user_summary- Check user’s assignments
Sourcepub async fn edit_registered_user(
&self,
registered_user_id: i64,
edit_data: &RegisteredUserEdit,
) -> Result<RegisteredUserResponse, Error>
pub async fn edit_registered_user( &self, registered_user_id: i64, edit_data: &RegisteredUserEdit, ) -> Result<RegisteredUserResponse, Error>
Updates registered user information.
This method allows you to modify the information of an existing registered user. Only the fields provided in the edit data will be updated; other fields remain unchanged.
§Arguments
registered_user_id- The ID of the registered user to updateedit_data- ARegisteredUserEditstruct containing the fields to update
§Returns
Returns a RegisteredUserResponse containing the updated user information.
§Errors
Returns an error if:
- Authentication fails or insufficient permissions
- The user ID is invalid or does not exist
- The edit data contains invalid values (e.g., invalid email format)
- The HTTP request fails
- The server returns an error status
- The response cannot be parsed
§Examples
let client = ApiClient::new().await?;
let user_id = 123;
let edit_data = RegisteredUserEdit {
name: Some("Jane Doe".to_string()),
};
let updated_user = client.edit_registered_user(user_id, &edit_data).await?;
println!("Updated user: {}", updated_user.name);§Related Methods
get_registered_user- Get current user informationadd_registered_user- Create a new userdelete_registered_user- Remove a user
Sourcepub async fn get_registered_user_summary(
&self,
registered_user_id: i64,
) -> Result<RegisteredUserSummary, Error>
pub async fn get_registered_user_summary( &self, registered_user_id: i64, ) -> Result<RegisteredUserSummary, Error>
Gets comprehensive summary information for a registered user including assets and distributions.
This method retrieves detailed summary information about a registered user, including their basic information, associated assets, assignment history, and distribution records. This provides a complete overview of the user’s activity and holdings in the system.
§Arguments
registered_user_id- The ID of the registered user to get summary for
§Returns
Returns a RegisteredUserSummary containing:
- Basic user information (name, email, etc.)
- List of associated GAIDs
- Asset assignments and their status
- Distribution history
- Balance information
- Activity timestamps
§Errors
Returns an error if:
- Authentication fails or insufficient permissions
- The user ID is invalid or does not exist
- The HTTP request fails
- The server returns an error status
- The response cannot be parsed
§Examples
let client = ApiClient::new().await?;
let user_id = 123;
let summary = client.get_registered_user_summary(user_id).await?;
println!("Asset UUID: {}", summary.asset_uuid);
println!("Asset ID: {}", summary.asset_id);
println!("Asset assignments: {}", summary.assignments.len());
println!("Distributions received: {}", summary.distributions.len());§Related Methods
get_registered_user- Get basic user informationget_registered_user_gaids- Get only GAIDsget_asset_assignments- Get assignments for specific asset
Sourcepub async fn get_registered_user_gaids(
&self,
registered_user_id: i64,
) -> Result<Vec<String>, Error>
pub async fn get_registered_user_gaids( &self, registered_user_id: i64, ) -> Result<Vec<String>, Error>
Gets all GAIDs (Green Address IDs) associated with a registered user.
This method retrieves a list of all GAIDs that are currently associated with the specified registered user. GAIDs are unique identifiers that can be used to receive assets and track ownership.
§Arguments
registered_user_id- The ID of the registered user to get GAIDs for
§Returns
Returns a vector of GAID strings associated with the user.
§Errors
Returns an error if:
- Authentication fails or insufficient permissions
- The user ID is invalid or does not exist
- The HTTP request fails
- The server returns an error status
- The response cannot be parsed
§Examples
let client = ApiClient::new().await?;
let user_id = 123;
let gaids = client.get_registered_user_gaids(user_id).await?;
println!("User {} has {} associated GAIDs:", user_id, gaids.len());
for gaid in gaids {
println!(" - {}", gaid);
}§Related Methods
add_gaid_to_registered_user- Associate a GAID with userset_default_gaid_for_registered_user- Set default GAIDget_gaid_registered_user- Find user by GAIDvalidate_gaid- Validate GAID format
Sourcepub async fn add_gaid_to_registered_user(
&self,
registered_user_id: i64,
gaid: &str,
) -> Result<(), Error>
pub async fn add_gaid_to_registered_user( &self, registered_user_id: i64, gaid: &str, ) -> Result<(), Error>
Associates a GAID with a registered user.
§Arguments
registered_user_id- The ID of the registered usergaid- The GAID to associate with the user
§Errors
Returns an error if:
- Authentication fails
- The HTTP request fails
- The server returns an error status
- The registered user ID is invalid
- The GAID is invalid or already associated
Sourcepub async fn set_default_gaid_for_registered_user(
&self,
registered_user_id: i64,
gaid: &str,
) -> Result<(), Error>
pub async fn set_default_gaid_for_registered_user( &self, registered_user_id: i64, gaid: &str, ) -> Result<(), Error>
Sets an existing GAID as the default for a registered user.
This method allows you to designate a specific GAID as the primary/default GAID for a registered user. The GAID must already be associated with the user.
§Arguments
registered_user_id- The ID of the registered usergaid- The GAID to set as default
§Returns
Returns Ok(()) if the operation is successful.
§Errors
Returns an error if:
- Authentication fails
- The HTTP request fails
- The server returns an error status
- The registered user ID is invalid
- The GAID is not associated with the user
Sourcepub async fn get_gaid_registered_user(
&self,
gaid: &str,
) -> Result<RegisteredUserResponse, Error>
pub async fn get_gaid_registered_user( &self, gaid: &str, ) -> Result<RegisteredUserResponse, Error>
Retrieves the registered user associated with a GAID
§Arguments
gaid- The GAID to look up
§Returns
Returns the registered user data if the GAID is associated with a user
§Errors
This function will return an error if:
- The GAID has no associated user
- The GAID is invalid
- Network or authentication errors occur
Sourcepub async fn get_gaid_balance(&self, gaid: &str) -> Result<Balance, Error>
pub async fn get_gaid_balance(&self, gaid: &str) -> Result<Balance, Error>
Gets the balance information for a specific GAID.
This method retrieves all asset balances associated with the given GAID, including confirmed balances and any lost outputs.
§Arguments
gaid- The GAID to query balance for
§Returns
Returns a Balance struct containing confirmed balances and lost outputs
§Errors
Returns an error if:
- The GAID is invalid
- Network or authentication errors occur
- The response cannot be parsed
§Examples
let client = ApiClient::new().await?;
let gaid = "GAbYScu6jkWUND2jo3L4KJxyvo55d";
let balance = client.get_gaid_balance(gaid).await?;
println!("GAID {} has {} balance entries", gaid, balance.len());
for entry in balance {
println!("Asset {}: {} units", entry.asset_id, entry.balance);
}Sourcepub async fn get_gaid_asset_balance(
&self,
gaid: &str,
asset_uuid: &str,
) -> Result<Ownership, Error>
pub async fn get_gaid_asset_balance( &self, gaid: &str, asset_uuid: &str, ) -> Result<Ownership, Error>
Retrieves the specific asset balance for a GAID
§Arguments
gaid- The GAID to queryasset_uuid- The UUID of the asset to query
§Returns
Returns the specific asset balance information
§Errors
Returns an error if:
- The GAID is invalid
- The asset UUID is invalid
- Network or authentication errors occur
- The response cannot be parsed
Sourcepub async fn get_categories(&self) -> Result<Vec<CategoryResponse>, Error>
pub async fn get_categories(&self) -> Result<Vec<CategoryResponse>, Error>
Gets a list of all categories.
§Returns
Returns a vector of CategoryResponse objects
§Errors
Returns an error if:
- Authentication fails
- The HTTP request fails
- The response cannot be parsed
§Examples
let client = ApiClient::new().await?;
let categories = client.get_categories().await?;
for category in categories {
println!("Category: {} (ID: {})", category.name, category.id);
if let Some(desc) = category.description {
println!(" Description: {}", desc);
}
}Sourcepub async fn add_category(
&self,
new_category: &CategoryAdd,
) -> Result<CategoryResponse, Error>
pub async fn add_category( &self, new_category: &CategoryAdd, ) -> Result<CategoryResponse, Error>
Creates a new category for organizing users and assets.
This method creates a new category that can be used to group registered users and assets for organizational purposes. Categories help manage permissions and provide logical groupings for assets and users.
§Arguments
new_category- ACategoryAddstruct containing the category information to create
§Returns
Returns a CategoryResponse containing the created category information including
the assigned category ID.
§Errors
Returns an error if:
- Authentication fails or insufficient permissions
- The category data is invalid (e.g., missing name, invalid characters)
- A category with the same name already exists
- The HTTP request fails
- The server returns an error status
- The response cannot be parsed
§Examples
let client = ApiClient::new().await?;
let new_category = CategoryAdd {
name: "Premium Users".to_string(),
description: Some("High-value users with special privileges".to_string()),
};
let created_category = client.add_category(&new_category).await?;
println!("Created category: {} with ID {}", created_category.name, created_category.id);§Related Methods
get_categories- List all categoriesedit_category- Update category informationdelete_category- Remove a categoryadd_registered_user_to_category- Add users to category
Sourcepub async fn get_category(
&self,
category_id: i64,
) -> Result<CategoryResponse, Error>
pub async fn get_category( &self, category_id: i64, ) -> Result<CategoryResponse, Error>
Gets a specific category by ID.
This method retrieves detailed information about a specific category, including its name, description, and associated users and assets.
§Arguments
category_id- The ID of the category to retrieve
§Returns
Returns a CategoryResponse containing the category information including:
- Category ID, name, and description
- List of associated registered users
- List of associated assets
- Creation and modification timestamps
§Errors
Returns an error if:
- Authentication fails or insufficient permissions
- The category ID is invalid or does not exist
- The HTTP request fails
- The server returns an error status
- The response cannot be parsed
§Examples
let client = ApiClient::new().await?;
let category_id = 1;
let category = client.get_category(category_id).await?;
println!("Category: {} (ID: {})", category.name, category.id);
if let Some(desc) = category.description {
println!("Description: {}", desc);
}
println!("Users: {}, Assets: {}", category.registered_users.len(), category.assets.len());§Related Methods
get_categories- List all categoriesadd_category- Create a new categoryedit_category- Update category informationdelete_category- Remove a category
Sourcepub async fn edit_category(
&self,
category_id: i64,
edit_category: &CategoryEdit,
) -> Result<CategoryResponse, Error>
pub async fn edit_category( &self, category_id: i64, edit_category: &CategoryEdit, ) -> Result<CategoryResponse, Error>
Updates category information.
This method allows you to modify the information of an existing category. Only the fields provided in the edit data will be updated; other fields remain unchanged.
§Arguments
category_id- The ID of the category to updateedit_category- ACategoryEditstruct containing the fields to update
§Returns
Returns a CategoryResponse containing the updated category information.
§Errors
Returns an error if:
- Authentication fails or insufficient permissions
- The category ID is invalid or does not exist
- The edit data contains invalid values (e.g., empty name, invalid characters)
- A category with the new name already exists (if name is being changed)
- The HTTP request fails
- The server returns an error status
- The response cannot be parsed
§Examples
let client = ApiClient::new().await?;
let category_id = 1;
let edit_data = CategoryEdit {
name: Some("VIP Users".to_string()),
description: Some("Very important users with premium access".to_string()),
};
let updated_category = client.edit_category(category_id, &edit_data).await?;
println!("Updated category: {}", updated_category.name);§Related Methods
get_category- Get current category informationadd_category- Create a new categorydelete_category- Remove a category
Sourcepub async fn delete_category(&self, category_id: i64) -> Result<(), Error>
pub async fn delete_category(&self, category_id: i64) -> Result<(), Error>
Removes a category from the system.
This method permanently deletes a category. All users and assets associated with the category will be disassociated, but the users and assets themselves are not deleted. This operation cannot be undone.
§Arguments
category_id- The ID of the category to delete
§Returns
Returns Ok(()) on successful deletion.
§Errors
Returns an error if:
- Authentication fails or insufficient permissions
- The category ID is invalid or does not exist
- The category is still in use and cannot be deleted (depending on system configuration)
- The HTTP request fails
- The server returns an error status
§Examples
let client = ApiClient::new().await?;
let category_id = 1;
client.delete_category(category_id).await?;
println!("Successfully deleted category with ID {}", category_id);§Related Methods
get_category- Get category information before deletionadd_category- Create a new categoryremove_registered_user_from_category- Remove users firstremove_asset_from_category- Remove assets first
Sourcepub async fn add_registered_user_to_category(
&self,
category_id: i64,
user_id: i64,
) -> Result<CategoryResponse, Error>
pub async fn add_registered_user_to_category( &self, category_id: i64, user_id: i64, ) -> Result<CategoryResponse, Error>
Associates a registered user with a category.
This method adds a registered user to a category, allowing for organized grouping of users. Users can belong to multiple categories, and categories can contain multiple users.
§Arguments
category_id- The ID of the category to add the user touser_id- The ID of the registered user to add to the category
§Returns
Returns a CategoryResponse containing the updated category information including
the newly added user.
§Errors
Returns an error if:
- Authentication fails or insufficient permissions
- The category ID is invalid or does not exist
- The user ID is invalid or does not exist
- The user is already associated with the category
- The HTTP request fails
- The server returns an error status
- The response cannot be parsed
§Examples
let client = ApiClient::new().await?;
let category_id = 1;
let user_id = 123;
let updated_category = client.add_registered_user_to_category(category_id, user_id).await?;
println!("Added user {} to category '{}'", user_id, updated_category.name);
println!("Category now has {} users", updated_category.registered_users.len());§Related Methods
remove_registered_user_from_category- Remove user from categoryget_category- Get category information including usersget_registered_user- Get user information
Sourcepub async fn remove_registered_user_from_category(
&self,
category_id: i64,
user_id: i64,
) -> Result<CategoryResponse, Error>
pub async fn remove_registered_user_from_category( &self, category_id: i64, user_id: i64, ) -> Result<CategoryResponse, Error>
Removes a registered user from a category.
This method disassociates a registered user from a category. The user remains in the system but is no longer part of the specified category. This does not affect the user’s association with other categories.
§Arguments
category_id- The ID of the category to remove the user fromuser_id- The ID of the registered user to remove from the category
§Returns
Returns a CategoryResponse containing the updated category information without
the removed user.
§Errors
Returns an error if:
- Authentication fails or insufficient permissions
- The category ID is invalid or does not exist
- The user ID is invalid or does not exist
- The user is not currently associated with the category
- The HTTP request fails
- The server returns an error status
- The response cannot be parsed
§Examples
let client = ApiClient::new().await?;
let category_id = 1;
let user_id = 123;
let updated_category = client.remove_registered_user_from_category(category_id, user_id).await?;
println!("Removed user {} from category '{}'", user_id, updated_category.name);
println!("Category now has {} users", updated_category.registered_users.len());§Related Methods
add_registered_user_to_category- Add user to categoryget_category- Get category information including usersget_registered_user- Get user information
Sourcepub async fn add_asset_to_category(
&self,
category_id: i64,
asset_uuid: &str,
) -> Result<CategoryResponse, Error>
pub async fn add_asset_to_category( &self, category_id: i64, asset_uuid: &str, ) -> Result<CategoryResponse, Error>
Associates an asset with a category.
This method adds an asset to a category, allowing for organized grouping of assets. Assets can belong to multiple categories, and categories can contain multiple assets. This helps with asset management and permission organization.
§Arguments
category_id- The ID of the category to add the asset toasset_uuid- The UUID of the asset to add to the category
§Returns
Returns a CategoryResponse containing the updated category information including
the newly added asset.
§Errors
Returns an error if:
- Authentication fails or insufficient permissions
- The category ID is invalid or does not exist
- The asset UUID is invalid or does not exist
- The asset is already associated with the category
- The HTTP request fails
- The server returns an error status
- The response cannot be parsed
§Examples
let client = ApiClient::new().await?;
let category_id = 1;
let asset_uuid = "550e8400-e29b-41d4-a716-446655440000";
let updated_category = client.add_asset_to_category(category_id, asset_uuid).await?;
println!("Added asset {} to category '{}'", asset_uuid, updated_category.name);
println!("Category now has {} assets", updated_category.assets.len());§Related Methods
remove_asset_from_category- Remove asset from categoryget_category- Get category information including assetsget_asset- Get asset information
Sourcepub async fn remove_asset_from_category(
&self,
category_id: i64,
asset_uuid: &str,
) -> Result<CategoryResponse, Error>
pub async fn remove_asset_from_category( &self, category_id: i64, asset_uuid: &str, ) -> Result<CategoryResponse, Error>
Removes an asset from a category.
This method disassociates an asset from a category. The asset remains in the system but is no longer part of the specified category. This does not affect the asset’s association with other categories.
§Arguments
category_id- The ID of the category to remove the asset fromasset_uuid- The UUID of the asset to remove from the category
§Returns
Returns a CategoryResponse containing the updated category information without
the removed asset.
§Errors
Returns an error if:
- Authentication fails or insufficient permissions
- The category ID is invalid or does not exist
- The asset UUID is invalid or does not exist
- The asset is not currently associated with the category
- The HTTP request fails
- The server returns an error status
- The response cannot be parsed
§Examples
let client = ApiClient::new().await?;
let category_id = 1;
let asset_uuid = "550e8400-e29b-41d4-a716-446655440000";
let updated_category = client.remove_asset_from_category(category_id, asset_uuid).await?;
println!("Removed asset {} from category '{}'", asset_uuid, updated_category.name);
println!("Category now has {} assets", updated_category.assets.len());§Related Methods
add_asset_to_category- Add asset to categoryget_category- Get category information including assetsget_asset- Get asset information
Sourcepub async fn validate_gaid(
&self,
gaid: &str,
) -> Result<ValidateGaidResponse, Error>
pub async fn validate_gaid( &self, gaid: &str, ) -> Result<ValidateGaidResponse, Error>
Validates a GAID (Green Address ID).
§Arguments
gaid- The GAID string to validate
§Returns
Returns a ValidateGaidResponse indicating whether the GAID is valid
§Errors
Returns an error if:
- Authentication fails
- The HTTP request fails
- The response cannot be parsed
§Examples
let client = ApiClient::new().await?;
let gaid = "GAbYScu6jkWUND2jo3L4KJxyvo55d";
let validation = client.validate_gaid(gaid).await?;
if validation.is_valid {
println!("GAID {} is valid", gaid);
} else {
println!("GAID {} is invalid: {:?}", gaid, validation.error);
}Sourcepub async fn get_gaid_address(
&self,
gaid: &str,
) -> Result<AddressGaidResponse, Error>
pub async fn get_gaid_address( &self, gaid: &str, ) -> Result<AddressGaidResponse, Error>
Gets the address associated with a GAID.
§Arguments
gaid- The GAID to get the address for
§Returns
Returns an AddressGaidResponse containing the address
§Errors
Returns an error if:
- The GAID is invalid
- Authentication fails
- The HTTP request fails
- The response cannot be parsed
§Examples
let client = ApiClient::new().await?;
let gaid = "GAbYScu6jkWUND2jo3L4KJxyvo55d";
let address_response = client.get_gaid_address(gaid).await?;
println!("Address for GAID {}: {}", gaid, address_response.address);Sourcepub async fn get_managers(&self) -> Result<Vec<Manager>, Error>
pub async fn get_managers(&self) -> Result<Vec<Manager>, Error>
Gets a list of all managers.
§Returns
Returns a vector of Manager objects
§Errors
Returns an error if:
- Authentication fails
- The HTTP request fails
- The response cannot be parsed
§Examples
let client = ApiClient::new().await?;
let managers = client.get_managers().await?;
for manager in managers {
println!("Manager: {} (ID: {})", manager.username, manager.id);
}Sourcepub async fn create_manager(
&self,
new_manager: &ManagerCreate,
) -> Result<Manager, Error>
pub async fn create_manager( &self, new_manager: &ManagerCreate, ) -> Result<Manager, Error>
Creates a new manager.
§Arguments
new_manager- The manager creation request containing username and password
§Returns
Returns the created Manager object
§Errors
Returns an error if:
- Authentication fails
- The HTTP request fails
- The manager creation request is invalid
- The response cannot be parsed
§Examples
let client = ApiClient::new().await?;
let new_manager = ManagerCreate {
username: "new_manager".to_string(),
password: "secure_password".to_string(),
};
let manager = client.create_manager(&new_manager).await?;
println!("Created manager: {} (ID: {})", manager.username, manager.id);Sourcepub async fn get_asset_assignments(
&self,
asset_uuid: &str,
) -> Result<Vec<Assignment>, Error>
pub async fn get_asset_assignments( &self, asset_uuid: &str, ) -> Result<Vec<Assignment>, Error>
Gets all assignments for a specific asset.
§Arguments
asset_uuid- The UUID of the asset to get assignments for
§Returns
Returns a vector of Assignment objects
§Errors
Returns an error if:
- Authentication fails
- The HTTP request fails
- The asset UUID is invalid
- The response cannot be parsed
§Examples
let client = ApiClient::new().await?;
let asset_uuid = "550e8400-e29b-41d4-a716-446655440000";
let assignments = client.get_asset_assignments(asset_uuid).await?;
for assignment in assignments {
println!("Assignment ID: {}, Amount: {}", assignment.id, assignment.amount);
}Sourcepub async fn create_asset_assignments(
&self,
asset_uuid: &str,
requests: &[CreateAssetAssignmentRequest],
) -> Result<Vec<Assignment>, Error>
pub async fn create_asset_assignments( &self, asset_uuid: &str, requests: &[CreateAssetAssignmentRequest], ) -> Result<Vec<Assignment>, Error>
Creates multiple asset assignments in batch.
This method creates multiple asset assignments for the specified asset. Each assignment allocates a specific amount of the asset to a registered user. The assignments are created individually due to API limitations, but this method handles the batch processing automatically.
§Arguments
asset_uuid- The UUID of the asset to create assignments forrequests- A slice ofCreateAssetAssignmentRequeststructs containing assignment details
§Returns
Returns a vector of Assignment structs representing the created assignments with their
assigned IDs and status information.
§Errors
Returns an error if:
- Authentication fails or insufficient permissions
- The asset UUID is invalid or does not exist
- Any assignment request contains invalid data (e.g., invalid user ID, negative amount)
- Insufficient asset balance for the total requested assignments
- Any individual assignment creation fails
- The HTTP request fails
- The server returns an error status
- The response cannot be parsed
§Examples
let client = ApiClient::new().await?;
let asset_uuid = "550e8400-e29b-41d4-a716-446655440000";
let requests = vec![
CreateAssetAssignmentRequest {
registered_user: 123,
amount: 1000,
vesting_timestamp: None,
ready_for_distribution: false,
},
CreateAssetAssignmentRequest {
registered_user: 456,
amount: 500,
vesting_timestamp: None,
ready_for_distribution: true,
},
];
let assignments = client.create_asset_assignments(asset_uuid, &requests).await?;
println!("Created {} assignments", assignments.len());
for assignment in assignments {
println!("Assignment {}: {} units to user {}",
assignment.id, assignment.amount, assignment.registered_user);
}§Related Methods
get_asset_assignments- List all assignments for an assetdelete_asset_assignment- Remove an assignmentedit_asset_assignment- Update assignment detailsset_assignment_ready_for_distribution- Mark for distribution
Sourcepub async fn get_asset_assignment(
&self,
asset_uuid: &str,
assignment_id: &str,
) -> Result<Assignment, Error>
pub async fn get_asset_assignment( &self, asset_uuid: &str, assignment_id: &str, ) -> Result<Assignment, Error>
Gets a specific asset assignment by asset UUID and assignment ID.
This method sends a GET request to retrieve detailed information about a specific asset assignment. Asset assignments represent the allocation of assets to users or entities, including information such as the assigned amount, recipient details, and assignment status.
§Arguments
asset_uuid- The UUID of the asset for which to retrieve the assignmentassignment_id- The ID of the specific assignment to retrieve
§Returns
Returns an Assignment struct containing the assignment details including:
- Assignment ID and amount
- Recipient information
- Assignment status and metadata
- Creation and modification timestamps
§Errors
Returns an error if:
- Authentication fails
- The HTTP request fails
- The server returns an error status
- The asset UUID is invalid or does not exist
- The assignment ID is invalid or does not exist
- The assignment is not accessible to the current user
- The response cannot be parsed as a valid Assignment
§Example
let client = ApiClient::new().await?;
// Retrieve assignment with ID "123" for asset "550e8400-e29b-41d4-a716-446655440000"
let asset_uuid = "550e8400-e29b-41d4-a716-446655440000";
let assignment_id = "123";
let assignment = client.get_asset_assignment(asset_uuid, assignment_id).await?;
println!("Assignment ID: {}", assignment.id);
println!("Assigned amount: {}", assignment.amount);
println!("Registered user: {}", assignment.registered_user);Sourcepub async fn create_distribution(
&self,
asset_uuid: &str,
assignments: Vec<AssetDistributionAssignment>,
) -> Result<DistributionResponse, AmpError>
pub async fn create_distribution( &self, asset_uuid: &str, assignments: Vec<AssetDistributionAssignment>, ) -> Result<DistributionResponse, AmpError>
Creates a distribution for an asset with the specified assignments.
This method initiates the distribution creation process by sending assignment details to the AMP API. The API will return a distribution UUID and address mappings that can be used for subsequent transaction creation and confirmation steps.
§Arguments
asset_uuid- The UUID of the asset to distributeassignments- A vector ofAssetDistributionAssignmentstructs containing user IDs, addresses, and amounts
§Returns
Returns a DistributionResponse containing:
distribution_uuid- Unique identifier for the created distributionmap_address_amount- Mapping of addresses to amounts to be distributedmap_address_asset- Mapping of addresses to asset IDsasset_id- The asset ID for the distribution
§Errors
Returns an AmpError if:
- Authentication fails or insufficient permissions
- The asset UUID is invalid or does not exist
- Assignment data is invalid (e.g., invalid user IDs, negative amounts, invalid addresses)
- Insufficient asset balance for the requested distribution
- The HTTP request fails
- The server returns an error status
- The response cannot be parsed
§Examples
let client = ApiClient::new().await.map_err(AmpError::from)?;
let asset_uuid = "550e8400-e29b-41d4-a716-446655440000";
let assignments = vec![
AssetDistributionAssignment {
user_id: "user123".to_string(),
address: "lq1qq2xvpcvfup5j8zscjq05u2wxxjcyewk7979f9lq".to_string(),
amount: 100.0,
},
AssetDistributionAssignment {
user_id: "user456".to_string(),
address: "lq1qq3xvpcvfup5j8zscjq05u2wxxjcyewk7979f9lq".to_string(),
amount: 50.0,
},
];
let distribution_response = client.create_distribution(asset_uuid, assignments).await?;
println!("Created distribution: {}", distribution_response.distribution_uuid);
println!("Asset ID: {}", distribution_response.asset_id);§Related Methods
get_asset_assignments- List assignments for an assetcreate_asset_assignments- Create new assignments
Sourcepub async fn confirm_distribution(
&self,
asset_uuid: &str,
distribution_uuid: &str,
tx_data: AmpTxData,
change_data: Vec<Unspent>,
) -> Result<(), AmpError>
pub async fn confirm_distribution( &self, asset_uuid: &str, distribution_uuid: &str, tx_data: AmpTxData, change_data: Vec<Unspent>, ) -> Result<(), AmpError>
Confirms a distribution with transaction and change data.
This method submits the final confirmation for a distribution by providing the transaction details and any change UTXOs to the AMP API. This completes the distribution workflow after the transaction has been broadcast and confirmed on the blockchain.
§Arguments
asset_uuid- The UUID of the asset being distributeddistribution_uuid- The UUID of the distribution to confirm (fromcreate_distributionresponse)tx_data- Transaction data containing details and txid from the blockchainchange_data- Vector of change UTXOs from the transaction
§Errors
Returns an error if:
- Authentication fails
- The asset UUID or distribution UUID is invalid
- The transaction data is invalid or incomplete
- The HTTP request fails
- The server returns an error status
- The response cannot be parsed
§Examples
let asset_uuid = "550e8400-e29b-41d4-a716-446655440000";
let distribution_uuid = "dist-550e8400-e29b-41d4-a716-446655440000";
// Transaction data for AMP API confirmation
let tx_data = AmpTxData {
details: serde_json::json!([{
"account": "",
"address": "lq1qq2xvpcvfup5j8zscjq05u2wxxjcyewk7979f9lq",
"category": "send",
"amount": -100.0,
"vout": 0,
"fee": -0.001
}]),
txid: "abc123def456...".to_string(),
};
// Change UTXOs from Elements node listunspent call
let change_data = vec![
Unspent {
txid: "abc123def456...".to_string(),
vout: 1,
amount: 25.0,
asset: "asset_id_hex".to_string(),
address: "change_address".to_string(),
spendable: true,
confirmations: Some(2),
scriptpubkey: Some("76a914...88ac".to_string()),
redeemscript: None,
witnessscript: None,
amountblinder: None,
assetblinder: None,
}
];
client.confirm_distribution(asset_uuid, distribution_uuid, tx_data, change_data).await?;
println!("Distribution confirmed successfully");§Related Methods
create_distribution- Create a new distributionget_asset_assignments- List assignments for an asset
Sourcepub async fn cancel_distribution(
&self,
asset_uuid: &str,
distribution_uuid: &str,
) -> Result<(), AmpError>
pub async fn cancel_distribution( &self, asset_uuid: &str, distribution_uuid: &str, ) -> Result<(), AmpError>
Cancels an in-progress distribution for an asset.
This method cancels a distribution that is currently in progress (unconfirmed status). Once a distribution is cancelled, it cannot be confirmed and the assigned amounts become available for new distributions.
§Arguments
asset_uuid- The UUID of the assetdistribution_uuid- The UUID of the distribution to cancel
§Returns
Returns Ok(()) if the distribution was successfully cancelled.
§Errors
Returns an error if:
- Authentication fails
- The HTTP request fails
- The server returns an error status
- The distribution is not found
- The distribution is already confirmed and cannot be cancelled
§Examples
use amp_rs::ApiClient;
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let client = ApiClient::new().await?;
client.cancel_distribution(
"asset-uuid-123",
"distribution-uuid-456"
).await?;
println!("Distribution cancelled successfully");
Ok(())Sourcepub async fn get_asset_distributions(
&self,
asset_uuid: &str,
) -> Result<Vec<Distribution>, Error>
pub async fn get_asset_distributions( &self, asset_uuid: &str, ) -> Result<Vec<Distribution>, Error>
Gets all distributions for a specific asset.
This method retrieves all distributions (both confirmed and unconfirmed) for the specified asset. This is useful for checking if there are any in-progress distributions before deleting an asset.
§Arguments
asset_uuid- The UUID of the asset to get distributions for
§Returns
Returns a vector of Distribution objects for the asset.
§Errors
Returns an error if:
- Authentication fails
- The HTTP request fails
- The server returns an error status
- The response cannot be parsed
§Examples
use amp_rs::ApiClient;
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let client = ApiClient::new().await?;
let distributions = client.get_asset_distributions("asset-uuid-123").await?;
for distribution in distributions {
println!("Distribution: {} - Status: {:?}",
distribution.distribution_uuid,
distribution.distribution_status);
}
Ok(())
}Sourcepub async fn get_asset_distribution(
&self,
asset_uuid: &str,
distribution_uuid: &str,
) -> Result<Distribution, Error>
pub async fn get_asset_distribution( &self, asset_uuid: &str, distribution_uuid: &str, ) -> Result<Distribution, Error>
Gets a specific distribution by UUID for an asset.
This method retrieves detailed information about a specific distribution, including its status, UUID, and associated transactions.
§Arguments
asset_uuid- The UUID of the assetdistribution_uuid- The UUID of the distribution to retrieve
§Returns
Returns a Distribution struct containing:
distribution_uuid- The unique identifier for the distributiondistribution_status- Current status of the distributiontransactions- List of transactions associated with the distribution
§Errors
Returns an error if:
- Authentication fails
- The HTTP request fails
- The server returns an error status
- The response cannot be parsed as JSON
- The asset UUID or distribution UUID is empty
§Examples
let client = ApiClient::new().await?;
let distribution = client.get_asset_distribution(
"asset-uuid-123",
"distribution-uuid-456"
).await?;
println!("Distribution: {} - Status: {:?}",
distribution.distribution_uuid,
distribution.distribution_status);§Related Methods
get_asset_distributions- List all distributions for an assetcreate_distribution- Create a new distributionconfirm_distribution- Confirm a distributioncancel_distribution- Cancel a distribution
Sourcepub async fn reissue_request(
&self,
asset_uuid: &str,
amount_to_reissue: i64,
) -> Result<ReissueRequestResponse, AmpError>
pub async fn reissue_request( &self, asset_uuid: &str, amount_to_reissue: i64, ) -> Result<ReissueRequestResponse, AmpError>
Requests reissuance data for an asset
This method creates a reissuance request with the AMP API and returns the necessary data to execute the reissuance transaction, including asset information, amount, and required UTXOs.
§Arguments
asset_uuid- The UUID of the asset to reissueamount_to_reissue- The amount to reissue (in satoshis for the asset)
§Returns
Returns a ReissueRequestResponse containing:
command- The command type (“reissue”)min_supported_client_script_version- Minimum script version requiredbase_url- Base URL for the AMP APIasset_uuid- The asset UUIDasset_id- The asset ID (hex string)amount- The amount to reissuereissuance_utxos- List of required reissuance token UTXOs
§Errors
Returns an AmpError if:
- Authentication fails or insufficient permissions
- The asset UUID is invalid or does not exist
- The asset is not reissuable
- Insufficient reissuance tokens are available
- The HTTP request fails
- The server returns an error status
- The response cannot be parsed
§Examples
let client = ApiClient::new().await.map_err(AmpError::from)?;
let asset_uuid = "550e8400-e29b-41d4-a716-446655440000";
let amount = 1000000; // 0.01 of an asset with 8 decimals
let response = client.reissue_request(asset_uuid, amount).await?;
println!("Reissuance request created for asset: {}", response.asset_id);
println!("Amount to reissue: {}", response.amount);§Related Methods
reissue_confirm- Confirm a completed reissuancereissue_asset- Complete reissuance workflow
Sourcepub async fn reissue_confirm(
&self,
asset_uuid: &str,
details: Value,
listissuances: Vec<Value>,
reissuance_output: Value,
) -> Result<ReissueResponse, AmpError>
pub async fn reissue_confirm( &self, asset_uuid: &str, details: Value, listissuances: Vec<Value>, reissuance_output: Value, ) -> Result<ReissueResponse, AmpError>
Confirms a completed reissuance transaction
This method confirms a reissuance transaction that has been broadcast to the Elements network. It provides the transaction details and issuance information to the AMP API to register the reissuance.
§Arguments
asset_uuid- The UUID of the asset that was reissueddetails- Transaction details fromgettransactionRPC call (as JSON Value)listissuances- List of issuances fromlistissuancesRPC call for this transactionreissuance_output- Reissuance output containing txid and vin (as JSON Value)
§Returns
Returns a ReissueResponse containing:
txid- The transaction IDvin- The input index of the reissuancereissuance_amount- The amount that was reissued
§Errors
Returns an AmpError if:
- Authentication fails or insufficient permissions
- The asset UUID is invalid or does not exist
- The transaction data is invalid or incomplete
- The reissuance transaction is not valid
- The HTTP request fails
- The server returns an error status
- The response cannot be parsed
§Examples
let client = ApiClient::new().await.map_err(AmpError::from)?;
let rpc = ElementsRpc::from_env()?;
let asset_uuid = "550e8400-e29b-41d4-a716-446655440000";
let txid = "abc123...";
// Get transaction details
let tx_detail = rpc.get_transaction(txid).await?;
let details = serde_json::to_value(&tx_detail.details).unwrap();
// Get issuances for this transaction
let issuances = rpc.list_issuances(None).await?;
let listissuances: Vec<_> = issuances
.into_iter()
.filter(|i| i.get("txid").and_then(|v| v.as_str()) == Some(txid))
.collect();
let reissuance_output = json!({"txid": txid, "vin": 0});
let response = client.reissue_confirm(
asset_uuid,
details,
listissuances,
reissuance_output,
).await?;
println!("Reissuance confirmed: txid={}, vin={}", response.txid, response.vin);§Related Methods
reissue_request- Create a reissuance requestreissue_asset- Complete reissuance workflow
Sourcepub async fn burn_request(
&self,
asset_uuid: &str,
amount: i64,
) -> Result<BurnCreate, AmpError>
pub async fn burn_request( &self, asset_uuid: &str, amount: i64, ) -> Result<BurnCreate, AmpError>
Creates a burn request for an asset
This method requests the data needed to burn (destroy) a specific amount of an asset. The response contains UTXOs that need to be available in the wallet for the burn operation.
§Arguments
asset_uuid- The UUID of the asset to burnamount- The amount to burn (in satoshis for the asset)
§Returns
Returns a BurnCreate containing:
- Asset information (UUID, asset ID)
- Amount to burn
- Required UTXOs that must be available in the wallet
§Errors
Returns an AmpError if:
- The asset UUID is invalid or empty
- The amount is invalid (non-positive)
- Authentication fails or insufficient permissions
- The asset does not exist
- The HTTP request fails
- The server returns an error status
§Examples
let client = ApiClient::new().await?;
let asset_uuid = "550e8400-e29b-41d4-a716-446655440000";
let amount = 1000000; // 0.01 of an asset with 8 decimals
let response = client.burn_request(asset_uuid, amount).await?;
println!("Burn request created for asset: {}", response.asset_id);
println!("Amount to burn: {}", response.amount);
println!("Required UTXOs: {:?}", response.utxos);§Related Methods
burn_confirm- Confirm a burn transactionburn_asset- Complete burn workflow
Sourcepub async fn burn_confirm(
&self,
asset_uuid: &str,
tx_data: Value,
change_data: Vec<Value>,
) -> Result<(), AmpError>
pub async fn burn_confirm( &self, asset_uuid: &str, tx_data: Value, change_data: Vec<Value>, ) -> Result<(), AmpError>
Confirms a completed burn transaction
This method confirms a burn transaction that has been broadcast to the Elements network. It provides the transaction details and change data to complete the burn registration with the AMP API.
§Arguments
asset_uuid- The UUID of the asset that was burnedtx_data- Transaction data fromgettransactionRPC call (as JSON Value, containing at least txid)change_data- Change data fromlistunspentRPC call filtered byasset_idand txid (as JSON Values)
§Returns
Returns Ok(()) on success (the API returns an empty response with status 200)
§Errors
Returns an AmpError if:
- Authentication fails or insufficient permissions
- The asset UUID is invalid or does not exist
- The transaction data is invalid or incomplete
- The burn transaction is not valid
- The HTTP request fails
- The server returns an error status
§Examples
let client = ApiClient::new().await?;
let asset_uuid = "550e8400-e29b-41d4-a716-446655440000";
let tx_data = serde_json::json!({
"txid": "abc123def456..."
});
let change_data = vec![serde_json::json!({
"txid": "abc123def456...",
"vout": 0,
"address": "tlq1qq...",
"amount": 100.0,
"asset": "asset_id_here",
"spendable": true
})];
client.burn_confirm(asset_uuid, tx_data, change_data).await?;
println!("Burn confirmed successfully");§Related Methods
burn_request- Create a burn requestburn_asset- Complete burn workflow
Sourcepub async fn manager_remove_asset(
&self,
manager_id: i64,
asset_uuid: &str,
) -> Result<(), Error>
pub async fn manager_remove_asset( &self, manager_id: i64, asset_uuid: &str, ) -> Result<(), Error>
Removes a manager’s permissions to modify a specific asset.
This method revokes a manager’s access to a specific asset, preventing them from performing asset management operations such as creating assignments, managing ownership, or modifying asset properties. The manager will no longer be able to access this asset through their management interface.
§Arguments
manager_id- The ID of the manager to remove permissions fromasset_uuid- The UUID of the asset to remove permissions for
§Returns
Returns Ok(()) on successful permission removal.
§Errors
Returns an error if:
- Authentication fails or insufficient permissions
- The manager ID is invalid or does not exist
- The asset UUID is invalid or does not exist
- The manager does not currently have permissions for this asset
- The HTTP request fails
- The server returns an error status
§Examples
let client = ApiClient::new().await?;
let manager_id = 123;
let asset_uuid = "550e8400-e29b-41d4-a716-446655440000";
client.manager_remove_asset(manager_id, asset_uuid).await?;
println!("Removed asset {} from manager {}", asset_uuid, manager_id);§Related Methods
add_asset_to_manager- Grant manager permissions for an assetget_manager- Get manager information including current assetsrevoke_manager- Remove all asset permissions from managerlock_manager- Lock manager account
Sourcepub async fn revoke_manager(&self, manager_id: i64) -> Result<(), Error>
pub async fn revoke_manager(&self, manager_id: i64) -> Result<(), Error>
Revokes all asset permissions for a manager.
This method first retrieves the manager’s current asset permissions, then removes the manager’s access to each asset they currently have access to.
§Arguments
manager_id- The ID of the manager to revoke permissions for
§Errors
Returns an error if:
- Authentication fails
- The HTTP request fails
- The server returns an error status
- Any individual asset removal fails
Sourcepub async fn get_current_manager_raw(&self) -> Result<Value, Error>
pub async fn get_current_manager_raw(&self) -> Result<Value, Error>
Gets the current manager information as raw JSON.
This method calls the /managers/me endpoint to retrieve information
about the currently authenticated manager.
§Errors
Returns an error if:
- Authentication fails
- The HTTP request fails
- The server returns an error status
- The response cannot be parsed as JSON
Sourcepub async fn lock_manager(&self, manager_id: i64) -> Result<(), Error>
pub async fn lock_manager(&self, manager_id: i64) -> Result<(), Error>
Locks a manager account to prevent further operations.
This method sends a PUT request to lock the specified manager, preventing any further operations on that manager account. This is typically used for security purposes or when a manager needs to be temporarily disabled.
§Arguments
manager_id- The ID of the manager to lock
§Returns
Returns Ok(()) if the manager was successfully locked.
§Errors
Returns an error if:
- Authentication fails
- The HTTP request fails
- The server returns an error status
- The manager ID is invalid or does not exist
- The manager is already locked
§Example
let client = ApiClient::new().await?;
// Lock manager with ID 123
client.lock_manager(123).await?;
println!("Manager 123 has been locked successfully");Sourcepub async fn add_asset_to_manager(
&self,
manager_id: i64,
asset_uuid: &str,
) -> Result<(), Error>
pub async fn add_asset_to_manager( &self, manager_id: i64, asset_uuid: &str, ) -> Result<(), Error>
Authorizes a manager to manage a specific asset.
This method sends a PUT request to authorize the specified manager to manage the given asset. Once authorized, the manager will have permissions to perform operations on the asset such as creating assignments, managing ownership, and other asset-related operations.
§Arguments
manager_id- The ID of the manager to authorizeasset_uuid- The UUID of the asset to add to the manager’s authorized assets
§Returns
Returns Ok(()) if the manager was successfully authorized for the asset.
§Errors
Returns an error if:
- Authentication fails or insufficient permissions
- The HTTP request fails
- The server returns an error status
- The manager ID is invalid or does not exist
- The asset UUID is invalid or does not exist
- The manager is already authorized for this asset
- The manager is locked and cannot be modified
§Examples
let client = ApiClient::new().await?;
// Authorize manager 123 to manage asset with UUID "550e8400-e29b-41d4-a716-446655440000"
let manager_id = 123;
let asset_uuid = "550e8400-e29b-41d4-a716-446655440000";
client.add_asset_to_manager(manager_id, asset_uuid).await?;
println!("Manager {} is now authorized to manage asset {}", manager_id, asset_uuid);§Related Methods
manager_remove_asset- Remove manager permissions for an assetget_manager- Get manager information including current assetsget_manager_permissions- Get manager’s current permissionslock_manager- Lock manager account
Sourcepub async fn delete_asset_assignment(
&self,
asset_uuid: &str,
assignment_id: &str,
) -> Result<(), Error>
pub async fn delete_asset_assignment( &self, asset_uuid: &str, assignment_id: &str, ) -> Result<(), Error>
Deletes a specific asset assignment.
§Arguments
asset_uuid- The UUID of the assetassignment_id- The ID of the assignment to delete
§Errors
Returns an error if:
- Authentication fails
- The HTTP request fails
- The server returns an error status Removes an asset assignment.
This method permanently deletes an asset assignment, returning the allocated assets back to the available pool. This operation cannot be undone. If the assignment has already been distributed, this operation may fail.
§Arguments
asset_uuid- The UUID of the asset containing the assignmentassignment_id- The ID of the assignment to delete
§Returns
Returns Ok(()) on successful deletion.
§Errors
Returns an error if:
- Authentication fails or insufficient permissions
- The asset UUID is invalid or does not exist
- The assignment ID is invalid or does not exist
- The assignment has already been distributed and cannot be deleted
- The assignment is locked and cannot be modified
- The HTTP request fails
- The server returns an error status
§Examples
let client = ApiClient::new().await?;
let asset_uuid = "550e8400-e29b-41d4-a716-446655440000";
let assignment_id = "123";
client.delete_asset_assignment(asset_uuid, assignment_id).await?;
println!("Successfully deleted assignment {}", assignment_id);§Related Methods
get_asset_assignment- Get assignment details before deletioncreate_asset_assignments- Create new assignmentsedit_asset_assignment- Update assignment instead of deletinglock_asset_assignment- Lock assignment to prevent changes
Sourcepub async fn lock_asset_assignment(
&self,
asset_uuid: &str,
assignment_id: &str,
) -> Result<Assignment, Error>
pub async fn lock_asset_assignment( &self, asset_uuid: &str, assignment_id: &str, ) -> Result<Assignment, Error>
Sourcepub async fn unlock_asset_assignment(
&self,
asset_uuid: &str,
assignment_id: &str,
) -> Result<Assignment, Error>
pub async fn unlock_asset_assignment( &self, asset_uuid: &str, assignment_id: &str, ) -> Result<Assignment, Error>
Sourcepub async fn add_categories_to_registered_user(
&self,
registered_user_id: i64,
categories: &[i64],
) -> Result<(), Error>
pub async fn add_categories_to_registered_user( &self, registered_user_id: i64, categories: &[i64], ) -> Result<(), Error>
Adds categories to a registered user.
§Arguments
registered_user_id- The ID of the registered usercategories- A slice of category IDs to add to the user
§Errors
Returns an error if:
- Authentication fails
- The HTTP request fails
- The server returns an error status
- The registered user ID is invalid
- Any category ID is invalid
Sourcepub async fn remove_categories_from_registered_user(
&self,
registered_user_id: i64,
categories: &[i64],
) -> Result<(), Error>
pub async fn remove_categories_from_registered_user( &self, registered_user_id: i64, categories: &[i64], ) -> Result<(), Error>
Removes categories from a registered user
§Arguments
registered_user_id- The ID of the registered usercategories- A slice of category IDs to remove from the user
§Returns
Returns Ok(()) if the categories are successfully removed, or an error if:
- Authentication fails
- The HTTP request fails
- The server returns an error status
- The registered user ID is invalid
- Any category ID is not associated with the user
Sourcepub async fn distribute_asset(
&self,
asset_uuid: &str,
assignments: Vec<AssetDistributionAssignment>,
node_rpc: &ElementsRpc,
wallet_name: &str,
signer: &dyn Signer,
) -> Result<(), AmpError>
pub async fn distribute_asset( &self, asset_uuid: &str, assignments: Vec<AssetDistributionAssignment>, node_rpc: &ElementsRpc, wallet_name: &str, signer: &dyn Signer, ) -> Result<(), AmpError>
Distributes assets to multiple users through a comprehensive workflow
This method orchestrates the complete asset distribution process:
- Validates input parameters (asset UUID format, assignments structure)
- Verifies
ElementsRpcconnection and signer interface availability - Authenticates with the AMP API using the client’s token
- Creates a distribution request via the AMP API
- Constructs and signs the blockchain transaction using the provided signer
- Broadcasts the transaction to the Elements network
- Waits for blockchain confirmations (2 confirmations minimum)
- Confirms the distribution with the AMP API
§Arguments
asset_uuid- The UUID of the asset to distribute (must be valid UUID format)assignments- Vector of assignments specifyinguser_id, address, and amountnode_rpc-ElementsRpcclient for blockchain operationssigner- Signer implementation for transaction signing
§Returns
Returns Ok(()) if the distribution completes successfully, or an AmpError if:
- Input validation fails (invalid UUID format, empty assignments, etc.)
ElementsRpcconnection cannot be established- Signer interface is not available
- Authentication with AMP API fails
- Distribution creation fails
- Transaction construction or signing fails
- Blockchain broadcasting fails
- Confirmation timeout occurs
- Distribution confirmation with AMP API fails
§Examples
let client = ApiClient::new().await?;
let elements_rpc = ElementsRpc::from_env()?;
let (_, signer) = LwkSoftwareSigner::generate_new()?;
let assignments = vec![
AssetDistributionAssignment {
user_id: "user123".to_string(),
address: "lq1qq2xvpcvfup5j8zscjq05u2wxxjcyewk7979f9lq".to_string(),
amount: 100.0,
},
];
client.distribute_asset(
"550e8400-e29b-41d4-a716-446655440000",
assignments,
&elements_rpc,
"wallet_name",
&signer
).await?;§Requirements
This method implements requirements:
- 1.1: Single method for complete distribution workflow
- 2.2: Assignment details validation
- 2.4: Input validation for all parameters
- 5.1: Comprehensive error handling with context
Sourcepub async fn reissue_asset(
&self,
asset_uuid: &str,
amount_to_reissue: i64,
node_rpc: &ElementsRpc,
signer: &dyn Signer,
) -> Result<(), AmpError>
pub async fn reissue_asset( &self, asset_uuid: &str, amount_to_reissue: i64, node_rpc: &ElementsRpc, signer: &dyn Signer, ) -> Result<(), AmpError>
Reissues an asset through a comprehensive workflow
This method orchestrates the complete asset reissuance process:
- Validates input parameters (asset UUID format, amount)
- Verifies
ElementsRpcconnection and signer interface availability - Authenticates with the AMP API using the client’s token
- Creates a reissuance request via the AMP API
- Waits for transaction propagation and checks for lost outputs
- Verifies reissuance token UTXOs are available
- Calls the Elements node’s
reissueassetRPC method - Waits for blockchain confirmations (2 confirmations minimum)
- Retrieves transaction details and issuance information
- Confirms the reissuance with the AMP API
§Arguments
asset_uuid- The UUID of the asset to reissue (must be valid UUID format)amount_to_reissue- The amount to reissue (in satoshis for the asset)node_rpc-ElementsRpcclient for blockchain operationssigner- Signer implementation for future support (currently not used, node RPC signs)
§Returns
Returns Ok(()) if the reissuance completes successfully, or an AmpError if:
- Input validation fails (invalid UUID format, invalid amount, etc.)
ElementsRpcconnection cannot be established- Signer interface is not available
- Authentication with AMP API fails
- Reissuance request creation fails
- Lost outputs are detected
- Required UTXOs are not available
- Reissuance transaction creation fails
- Confirmation timeout occurs
- Reissuance confirmation with AMP API fails
§Examples
let client = ApiClient::new().await?;
let elements_rpc = ElementsRpc::from_env()?;
let (_, signer) = LwkSoftwareSigner::generate_new()?;
let asset_uuid = "550e8400-e29b-41d4-a716-446655440000";
let amount = 1000000; // 0.01 of an asset with 8 decimals
client.reissue_asset(asset_uuid, amount, &elements_rpc, &signer).await?;
println!("Reissuance completed successfully");§Related Methods
reissue_request- Create a reissuance request onlyreissue_confirm- Confirm a reissuance transaction only
Sourcepub async fn burn_asset(
&self,
asset_uuid: &str,
amount_to_burn: i64,
node_rpc: &ElementsRpc,
wallet_name: &str,
signer: &dyn Signer,
) -> Result<(), AmpError>
pub async fn burn_asset( &self, asset_uuid: &str, amount_to_burn: i64, node_rpc: &ElementsRpc, wallet_name: &str, signer: &dyn Signer, ) -> Result<(), AmpError>
Burns (destroys) a specific amount of an asset
This method orchestrates the complete burn workflow:
- Validates input parameters (asset UUID format, amount)
- Validates Elements RPC connection and signer interface
- Authenticates with AMP API
- Creates a burn request via the AMP API
- Waits for transaction propagation and checks for lost outputs
- Verifies required UTXOs are available
- Verifies sufficient balance exists
- Calls the Elements node’s
destroyamountRPC method - Waits for blockchain confirmations (2 confirmations minimum)
- Retrieves transaction data and change information
- Confirms the burn with the AMP API
§Arguments
asset_uuid- The UUID of the asset to burn (must be valid UUID format)amount_to_burn- The amount to burn (in satoshis for the asset)node_rpc-ElementsRpcclient for blockchain operationswallet_name- Name of the Elements wallet containing the asset to burnsigner- Signer implementation for future support (currently not used, node RPC signs)
§Returns
Returns Ok(()) if the burn completes successfully, or an AmpError if:
- Input validation fails (invalid UUID format, invalid amount, etc.)
ElementsRpcconnection cannot be established- Signer interface is not available
- Authentication with AMP API fails
- Burn request creation fails
- Lost outputs are detected
- Required UTXOs are not available
- Insufficient balance exists
- Burn transaction creation fails
- Confirmation timeout occurs
- Burn confirmation with AMP API fails
§Examples
let client = ApiClient::new().await?;
let elements_rpc = ElementsRpc::from_env()?;
let (_, signer) = LwkSoftwareSigner::generate_new()?;
let asset_uuid = "550e8400-e29b-41d4-a716-446655440000";
let amount = 1000000; // 0.01 of an asset with 8 decimals
let wallet_name = "test_wallet";
client.burn_asset(asset_uuid, amount, &elements_rpc, wallet_name, &signer).await?;
println!("Burn completed successfully");§Related Methods
burn_request- Create a burn request onlyburn_confirm- Confirm a burn transaction only