choreo-content 0.2.3

Agentic coding assistant — daemon, TUI, and bridges
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
//! Substrate chain client — subxt against the Coordination Platform node.
//!
//! This is the crate's only async path: it drives `subxt` (node RPC + tx
//! submission) on the [tokio sidecar] so the daemon stays thread-only. IPFS and
//! the indexer are synchronous and never touch this runtime.
//!
//! ## Signing
//!
//! A Polkadot account is stored in the keystore as its **expanded ed25519
//! secret** (the 64 bytes that Polkadot-JS stores in its scrypt+XSalsa20
//! envelope, see `choreo-keystore::substrate`). `subxt-signer` cannot rebuild a
//! keypair from that form, so this module reconstructs a `schnorrkel::Keypair`
//! and wraps it in a [`ChoreoSigner`] implementing `subxt::tx::Signer<PolkadotConfig>`.
//!
//! [tokio sidecar]: crate::runtime

use sp_core::crypto::Ss58Codec;
use sp_core::sr25519::Public;
use subxt::OnlineClient;
use subxt::PolkadotConfig;
use subxt::config::Config;
use subxt::config::Header as SubxtHeader;
use subxt::utils::{AccountId32, MultiAddress, MultiSignature};

use crate::ContentError;
use crate::acuity_runtime::api;
use crate::config::CHAIN_WS_URL;
use zeroize::Zeroizing;

/// A signing keypair rebuilt from a stored expanded ed25519 secret.
struct ChoreoSigner(schnorrkel::Keypair);

impl ChoreoSigner {
    /// Build a signer from a 64-byte expanded ed25519 secret key.
    fn from_expanded_secret(secret: &[u8]) -> Result<Self, ContentError> {
        let secret_key: [u8; 64] = secret
            .try_into()
            .map_err(|_| ContentError::Account("expected a 64-byte ed25519 secret".into()))?;
        let secret = schnorrkel::SecretKey::from_ed25519_bytes(&secret_key)
            .map_err(|e| ContentError::Account(format!("invalid ed25519 secret: {e}")))?;
        let public = secret.to_public();
        Ok(Self(schnorrkel::Keypair { public, secret }))
    }

    /// The raw 32-byte public key (=== account id).
    fn account_id(&self) -> [u8; 32] {
        self.0.public.to_bytes()
    }
}

impl subxt::tx::Signer<PolkadotConfig> for ChoreoSigner {
    fn account_id(&self) -> <PolkadotConfig as Config>::AccountId {
        AccountId32(self.account_id())
    }
    fn sign(&self, signer_payload: &[u8]) -> <PolkadotConfig as Config>::Signature {
        // sr25519 signs over a Schnorrkel signing context (matching subxt-signer
        // and Substrate's on-chain verification).
        let context = schnorrkel::signing_context(b"substrate");
        let sig = self.0.sign(context.bytes(signer_payload));
        MultiSignature::Sr25519(sig.to_bytes())
    }
}

/// Parse an SS58 account address into its raw 32-byte account id.
///
/// # Errors
///
/// Fails with [`ContentError::InvalidArgument`] when `address` is not a valid
/// SS58-check encoding of a 32-byte sr25519 public key.
pub fn account_id_from_address(address: &str) -> Result<[u8; 32], ContentError> {
    let public = Public::from_ss58check(address).map_err(|e| {
        ContentError::InvalidArgument(format!("invalid SS58 address {address}: {e}"))
    })?;
    Ok(public.0)
}

/// Render a raw 32-byte account id as an SS58 address (chain prefix).
#[must_use]
pub fn account_address(bytes: [u8; 32]) -> String {
    AccountId32(bytes).to_string()
}

/// A chain account (public id + expanded secret), ready to sign & submit.
pub struct ChainAccount {
    /// SS58 address.
    pub address: String,
    /// Raw 32-byte account id.
    pub account_id: [u8; 32],
    /// Expanded ed25519 secret (64 bytes), zeroized on drop.
    ///
    /// The secret is cloned out of the `#[zeroize(drop)]` `ServiceCredential`
    /// into this per-call account, so it is held here in a `Zeroizing` buffer
    /// to ensure the private key is wiped from memory when the account is
    /// dropped (not left to the allocator).
    secret: Zeroizing<Vec<u8>>,
}

impl ChainAccount {
    /// Build a chain account from a 32-byte account id + 64-byte expanded secret.
    #[must_use]
    pub fn from_parts(account_id: [u8; 32], secret: Vec<u8>) -> Self {
        Self {
            address: account_address(account_id),
            account_id,
            secret: Zeroizing::new(secret),
        }
    }
    /// Build a chain account from an SS58 address + 64-byte expanded secret
    /// (validates that the address matches the secret's public key).
    ///
    /// # Errors
    ///
    /// Fails with [`ContentError::Account`] when `secret` is not a valid
    /// 64-byte expanded ed25519 secret, or when the address does not match
    /// the secret's derived public key; with
    /// [`ContentError::InvalidArgument`] when `address` is not valid SS58
    /// (see [`account_id_from_address`]).
    pub fn from_address(address: &str, secret: Vec<u8>) -> Result<Self, ContentError> {
        let signer = ChoreoSigner::from_expanded_secret(&secret)?;
        let account_id = account_id_from_address(address)?;
        if signer.account_id() != account_id {
            return Err(ContentError::Account(format!(
                "address {address} does not match the supplied secret"
            )));
        }
        Ok(Self {
            address: address.to_string(),
            account_id,
            secret: Zeroizing::new(secret),
        })
    }
    fn signer(&self) -> Result<ChoreoSigner, ContentError> {
        ChoreoSigner::from_expanded_secret(&self.secret)
    }
}

/// Connect to the node (async; run on the sidecar).
///
/// Verifies the connected node is the Coordination Platform by comparing its
/// reported genesis hash to the pinned [`crate::config::GENESIS_HASH`], so a
/// different chain at the same endpoint is rejected before any call is issued.
async fn connect() -> Result<OnlineClient<PolkadotConfig>, ContentError> {
    let client = OnlineClient::<PolkadotConfig>::from_insecure_url(CHAIN_WS_URL)
        .await
        .map_err(|e| {
            ContentError::Substrate(format!("failed to connect to {CHAIN_WS_URL}: {e}"))
        })?;

    let actual = crate::encode::bytes_to_hex(client.genesis_hash().as_ref());
    if actual != crate::config::GENESIS_HASH {
        return Err(ContentError::Substrate(format!(
            "node genesis {actual} does not match expected {}",
            crate::config::GENESIS_HASH
        )));
    }
    Ok(client)
}

/// Per-chain-operation wall-clock budget. A hung node (or an RPC that never
/// answers) must not block a daemon tool thread indefinitely, so every subxt
/// future runs inside this timeout on the sidecar.
const CHAIN_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(30);

/// Run a chain async operation, bounding it with [`CHAIN_TIMEOUT`]. The future
/// must resolve to a `ContentError`-bearing `Result` so a timeout maps to a
/// [`ContentError::Substrate`] that flows through the caller's `?`.
async fn with_chain_timeout<T, F>(fut: F) -> Result<T, ContentError>
where
    F: std::future::Future<Output = Result<T, ContentError>>,
{
    match tokio::time::timeout(CHAIN_TIMEOUT, fut).await {
        Ok(res) => res,
        Err(_) => Err(ContentError::Substrate("chain RPC timed out".into())),
    }
}

/// A finalized transaction result (what write tools report).
#[derive(Clone, Debug, serde::Serialize, schemars::JsonSchema)]
pub struct TxOutcome {
    /// The item id emitted by `Content::PublishItem`, if this call created one.
    pub item_id: Option<String>,
}

/// Submit a call, wait for finalized success, and return the finalized events.
/// Shared by every write extrinsic; the publish wrappers additionally parse the
/// created item id from those events (see [`submit_publish`]).
async fn submit_and_wait<Call>(
    call: &Call,
    account: &ChainAccount,
) -> Result<subxt::extrinsics::ExtrinsicEvents<PolkadotConfig>, ContentError>
where
    Call: subxt::tx::Payload,
{
    let client = connect().await?;
    let at = client
        .at_current_block()
        .await
        .map_err(|e| ContentError::Substrate(format!("failed to get block for tx: {e}")))?;
    let signer = account.signer()?;
    at.tx()
        .sign_and_submit_then_watch_default(call, &signer)
        .await
        .map_err(|e| ContentError::Transaction(format!("submit failed: {e}")))?
        .wait_for_finalized_success()
        .await
        .map_err(|e| ContentError::Transaction(format!("finalized failed: {e}")))
}

/// Submit a publish call and capture the `Content::PublishItem` item id.
async fn submit_publish<Call>(
    call: &Call,
    account: &ChainAccount,
) -> Result<TxOutcome, ContentError>
where
    Call: subxt::tx::Payload,
{
    let tx_events = submit_and_wait(call, account).await?;
    let item_id = tx_events
        .find_first::<api::content::events::PublishItem>()
        .transpose()
        .map_err(|e| ContentError::Transaction(format!("failed to decode PublishItem: {e}")))?
        .map(|evt| crate::encode::bytes_to_hex(&evt.item_id.0));
    Ok(TxOutcome { item_id })
}

// ── Read (on-chain authoritative state) ──────────────────────────────────────

/// A live chain status snapshot, read from a connected node.
#[derive(Clone, Debug, serde::Serialize, schemars::JsonSchema)]
pub struct ChainStatus {
    /// Genesis hash as reported by the node (hex, `0x`-prefixed). Verified
    /// against the pinned [`crate::config::GENESIS_HASH`] by [`connect`].
    pub genesis_hash: String,
    /// The chain's designated SS58 prefix (`System::SS58Prefix` constant).
    pub ss58_prefix: u16,
    /// The node's current best (head) block number.
    pub best_block: u64,
    /// The node's latest finalized block number.
    pub finalized_block: u64,
    /// Item-id derivation namespace (pinned config; not an on-chain constant).
    pub item_id_namespace: u32,
}

/// Probe the node and return a live chain status snapshot.
///
/// Connects (which itself verifies the node's genesis hash matches the pinned
/// [`crate::config::GENESIS_HASH`]), reads the SS58 prefix from the on-chain
/// `System` constants, and reads the best + finalized block headers. A down
/// node, a mismatched chain, or an RPC that never answers surfaces as an error
/// (bounded by [`CHAIN_TIMEOUT`]) so the caller's status report can show the
/// chain as unavailable rather than fabricating a healthy snapshot from pinned
/// configuration.
///
/// # Errors
///
/// Fails with [`ContentError::Substrate`] when the node cannot be reached at
/// [`crate::config::CHAIN_WS_URL`], its genesis hash does not match the pinned
/// [`crate::config::GENESIS_HASH`], the `System::SS58Prefix` constant or best
/// block header cannot be read, the node returns no best header, or the whole
/// probe exceeds [`CHAIN_TIMEOUT`]; with
/// [`ContentError::RuntimeNotInitialized`] when the sidecar runtime was never
/// initialized.
pub fn chain_status() -> Result<ChainStatus, ContentError> {
    crate::runtime::block_on(with_chain_timeout(async move {
        let client = connect().await?;
        let at = client
            .at_current_block()
            .await
            .map_err(|e| ContentError::Substrate(format!("failed to get block: {e}")))?;

        // `at_current_block` pins to the latest finalized block, so its number
        // is the finalized height; verify it's available before reporting.
        let finalized_block = at.block_number();

        // Read the chain's designated SS58 prefix from the on-chain `System`
        // constant (a static address resolved by the generated API).
        let addr = api::constants().system().ss58_prefix();
        let ss58_prefix = at
            .constants()
            .entry(addr)
            .map_err(|e| ContentError::Substrate(format!("failed to read ss58 prefix: {e}")))?;

        // Fetch the best (head) block via the node RPC: `chain_getHeader` with
        // no hash returns the latest best block. subxt does not expose a
        // one-shot best-block accessor on the `OnlineClient` channel, and the
        // finalized number above comes from `at_current_block` (which pins to
        // the latest finalized block), so a short-lived RPC client is opened
        // here just to read the head. It rides the same sidecar runtime and is
        // bounded by `CHAIN_TIMEOUT` like everything else in this probe.
        //
        // The generic is pinned to the Polkadot RPC config so header decoding
        // matches the chain config; the header's `number()` comes from
        // `subxt::config::Header`.
        let rpc = subxt::rpcs::RpcClient::from_insecure_url(crate::config::CHAIN_WS_URL)
            .await
            .map_err(|e| ContentError::Substrate(format!("failed to open rpc: {e}")))?;
        let methods =
            subxt::rpcs::LegacyRpcMethods::<subxt::config::RpcConfigFor<PolkadotConfig>>::new(rpc);
        let best_header = methods
            .chain_get_header(None)
            .await
            .map_err(|e| ContentError::Substrate(format!("failed to read best block header: {e}")))?
            .ok_or_else(|| ContentError::Substrate("node returned no best block header".into()))?;
        let best_block = best_header.number();

        Ok(ChainStatus {
            genesis_hash: crate::encode::bytes_to_hex(client.genesis_hash().as_ref()),
            ss58_prefix,
            best_block,
            finalized_block,
            item_id_namespace: crate::config::ITEM_ID_NAMESPACE,
        })
    }))?
}

/// Read an item's on-chain control state (owner, revision, flags).
///
/// # Errors
///
/// Fails with [`ContentError::Content`] when the item does not exist on-chain;
/// with [`ContentError::Substrate`] when the node is unreachable, the genesis
/// hash mismatches, the storage query or decode fails, or [`CHAIN_TIMEOUT`]
/// is exceeded; with [`ContentError::RuntimeNotInitialized`] when the sidecar
/// runtime was never initialized.
pub fn item_state(item_id: [u8; 32]) -> Result<ItemState, ContentError> {
    crate::runtime::block_on(with_chain_timeout(async move {
        let client = connect().await?;
        let at = client
            .at_current_block()
            .await
            .map_err(|e| ContentError::Substrate(format!("failed to get block: {e}")))?;
        let addr = api::storage().content().item_state();
        let thunk = at
            .storage()
            .try_fetch(
                addr,
                (api::runtime_types::pallet_content::pallet::ItemId(item_id),),
            )
            .await
            .map_err(|e| ContentError::Substrate(format!("item state query failed: {e}")))?;
        match thunk {
            Some(thunk) => {
                let item = thunk
                    .decode()
                    .map_err(|e| ContentError::Substrate(format!("decode item failed: {e}")))?;
                Ok(ItemState {
                    owner: crate::encode::bytes_to_hex(&item.owner.0),
                    revision_id: item.revision_id,
                    flags: item.flags,
                })
            }
            None => Err(ContentError::Content("item not found on-chain".into())),
        }
    }))?
}

/// Read the list of item ids an account has pinned in `pallet-account-content`.
///
/// # Errors
///
/// Fails with [`ContentError::Substrate`] when the node is unreachable, the
/// genesis hash mismatches, the storage query or bounded-vec decode fails, or
/// [`CHAIN_TIMEOUT`] is exceeded; with
/// [`ContentError::RuntimeNotInitialized`] when the sidecar runtime was never
/// initialized. An account with no pinned items yields `Ok(vec![])`.
pub fn account_item_ids(account: [u8; 32]) -> Result<Vec<[u8; 32]>, ContentError> {
    crate::runtime::block_on(with_chain_timeout(async move {
        let client = connect().await?;
        let at = client
            .at_current_block()
            .await
            .map_err(|e| ContentError::Substrate(format!("failed to get block: {e}")))?;
        let addr = api::storage().account_content().account_item_ids();
        let thunk = at
            .storage()
            .try_fetch(addr, (AccountId32(account),))
            .await
            .map_err(|e| ContentError::Substrate(format!("account items query failed: {e}")))?;
        match thunk {
            Some(thunk) => {
                let bounded = thunk
                    .decode()
                    .map_err(|e| ContentError::Substrate(format!("decode items failed: {e}")))?;
                Ok(bounded.0.into_iter().map(|id| id.0).collect())
            }
            None => Ok(Vec::new()),
        }
    }))?
}

/// Read the profile item id an account has set (`pallet-account-profile`).
///
/// # Errors
///
/// Fails with [`ContentError::Substrate`] when the node is unreachable, the
/// genesis hash mismatches, the storage query or decode fails, or
/// [`CHAIN_TIMEOUT`] is exceeded; with
/// [`ContentError::RuntimeNotInitialized`] when the sidecar runtime was never
/// initialized. `Ok(None)` means the account has no profile set.
pub fn profile_item(account: [u8; 32]) -> Result<Option<[u8; 32]>, ContentError> {
    crate::runtime::block_on(with_chain_timeout(async move {
        let client = connect().await?;
        let at = client
            .at_current_block()
            .await
            .map_err(|e| ContentError::Substrate(format!("failed to get block: {e}")))?;
        let addr = api::storage().account_profile().account_profile();
        let thunk = at
            .storage()
            .try_fetch(addr, (AccountId32(account),))
            .await
            .map_err(|e| ContentError::Substrate(format!("profile query failed: {e}")))?;
        match thunk {
            Some(thunk) => {
                let decoded = thunk
                    .decode()
                    .map_err(|e| ContentError::Substrate(format!("decode profile failed: {e}")))?;
                Ok(Some(decoded.0))
            }
            None => Ok(None),
        }
    }))?
}

/// On-chain control state of an item.
#[derive(Clone, Debug, serde::Serialize, schemars::JsonSchema)]
pub struct ItemState {
    /// Owner account id (hex `0x`).
    pub owner: String,
    /// Latest revision counter.
    pub revision_id: u32,
    /// Lifecycle flag bitmask.
    pub flags: u8,
}

// ── Bounded-collection helpers ───────────────────────────────────────────────

use api::runtime_types::bounded_collections::bounded_vec::BoundedVec;
use api::runtime_types::pallet_content::pallet::ItemId;

/// Build a content `BoundedVec<ItemId>` from raw item-id bytes.
fn item_bounded(list: &[[u8; 32]]) -> BoundedVec<ItemId> {
    BoundedVec(list.iter().map(|b| ItemId(*b)).collect())
}

/// Build a `BoundedVec<AccountId32>` from raw account-id bytes.
fn account_bounded(list: &[[u8; 32]]) -> BoundedVec<AccountId32> {
    BoundedVec(list.iter().map(|b| AccountId32(*b)).collect())
}

// ── Write (submit extrinsics) ────────────────────────────────────────────────

/// Publish a brand-new item (optionally batched with an account add).
///
/// # Errors
///
/// Fails with [`ContentError::Transaction`] when the extrinsic cannot be
/// submitted, is not finalized successfully, or the `PublishItem` event
/// cannot be decoded; with [`ContentError::Substrate`] when the node is
/// unreachable, the genesis hash mismatches, or [`CHAIN_TIMEOUT`] is
/// exceeded; with [`ContentError::Account`] when the stored secret cannot be
/// rebuilt into a signer; with [`ContentError::RuntimeNotInitialized`] when
/// the sidecar runtime was never initialized.
pub fn publish_item(
    account: &ChainAccount,
    nonce: [u8; 32],
    parents: &[[u8; 32]],
    flags: u8,
    links: &[[u8; 32]],
    mentions: &[[u8; 32]],
    ipfs_hash: [u8; 32],
) -> Result<TxOutcome, ContentError> {
    let call = api::tx().content().publish_item(
        api::runtime_types::pallet_content::Nonce(nonce),
        item_bounded(parents),
        flags,
        item_bounded(links),
        account_bounded(mentions),
        api::runtime_types::pallet_content::pallet::IpfsHash(ipfs_hash),
    );
    crate::runtime::block_on(with_chain_timeout(submit_publish(&call, account)))?
}

/// Publish a new revision of an existing item.
///
/// # Errors
///
/// Fails with [`ContentError::Transaction`] when the extrinsic cannot be
/// submitted, is not finalized successfully, or the `PublishItem` event
/// cannot be decoded; with [`ContentError::Substrate`] when the node is
/// unreachable, the genesis hash mismatches, or [`CHAIN_TIMEOUT`] is
/// exceeded; with [`ContentError::Account`] when the stored secret cannot be
/// rebuilt into a signer; with [`ContentError::RuntimeNotInitialized`] when
/// the sidecar runtime was never initialized.
pub fn publish_revision(
    account: &ChainAccount,
    item_id: [u8; 32],
    links: &[[u8; 32]],
    mentions: &[[u8; 32]],
    ipfs_hash: [u8; 32],
) -> Result<TxOutcome, ContentError> {
    let call = api::tx().content().publish_revision(
        ItemId(item_id),
        item_bounded(links),
        account_bounded(mentions),
        api::runtime_types::pallet_content::pallet::IpfsHash(ipfs_hash),
    );
    crate::runtime::block_on(with_chain_timeout(submit_publish(&call, account)))?
}

/// Retract an item.
///
/// # Errors
///
/// Fails with [`ContentError::Transaction`] when the extrinsic cannot be
/// submitted or is not finalized successfully; with
/// [`ContentError::Substrate`] when the node is unreachable, the genesis
/// hash mismatches, or [`CHAIN_TIMEOUT`] is exceeded; with
/// [`ContentError::Account`] when the stored secret cannot be rebuilt into a
/// signer; with [`ContentError::RuntimeNotInitialized`] when the sidecar
/// runtime was never initialized.
pub fn retract_item(account: &ChainAccount, item_id: [u8; 32]) -> Result<(), ContentError> {
    let call = api::tx()
        .content()
        .retract_item(api::runtime_types::pallet_content::pallet::ItemId(item_id));
    let _ = crate::runtime::block_on(with_chain_timeout(submit_and_wait(&call, account)))?;
    Ok(())
}

/// Clear the REVISIONABLE flag on an item.
///
/// # Errors
///
/// Fails with [`ContentError::Transaction`] when the extrinsic cannot be
/// submitted or is not finalized successfully; with
/// [`ContentError::Substrate`] when the node is unreachable, the genesis
/// hash mismatches, or [`CHAIN_TIMEOUT`] is exceeded; with
/// [`ContentError::Account`] when the stored secret cannot be rebuilt into a
/// signer; with [`ContentError::RuntimeNotInitialized`] when the sidecar
/// runtime was never initialized.
pub fn set_not_revisionable(account: &ChainAccount, item_id: [u8; 32]) -> Result<(), ContentError> {
    let call = api::tx()
        .content()
        .set_not_revisionable(api::runtime_types::pallet_content::pallet::ItemId(item_id));
    let _ = crate::runtime::block_on(with_chain_timeout(submit_and_wait(&call, account)))?;
    Ok(())
}

/// Clear the RETRACTABLE flag on an item.
///
/// # Errors
///
/// Fails with [`ContentError::Transaction`] when the extrinsic cannot be
/// submitted or is not finalized successfully; with
/// [`ContentError::Substrate`] when the node is unreachable, the genesis
/// hash mismatches, or [`CHAIN_TIMEOUT`] is exceeded; with
/// [`ContentError::Account`] when the stored secret cannot be rebuilt into a
/// signer; with [`ContentError::RuntimeNotInitialized`] when the sidecar
/// runtime was never initialized.
pub fn set_not_retractable(account: &ChainAccount, item_id: [u8; 32]) -> Result<(), ContentError> {
    let call = api::tx()
        .content()
        .set_not_retractable(api::runtime_types::pallet_content::pallet::ItemId(item_id));
    let _ = crate::runtime::block_on(with_chain_timeout(submit_and_wait(&call, account)))?;
    Ok(())
}

/// Pin an item to an account (`account_content::add_item`).
///
/// # Errors
///
/// Fails with [`ContentError::Transaction`] when the extrinsic cannot be
/// submitted or is not finalized successfully; with
/// [`ContentError::Substrate`] when the node is unreachable, the genesis
/// hash mismatches, or [`CHAIN_TIMEOUT`] is exceeded; with
/// [`ContentError::Account`] when the stored secret cannot be rebuilt into a
/// signer; with [`ContentError::RuntimeNotInitialized`] when the sidecar
/// runtime was never initialized.
pub fn add_account_item(account: &ChainAccount, item_id: [u8; 32]) -> Result<(), ContentError> {
    let call = api::tx()
        .account_content()
        .add_item(api::runtime_types::pallet_content::pallet::ItemId(item_id));
    let _ = crate::runtime::block_on(with_chain_timeout(submit_and_wait(&call, account)))?;
    Ok(())
}

/// Unpin an item from an account (`account_content::remove_item`).
///
/// # Errors
///
/// Fails with [`ContentError::Transaction`] when the extrinsic cannot be
/// submitted or is not finalized successfully; with
/// [`ContentError::Substrate`] when the node is unreachable, the genesis
/// hash mismatches, or [`CHAIN_TIMEOUT`] is exceeded; with
/// [`ContentError::Account`] when the stored secret cannot be rebuilt into a
/// signer; with [`ContentError::RuntimeNotInitialized`] when the sidecar
/// runtime was never initialized.
pub fn remove_account_item(account: &ChainAccount, item_id: [u8; 32]) -> Result<(), ContentError> {
    let call = api::tx()
        .account_content()
        .remove_item(api::runtime_types::pallet_content::pallet::ItemId(item_id));
    let _ = crate::runtime::block_on(submit_publish(&call, account))?;
    Ok(())
}

/// Point an account's profile at an item (`account_profile::set_profile`).
///
/// # Errors
///
/// Fails with [`ContentError::Transaction`] when the extrinsic cannot be
/// submitted or is not finalized successfully; with
/// [`ContentError::Substrate`] when the node is unreachable, the genesis
/// hash mismatches, or [`CHAIN_TIMEOUT`] is exceeded; with
/// [`ContentError::Account`] when the stored secret cannot be rebuilt into a
/// signer; with [`ContentError::RuntimeNotInitialized`] when the sidecar
/// runtime was never initialized.
pub fn set_profile(account: &ChainAccount, item_id: [u8; 32]) -> Result<(), ContentError> {
    let call = api::tx()
        .account_profile()
        .set_profile(api::runtime_types::pallet_content::pallet::ItemId(item_id));
    let _ = crate::runtime::block_on(with_chain_timeout(submit_and_wait(&call, account)))?;
    Ok(())
}

/// The `MultiAddress` identity for an account (for extrinsics that need it).
#[allow(dead_code)]
pub(crate) fn multi_address(account: [u8; 32]) -> MultiAddress<AccountId32, ()> {
    MultiAddress::Id(AccountId32(account))
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn account_id_from_address_round_trips() {
        let mut bytes = [0u8; 32];
        bytes[0] = 9;
        let address = account_address(bytes);
        assert_eq!(account_id_from_address(&address).unwrap(), bytes);
    }

    #[test]
    fn account_id_from_address_rejects_garbage() {
        assert!(account_id_from_address("not-an-address").is_err());
    }
}