From 8872f2d49e1a5a28f101196d5b576a9d2fc2bd53 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Marko=20Petrli=C4=87?= Date: Wed, 11 Sep 2024 03:28:13 +0200 Subject: [PATCH 1/4] Marko/add nom pools txs to sdks (#655) * Moved files and made them slimmer * Added two mor nom pool txs * Moved functions around * Replaced Pramas with Options * updated docs * Updated Advanced Examples * Added docs and example for nom pools --- .../extrinsic_params_sdk/src/main.rs | 21 +- .../insecure_connection/Cargo.toml | 2 +- avail-rust/docs/extrinsics/README.md | 629 +++++++-- .../balance_transfer_all/src/main.rs | 6 +- .../balance_transfer_allow_death/src/main.rs | 6 +- .../balance_transfer_keep_alive/src/main.rs | 6 +- .../da_create_application_key/src/main.rs | 6 +- .../da_set_application_key/src/main.rs | 6 +- .../src/main.rs | 6 +- .../src/main.rs | 6 +- .../extrinsics/da_submit_data/src/main.rs | 6 +- .../nomination_pools_create/Cargo.toml | 9 + .../nomination_pools_create/src/main.rs | 35 + .../Cargo.toml | 9 + .../src/main.rs | 37 + .../nomination_pools_join/Cargo.toml | 9 + .../nomination_pools_join/src/main.rs | 25 + .../nomination_pools_nominate/Cargo.toml | 9 + .../nomination_pools_nominate/src/main.rs | 28 + .../extrinsics/session_set_keys/src/main.rs | 8 +- .../docs/extrinsics/staking_bond/src/main.rs | 6 +- .../extrinsics/staking_bond_extra/src/main.rs | 6 +- .../docs/extrinsics/staking_chill/src/main.rs | 6 +- .../staking_chill_other/src/main.rs | 6 +- .../extrinsics/staking_nominate/src/main.rs | 6 +- .../extrinsics/staking_unbond/src/main.rs | 6 +- .../extrinsics/staking_validate/src/main.rs | 6 +- avail-rust/src/lib.rs | 6 +- avail-rust/src/sdk.rs | 10 +- avail-rust/src/transaction_data.rs | 97 -- avail-rust/src/transactions.rs | 1138 ----------------- avail-rust/src/transactions/balances.rs | 200 +++ avail-rust/src/transactions/da.rs | 360 ++++++ avail-rust/src/transactions/mod.rs | 122 ++ avail-rust/src/transactions/nom_pools.rs | 271 ++++ avail-rust/src/transactions/options.rs | 118 ++ avail-rust/src/transactions/session.rs | 83 ++ avail-rust/src/transactions/staking.rs | 386 ++++++ 38 files changed, 2337 insertions(+), 1365 deletions(-) create mode 100644 avail-rust/docs/extrinsics/nomination_pools_create/Cargo.toml create mode 100644 avail-rust/docs/extrinsics/nomination_pools_create/src/main.rs create mode 100644 avail-rust/docs/extrinsics/nomination_pools_create_with_pool_id/Cargo.toml create mode 100644 avail-rust/docs/extrinsics/nomination_pools_create_with_pool_id/src/main.rs create mode 100644 avail-rust/docs/extrinsics/nomination_pools_join/Cargo.toml create mode 100644 avail-rust/docs/extrinsics/nomination_pools_join/src/main.rs create mode 100644 avail-rust/docs/extrinsics/nomination_pools_nominate/Cargo.toml create mode 100644 avail-rust/docs/extrinsics/nomination_pools_nominate/src/main.rs delete mode 100644 avail-rust/src/transaction_data.rs delete mode 100644 avail-rust/src/transactions.rs create mode 100644 avail-rust/src/transactions/balances.rs create mode 100644 avail-rust/src/transactions/da.rs create mode 100644 avail-rust/src/transactions/mod.rs create mode 100644 avail-rust/src/transactions/nom_pools.rs create mode 100644 avail-rust/src/transactions/options.rs create mode 100644 avail-rust/src/transactions/session.rs create mode 100644 avail-rust/src/transactions/staking.rs diff --git a/avail-rust/docs/advanced-examples/extrinsic_params_sdk/src/main.rs b/avail-rust/docs/advanced-examples/extrinsic_params_sdk/src/main.rs index 0ad028c5f..c7286c94c 100644 --- a/avail-rust/docs/advanced-examples/extrinsic_params_sdk/src/main.rs +++ b/avail-rust/docs/advanced-examples/extrinsic_params_sdk/src/main.rs @@ -1,4 +1,6 @@ -use avail_rust::{AvailExtrinsicParamsBuilder, Data, Key, Keypair, SecretUri, SDK}; +use avail_rust::{ + AvailExtrinsicParamsBuilder, Data, Key, Keypair, Mortality, Nonce, Options, SecretUri, SDK, +}; use core::str::FromStr; #[tokio::main] @@ -21,12 +23,11 @@ async fn main() -> Result<(), String> { let nonce = sdk.api.tx().account_nonce(&account_id).await.unwrap(); let app_id = result.event.id; - let options = AvailExtrinsicParamsBuilder::new() - .nonce(nonce) + let options = Options::new() + .nonce(Nonce::BestBlock) .app_id(app_id.0) .tip(1_000_000_000_000_000_000u128) - .mortal(block.header(), 400) - .build(); + .mortality(Mortality::new(32, None)); let data = String::from("My Awesome Data").as_bytes().to_vec(); let data = Data { 0: data }; @@ -41,15 +42,7 @@ async fn main() -> Result<(), String> { ) .await?; - println!( - "Who={}, DataHash={:?}", - result.event.who, result.event.data_hash - ); - println!("TxData={:?}", result.tx_data.data); - println!( - "TxHash={:?}, BlockHash={:?}", - result.tx_hash, result.block_hash - ); + dbg!(result); Ok(()) } diff --git a/avail-rust/docs/advanced-examples/insecure_connection/Cargo.toml b/avail-rust/docs/advanced-examples/insecure_connection/Cargo.toml index 6fefd7654..03e1e2340 100644 --- a/avail-rust/docs/advanced-examples/insecure_connection/Cargo.toml +++ b/avail-rust/docs/advanced-examples/insecure_connection/Cargo.toml @@ -6,5 +6,5 @@ edition = "2021" version = "0.1.0" [dependencies] -avail-rust = { path = "../../../." } +avail-rust = { git = "https://github.com/availproject/avail" } tokio = { version = "1.38.0", features = ["rt-multi-thread"] } diff --git a/avail-rust/docs/extrinsics/README.md b/avail-rust/docs/extrinsics/README.md index f8fd0ef31..5bd97c804 100644 --- a/avail-rust/docs/extrinsics/README.md +++ b/avail-rust/docs/extrinsics/README.md @@ -11,7 +11,7 @@ Origin Level: Signed ### Interface ```rust -async fn create_application_key(&self, key: Key, wait_for: WaitFor, account: &Keypair, options: Option) -> Result; +async fn create_application_key(&self, key: Key, wait_for: WaitFor, account: &Keypair, options: Option) -> Result; ``` #### Parameters @@ -21,7 +21,7 @@ async fn create_application_key(&self, key: Key, wait_for: WaitFor, account: &Ke | key | Key | false | name of the application key | | waitFor | WaitFor | false | wait for block inclusion or finalization | | account | KeyringPair | false | account that will send and sign the transaction | -| options | Params | true | transaction params | +| options | Options | true | transaction parameters | ### Minimal Example @@ -40,7 +40,7 @@ tokio = { version = "1.38.0", features = ["rt-multi-thread"] } #### main.rs ```rust -use avail_rust::{Key, Keypair, SecretUri, WaitFor, SDK}; +use avail_rust::{Key, Keypair, Nonce, Options, SecretUri, WaitFor, SDK}; use core::str::FromStr; #[tokio::main] @@ -53,10 +53,12 @@ async fn main() -> Result<(), String> { let key = String::from("MyAwesomeKey").as_bytes().to_vec(); let key = Key { 0: key }; + let wait_for = WaitFor::BlockInclusion; + let options = Options::new().nonce(Nonce::BestBlockAndTxPool); let result = sdk .tx .data_availability - .create_application_key(key, WaitFor::BlockInclusion, &account, None) + .create_application_key(key, wait_for, &account, Some(options)) .await?; dbg!(result); @@ -109,7 +111,7 @@ Origin Level: Signed ### Interface ```rust -async fn submit_data(&self, data: Data, wait_for: WaitFor, account: &Keypair, options: Option) -> Result; +async fn submit_data(&self, data: Data, wait_for: WaitFor, account: &Keypair, options: Option) -> Result; ``` #### Parameters @@ -119,7 +121,7 @@ async fn submit_data(&self, data: Data, wait_for: WaitFor, account: &Keypair, op | data | Data | false | data to be submitted | | waitFor | WaitFor | false | wait for block inclusion or finalization | | account | KeyringPair | false | account that will send and sign the transaction | -| options | Params | true | transaction params | +| options | Options | true | transaction parameters | ### Minimal Example @@ -138,7 +140,7 @@ tokio = { version = "1.38.0", features = ["rt-multi-thread"] } #### main.rs ```rust -use avail_rust::{Data, Keypair, SecretUri, WaitFor, SDK}; +use avail_rust::{Data, Keypair, Nonce, Options, SecretUri, WaitFor, SDK}; use core::str::FromStr; #[tokio::main] @@ -151,10 +153,12 @@ async fn main() -> Result<(), String> { let data = String::from("My Awesome Data").as_bytes().to_vec(); let data = Data { 0: data }; + let wait_for = WaitFor::BlockInclusion; + let options = Options::new().nonce(Nonce::BestBlockAndTxPool); let result = sdk .tx .data_availability - .submit_data(data, WaitFor::BlockInclusion, &account, None) + .submit_data(data, wait_for, &account, Some(options)) .await?; dbg!(result); @@ -205,7 +209,7 @@ Origin Level: Root ### Interface ```rust -async fn submit_block_length_proposal(&self, rows: u32, cols: u32, wait_for: WaitFor, account: &Keypair, options: Option) -> Result; +async fn submit_block_length_proposal(&self, rows: u32, cols: u32, wait_for: WaitFor, account: &Keypair, options: Option) -> Result; ``` #### Parameters @@ -216,7 +220,7 @@ async fn submit_block_length_proposal(&self, rows: u32, cols: u32, wait_for: Wai | cols | u32 | false | number of cols in block | | waitFor | WaitFor | false | wait for block inclusion or finalization | | account | KeyringPair | false | account that will send and sign the transaction | -| options | Params | true | transaction params | +| options | Options | true | transaction parameters | ### Minimal Example @@ -235,7 +239,7 @@ tokio = { version = "1.38.0", features = ["rt-multi-thread"] } #### main.rs ```rust -use avail_rust::{Keypair, SecretUri, WaitFor, SDK}; +use avail_rust::{Keypair, Nonce, Options, SecretUri, WaitFor, SDK}; use core::str::FromStr; #[tokio::main] @@ -249,13 +253,19 @@ async fn main() -> Result<(), String> { let rows = 128; let cols = 128; + let wait_for = WaitFor::BlockInclusion; + let options = Options::new().nonce(Nonce::BestBlockAndTxPool); let result = sdk .tx .data_availability - .submit_block_length_proposal(rows, cols, WaitFor::BlockInclusion, &account, None) + .submit_block_length_proposal(rows, cols, wait_for, &account, Some(options)) .await?; - dbg!(result); + println!("Rows={:?}, Cols={:?}", result.event.rows, result.event.cols); + println!( + "TxHash={:?}, BlockHash={:?}", + result.tx_hash, result.block_hash + ); Ok(()) } @@ -268,7 +278,7 @@ Origin Level: Root ### Interface ```rust -async fn set_application_key(&self, old_key: Key, new_key: Key, wait_for: WaitFor, account: &Keypair, options: Option) -> Result; +async fn set_application_key(&self, old_key: Key, new_key: Key, wait_for: WaitFor, account: &Keypair, options: Option) -> Result; ``` #### Parameters @@ -279,7 +289,7 @@ async fn set_application_key(&self, old_key: Key, new_key: Key, wait_for: WaitFo | newKey | Key | false | application key that will replace the old one | | waitFor | WaitFor | false | wait for block inclusion or finalization | | account | KeyringPair | false | account that will send and sign the transaction | -| options | Params | true | transaction params | +| options | Options | true | transaction parameters | ### Minimal Example @@ -298,7 +308,7 @@ tokio = { version = "1.38.0", features = ["rt-multi-thread"] } #### main.rs ```rust -use avail_rust::{Key, Keypair, SecretUri, WaitFor, SDK}; +use avail_rust::{Key, Keypair, Nonce, Options, SecretUri, WaitFor, SDK}; use core::str::FromStr; #[tokio::main] @@ -314,13 +324,22 @@ async fn main() -> Result<(), String> { let new_key = String::from("MyAwesomeKey2").as_bytes().to_vec(); let new_key = Key { 0: new_key }; + let wait_for = WaitFor::BlockInclusion; + let options = Options::new().nonce(Nonce::BestBlockAndTxPool); let result = sdk .tx .data_availability - .set_application_key(old_key, new_key, WaitFor::BlockInclusion, &account, None) + .set_application_key(old_key, new_key, wait_for, &account, Some(options)) .await?; - dbg!(result); + println!( + "OldKey={:?}, NewKey={:?}", + result.event.old_key, result.event.new_key + ); + println!( + "TxHash={:?}, BlockHash={:?}", + result.tx_hash, result.block_hash + ); Ok(()) } @@ -333,7 +352,7 @@ Origin Level: Root ### Interface ```rust -async fn set_submit_data_fee_modifier(&self, modifier: DispatchFeeModifier, wait_for: WaitFor, account: &Keypair, options: Option) -> Result; +async fn set_submit_data_fee_modifier(&self, modifier: DispatchFeeModifier, wait_for: WaitFor, account: &Keypair, options: Option) -> Result; ``` #### Parameters @@ -343,7 +362,7 @@ async fn set_submit_data_fee_modifier(&self, modifier: DispatchFeeModifier, wait | modifier | DispatchFeeModifier | false | new fee modifier values | | waitFor | WaitFor | false | wait for block inclusion or finalization | | account | KeyringPair | false | account that will send and sign the transaction | -| options | Params | true | transaction params | +| options | Options | true | transaction parameters | ### Minimal Example @@ -362,7 +381,7 @@ tokio = { version = "1.38.0", features = ["rt-multi-thread"] } #### main.rs ```rust -use avail_rust::{DispatchFeeModifier, Keypair, SecretUri, WaitFor, SDK}; +use avail_rust::{DispatchFeeModifier, Keypair, Nonce, Options, SecretUri, WaitFor, SDK}; use core::str::FromStr; #[tokio::main] @@ -379,10 +398,12 @@ async fn main() -> Result<(), String> { weight_fee_multiplier: None, }; + let wait_for = WaitFor::BlockInclusion; + let options = Options::new().nonce(Nonce::BestBlockAndTxPool); let result = sdk .tx .data_availability - .set_submit_data_fee_modifier(modifier, WaitFor::BlockInclusion, &account, None) + .set_submit_data_fee_modifier(modifier, wait_for, &account, Some(options)) .await?; dbg!(result); @@ -441,7 +462,7 @@ Origin Level: Signed ### Interface ```rust -async fn transfer_keep_alive(&self, dest: &str, value: u128, wait_for: WaitFor, account: &Keypair, options: Option) -> Result; +async fn transfer_keep_alive(&self, dest: &str, value: u128, wait_for: WaitFor, account: &Keypair, options: Option) -> Result; ``` #### Parameters @@ -452,7 +473,7 @@ async fn transfer_keep_alive(&self, dest: &str, value: u128, wait_for: WaitFor, | value | u128 | false | amount that is send. 10^18 is equal to 1 AVL | | waitFor | WaitFor | false | wait for block inclusion or finalization | | account | KeyringPair | false | account that will send and sign the transaction | -| options | Params | true | transaction params | +| options | Options | true | transaction parameters | ### Minimal Example @@ -471,7 +492,7 @@ tokio = { version = "1.38.0", features = ["rt-multi-thread"] } #### main.rs ```rust -use avail_rust::{Keypair, SecretUri, WaitFor, SDK}; +use avail_rust::{Keypair, Nonce, Options, SecretUri, WaitFor, SDK}; use core::str::FromStr; #[tokio::main] @@ -484,10 +505,12 @@ async fn main() -> Result<(), String> { let dest: &str = "5HGjWAeFDfFCWPsjFQdVV2Msvz2XtMktvgocEZcCj68kUMaw"; // Eve let amount = 1_000_000_000_000_000_000u128; // 1 Avail + let wait_for = WaitFor::BlockInclusion; + let options = Options::new().nonce(Nonce::BestBlockAndTxPool); let result = sdk .tx .balances - .transfer_keep_alive(dest, amount, WaitFor::BlockInclusion, &account, None) + .transfer_keep_alive(dest, amount, wait_for, &account, Some(options)) .await?; dbg!(result); @@ -536,7 +559,7 @@ Origin Level: Signed ### Interface ```rust -async fn transfer_allow_death(&self, dest: &str, value: u128, wait_for: WaitFor, account: &Keypair, options: Option) -> Result; +async fn transfer_allow_death(&self, dest: &str, value: u128, wait_for: WaitFor, account: &Keypair, options: Option) -> Result; ``` #### Parameters @@ -547,7 +570,7 @@ async fn transfer_allow_death(&self, dest: &str, value: u128, wait_for: WaitFor, | value | BN | false | amount that is send. 10^18 is equal to 1 AVL | | waitFor | WaitFor | false | wait for block inclusion or finalization | | account | KeyringPair | false | account that will send and sign the transaction | -| options | Params | true | transaction params | +| options | Options | true | transaction parameters | ### Minimal Example @@ -566,7 +589,7 @@ tokio = { version = "1.38.0", features = ["rt-multi-thread"] } #### main.rs ```rust -use avail_rust::{Keypair, SecretUri, WaitFor, SDK}; +use avail_rust::{Keypair, Nonce, Options, SecretUri, WaitFor, SDK}; use core::str::FromStr; #[tokio::main] @@ -579,10 +602,12 @@ async fn main() -> Result<(), String> { let dest = "5HGjWAeFDfFCWPsjFQdVV2Msvz2XtMktvgocEZcCj68kUMaw"; // Eve let amount = 1_000_000_000_000_000_00u128; // 1 Avail + let wait_for = WaitFor::BlockInclusion; + let options = Options::new().nonce(Nonce::BestBlockAndTxPool); let result = sdk .tx .balances - .transfer_allow_death(dest, amount, WaitFor::BlockInclusion, &account, None) + .transfer_allow_death(dest, amount, wait_for, &account, Some(options)) .await?; if let Some(event) = &result.event2 { @@ -636,7 +661,7 @@ Origin Level: Signed ### Interface ```rust -async fn transfer_all(&self, dest: &str, keep_alive: bool, wait_for: WaitFor, account: &Keypair, options: Option) -> Result; +async fn transfer_all(&self, dest: &str, keep_alive: bool, wait_for: WaitFor, account: &Keypair, options: Option) -> Result; ``` #### Parameters @@ -647,7 +672,7 @@ async fn transfer_all(&self, dest: &str, keep_alive: bool, wait_for: WaitFor, ac | keepAlive | bool | false | if set to false it will reap the account as well | | waitFor | WaitFor | false | wait for block inclusion or finalization | | account | KeyringPair | false | account that will send and sign the transaction | -| options | Params | true | transaction params | +| options | Options | true | transaction parameters | ### Minimal Example @@ -666,7 +691,7 @@ tokio = { version = "1.38.0", features = ["rt-multi-thread"] } #### main.rs ```rust -use avail_rust::{Keypair, SecretUri, WaitFor, SDK}; +use avail_rust::{Keypair, Nonce, Options, SecretUri, WaitFor, SDK}; use core::str::FromStr; #[tokio::main] @@ -679,10 +704,12 @@ async fn main() -> Result<(), String> { let dest = "5HGjWAeFDfFCWPsjFQdVV2Msvz2XtMktvgocEZcCj68kUMaw"; // Eve let keep_alive = false; + let wait_for = WaitFor::BlockInclusion; + let options = Options::new().nonce(Nonce::BestBlockAndTxPool); let result = sdk .tx .balances - .transfer_all(dest, keep_alive, WaitFor::BlockInclusion, &account, None) + .transfer_all(dest, keep_alive, wait_for, &account, Some(options)) .await?; if let Some(event) = &result.event2 { @@ -746,7 +773,7 @@ Origin Level: Signed ### Interface ```rust -async fn bond(&self, value: u128, payee: RewardDestination, wait_for: WaitFor, account: &Keypair, options: Option) -> Result; +async fn bond(&self, value: u128, payee: RewardDestination, wait_for: WaitFor, account: &Keypair, options: Option) -> Result; ``` #### Parameters @@ -757,7 +784,7 @@ async fn bond(&self, value: u128, payee: RewardDestination, wait_for: WaitFor, a | payee | RewardDestination | false | Can be: "Staked", "Stash", "None" or an account address | | waitFor | WaitFor | false | wait for block inclusion or finalization | | account | KeyringPair | false | account that will send and sign the transaction | -| options | Params | true | transaction params | +| options | Options | true | transaction parameters | ### Minimal Example @@ -776,7 +803,7 @@ tokio = { version = "1.38.0", features = ["rt-multi-thread"] } #### main.rs ```rust -use avail_rust::{Keypair, RewardDestination, SecretUri, WaitFor, SDK}; +use avail_rust::{Keypair, Nonce, Options, RewardDestination, SecretUri, WaitFor, SDK}; use core::str::FromStr; #[tokio::main] @@ -789,10 +816,12 @@ async fn main() -> Result<(), String> { let value = 1_000_000_000_000_000_000u128 * 100_000u128; // 100_000 Avail let payee = RewardDestination::Staked; + let wait_for = WaitFor::BlockInclusion; + let options = Options::new().nonce(Nonce::BestBlockAndTxPool); let result = sdk .tx .staking - .bond(value, payee, WaitFor::BlockInclusion, &account, None) + .bond(value, payee, wait_for, &account, Some(options)) .await?; dbg!(result); @@ -840,7 +869,7 @@ Origin Level: Signed ### Interface ```rust -async fn bond_extra(&self, max_additional: u128, wait_for: WaitFor, account: &Keypair, options: Option) -> Result; +async fn bond_extra(&self, max_additional: u128, wait_for: WaitFor, account: &Keypair, options: Option) -> Result; ``` #### Parameters @@ -850,7 +879,7 @@ async fn bond_extra(&self, max_additional: u128, wait_for: WaitFor, account: &Ke | maxAdditional | u128 | false | additional amount that is bond. 10^18 is equal to 1 Avail | | waitFor | WaitFor | false | wait for block inclusion or finalization | | account | KeyringPair | false | account that will send and sign the transaction | -| options | Params | true | transaction params | +| options | Options | true | transaction parameters | ### Minimal Example @@ -869,7 +898,7 @@ tokio = { version = "1.38.0", features = ["rt-multi-thread"] } #### main.rs ```rust -use avail_rust::{Keypair, SecretUri, WaitFor, SDK}; +use avail_rust::{Keypair, Nonce, Options, SecretUri, WaitFor, SDK}; use core::str::FromStr; #[tokio::main] @@ -881,10 +910,12 @@ async fn main() -> Result<(), String> { let account = Keypair::from_uri(&secret_uri).unwrap(); let max_additional = 1_000_000_000_000_000_000u128; // 1 AVAIL + let wait_for = WaitFor::BlockInclusion; + let options = Options::new().nonce(Nonce::BestBlockAndTxPool); let result = sdk .tx .staking - .bond_extra(max_additional, WaitFor::BlockInclusion, &account, None) + .bond_extra(max_additional, wait_for, &account, Some(options)) .await?; dbg!(result); @@ -932,7 +963,7 @@ Origin Level: Signed ### Interface ```rust -async fn chill(&self, wait_for: WaitFor, account: &Keypair, options: Option) -> Result; +async fn chill(&self, wait_for: WaitFor, account: &Keypair, options: Option) -> Result; ``` #### Parameters @@ -941,7 +972,7 @@ async fn chill(&self, wait_for: WaitFor, account: &Keypair, options: Option Result<(), String> { let secret_uri = SecretUri::from_str("//Alice//stash").unwrap(); let account = Keypair::from_uri(&secret_uri).unwrap(); + let wait_for = WaitFor::BlockInclusion; + let options = Options::new().nonce(Nonce::BestBlockAndTxPool); let result = sdk .tx .staking - .chill(WaitFor::BlockInclusion, &account, None) + .chill(wait_for, &account, Some(options)) .await?; dbg!(result); @@ -1023,7 +1056,7 @@ Origin Level: Signed ### Interface ```rust -async fn chill_other(&self, stash: &str, wait_for: WaitFor, account: &Keypair, options: Option) -> Result; +async fn chill_other(&self, stash: &str, wait_for: WaitFor, account: &Keypair, options: Option) -> Result; ``` #### Parameters @@ -1033,7 +1066,7 @@ async fn chill_other(&self, stash: &str, wait_for: WaitFor, account: &Keypair, o | stash | &str | false | address of stash account to chill | | waitFor | WaitFor | false | wait for block inclusion or finalization | | account | KeyringPair | false | account that will send and sign the transaction | -| options | Params | true | transaction params | +| options | Options | true | transaction parameters | ### Minimal Example @@ -1052,7 +1085,7 @@ tokio = { version = "1.38.0", features = ["rt-multi-thread"] } #### main.rs ```rust -use avail_rust::{Keypair, SecretUri, WaitFor, SDK}; +use avail_rust::{Keypair, Nonce, Options, SecretUri, WaitFor, SDK}; use core::str::FromStr; #[tokio::main] @@ -1064,10 +1097,12 @@ async fn main() -> Result<(), String> { let account = Keypair::from_uri(&secret_uri).unwrap(); let stash = "5GNJqTPyNqANBkUVMN1LPPrxXnFouWXoe2wNSmmEoLctxiZY"; // Alice Stash + let wait_for = WaitFor::BlockInclusion; + let options = Options::new().nonce(Nonce::BestBlockAndTxPool); let result = sdk .tx .staking - .chill_other(stash, WaitFor::BlockInclusion, &account, None) + .chill_other(stash, wait_for, &account, Some(options)) .await?; dbg!(result); @@ -1083,7 +1118,7 @@ Origin Level: Signed ### Interface ```rust -async fn nominate( &self, targets: &[String], wait_for: WaitFor, account: &Keypair, options: Option) -> Result; +async fn nominate( &self, targets: &[String], wait_for: WaitFor, account: &Keypair, options: Option) -> Result; ``` #### Parameters @@ -1093,7 +1128,7 @@ async fn nominate( &self, targets: &[String], wait_for: WaitFor, account: &Keypa | targets | &[String] | false | list od addresses to nominate | | waitFor | WaitFor | false | wait for block inclusion or finalization | | account | KeyringPair | false | account that will send and sign the transaction | -| options | Params | true | transaction params | +| options | Options | true | transaction parameters | ### Minimal Example @@ -1112,7 +1147,7 @@ tokio = { version = "1.38.0", features = ["rt-multi-thread"] } #### main.rs ```rust -use avail_rust::{Keypair, SecretUri, WaitFor, SDK}; +use avail_rust::{Keypair, Nonce, Options, SecretUri, WaitFor, SDK}; use core::str::FromStr; #[tokio::main] @@ -1127,10 +1162,12 @@ async fn main() -> Result<(), String> { String::from("5FHneW46xGXgs5mUiveU4sbTyGBzmstUspZC92UhjJM694ty"), // Bob; ]; + let wait_for = WaitFor::BlockInclusion; + let options = Options::new().nonce(Nonce::BestBlockAndTxPool); let result = sdk .tx .staking - .nominate(&targets, WaitFor::BlockInclusion, &account, None) + .nominate(&targets, wait_for, &account, Some(options)) .await?; dbg!(result); @@ -1166,8 +1203,8 @@ NominateTxSuccess { }, tx_data: Nominate { targets: [ - "5GNJqTPyNqANBkUVMN1LPPrxXnFouWXoe2wNSmmEoLctxiZY", - "5FHneW46xGXgs5mUiveU4sbTyGBzmstUspZC92UhjJM694ty", + Id(AccountId32(...)), + Id(AccountId32(...)), ], }, tx_hash: 0x6e0ae6fde353974f8b46aace441c49ba7ab135fa3743e0e1331d35c4528dacfb, @@ -1184,18 +1221,17 @@ Origin Level: Signed ### Interface ```rust -async fn unbond(&self, value: u128, wait_for: WaitFor, account: &Keypair, options: Option) -> Result; +async fn unbond(&self, value: u128, wait_for: WaitFor, account: &Keypair, options: Option) -> Result; ``` #### Parameters -| parameter | type | optional | description | -| --------- | ------------- | -------- | ----------------------------------------------- | -| value | u128 | false | amount of tokens to unbond | -| waitFor | WaitFor | false | wait for block inclusion or finalization | -| account | KeyringPair | false | account that will send and sign the transaction | -| options | SignerOptions | true | used to overwrite existing signer options | -| options | Params | true | transaction params | +| parameter | type | optional | description | +| --------- | ----------- | -------- | ----------------------------------------------- | +| value | u128 | false | amount of tokens to unbond | +| waitFor | WaitFor | false | wait for block inclusion or finalization | +| account | KeyringPair | false | account that will send and sign the transaction | +| options | Options | true | transaction parameters | ### Minimal Example @@ -1214,7 +1250,7 @@ tokio = { version = "1.38.0", features = ["rt-multi-thread"] } #### main.rs ```rust -use avail_rust::{Keypair, SecretUri, WaitFor, SDK}; +use avail_rust::{Keypair, Nonce, Options, SecretUri, WaitFor, SDK}; use core::str::FromStr; #[tokio::main] @@ -1226,10 +1262,12 @@ async fn main() -> Result<(), String> { let account = Keypair::from_uri(&secret_uri).unwrap(); let value = 1_000_000_000_000_000_000u128; // 1 Avail + let wait_for = WaitFor::BlockInclusion; + let options = Options::new().nonce(Nonce::BestBlockAndTxPool); let result = sdk .tx .staking - .unbond(value, WaitFor::BlockInclusion, &account, None) + .unbond(value, wait_for, &account, Some(options)) .await?; dbg!(result); @@ -1277,7 +1315,7 @@ Origin Level: Signed ### Interface ```rust -async fn validate(&self, commission: u8, blocked: bool, wait_for: WaitFor, account: &Keypair, options: Option) -> Result; +async fn validate(&self, commission: u8, blocked: bool, wait_for: WaitFor, account: &Keypair, options: Option) -> Result; ``` #### Parameters @@ -1288,7 +1326,7 @@ async fn validate(&self, commission: u8, blocked: bool, wait_for: WaitFor, accou | blocked | bool | false | whether or not this validator accepts nominations | | waitFor | WaitFor | false | wait for block inclusion or finalization | | account | KeyringPair | false | account that will send and sign the transaction | -| options | Params | true | transaction params | +| options | Options | true | transaction parameters | ### Minimal Example @@ -1307,7 +1345,7 @@ tokio = { version = "1.38.0", features = ["rt-multi-thread"] } #### main.rs ```rust -use avail_rust::{Keypair, SecretUri, WaitFor, SDK}; +use avail_rust::{Keypair, Nonce, Options, SecretUri, WaitFor, SDK}; use core::str::FromStr; #[tokio::main] @@ -1320,10 +1358,12 @@ async fn main() -> Result<(), String> { let commission = 100; let blocked = false; + let wait_for = WaitFor::BlockInclusion; + let options = Options::new().nonce(Nonce::BestBlockAndTxPool); let result = sdk .tx .staking - .validate(commission, blocked, WaitFor::BlockInclusion, &account, None) + .validate(commission, blocked, wait_for, &account, Some(options)) .await?; dbg!(result); @@ -1382,7 +1422,7 @@ Origin Level: Signed ### Interface ```rust -async fn set_keys(&self, keys: SessionKeys, wait_for: WaitFor, account: &Keypair, options: Option) -> Result; +async fn set_keys(&self, keys: SessionKeys, wait_for: WaitFor, account: &Keypair, options: Option) -> Result; ``` #### Parameters @@ -1392,7 +1432,7 @@ async fn set_keys(&self, keys: SessionKeys, wait_for: WaitFor, account: &Keypair | keys | SessionKeys | false | session keys | | waitFor | WaitFor | false | wait for block inclusion or finalization | | account | KeyringPair | false | account that will send and sign the transaction | -| options | Params | true | transaction params | +| options | Options | true | transaction parameters | ### Minimal Example @@ -1411,7 +1451,7 @@ tokio = { version = "1.38.0", features = ["rt-multi-thread"] } #### main.rs ```rust -use avail_rust::{Keypair, SecretUri, WaitFor, SDK}; +use avail_rust::{Keypair, Nonce, Options, SecretUri, WaitFor, SDK}; use core::str::FromStr; #[tokio::main] @@ -1421,13 +1461,15 @@ async fn main() -> Result<(), String> { // Input let secret_uri = SecretUri::from_str("//Alice").unwrap(); let account = Keypair::from_uri(&secret_uri).unwrap(); - let keys = sdk.rpc.author.rotate_keys().await.unwrap(); let keys = sdk.util.deconstruct_session_keys(keys)?; + + let wait_for = WaitFor::BlockInclusion; + let options = Options::new().nonce(Nonce::BestBlockAndTxPool); let result = sdk .tx .session - .set_keys(keys, WaitFor::BlockInclusion, &account, None) + .set_keys(keys, wait_for, &account, Some(options)) .await?; dbg!(result); @@ -1480,3 +1522,440 @@ SetKeysTxSuccess { block_number: 124, } ``` + +# Nomination Pools + +Runtime Component: Nomination Pools\ +Runtime Index: 36\ +Interface Module Name: nominationPools + +## Create + +Origin Level: Signed + +### Interface + +```rust +async fn create(&self, amount: u128, root: &str, nominator: &str, bouncer: &str, wait_for: WaitFor, account: &Keypair, options: Option) -> Result; +``` + +#### Parameters + +| parameter | type | optional | description | +| --------- | ----------- | -------- | -------------------------------------------------- | +| amount | u128 | false | The amount of funds to delegate to the pool | +| root | WaitFor | false | The account to set as [`PoolRoles::root`] | +| nominator | &str | false | The account to set as the [`PoolRoles::nominator`] | +| bouncer | &str | false | The account to set as the [`PoolRoles::bouncer`] | +| waitFor | WaitFor | false | wait for block inclusion or finalization | +| account | KeyringPair | false | account that will send and sign the transaction | +| options | Options | true | transaction parameters | + +### Minimal Example + +#### Cargo.toml + +```rust +[package] +name = "nomination-pools-create" +edition = "2021" + +[dependencies] +avail-rust = { git = "https://github.com/availproject/avail" } +tokio = { version = "1.38.0", features = ["rt-multi-thread"] } +``` + +#### main.rs + +```rust +use avail_rust::{Keypair, Nonce, Options, SecretUri, WaitFor, SDK}; +use core::str::FromStr; + +#[tokio::main] +async fn main() -> Result<(), String> { + let sdk = SDK::new("ws://127.0.0.1:9944").await.unwrap(); + + // Input + let secret_uri = SecretUri::from_str("//Alice").unwrap(); + let account = Keypair::from_uri(&secret_uri).unwrap(); + let amount = 1_000_000_000_000_000_000_000_000u128; // 1_000_000 Avail tokens + let root = "5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY"; // Alice + let nominator = "5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY"; // Alice + let bouncer = "5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY"; // Alice + + let wait_for = WaitFor::BlockInclusion; + let options = Options::new().nonce(Nonce::BestBlockAndTxPool); + let result = sdk + .tx + .nomination_pools + .create( + amount, + root, + nominator, + bouncer, + wait_for, + &account, + Some(options), + ) + .await?; + + dbg!(result); + + Ok(()) +} +``` + +### Example Output + +#### On Failure + +If the operation fails, the function will return an error message indicating the nature of the issue. + +#### On Success + +If the operation is successful, the function will return a object of type `PoolCreateTxSuccess`. + +```rust +PoolCreateTxSuccess { + event: Created { + depositor: AccountId32(...), + pool_id: 1, + }, + event2: Bonded { + member: AccountId32(...), + pool_id: 1, + bonded: 1000000000000000000000000, + joined: true, + }, + events: ExtrinsicEvents { + ext_hash: 0xd68cd496c042b1de9484c03160dcaea0b66d939a7293d457b721e908542ce4dd, + idx: 1, + events: Events { + event_bytes: [...], + start_idx: 1, + num_events: 19, + }, + }, + tx_hash: 0xd68cd496c042b1de9484c03160dcaea0b66d939a7293d457b721e908542ce4dd, + tx_index: 1, + block_hash: 0x21119a080adf597abb22db237f8824a0dbd823feb6a809e2f2d9bb7872377e9d, + block_number: 1, +} +``` + +## Create with Pool Id + +Origin Level: Signed + +### Interface + +```rust +async fn create_with_pool_id(&self, amount: u128, root: &str, nominator: &str, bouncer: &str, pool_id: u32, wait_for: WaitFor, account: &Keypair, options: Option) -> Result; +``` + +#### Parameters + +| parameter | type | optional | description | +| --------- | ----------- | -------- | -------------------------------------------------- | +| amount | u128 | false | The amount of funds to delegate to the pool | +| root | WaitFor | false | The account to set as [`PoolRoles::root`] | +| nominator | &str | false | The account to set as the [`PoolRoles::nominator`] | +| bouncer | &str | false | The account to set as the [`PoolRoles::bouncer`] | +| pool id | u32 | false | pool id | +| waitFor | WaitFor | false | wait for block inclusion or finalization | +| account | KeyringPair | false | account that will send and sign the transaction | +| options | Options | true | transaction parameters | + +### Minimal Example + +#### Cargo.toml + +```rust +[package] +name = "nomination-pools-create-with-pool-id" +edition = "2021" + +[dependencies] +avail-rust = { git = "https://github.com/availproject/avail" } +tokio = { version = "1.38.0", features = ["rt-multi-thread"] } +``` + +#### main.rs + +```rust +use avail_rust::{Keypair, Nonce, Options, SecretUri, WaitFor, SDK}; +use core::str::FromStr; + +#[tokio::main] +async fn main() -> Result<(), String> { + let sdk = SDK::new("ws://127.0.0.1:9944").await.unwrap(); + + // Input + let secret_uri = SecretUri::from_str("//Alice").unwrap(); + let account = Keypair::from_uri(&secret_uri).unwrap(); + let amount = 1_000_000_000_000_000_000_000_000u128; // 1_000_000 Avail tokens + let root = "5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY"; // Alice + let nominator = "5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY"; // Alice + let bouncer = "5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY"; // Alice + let pool_id = 0; + + let wait_for = WaitFor::BlockInclusion; + let options = Options::new().nonce(Nonce::BestBlockAndTxPool); + let result = sdk + .tx + .nomination_pools + .create_with_pool_id( + amount, + root, + nominator, + bouncer, + pool_id, + wait_for, + &account, + Some(options), + ) + .await?; + + dbg!(result); + + Ok(()) +} +``` + +### Example Output + +#### On Failure + +If the operation fails, the function will return an error message indicating the nature of the issue. + +#### On Success + +If the operation is successful, the function will return a object of type `PoolCreateWithPoolIdTxSuccess`. + +```rust +PoolCreateWithPoolIdTxSuccess { + event: Created { + depositor: AccountId32(...), + pool_id: 0, + }, + event2: Bonded { + member: AccountId32(...), + pool_id: 0, + bonded: 1000000000000000000000000, + joined: true, + }, + events: ExtrinsicEvents { + ext_hash: 0xaa16bad7378608bda89476353a61c1ae1ecc36166f0c5adda50cd563162889db, + idx: 1, + events: Events { + event_bytes: [], + start_idx: 1, + num_events: 19, + }, + }, + tx_hash: 0xaa16bad7378608bda89476353a61c1ae1ecc36166f0c5adda50cd563162889db, + tx_index: 1, + block_hash: 0xc04789228e6fa209119336ac33bcd6280b6b0c22e5ef9125c36b9f4a04e58adc, + block_number: 32, +} +``` + +## Join + +Origin Level: Signed + +### Interface + +```rust +async fn join(&self, amount: u128, pool_id: u32, wait_for: WaitFor, account: &Keypair, options: Option) -> Result; +``` + +#### Parameters + +| parameter | type | optional | description | +| --------- | ----------- | -------- | ----------------------------------------------- | +| amount | u128 | false | The amount of funds to delegate to the pool | +| pool id | u32 | false | pool id | +| waitFor | WaitFor | false | wait for block inclusion or finalization | +| account | KeyringPair | false | account that will send and sign the transaction | +| options | Options | true | transaction parameters | + +### Minimal Example + +#### Cargo.toml + +```rust +[package] +name = "nomination-pools-join" +edition = "2021" + +[dependencies] +avail-rust = { git = "https://github.com/availproject/avail" } +tokio = { version = "1.38.0", features = ["rt-multi-thread"] } +``` + +#### main.rs + +```rust +use avail_rust::{Keypair, Nonce, Options, SecretUri, WaitFor, SDK}; +use core::str::FromStr; + +#[tokio::main] +async fn main() -> Result<(), String> { + let sdk = SDK::new("ws://127.0.0.1:9944").await.unwrap(); + + // Input + let secret_uri = SecretUri::from_str("//Bob").unwrap(); + let account = Keypair::from_uri(&secret_uri).unwrap(); + let amount = 1_000_000_000_000_000_000_000_000u128; // 1_000_000 Avail tokens + let pool_id = 1; + + let wait_for = WaitFor::BlockInclusion; + let options = Options::new().nonce(Nonce::BestBlockAndTxPool); + let result = sdk + .tx + .nomination_pools + .join(amount, pool_id, wait_for, &account, Some(options)) + .await?; + + dbg!(result); + + Ok(()) +} +``` + +### Example Output + +#### On Failure + +If the operation fails, the function will return an error message indicating the nature of the issue. + +#### On Success + +If the operation is successful, the function will return a object of type `PoolJoinTxSuccess`. + +```rust +PoolJoinTxSuccess { + event: Bonded { + member: AccountId32(...), + pool_id: 1, + bonded: 1000000000000000000000000, + joined: true, + }, + events: ExtrinsicEvents { + ext_hash: 0x1c3c2412859e9c1d29a17cdaad48ff835bfbc7bb1b2bda5686d152f7c5145a40, + idx: 1, + events: Events { + event_bytes: [...], + start_idx: 1, + num_events: 12, + }, + }, + tx_hash: 0x1c3c2412859e9c1d29a17cdaad48ff835bfbc7bb1b2bda5686d152f7c5145a40, + tx_index: 1, + block_hash: 0x67f28bfd6826522dc53ccfdec24dffbe9954ff4af8d96e81e983227af101786b, + block_number: 24, +} +``` + +## Nominate + +Origin Level: Signed + +### Interface + +```rust +async fn nominate(&self, pool_id: u32, validators: Vec, wait_for: WaitFor, account: &Keypair, options: Option) -> Result; +``` + +#### Parameters + +| parameter | type | optional | description | +| ---------- | ----------- | -------- | ----------------------------------------------- | +| pool id | u32 | false | pool id | +| validators | String | false | list of validators to nominate | +| waitFor | WaitFor | false | wait for block inclusion or finalization | +| account | KeyringPair | false | account that will send and sign the transaction | +| options | Options | true | transaction parameters | + +### Minimal Example + +#### Cargo.toml + +```rust +[package] +name = "nomination-pools-nominate" +edition = "2021" + +[dependencies] +avail-rust = { git = "https://github.com/availproject/avail" } +tokio = { version = "1.38.0", features = ["rt-multi-thread"] } +``` + +#### main.rs + +```rust +use avail_rust::{Keypair, Nonce, Options, SecretUri, WaitFor, SDK}; +use core::str::FromStr; + +#[tokio::main] +async fn main() -> Result<(), String> { + let sdk = SDK::new("ws://127.0.0.1:9944").await.unwrap(); + + // Input + let secret_uri = SecretUri::from_str("//Alice").unwrap(); + let account = Keypair::from_uri(&secret_uri).unwrap(); + let pool_id = 1; + let validators = vec![ + String::from("5GNJqTPyNqANBkUVMN1LPPrxXnFouWXoe2wNSmmEoLctxiZY"), // Alice_Stash + String::from("5FHneW46xGXgs5mUiveU4sbTyGBzmstUspZC92UhjJM694ty"), // Bob + ]; + + let wait_for = WaitFor::BlockInclusion; + let options = Options::new().nonce(Nonce::BestBlockAndTxPool); + let result = sdk + .tx + .nomination_pools + .nominate(pool_id, validators, wait_for, &account, Some(options)) + .await?; + + dbg!(result); + + Ok(()) +} +``` + +### Example Output + +#### On Failure + +If the operation fails, the function will return an error message indicating the nature of the issue. + +#### On Success + +If the operation is successful, the function will return a object of type `PoolNominateTxSuccess`. + +```rust +PoolNominateTxSuccess { + events: ExtrinsicEvents { + ext_hash: 0xde74e9df59143b84ed216e4e52fd58ec8bd557fae4b54d992a9abb1adf750446, + idx: 1, + events: Events { + event_bytes: [...], + start_idx: 1, + num_events: 8, + }, + }, + tx_data: Nominate { + pool_id: 1, + validators: [ + AccountId32(...), + AccountId32(...), + ], + }, + tx_hash: 0xde74e9df59143b84ed216e4e52fd58ec8bd557fae4b54d992a9abb1adf750446, + tx_index: 1, + block_hash: 0x599dd28c28fe3d892ebbe7dfdc315bee03fa2a3d968a5c53f4cd031656a94a9a, + block_number: 86, +} +``` diff --git a/avail-rust/docs/extrinsics/balance_transfer_all/src/main.rs b/avail-rust/docs/extrinsics/balance_transfer_all/src/main.rs index bcc715408..7850943fc 100644 --- a/avail-rust/docs/extrinsics/balance_transfer_all/src/main.rs +++ b/avail-rust/docs/extrinsics/balance_transfer_all/src/main.rs @@ -1,4 +1,4 @@ -use avail_rust::{Keypair, SecretUri, WaitFor, SDK}; +use avail_rust::{Keypair, Nonce, Options, SecretUri, WaitFor, SDK}; use core::str::FromStr; #[tokio::main] @@ -11,10 +11,12 @@ async fn main() -> Result<(), String> { let dest = "5HGjWAeFDfFCWPsjFQdVV2Msvz2XtMktvgocEZcCj68kUMaw"; // Eve let keep_alive = false; + let wait_for = WaitFor::BlockInclusion; + let options = Options::new().nonce(Nonce::BestBlockAndTxPool); let result = sdk .tx .balances - .transfer_all(dest, keep_alive, WaitFor::BlockInclusion, &account, None) + .transfer_all(dest, keep_alive, wait_for, &account, Some(options)) .await?; if let Some(event) = &result.event2 { diff --git a/avail-rust/docs/extrinsics/balance_transfer_allow_death/src/main.rs b/avail-rust/docs/extrinsics/balance_transfer_allow_death/src/main.rs index 8883af5fd..0e5f38634 100644 --- a/avail-rust/docs/extrinsics/balance_transfer_allow_death/src/main.rs +++ b/avail-rust/docs/extrinsics/balance_transfer_allow_death/src/main.rs @@ -1,4 +1,4 @@ -use avail_rust::{Keypair, SecretUri, WaitFor, SDK}; +use avail_rust::{Keypair, Nonce, Options, SecretUri, WaitFor, SDK}; use core::str::FromStr; #[tokio::main] @@ -11,10 +11,12 @@ async fn main() -> Result<(), String> { let dest = "5HGjWAeFDfFCWPsjFQdVV2Msvz2XtMktvgocEZcCj68kUMaw"; // Eve let amount = 1_000_000_000_000_000_00u128; // 1 Avail + let wait_for = WaitFor::BlockInclusion; + let options = Options::new().nonce(Nonce::BestBlockAndTxPool); let result = sdk .tx .balances - .transfer_allow_death(dest, amount, WaitFor::BlockInclusion, &account, None) + .transfer_allow_death(dest, amount, wait_for, &account, Some(options)) .await?; if let Some(event) = &result.event2 { diff --git a/avail-rust/docs/extrinsics/balance_transfer_keep_alive/src/main.rs b/avail-rust/docs/extrinsics/balance_transfer_keep_alive/src/main.rs index d05c25e0e..74165b99a 100644 --- a/avail-rust/docs/extrinsics/balance_transfer_keep_alive/src/main.rs +++ b/avail-rust/docs/extrinsics/balance_transfer_keep_alive/src/main.rs @@ -1,4 +1,4 @@ -use avail_rust::{Keypair, SecretUri, WaitFor, SDK}; +use avail_rust::{Keypair, Nonce, Options, SecretUri, WaitFor, SDK}; use core::str::FromStr; #[tokio::main] @@ -11,10 +11,12 @@ async fn main() -> Result<(), String> { let dest: &str = "5HGjWAeFDfFCWPsjFQdVV2Msvz2XtMktvgocEZcCj68kUMaw"; // Eve let amount = 1_000_000_000_000_000_000u128; // 1 Avail + let wait_for = WaitFor::BlockInclusion; + let options = Options::new().nonce(Nonce::BestBlockAndTxPool); let result = sdk .tx .balances - .transfer_keep_alive(dest, amount, WaitFor::BlockInclusion, &account, None) + .transfer_keep_alive(dest, amount, wait_for, &account, Some(options)) .await?; dbg!(result); diff --git a/avail-rust/docs/extrinsics/da_create_application_key/src/main.rs b/avail-rust/docs/extrinsics/da_create_application_key/src/main.rs index b47823fc5..5606bb623 100644 --- a/avail-rust/docs/extrinsics/da_create_application_key/src/main.rs +++ b/avail-rust/docs/extrinsics/da_create_application_key/src/main.rs @@ -1,4 +1,4 @@ -use avail_rust::{Key, Keypair, SecretUri, WaitFor, SDK}; +use avail_rust::{Key, Keypair, Nonce, Options, SecretUri, WaitFor, SDK}; use core::str::FromStr; #[tokio::main] @@ -11,10 +11,12 @@ async fn main() -> Result<(), String> { let key = String::from("MyAwesomeKey").as_bytes().to_vec(); let key = Key { 0: key }; + let wait_for = WaitFor::BlockInclusion; + let options = Options::new().nonce(Nonce::BestBlockAndTxPool); let result = sdk .tx .data_availability - .create_application_key(key, WaitFor::BlockInclusion, &account, None) + .create_application_key(key, wait_for, &account, Some(options)) .await?; dbg!(result); diff --git a/avail-rust/docs/extrinsics/da_set_application_key/src/main.rs b/avail-rust/docs/extrinsics/da_set_application_key/src/main.rs index e3df9b81a..2ff8c9899 100644 --- a/avail-rust/docs/extrinsics/da_set_application_key/src/main.rs +++ b/avail-rust/docs/extrinsics/da_set_application_key/src/main.rs @@ -1,4 +1,4 @@ -use avail_rust::{Key, Keypair, SecretUri, WaitFor, SDK}; +use avail_rust::{Key, Keypair, Nonce, Options, SecretUri, WaitFor, SDK}; use core::str::FromStr; #[tokio::main] @@ -14,10 +14,12 @@ async fn main() -> Result<(), String> { let new_key = String::from("MyAwesomeKey2").as_bytes().to_vec(); let new_key = Key { 0: new_key }; + let wait_for = WaitFor::BlockInclusion; + let options = Options::new().nonce(Nonce::BestBlockAndTxPool); let result = sdk .tx .data_availability - .set_application_key(old_key, new_key, WaitFor::BlockInclusion, &account, None) + .set_application_key(old_key, new_key, wait_for, &account, Some(options)) .await?; println!( diff --git a/avail-rust/docs/extrinsics/da_set_submit_data_fee_modifier/src/main.rs b/avail-rust/docs/extrinsics/da_set_submit_data_fee_modifier/src/main.rs index 798bcf564..3e21a49b6 100644 --- a/avail-rust/docs/extrinsics/da_set_submit_data_fee_modifier/src/main.rs +++ b/avail-rust/docs/extrinsics/da_set_submit_data_fee_modifier/src/main.rs @@ -1,4 +1,4 @@ -use avail_rust::{DispatchFeeModifier, Keypair, SecretUri, WaitFor, SDK}; +use avail_rust::{DispatchFeeModifier, Keypair, Nonce, Options, SecretUri, WaitFor, SDK}; use core::str::FromStr; #[tokio::main] @@ -15,10 +15,12 @@ async fn main() -> Result<(), String> { weight_fee_multiplier: None, }; + let wait_for = WaitFor::BlockInclusion; + let options = Options::new().nonce(Nonce::BestBlockAndTxPool); let result = sdk .tx .data_availability - .set_submit_data_fee_modifier(modifier, WaitFor::BlockInclusion, &account, None) + .set_submit_data_fee_modifier(modifier, wait_for, &account, Some(options)) .await?; dbg!(result); diff --git a/avail-rust/docs/extrinsics/da_submit_block_length_proposal/src/main.rs b/avail-rust/docs/extrinsics/da_submit_block_length_proposal/src/main.rs index 751648026..94262d95d 100644 --- a/avail-rust/docs/extrinsics/da_submit_block_length_proposal/src/main.rs +++ b/avail-rust/docs/extrinsics/da_submit_block_length_proposal/src/main.rs @@ -1,4 +1,4 @@ -use avail_rust::{Keypair, SecretUri, WaitFor, SDK}; +use avail_rust::{Keypair, Nonce, Options, SecretUri, WaitFor, SDK}; use core::str::FromStr; #[tokio::main] @@ -12,10 +12,12 @@ async fn main() -> Result<(), String> { let rows = 128; let cols = 128; + let wait_for = WaitFor::BlockInclusion; + let options = Options::new().nonce(Nonce::BestBlockAndTxPool); let result = sdk .tx .data_availability - .submit_block_length_proposal(rows, cols, WaitFor::BlockInclusion, &account, None) + .submit_block_length_proposal(rows, cols, wait_for, &account, Some(options)) .await?; println!("Rows={:?}, Cols={:?}", result.event.rows, result.event.cols); diff --git a/avail-rust/docs/extrinsics/da_submit_data/src/main.rs b/avail-rust/docs/extrinsics/da_submit_data/src/main.rs index ec4ba2c05..36f4a8349 100644 --- a/avail-rust/docs/extrinsics/da_submit_data/src/main.rs +++ b/avail-rust/docs/extrinsics/da_submit_data/src/main.rs @@ -1,4 +1,4 @@ -use avail_rust::{Data, Keypair, SecretUri, WaitFor, SDK}; +use avail_rust::{Data, Keypair, Nonce, Options, SecretUri, WaitFor, SDK}; use core::str::FromStr; #[tokio::main] @@ -11,10 +11,12 @@ async fn main() -> Result<(), String> { let data = String::from("My Awesome Data").as_bytes().to_vec(); let data = Data { 0: data }; + let wait_for = WaitFor::BlockInclusion; + let options = Options::new().nonce(Nonce::BestBlockAndTxPool); let result = sdk .tx .data_availability - .submit_data(data, WaitFor::BlockInclusion, &account, None) + .submit_data(data, wait_for, &account, Some(options)) .await?; dbg!(result); diff --git a/avail-rust/docs/extrinsics/nomination_pools_create/Cargo.toml b/avail-rust/docs/extrinsics/nomination_pools_create/Cargo.toml new file mode 100644 index 000000000..5eaec4872 --- /dev/null +++ b/avail-rust/docs/extrinsics/nomination_pools_create/Cargo.toml @@ -0,0 +1,9 @@ +[workspace] + +[package] +name = "nomination-pools-create" +edition = "2021" + +[dependencies] +avail-rust = { git = "https://github.com/availproject/avail" } +tokio = { version = "1.38.0", features = ["rt-multi-thread"] } diff --git a/avail-rust/docs/extrinsics/nomination_pools_create/src/main.rs b/avail-rust/docs/extrinsics/nomination_pools_create/src/main.rs new file mode 100644 index 000000000..8a557d84f --- /dev/null +++ b/avail-rust/docs/extrinsics/nomination_pools_create/src/main.rs @@ -0,0 +1,35 @@ +use avail_rust::{Keypair, Nonce, Options, SecretUri, WaitFor, SDK}; +use core::str::FromStr; + +#[tokio::main] +async fn main() -> Result<(), String> { + let sdk = SDK::new("ws://127.0.0.1:9944").await.unwrap(); + + // Input + let secret_uri = SecretUri::from_str("//Alice").unwrap(); + let account = Keypair::from_uri(&secret_uri).unwrap(); + let amount = 1_000_000_000_000_000_000_000_000u128; // 1_000_000 Avail tokens + let root = "5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY"; // Alice + let nominator = "5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY"; // Alice + let bouncer = "5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY"; // Alice + + let wait_for = WaitFor::BlockInclusion; + let options = Options::new().nonce(Nonce::BestBlockAndTxPool); + let result = sdk + .tx + .nomination_pools + .create( + amount, + root, + nominator, + bouncer, + wait_for, + &account, + Some(options), + ) + .await?; + + dbg!(result); + + Ok(()) +} diff --git a/avail-rust/docs/extrinsics/nomination_pools_create_with_pool_id/Cargo.toml b/avail-rust/docs/extrinsics/nomination_pools_create_with_pool_id/Cargo.toml new file mode 100644 index 000000000..c1de54e60 --- /dev/null +++ b/avail-rust/docs/extrinsics/nomination_pools_create_with_pool_id/Cargo.toml @@ -0,0 +1,9 @@ +[workspace] + +[package] +name = "nomination-pools-create-with-pool-id" +edition = "2021" + +[dependencies] +avail-rust = { git = "https://github.com/availproject/avail" } +tokio = { version = "1.38.0", features = ["rt-multi-thread"] } diff --git a/avail-rust/docs/extrinsics/nomination_pools_create_with_pool_id/src/main.rs b/avail-rust/docs/extrinsics/nomination_pools_create_with_pool_id/src/main.rs new file mode 100644 index 000000000..0d14604d1 --- /dev/null +++ b/avail-rust/docs/extrinsics/nomination_pools_create_with_pool_id/src/main.rs @@ -0,0 +1,37 @@ +use avail_rust::{Keypair, Nonce, Options, SecretUri, WaitFor, SDK}; +use core::str::FromStr; + +#[tokio::main] +async fn main() -> Result<(), String> { + let sdk = SDK::new("ws://127.0.0.1:9944").await.unwrap(); + + // Input + let secret_uri = SecretUri::from_str("//Alice").unwrap(); + let account = Keypair::from_uri(&secret_uri).unwrap(); + let amount = 1_000_000_000_000_000_000_000_000u128; // 1_000_000 Avail tokens + let root = "5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY"; // Alice + let nominator = "5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY"; // Alice + let bouncer = "5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY"; // Alice + let pool_id = 0; + + let wait_for = WaitFor::BlockInclusion; + let options = Options::new().nonce(Nonce::BestBlockAndTxPool); + let result = sdk + .tx + .nomination_pools + .create_with_pool_id( + amount, + root, + nominator, + bouncer, + pool_id, + wait_for, + &account, + Some(options), + ) + .await?; + + dbg!(result); + + Ok(()) +} diff --git a/avail-rust/docs/extrinsics/nomination_pools_join/Cargo.toml b/avail-rust/docs/extrinsics/nomination_pools_join/Cargo.toml new file mode 100644 index 000000000..fa2fcfd77 --- /dev/null +++ b/avail-rust/docs/extrinsics/nomination_pools_join/Cargo.toml @@ -0,0 +1,9 @@ +[workspace] + +[package] +name = "nomination-pools-join" +edition = "2021" + +[dependencies] +avail-rust = { git = "https://github.com/availproject/avail" } +tokio = { version = "1.38.0", features = ["rt-multi-thread"] } diff --git a/avail-rust/docs/extrinsics/nomination_pools_join/src/main.rs b/avail-rust/docs/extrinsics/nomination_pools_join/src/main.rs new file mode 100644 index 000000000..a87790bea --- /dev/null +++ b/avail-rust/docs/extrinsics/nomination_pools_join/src/main.rs @@ -0,0 +1,25 @@ +use avail_rust::{Keypair, Nonce, Options, SecretUri, WaitFor, SDK}; +use core::str::FromStr; + +#[tokio::main] +async fn main() -> Result<(), String> { + let sdk = SDK::new("ws://127.0.0.1:9944").await.unwrap(); + + // Input + let secret_uri = SecretUri::from_str("//Bob").unwrap(); + let account = Keypair::from_uri(&secret_uri).unwrap(); + let amount = 1_000_000_000_000_000_000_000_000u128; // 1_000_000 Avail tokens + let pool_id = 1; + + let wait_for = WaitFor::BlockInclusion; + let options = Options::new().nonce(Nonce::BestBlockAndTxPool); + let result = sdk + .tx + .nomination_pools + .join(amount, pool_id, wait_for, &account, Some(options)) + .await?; + + dbg!(result); + + Ok(()) +} diff --git a/avail-rust/docs/extrinsics/nomination_pools_nominate/Cargo.toml b/avail-rust/docs/extrinsics/nomination_pools_nominate/Cargo.toml new file mode 100644 index 000000000..0fbfad3a8 --- /dev/null +++ b/avail-rust/docs/extrinsics/nomination_pools_nominate/Cargo.toml @@ -0,0 +1,9 @@ +[workspace] + +[package] +name = "nomination-pools-nominate" +edition = "2021" + +[dependencies] +avail-rust = { git = "https://github.com/availproject/avail" } +tokio = { version = "1.38.0", features = ["rt-multi-thread"] } diff --git a/avail-rust/docs/extrinsics/nomination_pools_nominate/src/main.rs b/avail-rust/docs/extrinsics/nomination_pools_nominate/src/main.rs new file mode 100644 index 000000000..81c7a7a9b --- /dev/null +++ b/avail-rust/docs/extrinsics/nomination_pools_nominate/src/main.rs @@ -0,0 +1,28 @@ +use avail_rust::{Keypair, Nonce, Options, SecretUri, WaitFor, SDK}; +use core::str::FromStr; + +#[tokio::main] +async fn main() -> Result<(), String> { + let sdk = SDK::new("ws://127.0.0.1:9944").await.unwrap(); + + // Input + let secret_uri = SecretUri::from_str("//Alice").unwrap(); + let account = Keypair::from_uri(&secret_uri).unwrap(); + let pool_id = 1; + let validators = vec![ + String::from("5GNJqTPyNqANBkUVMN1LPPrxXnFouWXoe2wNSmmEoLctxiZY"), // Alice_Stash + String::from("5FHneW46xGXgs5mUiveU4sbTyGBzmstUspZC92UhjJM694ty"), // Bob + ]; + + let wait_for = WaitFor::BlockInclusion; + let options = Options::new().nonce(Nonce::BestBlockAndTxPool); + let result = sdk + .tx + .nomination_pools + .nominate(pool_id, validators, wait_for, &account, Some(options)) + .await?; + + dbg!(result); + + Ok(()) +} diff --git a/avail-rust/docs/extrinsics/session_set_keys/src/main.rs b/avail-rust/docs/extrinsics/session_set_keys/src/main.rs index c7cd3d969..5bbce162b 100644 --- a/avail-rust/docs/extrinsics/session_set_keys/src/main.rs +++ b/avail-rust/docs/extrinsics/session_set_keys/src/main.rs @@ -1,4 +1,4 @@ -use avail_rust::{Keypair, SecretUri, WaitFor, SDK}; +use avail_rust::{Keypair, Nonce, Options, SecretUri, WaitFor, SDK}; use core::str::FromStr; #[tokio::main] @@ -8,13 +8,15 @@ async fn main() -> Result<(), String> { // Input let secret_uri = SecretUri::from_str("//Alice").unwrap(); let account = Keypair::from_uri(&secret_uri).unwrap(); - let keys = sdk.rpc.author.rotate_keys().await.unwrap(); let keys = sdk.util.deconstruct_session_keys(keys)?; + + let wait_for = WaitFor::BlockInclusion; + let options = Options::new().nonce(Nonce::BestBlockAndTxPool); let result = sdk .tx .session - .set_keys(keys, WaitFor::BlockInclusion, &account, None) + .set_keys(keys, wait_for, &account, Some(options)) .await?; dbg!(result); diff --git a/avail-rust/docs/extrinsics/staking_bond/src/main.rs b/avail-rust/docs/extrinsics/staking_bond/src/main.rs index 9e1914cba..a69f80bc2 100644 --- a/avail-rust/docs/extrinsics/staking_bond/src/main.rs +++ b/avail-rust/docs/extrinsics/staking_bond/src/main.rs @@ -1,4 +1,4 @@ -use avail_rust::{Keypair, RewardDestination, SecretUri, WaitFor, SDK}; +use avail_rust::{Keypair, Nonce, Options, RewardDestination, SecretUri, WaitFor, SDK}; use core::str::FromStr; #[tokio::main] @@ -11,10 +11,12 @@ async fn main() -> Result<(), String> { let value = 1_000_000_000_000_000_000u128 * 100_000u128; // 100_000 Avail let payee = RewardDestination::Staked; + let wait_for = WaitFor::BlockInclusion; + let options = Options::new().nonce(Nonce::BestBlockAndTxPool); let result = sdk .tx .staking - .bond(value, payee, WaitFor::BlockInclusion, &account, None) + .bond(value, payee, wait_for, &account, Some(options)) .await?; dbg!(result); diff --git a/avail-rust/docs/extrinsics/staking_bond_extra/src/main.rs b/avail-rust/docs/extrinsics/staking_bond_extra/src/main.rs index d498cfcc3..de616a9a3 100644 --- a/avail-rust/docs/extrinsics/staking_bond_extra/src/main.rs +++ b/avail-rust/docs/extrinsics/staking_bond_extra/src/main.rs @@ -1,4 +1,4 @@ -use avail_rust::{Keypair, SecretUri, WaitFor, SDK}; +use avail_rust::{Keypair, Nonce, Options, SecretUri, WaitFor, SDK}; use core::str::FromStr; #[tokio::main] @@ -10,10 +10,12 @@ async fn main() -> Result<(), String> { let account = Keypair::from_uri(&secret_uri).unwrap(); let max_additional = 1_000_000_000_000_000_000u128; // 1 AVAIL + let wait_for = WaitFor::BlockInclusion; + let options = Options::new().nonce(Nonce::BestBlockAndTxPool); let result = sdk .tx .staking - .bond_extra(max_additional, WaitFor::BlockInclusion, &account, None) + .bond_extra(max_additional, wait_for, &account, Some(options)) .await?; dbg!(result); diff --git a/avail-rust/docs/extrinsics/staking_chill/src/main.rs b/avail-rust/docs/extrinsics/staking_chill/src/main.rs index 3ba5bc41d..a99aea38a 100644 --- a/avail-rust/docs/extrinsics/staking_chill/src/main.rs +++ b/avail-rust/docs/extrinsics/staking_chill/src/main.rs @@ -1,4 +1,4 @@ -use avail_rust::{Keypair, SecretUri, WaitFor, SDK}; +use avail_rust::{Keypair, Nonce, Options, SecretUri, WaitFor, SDK}; use core::str::FromStr; #[tokio::main] @@ -9,10 +9,12 @@ async fn main() -> Result<(), String> { let secret_uri = SecretUri::from_str("//Alice//stash").unwrap(); let account = Keypair::from_uri(&secret_uri).unwrap(); + let wait_for = WaitFor::BlockInclusion; + let options = Options::new().nonce(Nonce::BestBlockAndTxPool); let result = sdk .tx .staking - .chill(WaitFor::BlockInclusion, &account, None) + .chill(wait_for, &account, Some(options)) .await?; dbg!(result); diff --git a/avail-rust/docs/extrinsics/staking_chill_other/src/main.rs b/avail-rust/docs/extrinsics/staking_chill_other/src/main.rs index 1612922d8..75937e8d0 100644 --- a/avail-rust/docs/extrinsics/staking_chill_other/src/main.rs +++ b/avail-rust/docs/extrinsics/staking_chill_other/src/main.rs @@ -1,4 +1,4 @@ -use avail_rust::{Keypair, SecretUri, WaitFor, SDK}; +use avail_rust::{Keypair, Nonce, Options, SecretUri, WaitFor, SDK}; use core::str::FromStr; #[tokio::main] @@ -10,10 +10,12 @@ async fn main() -> Result<(), String> { let account = Keypair::from_uri(&secret_uri).unwrap(); let stash = "5GNJqTPyNqANBkUVMN1LPPrxXnFouWXoe2wNSmmEoLctxiZY"; // Alice Stash + let wait_for = WaitFor::BlockInclusion; + let options = Options::new().nonce(Nonce::BestBlockAndTxPool); let result = sdk .tx .staking - .chill_other(stash, WaitFor::BlockInclusion, &account, None) + .chill_other(stash, wait_for, &account, Some(options)) .await?; dbg!(result); diff --git a/avail-rust/docs/extrinsics/staking_nominate/src/main.rs b/avail-rust/docs/extrinsics/staking_nominate/src/main.rs index 50de3fbc8..409c10f3e 100644 --- a/avail-rust/docs/extrinsics/staking_nominate/src/main.rs +++ b/avail-rust/docs/extrinsics/staking_nominate/src/main.rs @@ -1,4 +1,4 @@ -use avail_rust::{Keypair, SecretUri, WaitFor, SDK}; +use avail_rust::{Keypair, Nonce, Options, SecretUri, WaitFor, SDK}; use core::str::FromStr; #[tokio::main] @@ -13,10 +13,12 @@ async fn main() -> Result<(), String> { String::from("5FHneW46xGXgs5mUiveU4sbTyGBzmstUspZC92UhjJM694ty"), // Bob; ]; + let wait_for = WaitFor::BlockInclusion; + let options = Options::new().nonce(Nonce::BestBlockAndTxPool); let result = sdk .tx .staking - .nominate(&targets, WaitFor::BlockInclusion, &account, None) + .nominate(&targets, wait_for, &account, Some(options)) .await?; dbg!(result); diff --git a/avail-rust/docs/extrinsics/staking_unbond/src/main.rs b/avail-rust/docs/extrinsics/staking_unbond/src/main.rs index 82dd0db60..e163a1d0d 100644 --- a/avail-rust/docs/extrinsics/staking_unbond/src/main.rs +++ b/avail-rust/docs/extrinsics/staking_unbond/src/main.rs @@ -1,4 +1,4 @@ -use avail_rust::{Keypair, SecretUri, WaitFor, SDK}; +use avail_rust::{Keypair, Nonce, Options, SecretUri, WaitFor, SDK}; use core::str::FromStr; #[tokio::main] @@ -10,10 +10,12 @@ async fn main() -> Result<(), String> { let account = Keypair::from_uri(&secret_uri).unwrap(); let value = 1_000_000_000_000_000_000u128; // 1 Avail + let wait_for = WaitFor::BlockInclusion; + let options = Options::new().nonce(Nonce::BestBlockAndTxPool); let result = sdk .tx .staking - .unbond(value, WaitFor::BlockInclusion, &account, None) + .unbond(value, wait_for, &account, Some(options)) .await?; dbg!(result); diff --git a/avail-rust/docs/extrinsics/staking_validate/src/main.rs b/avail-rust/docs/extrinsics/staking_validate/src/main.rs index be9ccf56d..1ed59a3d8 100644 --- a/avail-rust/docs/extrinsics/staking_validate/src/main.rs +++ b/avail-rust/docs/extrinsics/staking_validate/src/main.rs @@ -1,4 +1,4 @@ -use avail_rust::{Keypair, SecretUri, WaitFor, SDK}; +use avail_rust::{Keypair, Nonce, Options, SecretUri, WaitFor, SDK}; use core::str::FromStr; #[tokio::main] @@ -11,10 +11,12 @@ async fn main() -> Result<(), String> { let commission = 100; let blocked = false; + let wait_for = WaitFor::BlockInclusion; + let options = Options::new().nonce(Nonce::BestBlockAndTxPool); let result = sdk .tx .staking - .validate(commission, blocked, WaitFor::BlockInclusion, &account, None) + .validate(commission, blocked, wait_for, &account, Some(options)) .await?; dbg!(result); diff --git a/avail-rust/src/lib.rs b/avail-rust/src/lib.rs index 6ba86b31e..bccf006dd 100644 --- a/avail-rust/src/lib.rs +++ b/avail-rust/src/lib.rs @@ -3,12 +3,11 @@ mod config; mod from_substrate; mod rpcs; mod sdk; -mod transactions; mod utils; // Export types for internal and external consumption pub mod primitives; -pub mod transaction_data; +pub mod transactions; pub type RewardDestination = api_dev::api::runtime_types::pallet_staking::RewardDestination; @@ -30,9 +29,10 @@ pub use primitives::block::{ AppUncheckedExtrinsic, AvailHeader, DefaultExtrinsicParams, DefaultExtrinsicParamsBuilder, }; pub use primitives::kate::{Cell, GDataProof, GRow}; +pub use sp_core; pub use subxt; pub use subxt::config::polkadot::U256; pub use subxt_signer; +pub use transactions::{Mortality, Nonce, Options}; pub use utils::utils_raw; pub use utils::FetchTransactionError; -pub use sp_core; diff --git a/avail-rust/src/sdk.rs b/avail-rust/src/sdk.rs index 85bf1fe86..c026e2171 100644 --- a/avail-rust/src/sdk.rs +++ b/avail-rust/src/sdk.rs @@ -11,22 +11,24 @@ pub struct SDK { impl SDK { pub async fn new(endpoint: &str) -> Result> { let api = Api::from_url(endpoint).await?; + let rpc = Rpc::new(endpoint, true).await?; Ok(SDK { - tx: Transactions::new(api.clone()), + tx: Transactions::new(api.clone(), rpc.clone()), util: Util::new(api.clone()), - rpc: Rpc::new(endpoint, true).await?, + rpc, api, }) } pub async fn new_insecure(endpoint: &str) -> Result> { let api = Api::from_insecure_url(endpoint).await?; + let rpc = Rpc::new(endpoint, false).await?; Ok(SDK { - tx: Transactions::new(api.clone()), + tx: Transactions::new(api.clone(), rpc.clone()), util: Util::new(api.clone()), - rpc: Rpc::new(endpoint, false).await?, + rpc, api, }) } diff --git a/avail-rust/src/transaction_data.rs b/avail-rust/src/transaction_data.rs deleted file mode 100644 index 3c98a6dc5..000000000 --- a/avail-rust/src/transaction_data.rs +++ /dev/null @@ -1,97 +0,0 @@ -use crate::api_dev::api::data_availability::calls::types::submit_data::Data; -use crate::utils_raw::fetch_transaction; -use crate::BlockHash; -use crate::{avail, AccountId, AvailBlocksClient}; - -use subxt_core::utils::MultiAddress; - -use avail::data_availability::calls::types as DataAvailabilityCalls; -use avail::session::calls::types as SessionCalls; -use avail::staking::calls::types as StakingCalls; - -pub mod data_availability { - use super::*; - - #[derive(Debug, Clone, Eq, PartialEq)] - pub struct SubmitData { - pub data: Data, - } - - impl SubmitData { - pub async fn new( - block_hash: BlockHash, - tx_hash: BlockHash, - blocks: &AvailBlocksClient, - ) -> Result { - let transaction = - fetch_transaction::(block_hash, tx_hash, blocks) - .await; - let transaction = transaction.map_err(|err| err.to_string())?; - - Ok(Self { - data: transaction.value.data, - }) - } - } -} -pub mod staking { - use super::*; - - #[derive(Debug, Clone, Eq, PartialEq)] - pub struct Nominate { - pub targets: Vec, - } - - impl Nominate { - pub async fn new( - block_hash: BlockHash, - tx_hash: BlockHash, - blocks: &AvailBlocksClient, - ) -> Result { - let transaction = - fetch_transaction::(block_hash, tx_hash, blocks).await; - let transaction = transaction.map_err(|err| err.to_string())?; - - let targets = transaction.value.targets; - let targets: Vec = targets - .into_iter() - .map(|a| match a { - MultiAddress::Id(account) => account, - _ => panic!("Should never happen"), - }) - .collect(); - let targets = targets.into_iter().map(|a| std::format!("{}", a)).collect(); - - Ok(Self { targets }) - } - } -} - -pub mod session { - use super::*; - use crate::avail::runtime_types::da_runtime::primitives::SessionKeys; - - #[allow(dead_code)] - #[derive(Debug)] - pub struct SetKeys { - keys: SessionKeys, - proof: Vec, - } - - impl SetKeys { - pub async fn new( - block_hash: BlockHash, - tx_hash: BlockHash, - blocks: &AvailBlocksClient, - ) -> Result { - let transaction = - fetch_transaction::(block_hash, tx_hash, blocks).await; - let transaction = transaction.map_err(|err| err.to_string())?; - - let keys = transaction.value.keys; - let proof = transaction.value.proof; - - Ok(Self { keys, proof }) - } - } -} diff --git a/avail-rust/src/transactions.rs b/avail-rust/src/transactions.rs deleted file mode 100644 index b1404223c..000000000 --- a/avail-rust/src/transactions.rs +++ /dev/null @@ -1,1138 +0,0 @@ -use crate::api_dev::api::data_availability::calls::types::create_application_key::Key; -use crate::api_dev::api::data_availability::calls::types::submit_data::Data; -use crate::api_dev::api::runtime_types::frame_support::dispatch::DispatchFeeModifier; -use crate::api_dev::api::runtime_types::pallet_staking::ValidatorPrefs; -use crate::api_dev::api::runtime_types::sp_arithmetic::per_things::Perbill; -use crate::api_dev::api::Call; -use crate::avail::runtime_types::da_runtime::primitives::SessionKeys; -use crate::sdk::WaitFor; -use crate::utils_raw::progress_transaction; -use crate::{ - avail, transaction_data, AccountId, Api, AvailBlocksClient, AvailConfig, BlockHash, - RewardDestination, TxApi, -}; - -use std::str::FromStr; -use subxt::blocks::ExtrinsicEvents; -use subxt_core::utils::MultiAddress; -use subxt_signer::sr25519::Keypair; - -use avail::balances::events as BalancesEvents; -use avail::data_availability::events as DataAvailabilityEvents; -use avail::staking::events as StakingEvents; -use avail::sudo::events as SudoEvents; -use avail::system::events as SystemEvents; - -pub type Params = - <::ExtrinsicParams as subxt::config::ExtrinsicParams< - AvailConfig, - >>::Params; - -#[derive(Debug)] -pub struct TransferAllTxSuccess { - pub event: BalancesEvents::Transfer, - pub event2: Option, - pub events: ExtrinsicEvents, - pub tx_hash: BlockHash, - pub tx_index: u32, - pub block_hash: BlockHash, - pub block_number: u32, -} - -#[derive(Debug)] -pub struct TransferAllowDeathTxSuccess { - pub event: BalancesEvents::Transfer, - pub event2: Option, - pub events: ExtrinsicEvents, - pub tx_hash: BlockHash, - pub tx_index: u32, - pub block_hash: BlockHash, - pub block_number: u32, -} - -#[derive(Debug)] -pub struct TransferKeepAliveTxSuccess { - pub event: BalancesEvents::Transfer, - pub events: ExtrinsicEvents, - pub tx_hash: BlockHash, - pub tx_index: u32, - pub block_hash: BlockHash, - pub block_number: u32, -} - -#[derive(Debug)] -pub struct BondTxSuccess { - pub event: StakingEvents::Bonded, - pub events: ExtrinsicEvents, - pub tx_hash: BlockHash, - pub tx_index: u32, - pub block_hash: BlockHash, - pub block_number: u32, -} - -#[derive(Debug)] -pub struct BondExtraTxSuccess { - pub event: StakingEvents::Bonded, - pub events: ExtrinsicEvents, - pub tx_hash: BlockHash, - pub tx_index: u32, - pub block_hash: BlockHash, - pub block_number: u32, -} - -#[derive(Debug)] -pub struct ChillTxSuccess { - pub event: Option, - pub events: ExtrinsicEvents, - pub tx_hash: BlockHash, - pub tx_index: u32, - pub block_hash: BlockHash, - pub block_number: u32, -} - -#[derive(Debug)] -pub struct ChillOtherTxSuccess { - pub event: StakingEvents::Chilled, - pub events: ExtrinsicEvents, - pub tx_hash: BlockHash, - pub tx_index: u32, - pub block_hash: BlockHash, - pub block_number: u32, -} - -#[derive(Debug)] -pub struct NominateTxSuccess { - pub events: ExtrinsicEvents, - pub tx_data: transaction_data::staking::Nominate, - pub tx_hash: BlockHash, - pub tx_index: u32, - pub block_hash: BlockHash, - pub block_number: u32, -} - -#[derive(Debug)] -pub struct UnbondTxSuccess { - pub event: StakingEvents::Unbonded, - pub events: ExtrinsicEvents, - pub tx_hash: BlockHash, - pub tx_index: u32, - pub block_hash: BlockHash, - pub block_number: u32, -} - -#[derive(Debug)] -pub struct ValidateTxSuccess { - pub event: StakingEvents::ValidatorPrefsSet, - pub events: ExtrinsicEvents, - pub tx_hash: BlockHash, - pub tx_index: u32, - pub block_hash: BlockHash, - pub block_number: u32, -} - -#[derive(Debug)] -pub struct SubmitDataTxSuccess { - pub event: DataAvailabilityEvents::DataSubmitted, - pub events: ExtrinsicEvents, - pub tx_data: transaction_data::data_availability::SubmitData, - pub tx_hash: BlockHash, - pub tx_index: u32, - pub block_hash: BlockHash, - pub block_number: u32, -} - -#[derive(Debug)] -pub struct CreateApplicationKeyTxSuccess { - pub event: DataAvailabilityEvents::ApplicationKeyCreated, - pub events: ExtrinsicEvents, - pub tx_hash: BlockHash, - pub tx_index: u32, - pub block_hash: BlockHash, - pub block_number: u32, -} - -#[derive(Debug)] -pub struct SetApplicationKeyTxSuccess { - pub event: DataAvailabilityEvents::ApplicationKeySet, - pub events: ExtrinsicEvents, - pub tx_hash: BlockHash, - pub tx_index: u32, - pub block_hash: BlockHash, - pub block_number: u32, -} - -#[derive(Debug)] -pub struct SubmitBlockLengthProposalTxSuccess { - pub event: DataAvailabilityEvents::BlockLengthProposalSubmitted, - pub events: ExtrinsicEvents, - pub tx_hash: BlockHash, - pub tx_index: u32, - pub block_hash: BlockHash, - pub block_number: u32, -} - -#[derive(Debug)] -pub struct SetSubmitDataFeeModifierTxSuccess { - pub event: DataAvailabilityEvents::SubmitDataFeeModifierSet, - pub events: ExtrinsicEvents, - pub tx_hash: BlockHash, - pub tx_index: u32, - pub block_hash: BlockHash, - pub block_number: u32, -} - -#[derive(Debug)] -pub struct SetKeysTxSuccess { - pub events: ExtrinsicEvents, - pub tx_data: transaction_data::session::SetKeys, - pub tx_hash: BlockHash, - pub tx_index: u32, - pub block_hash: BlockHash, - pub block_number: u32, -} - -#[derive(Clone)] -pub struct Transactions { - pub balances: Balances, - pub staking: Staking, - pub data_availability: DataAvailability, - pub session: Session, -} - -impl Transactions { - pub fn new(api: Api) -> Self { - let tx = api.tx(); - let blocks = api.blocks(); - - Self { - balances: Balances::new(tx.clone(), blocks.clone()), - staking: Staking::new(tx.clone(), blocks.clone()), - data_availability: DataAvailability::new(tx.clone(), blocks.clone()), - session: Session::new(tx.clone(), blocks), - } - } -} - -async fn get_block_number( - blocks: &AvailBlocksClient, - block_hash: BlockHash, -) -> Result { - let block_number = blocks - .at(block_hash) - .await - .map_err(|e| e.to_string())? - .number(); - - Ok(block_number) -} - -#[derive(Clone)] -pub struct Session { - api: TxApi, - blocks: AvailBlocksClient, -} - -impl Session { - pub fn new(api: TxApi, blocks: AvailBlocksClient) -> Self { - Self { api, blocks } - } - - pub async fn set_keys( - &self, - keys: SessionKeys, - wait_for: WaitFor, - account: &Keypair, - options: Option, - ) -> Result { - let params = options.unwrap_or_default(); - let call = avail::tx().session().set_keys(keys, vec![]); - - let maybe_tx_progress = self - .api - .sign_and_submit_then_watch(&call, account, params) - .await; - - let transaction = progress_transaction(maybe_tx_progress, wait_for).await; - let tx_in_block = match transaction { - Ok(tx_in_block) => tx_in_block, - Err(message) => return Err(message), - }; - - let events = match tx_in_block.wait_for_success().await { - Ok(e) => e, - Err(error) => return Err(error.to_string()), - }; - - let tx_hash = tx_in_block.extrinsic_hash(); - let tx_index = events.extrinsic_index(); - let block_hash = tx_in_block.block_hash(); - let block_number = get_block_number(&self.blocks, block_hash).await?; - - let tx_data = - transaction_data::session::SetKeys::new(block_hash, tx_hash, &self.blocks).await?; - - Ok(SetKeysTxSuccess { - events, - tx_data, - tx_hash, - tx_index, - block_hash, - block_number, - }) - } -} - -#[derive(Clone)] -pub struct Balances { - api: TxApi, - blocks: AvailBlocksClient, -} - -impl Balances { - pub fn new(api: TxApi, blocks: AvailBlocksClient) -> Self { - Self { api, blocks } - } - - pub async fn transfer_all( - &self, - dest: &str, - keep_alive: bool, - wait_for: WaitFor, - account: &Keypair, - options: Option, - ) -> Result { - let dest = match AccountId::from_str(dest) { - Ok(dest) => dest, - Err(error) => return Err(std::format!("{:?}", error)), - }; - - let params = options.unwrap_or_default(); - let call = avail::tx().balances().transfer_all(dest.into(), keep_alive); - - let maybe_tx_progress = self - .api - .sign_and_submit_then_watch(&call, account, params) - .await; - - let transaction = progress_transaction(maybe_tx_progress, wait_for).await; - let tx_in_block = match transaction { - Ok(tx_in_block) => tx_in_block, - Err(message) => return Err(message), - }; - - let events = match tx_in_block.wait_for_success().await { - Ok(e) => e, - Err(error) => return Err(error.to_string()), - }; - - let event = events.find_first::(); - let Some(event) = event.ok().flatten() else { - return Err(String::from("Failed to find Transfer event")); - }; - - let event2 = events.find_first::(); - let event2 = event2.ok().flatten(); - - let tx_hash = tx_in_block.extrinsic_hash(); - let tx_index = events.extrinsic_index(); - let block_hash = tx_in_block.block_hash(); - let block_number = get_block_number(&self.blocks, block_hash).await?; - - Ok(TransferAllTxSuccess { - event, - event2, - events, - tx_hash, - tx_index, - block_hash, - block_number, - }) - } - - pub async fn transfer_allow_death( - &self, - dest: &str, - amount: u128, - wait_for: WaitFor, - account: &Keypair, - options: Option, - ) -> Result { - let dest = match AccountId::from_str(dest) { - Ok(dest) => dest, - Err(error) => return Err(std::format!("{:?}", error)), - }; - - let params = options.unwrap_or_default(); - let call = avail::tx() - .balances() - .transfer_allow_death(dest.into(), amount); - - let maybe_tx_progress = self - .api - .sign_and_submit_then_watch(&call, account, params) - .await; - - let transaction = progress_transaction(maybe_tx_progress, wait_for).await; - let tx_in_block = match transaction { - Ok(tx_in_block) => tx_in_block, - Err(message) => return Err(message), - }; - - let events = match tx_in_block.wait_for_success().await { - Ok(e) => e, - Err(error) => return Err(error.to_string()), - }; - - let event = events.find_first::(); - let Some(event) = event.ok().flatten() else { - return Err(String::from("Failed to find Transfer event")); - }; - - let event2 = events.find_first::(); - let event2 = event2.ok().flatten(); - - let tx_hash = tx_in_block.extrinsic_hash(); - let tx_index = events.extrinsic_index(); - let block_hash = tx_in_block.block_hash(); - let block_number = get_block_number(&self.blocks, block_hash).await?; - - Ok(TransferAllowDeathTxSuccess { - event, - event2, - events, - tx_hash, - tx_index, - block_hash, - block_number, - }) - } - - pub async fn transfer_keep_alive( - &self, - dest: &str, - value: u128, - wait_for: WaitFor, - account: &Keypair, - options: Option, - ) -> Result { - let dest = match AccountId::from_str(dest) { - Ok(dest) => dest, - Err(error) => return Err(std::format!("{:?}", error)), - }; - - let params = options.unwrap_or_default(); - let call = avail::tx() - .balances() - .transfer_keep_alive(dest.into(), value); - - let maybe_tx_progress = self - .api - .sign_and_submit_then_watch(&call, account, params) - .await; - - let transaction = progress_transaction(maybe_tx_progress, wait_for).await; - let tx_in_block = match transaction { - Ok(tx_in_block) => tx_in_block, - Err(message) => return Err(message), - }; - - let events = match tx_in_block.wait_for_success().await { - Ok(e) => e, - Err(error) => return Err(error.to_string()), - }; - - let event = events.find_first::(); - let Some(event) = event.ok().flatten() else { - return Err(String::from("Failed to find Transfer event")); - }; - - let tx_hash = tx_in_block.extrinsic_hash(); - let tx_index = events.extrinsic_index(); - let block_hash = tx_in_block.block_hash(); - let block_number = get_block_number(&self.blocks, block_hash).await?; - - Ok(TransferKeepAliveTxSuccess { - event, - events, - tx_hash, - tx_index, - block_hash, - block_number, - }) - } -} - -#[derive(Clone)] -pub struct Staking { - api: TxApi, - blocks: AvailBlocksClient, -} - -impl Staking { - pub fn new(api: TxApi, blocks: AvailBlocksClient) -> Self { - Self { api, blocks } - } - - pub async fn bond( - &self, - value: u128, - payee: RewardDestination, - wait_for: WaitFor, - account: &Keypair, - options: Option, - ) -> Result { - let params = options.unwrap_or_default(); - let call = avail::tx().staking().bond(value, payee); - - let maybe_tx_progress = self - .api - .sign_and_submit_then_watch(&call, account, params) - .await; - - let transaction = progress_transaction(maybe_tx_progress, wait_for).await; - let tx_in_block = match transaction { - Ok(tx_in_block) => tx_in_block, - Err(message) => return Err(message), - }; - - let events = match tx_in_block.wait_for_success().await { - Ok(e) => e, - Err(error) => return Err(error.to_string()), - }; - - let event = events.find_first::(); - let Some(event) = event.ok().flatten() else { - return Err(String::from("Failed to find Bonded event")); - }; - - let tx_hash = tx_in_block.extrinsic_hash(); - let tx_index = events.extrinsic_index(); - let block_hash = tx_in_block.block_hash(); - let block_number = get_block_number(&self.blocks, block_hash).await?; - - Ok(BondTxSuccess { - event, - events, - tx_hash, - tx_index, - block_hash, - block_number, - }) - } - - pub async fn bond_extra( - &self, - max_additional: u128, - wait_for: WaitFor, - account: &Keypair, - options: Option, - ) -> Result { - let params = options.unwrap_or_default(); - let call = avail::tx().staking().bond_extra(max_additional); - - let maybe_tx_progress = self - .api - .sign_and_submit_then_watch(&call, account, params) - .await; - - let transaction = progress_transaction(maybe_tx_progress, wait_for).await; - let tx_in_block = match transaction { - Ok(tx_in_block) => tx_in_block, - Err(message) => return Err(message), - }; - - let events = match tx_in_block.wait_for_success().await { - Ok(e) => e, - Err(error) => return Err(error.to_string()), - }; - - let event = events.find_first::(); - let Some(event) = event.ok().flatten() else { - return Err(String::from("Failed to find Bonded event")); - }; - - let tx_hash = tx_in_block.extrinsic_hash(); - let tx_index = events.extrinsic_index(); - let block_hash = tx_in_block.block_hash(); - let block_number = get_block_number(&self.blocks, block_hash).await?; - - Ok(BondExtraTxSuccess { - event, - events, - tx_hash, - tx_index, - block_hash, - block_number, - }) - } - - pub async fn chill( - &self, - wait_for: WaitFor, - account: &Keypair, - options: Option, - ) -> Result { - let params = options.unwrap_or_default(); - let call = avail::tx().staking().chill(); - - let maybe_tx_progress = self - .api - .sign_and_submit_then_watch(&call, account, params) - .await; - - let transaction = progress_transaction(maybe_tx_progress, wait_for).await; - let tx_in_block = match transaction { - Ok(tx_in_block) => tx_in_block, - Err(message) => return Err(message), - }; - - let events = match tx_in_block.wait_for_success().await { - Ok(e) => e, - Err(error) => return Err(error.to_string()), - }; - - let event = events.find_first::().ok().flatten(); - - let tx_hash = tx_in_block.extrinsic_hash(); - let tx_index = events.extrinsic_index(); - let block_hash = tx_in_block.block_hash(); - let block_number = get_block_number(&self.blocks, block_hash).await?; - - Ok(ChillTxSuccess { - event, - events, - tx_hash, - tx_index, - block_hash, - block_number, - }) - } - - pub async fn chill_other( - &self, - stash: &str, - wait_for: WaitFor, - account: &Keypair, - options: Option, - ) -> Result { - let stash = match AccountId::from_str(stash) { - Ok(stash) => stash, - Err(error) => return Err(std::format!("{:?}", error)), - }; - - let params = options.unwrap_or_default(); - let call = avail::tx().staking().chill_other(stash); - - let maybe_tx_progress = self - .api - .sign_and_submit_then_watch(&call, account, params) - .await; - - let transaction = progress_transaction(maybe_tx_progress, wait_for).await; - let tx_in_block = match transaction { - Ok(tx_in_block) => tx_in_block, - Err(message) => return Err(message), - }; - - let events = match tx_in_block.wait_for_success().await { - Ok(e) => e, - Err(error) => return Err(error.to_string()), - }; - - let event = events.find_first::(); - let Some(event) = event.ok().flatten() else { - return Err(String::from("Failed to find Chilled event")); - }; - - let tx_hash = tx_in_block.extrinsic_hash(); - let tx_index = events.extrinsic_index(); - let block_hash = tx_in_block.block_hash(); - let block_number = get_block_number(&self.blocks, block_hash).await?; - - Ok(ChillOtherTxSuccess { - event, - events, - tx_hash, - tx_index, - block_hash, - block_number, - }) - } - - pub async fn nominate( - &self, - targets: &[String], - wait_for: WaitFor, - account: &Keypair, - options: Option, - ) -> Result { - let targets: Result, _> = targets - .iter() - .map(|address| AccountId::from_str(address)) - .collect(); - let targets = targets.map_err(|e| std::format!("{:?}", e))?; - let targets = targets.into_iter().map(|a| MultiAddress::Id(a)).collect(); - - let params = options.unwrap_or_default(); - let call = avail::tx().staking().nominate(targets); - - let maybe_tx_progress = self - .api - .sign_and_submit_then_watch(&call, account, params) - .await; - - let transaction = progress_transaction(maybe_tx_progress, wait_for).await; - let tx_in_block = match transaction { - Ok(tx_in_block) => tx_in_block, - Err(message) => return Err(message), - }; - - let events = match tx_in_block.wait_for_success().await { - Ok(e) => e, - Err(error) => return Err(error.to_string()), - }; - - let (tx_hash, block_hash) = (tx_in_block.extrinsic_hash(), tx_in_block.block_hash()); - - let tx_data = - transaction_data::staking::Nominate::new(block_hash, tx_hash, &self.blocks).await?; - - let tx_hash = tx_in_block.extrinsic_hash(); - let tx_index = events.extrinsic_index(); - let block_hash = tx_in_block.block_hash(); - let block_number = get_block_number(&self.blocks, block_hash).await?; - - Ok(NominateTxSuccess { - events, - tx_data, - tx_hash, - tx_index, - block_hash, - block_number, - }) - } - - pub async fn unbond( - &self, - value: u128, - wait_for: WaitFor, - account: &Keypair, - options: Option, - ) -> Result { - let call = avail::tx().staking().unbond(value); - - let params = options.unwrap_or_default(); - let maybe_tx_progress = self - .api - .sign_and_submit_then_watch(&call, account, params) - .await; - - let transaction = progress_transaction(maybe_tx_progress, wait_for).await; - let tx_in_block = match transaction { - Ok(tx_in_block) => tx_in_block, - Err(message) => return Err(message), - }; - - let events = match tx_in_block.wait_for_success().await { - Ok(e) => e, - Err(error) => return Err(error.to_string()), - }; - - let event = events.find_first::(); - let Some(event) = event.ok().flatten() else { - return Err(String::from("Failed to find Unbonded event")); - }; - - let tx_hash = tx_in_block.extrinsic_hash(); - let tx_index = events.extrinsic_index(); - let block_hash = tx_in_block.block_hash(); - let block_number = get_block_number(&self.blocks, block_hash).await?; - - Ok(UnbondTxSuccess { - event, - events, - tx_hash, - tx_index, - block_hash, - block_number, - }) - } - - pub async fn validate( - &self, - commission: u8, - blocked: bool, - wait_for: WaitFor, - account: &Keypair, - options: Option, - ) -> Result { - if commission > 100 { - return Err(String::from("Commission cannot be more than 100")); - } - - let commission = Perbill(commission as u32); - let perfs = ValidatorPrefs { - commission, - blocked, - }; - - let params = options.unwrap_or_default(); - let call = avail::tx().staking().validate(perfs); - - let maybe_tx_progress = self - .api - .sign_and_submit_then_watch(&call, account, params) - .await; - - let transaction = progress_transaction(maybe_tx_progress, wait_for).await; - let tx_in_block = match transaction { - Ok(tx_in_block) => tx_in_block, - Err(message) => return Err(message), - }; - - let events = match tx_in_block.wait_for_success().await { - Ok(e) => e, - Err(error) => return Err(error.to_string()), - }; - - let event = events.find_first::(); - let Some(event) = event.ok().flatten() else { - return Err(String::from("Failed to find ValidatorPrefsSet event")); - }; - - let tx_hash = tx_in_block.extrinsic_hash(); - let tx_index = events.extrinsic_index(); - let block_hash = tx_in_block.block_hash(); - let block_number = get_block_number(&self.blocks, block_hash).await?; - - Ok(ValidateTxSuccess { - event, - events, - tx_hash, - tx_index, - block_hash, - block_number, - }) - } -} - -#[derive(Clone)] -pub struct DataAvailability { - api: TxApi, - blocks: AvailBlocksClient, -} - -impl DataAvailability { - pub fn new(api: TxApi, blocks: AvailBlocksClient) -> Self { - Self { api, blocks } - } - - pub async fn submit_data( - &self, - data: Data, - wait_for: WaitFor, - account: &Keypair, - options: Option, - ) -> Result { - let params = options.unwrap_or_default(); - let call = avail::tx().data_availability().submit_data(data); - - let maybe_tx_progress = self - .api - .sign_and_submit_then_watch(&call, account, params) - .await; - - let transaction = progress_transaction(maybe_tx_progress, wait_for).await; - let tx_in_block = match transaction { - Ok(tx_in_block) => tx_in_block, - Err(message) => return Err(message), - }; - - let events = match tx_in_block.wait_for_success().await { - Ok(e) => e, - Err(error) => return Err(error.to_string()), - }; - - let event = events.find_first::(); - let Some(event) = event.ok().flatten() else { - return Err(String::from("Failed to find DataSubmitted event")); - }; - - let (tx_hash, block_hash) = (tx_in_block.extrinsic_hash(), tx_in_block.block_hash()); - - let tx_data = - transaction_data::data_availability::SubmitData::new(block_hash, tx_hash, &self.blocks) - .await?; - - let tx_hash = tx_in_block.extrinsic_hash(); - let tx_index = events.extrinsic_index(); - let block_hash = tx_in_block.block_hash(); - let block_number = get_block_number(&self.blocks, block_hash).await?; - - Ok(SubmitDataTxSuccess { - event, - events, - tx_data, - tx_hash, - tx_index, - block_hash, - block_number, - }) - } - - pub async fn create_application_key( - &self, - key: Key, - wait_for: WaitFor, - account: &Keypair, - options: Option, - ) -> Result { - let params = options.unwrap_or_default(); - let call = avail::tx().data_availability().create_application_key(key); - - let maybe_tx_progress = self - .api - .sign_and_submit_then_watch(&call, account, params) - .await; - - let transaction = progress_transaction(maybe_tx_progress, wait_for).await; - let tx_in_block = match transaction { - Ok(tx_in_block) => tx_in_block, - Err(message) => return Err(message), - }; - - let events = match tx_in_block.wait_for_success().await { - Ok(e) => e, - Err(error) => return Err(error.to_string()), - }; - - let event = events.find_first::(); - let Some(event) = event.ok().flatten() else { - return Err(String::from("Failed to find ApplicationKeyCreated event")); - }; - - let tx_hash = tx_in_block.extrinsic_hash(); - let tx_index = events.extrinsic_index(); - let block_hash = tx_in_block.block_hash(); - let block_number = get_block_number(&self.blocks, block_hash).await?; - - Ok(CreateApplicationKeyTxSuccess { - event, - events, - tx_hash, - tx_index, - block_hash, - block_number, - }) - } - - pub async fn set_application_key( - &self, - old_key: Key, - new_key: Key, - wait_for: WaitFor, - account: &Keypair, - options: Option, - ) -> Result { - let params = options.unwrap_or_default(); - let call = Call::DataAvailability( - avail::runtime_types::da_control::pallet::Call::set_application_key { - old_key, - new_key, - }, - ); - let sudo = avail::tx().sudo().sudo(call); - - let maybe_tx_progress = self - .api - .sign_and_submit_then_watch(&sudo, account, params) - .await; - - let transaction = progress_transaction(maybe_tx_progress, wait_for).await; - let tx_in_block = match transaction { - Ok(tx_in_block) => tx_in_block, - Err(message) => return Err(message), - }; - - let events = match tx_in_block.wait_for_success().await { - Ok(e) => e, - Err(error) => return Err(error.to_string()), - }; - - let sudo_event = events.find_first::(); - let Some(sudo_event) = sudo_event.ok().flatten() else { - return Err(String::from("Failed to find Sudid event")); - }; - - if let Err(error) = sudo_event.sudo_result { - return Err(std::format!("{:?}", error)); - } - - let event = events.find_first::(); - let Some(event) = event.ok().flatten() else { - return Err(String::from("Failed to find ApplicationKeySet event")); - }; - - let tx_hash = tx_in_block.extrinsic_hash(); - let tx_index = events.extrinsic_index(); - let block_hash = tx_in_block.block_hash(); - let block_number = get_block_number(&self.blocks, block_hash).await?; - - Ok(SetApplicationKeyTxSuccess { - event, - events, - tx_hash, - tx_index, - block_hash, - block_number, - }) - } - - pub async fn submit_block_length_proposal( - &self, - rows: u32, - cols: u32, - wait_for: WaitFor, - account: &Keypair, - options: Option, - ) -> Result { - let params = options.unwrap_or_default(); - let call = Call::DataAvailability( - avail::runtime_types::da_control::pallet::Call::submit_block_length_proposal { - rows, - cols, - }, - ); - let sudo = avail::tx().sudo().sudo(call); - - let maybe_tx_progress = self - .api - .sign_and_submit_then_watch(&sudo, account, params) - .await; - - let transaction = progress_transaction(maybe_tx_progress, wait_for).await; - let tx_in_block = match transaction { - Ok(tx_in_block) => tx_in_block, - Err(message) => return Err(message), - }; - - let events = match tx_in_block.wait_for_success().await { - Ok(e) => e, - Err(error) => return Err(error.to_string()), - }; - - let sudo_event = events.find_first::(); - let Some(sudo_event) = sudo_event.ok().flatten() else { - return Err(String::from("Failed to find Sudid event")); - }; - - if let Err(error) = sudo_event.sudo_result { - return Err(std::format!("{:?}", error)); - } - - let event = events.find_first::(); - let Some(event) = event.ok().flatten() else { - return Err(String::from( - "Failed to find BlockLengthProposalSubmitted event", - )); - }; - - let tx_hash = tx_in_block.extrinsic_hash(); - let tx_index = events.extrinsic_index(); - let block_hash = tx_in_block.block_hash(); - let block_number = get_block_number(&self.blocks, block_hash).await?; - - Ok(SubmitBlockLengthProposalTxSuccess { - event, - events, - tx_hash, - tx_index, - block_hash, - block_number, - }) - } - - pub async fn set_submit_data_fee_modifier( - &self, - modifier: DispatchFeeModifier, - wait_for: WaitFor, - account: &Keypair, - options: Option, - ) -> Result { - let params = options.unwrap_or_default(); - let call = Call::DataAvailability( - avail::runtime_types::da_control::pallet::Call::set_submit_data_fee_modifier { - modifier, - }, - ); - let sudo = avail::tx().sudo().sudo(call); - - let maybe_tx_progress = self - .api - .sign_and_submit_then_watch(&sudo, account, params) - .await; - - let transaction = progress_transaction(maybe_tx_progress, wait_for).await; - let tx_in_block = match transaction { - Ok(tx_in_block) => tx_in_block, - Err(message) => return Err(message), - }; - - let events = match tx_in_block.wait_for_success().await { - Ok(e) => e, - Err(error) => return Err(error.to_string()), - }; - - let sudo_event = events.find_first::(); - let Some(sudo_event) = sudo_event.ok().flatten() else { - return Err(String::from("Failed to find Sudid event")); - }; - - if let Err(error) = sudo_event.sudo_result { - return Err(std::format!("{:?}", error)); - } - - let event = events.find_first::(); - let Some(event) = event.ok().flatten() else { - return Err(String::from( - "Failed to find SubmitDataFeeModifierSet event", - )); - }; - - let tx_hash = tx_in_block.extrinsic_hash(); - let tx_index = events.extrinsic_index(); - let block_hash = tx_in_block.block_hash(); - let block_number = get_block_number(&self.blocks, block_hash).await?; - - Ok(SetSubmitDataFeeModifierTxSuccess { - event, - events, - tx_hash, - tx_index, - block_hash, - block_number, - }) - } -} - -#[cfg(test)] -mod tests { - use super::*; - - #[tokio::test] - async fn testing_function() { - let sdk = crate::sdk::SDK::new("ws://127.0.0.1:9944").await.unwrap(); - let h = BlockHash::from_str( - "0x6c5ebed687ed008b76028072fe1ad0a06ecf3c00dd9067aa049ea14e180702f8", - ) - .unwrap(); - match sdk.rpc.kate.query_rows(vec![0], Some(h)).await { - Ok(a) => { - dbg!(a); - }, - Err(a) => { - dbg!(a); - }, - }; - } -} diff --git a/avail-rust/src/transactions/balances.rs b/avail-rust/src/transactions/balances.rs new file mode 100644 index 000000000..8a1367c78 --- /dev/null +++ b/avail-rust/src/transactions/balances.rs @@ -0,0 +1,200 @@ +use crate::rpcs::Rpc; +use crate::sdk::WaitFor; +use crate::{avail, AccountId, AvailBlocksClient, AvailConfig, BlockHash, TxApi}; + +use std::str::FromStr; +use subxt::blocks::ExtrinsicEvents; +use subxt_signer::sr25519::Keypair; + +use avail::balances::events as BalancesEvents; +use avail::system::events as SystemEvents; + +use super::options::{from_options_to_params, Options}; +use super::progress_transaction_ex; + +#[derive(Debug)] +pub struct TransferAllTxSuccess { + pub event: BalancesEvents::Transfer, + pub event2: Option, + pub events: ExtrinsicEvents, + pub tx_hash: BlockHash, + pub tx_index: u32, + pub block_hash: BlockHash, + pub block_number: u32, +} + +#[derive(Debug)] +pub struct TransferAllowDeathTxSuccess { + pub event: BalancesEvents::Transfer, + pub event2: Option, + pub events: ExtrinsicEvents, + pub tx_hash: BlockHash, + pub tx_index: u32, + pub block_hash: BlockHash, + pub block_number: u32, +} + +#[derive(Debug)] +pub struct TransferKeepAliveTxSuccess { + pub event: BalancesEvents::Transfer, + pub events: ExtrinsicEvents, + pub tx_hash: BlockHash, + pub tx_index: u32, + pub block_hash: BlockHash, + pub block_number: u32, +} + +#[derive(Clone)] +pub struct Balances { + api: TxApi, + rpc_client: Rpc, + blocks: AvailBlocksClient, +} + +impl Balances { + pub fn new(api: TxApi, rpc_client: Rpc, blocks: AvailBlocksClient) -> Self { + Self { + api, + rpc_client, + blocks, + } + } + + pub async fn transfer_all( + &self, + dest: &str, + keep_alive: bool, + wait_for: WaitFor, + account: &Keypair, + options: Option, + ) -> Result { + let dest = match AccountId::from_str(dest) { + Ok(dest) => dest, + Err(error) => return Err(std::format!("{:?}", error)), + }; + + let account_id = account.public_key().to_account_id(); + let params = + from_options_to_params(options, &self.rpc_client, account_id, &self.blocks).await?; + let call = avail::tx().balances().transfer_all(dest.into(), keep_alive); + + let maybe_tx_progress = self + .api + .sign_and_submit_then_watch(&call, account, params) + .await; + + let (events, data) = + progress_transaction_ex(maybe_tx_progress, wait_for, &self.blocks).await?; + let (block_hash, block_number, tx_hash, tx_index) = data; + + let event = events.find_first::(); + let Some(event) = event.ok().flatten() else { + return Err(String::from("Failed to find Transfer event")); + }; + + let event2 = events.find_first::(); + let event2 = event2.ok().flatten(); + + Ok(TransferAllTxSuccess { + event, + event2, + events, + tx_hash, + tx_index, + block_hash, + block_number, + }) + } + + pub async fn transfer_allow_death( + &self, + dest: &str, + amount: u128, + wait_for: WaitFor, + account: &Keypair, + options: Option, + ) -> Result { + let dest = match AccountId::from_str(dest) { + Ok(dest) => dest, + Err(error) => return Err(std::format!("{:?}", error)), + }; + + let account_id = account.public_key().to_account_id(); + let params = + from_options_to_params(options, &self.rpc_client, account_id, &self.blocks).await?; + let call = avail::tx() + .balances() + .transfer_allow_death(dest.into(), amount); + + let maybe_tx_progress = self + .api + .sign_and_submit_then_watch(&call, account, params) + .await; + + let (events, data) = + progress_transaction_ex(maybe_tx_progress, wait_for, &self.blocks).await?; + let (block_hash, block_number, tx_hash, tx_index) = data; + + let event = events.find_first::(); + let Some(event) = event.ok().flatten() else { + return Err(String::from("Failed to find Transfer event")); + }; + + let event2 = events.find_first::(); + let event2 = event2.ok().flatten(); + + Ok(TransferAllowDeathTxSuccess { + event, + event2, + events, + tx_hash, + tx_index, + block_hash, + block_number, + }) + } + + pub async fn transfer_keep_alive( + &self, + dest: &str, + value: u128, + wait_for: WaitFor, + account: &Keypair, + options: Option, + ) -> Result { + let dest = match AccountId::from_str(dest) { + Ok(dest) => dest, + Err(error) => return Err(std::format!("{:?}", error)), + }; + + let account_id = account.public_key().to_account_id(); + let params = + from_options_to_params(options, &self.rpc_client, account_id, &self.blocks).await?; + let call = avail::tx() + .balances() + .transfer_keep_alive(dest.into(), value); + + let maybe_tx_progress = self + .api + .sign_and_submit_then_watch(&call, account, params) + .await; + + let (events, data) = + progress_transaction_ex(maybe_tx_progress, wait_for, &self.blocks).await?; + let (block_hash, block_number, tx_hash, tx_index) = data; + + let event = events.find_first::(); + let Some(event) = event.ok().flatten() else { + return Err(String::from("Failed to find Transfer event")); + }; + + Ok(TransferKeepAliveTxSuccess { + event, + events, + tx_hash, + tx_index, + block_hash, + block_number, + }) + } +} diff --git a/avail-rust/src/transactions/da.rs b/avail-rust/src/transactions/da.rs new file mode 100644 index 000000000..a2039fa2b --- /dev/null +++ b/avail-rust/src/transactions/da.rs @@ -0,0 +1,360 @@ +use crate::api_dev::api::data_availability::calls::types::create_application_key::Key; +use crate::api_dev::api::data_availability::calls::types::submit_data::Data; +use crate::api_dev::api::runtime_types::frame_support::dispatch::DispatchFeeModifier; +use crate::api_dev::api::Call; +use crate::rpcs::Rpc; +use crate::sdk::WaitFor; +use crate::utils_raw::{fetch_transaction, progress_transaction}; +use crate::{avail, AvailBlocksClient, AvailConfig, BlockHash, TxApi}; + +use subxt::blocks::ExtrinsicEvents; +use subxt_signer::sr25519::Keypair; + +use avail::data_availability::calls::types as DataAvailabilityCalls; +use avail::data_availability::events as DataAvailabilityEvents; +use avail::sudo::events as SudoEvents; + +use super::options::{from_options_to_params, Options}; +use super::{block_and_tx_hash, progress_transaction_ex}; + +#[derive(Debug)] +pub struct SubmitDataTxSuccess { + pub event: DataAvailabilityEvents::DataSubmitted, + pub events: ExtrinsicEvents, + pub tx_data: DataAvailabilityCalls::SubmitData, + pub tx_hash: BlockHash, + pub tx_index: u32, + pub block_hash: BlockHash, + pub block_number: u32, +} + +#[derive(Debug)] +pub struct CreateApplicationKeyTxSuccess { + pub event: DataAvailabilityEvents::ApplicationKeyCreated, + pub events: ExtrinsicEvents, + pub tx_hash: BlockHash, + pub tx_index: u32, + pub block_hash: BlockHash, + pub block_number: u32, +} + +#[derive(Debug)] +pub struct SetApplicationKeyTxSuccess { + pub event: DataAvailabilityEvents::ApplicationKeySet, + pub events: ExtrinsicEvents, + pub tx_hash: BlockHash, + pub tx_index: u32, + pub block_hash: BlockHash, + pub block_number: u32, +} + +#[derive(Debug)] +pub struct SubmitBlockLengthProposalTxSuccess { + pub event: DataAvailabilityEvents::BlockLengthProposalSubmitted, + pub events: ExtrinsicEvents, + pub tx_hash: BlockHash, + pub tx_index: u32, + pub block_hash: BlockHash, + pub block_number: u32, +} + +#[derive(Debug)] +pub struct SetSubmitDataFeeModifierTxSuccess { + pub event: DataAvailabilityEvents::SubmitDataFeeModifierSet, + pub events: ExtrinsicEvents, + pub tx_hash: BlockHash, + pub tx_index: u32, + pub block_hash: BlockHash, + pub block_number: u32, +} + +#[derive(Clone)] +pub struct DataAvailability { + api: TxApi, + rpc_client: Rpc, + blocks: AvailBlocksClient, +} + +impl DataAvailability { + pub fn new(api: TxApi, rpc_client: Rpc, blocks: AvailBlocksClient) -> Self { + Self { + api, + rpc_client, + blocks, + } + } + + pub async fn submit_data( + &self, + data: Data, + wait_for: WaitFor, + account: &Keypair, + options: Option, + ) -> Result { + let account_id = account.public_key().to_account_id(); + let params = + from_options_to_params(options, &self.rpc_client, account_id, &self.blocks).await?; + let call = avail::tx().data_availability().submit_data(data); + + let maybe_tx_progress = self + .api + .sign_and_submit_then_watch(&call, account, params) + .await; + + let (events, data) = + progress_transaction_ex(maybe_tx_progress, wait_for, &self.blocks).await?; + let (block_hash, block_number, tx_hash, tx_index) = data; + + let event = events.find_first::(); + let Some(event) = event.ok().flatten() else { + return Err(String::from("Failed to find DataSubmitted event")); + }; + + let tx_data = tx_data_da_submit_data(block_hash, tx_hash, &self.blocks).await?; + + Ok(SubmitDataTxSuccess { + event, + events, + tx_data, + tx_hash, + tx_index, + block_hash, + block_number, + }) + } + + pub async fn create_application_key( + &self, + key: Key, + wait_for: WaitFor, + account: &Keypair, + options: Option, + ) -> Result { + let account_id = account.public_key().to_account_id(); + let params = + from_options_to_params(options, &self.rpc_client, account_id, &self.blocks).await?; + let call = avail::tx().data_availability().create_application_key(key); + + let maybe_tx_progress = self + .api + .sign_and_submit_then_watch(&call, account, params) + .await; + + let (events, data) = + progress_transaction_ex(maybe_tx_progress, wait_for, &self.blocks).await?; + let (block_hash, block_number, tx_hash, tx_index) = data; + + let event = events.find_first::(); + let Some(event) = event.ok().flatten() else { + return Err(String::from("Failed to find ApplicationKeyCreated event")); + }; + + Ok(CreateApplicationKeyTxSuccess { + event, + events, + tx_hash, + tx_index, + block_hash, + block_number, + }) + } + + pub async fn set_application_key( + &self, + old_key: Key, + new_key: Key, + wait_for: WaitFor, + account: &Keypair, + options: Option, + ) -> Result { + let account_id = account.public_key().to_account_id(); + let params = + from_options_to_params(options, &self.rpc_client, account_id, &self.blocks).await?; + let call = Call::DataAvailability( + avail::runtime_types::da_control::pallet::Call::set_application_key { + old_key, + new_key, + }, + ); + let sudo = avail::tx().sudo().sudo(call); + + let maybe_tx_progress = self + .api + .sign_and_submit_then_watch(&sudo, account, params) + .await; + + let transaction = progress_transaction(maybe_tx_progress, wait_for).await; + let tx_in_block = match transaction { + Ok(tx_in_block) => tx_in_block, + Err(message) => return Err(message), + }; + + let events = match tx_in_block.wait_for_success().await { + Ok(e) => e, + Err(error) => return Err(error.to_string()), + }; + + let sudo_event = events.find_first::(); + let Some(sudo_event) = sudo_event.ok().flatten() else { + return Err(String::from("Failed to find Sudid event")); + }; + + if let Err(error) = sudo_event.sudo_result { + return Err(std::format!("{:?}", error)); + } + + let event = events.find_first::(); + let Some(event) = event.ok().flatten() else { + return Err(String::from("Failed to find ApplicationKeySet event")); + }; + + let (block_hash, block_number, tx_hash, tx_index) = + block_and_tx_hash(&tx_in_block, &events, &self.blocks).await?; + + Ok(SetApplicationKeyTxSuccess { + event, + events, + tx_hash, + tx_index, + block_hash, + block_number, + }) + } + + pub async fn submit_block_length_proposal( + &self, + rows: u32, + cols: u32, + wait_for: WaitFor, + account: &Keypair, + options: Option, + ) -> Result { + let account_id = account.public_key().to_account_id(); + let params = + from_options_to_params(options, &self.rpc_client, account_id, &self.blocks).await?; + let call = Call::DataAvailability( + avail::runtime_types::da_control::pallet::Call::submit_block_length_proposal { + rows, + cols, + }, + ); + let sudo = avail::tx().sudo().sudo(call); + + let maybe_tx_progress = self + .api + .sign_and_submit_then_watch(&sudo, account, params) + .await; + + let transaction = progress_transaction(maybe_tx_progress, wait_for).await; + let tx_in_block = match transaction { + Ok(tx_in_block) => tx_in_block, + Err(message) => return Err(message), + }; + + let events = match tx_in_block.wait_for_success().await { + Ok(e) => e, + Err(error) => return Err(error.to_string()), + }; + + let sudo_event = events.find_first::(); + let Some(sudo_event) = sudo_event.ok().flatten() else { + return Err(String::from("Failed to find Sudid event")); + }; + + if let Err(error) = sudo_event.sudo_result { + return Err(std::format!("{:?}", error)); + } + + let event = events.find_first::(); + let Some(event) = event.ok().flatten() else { + return Err(String::from( + "Failed to find BlockLengthProposalSubmitted event", + )); + }; + + let (block_hash, block_number, tx_hash, tx_index) = + block_and_tx_hash(&tx_in_block, &events, &self.blocks).await?; + + Ok(SubmitBlockLengthProposalTxSuccess { + event, + events, + tx_hash, + tx_index, + block_hash, + block_number, + }) + } + + pub async fn set_submit_data_fee_modifier( + &self, + modifier: DispatchFeeModifier, + wait_for: WaitFor, + account: &Keypair, + options: Option, + ) -> Result { + let account_id = account.public_key().to_account_id(); + let params = + from_options_to_params(options, &self.rpc_client, account_id, &self.blocks).await?; + let call = Call::DataAvailability( + avail::runtime_types::da_control::pallet::Call::set_submit_data_fee_modifier { + modifier, + }, + ); + let sudo = avail::tx().sudo().sudo(call); + + let maybe_tx_progress = self + .api + .sign_and_submit_then_watch(&sudo, account, params) + .await; + + let transaction = progress_transaction(maybe_tx_progress, wait_for).await; + let tx_in_block = match transaction { + Ok(tx_in_block) => tx_in_block, + Err(message) => return Err(message), + }; + + let events = match tx_in_block.wait_for_success().await { + Ok(e) => e, + Err(error) => return Err(error.to_string()), + }; + + let sudo_event = events.find_first::(); + let Some(sudo_event) = sudo_event.ok().flatten() else { + return Err(String::from("Failed to find Sudid event")); + }; + + if let Err(error) = sudo_event.sudo_result { + return Err(std::format!("{:?}", error)); + } + + let event = events.find_first::(); + let Some(event) = event.ok().flatten() else { + return Err(String::from( + "Failed to find SubmitDataFeeModifierSet event", + )); + }; + + let (block_hash, block_number, tx_hash, tx_index) = + block_and_tx_hash(&tx_in_block, &events, &self.blocks).await?; + + Ok(SetSubmitDataFeeModifierTxSuccess { + event, + events, + tx_hash, + tx_index, + block_hash, + block_number, + }) + } +} + +pub async fn tx_data_da_submit_data( + block_hash: BlockHash, + tx_hash: BlockHash, + blocks: &AvailBlocksClient, +) -> Result { + let transaction = + fetch_transaction::(block_hash, tx_hash, blocks).await; + let transaction = transaction.map_err(|err| err.to_string())?; + Ok(transaction.value) +} diff --git a/avail-rust/src/transactions/mod.rs b/avail-rust/src/transactions/mod.rs new file mode 100644 index 000000000..ca52d1b6b --- /dev/null +++ b/avail-rust/src/transactions/mod.rs @@ -0,0 +1,122 @@ +mod balances; +mod da; +mod nom_pools; +mod options; +mod session; +mod staking; + +pub use balances::*; +pub use da::*; +pub use nom_pools::*; +pub use options::{Mortality, Nonce, Options}; +pub use session::*; +pub use staking::*; + +use crate::{ + rpcs::Rpc, utils_raw::progress_transaction, Api, AvailBlocksClient, AvailConfig, BlockHash, + TransactionInBlock, WaitFor, +}; +use sp_core::H256; +use subxt::{blocks::ExtrinsicEvents, tx::TxProgress}; + +pub type Params = + <::ExtrinsicParams as subxt::config::ExtrinsicParams< + AvailConfig, + >>::Params; + +#[derive(Clone)] +pub struct Transactions { + pub balances: Balances, + pub staking: Staking, + pub data_availability: DataAvailability, + pub session: Session, + pub nomination_pools: NominationPools, +} + +impl Transactions { + pub fn new(api: Api, rpc_client: Rpc) -> Self { + let tx = api.tx(); + let blocks = api.blocks(); + + Self { + balances: Balances::new(tx.clone(), rpc_client.clone(), blocks.clone()), + staking: Staking::new(tx.clone(), rpc_client.clone(), blocks.clone()), + data_availability: DataAvailability::new( + tx.clone(), + rpc_client.clone(), + blocks.clone(), + ), + session: Session::new(tx.clone(), rpc_client.clone(), blocks.clone()), + nomination_pools: NominationPools::new(tx.clone(), rpc_client.clone(), blocks.clone()), + } + } +} + +async fn block_and_tx_hash( + tx_in_block: &TransactionInBlock, + events: &ExtrinsicEvents, + blocks: &AvailBlocksClient, +) -> Result<(H256, u32, H256, u32), String> { + let tx_hash = tx_in_block.extrinsic_hash(); + let tx_index = events.extrinsic_index(); + let block_hash = tx_in_block.block_hash(); + let block_number = get_block_number(blocks, block_hash).await?; + + Ok((block_hash, block_number, tx_hash, tx_index)) +} + +async fn get_block_number( + blocks: &AvailBlocksClient, + block_hash: BlockHash, +) -> Result { + let block_number = blocks + .at(block_hash) + .await + .map_err(|e| e.to_string())? + .number(); + + Ok(block_number) +} + +async fn progress_transaction_ex( + maybe_tx_progress: Result, subxt::Error>, + wait_for: WaitFor, + blocks: &AvailBlocksClient, +) -> Result<(ExtrinsicEvents, (H256, u32, H256, u32)), String> { + let transaction = progress_transaction(maybe_tx_progress, wait_for).await; + let tx_in_block = match transaction { + Ok(tx_in_block) => tx_in_block, + Err(message) => return Err(message), + }; + + let events = match tx_in_block.wait_for_success().await { + Ok(e) => e, + Err(error) => return Err(error.to_string()), + }; + + let data = block_and_tx_hash(&tx_in_block, &events, blocks).await?; + + Ok((events, data)) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[tokio::test] + async fn testing_function() { + let sdk = crate::sdk::SDK::new("ws://127.0.0.1:9944").await.unwrap(); + let h = BlockHash::from_str( + "0x6c5ebed687ed008b76028072fe1ad0a06ecf3c00dd9067aa049ea14e180702f8", + ) + .unwrap(); + match sdk.rpc.kate.query_rows(vec![0], Some(h)).await { + Ok(a) => { + dbg!(a); + }, + Err(a) => { + dbg!(a); + }, + }; + } +} diff --git a/avail-rust/src/transactions/nom_pools.rs b/avail-rust/src/transactions/nom_pools.rs new file mode 100644 index 000000000..5b1ab3076 --- /dev/null +++ b/avail-rust/src/transactions/nom_pools.rs @@ -0,0 +1,271 @@ +use crate::rpcs::Rpc; +use crate::sdk::WaitFor; +use crate::utils_raw::fetch_transaction; +use crate::{avail, AccountId, AvailBlocksClient, AvailConfig, BlockHash, TxApi}; + +use std::str::FromStr; +use subxt::blocks::ExtrinsicEvents; +use subxt_signer::sr25519::Keypair; + +use avail::nomination_pools::calls::types as NominationPoolsCalls; +use avail::nomination_pools::events as NominationPoolsEvents; + +use super::options::{from_options_to_params, Options}; +use super::progress_transaction_ex; + +#[derive(Debug)] +pub struct PoolCreateTxSuccess { + pub event: NominationPoolsEvents::Created, + pub event2: NominationPoolsEvents::Bonded, + pub events: ExtrinsicEvents, + pub tx_hash: BlockHash, + pub tx_index: u32, + pub block_hash: BlockHash, + pub block_number: u32, +} + +#[derive(Debug)] +pub struct PoolCreateWithPoolIdTxSuccess { + pub event: NominationPoolsEvents::Created, + pub event2: NominationPoolsEvents::Bonded, + pub events: ExtrinsicEvents, + pub tx_hash: BlockHash, + pub tx_index: u32, + pub block_hash: BlockHash, + pub block_number: u32, +} + +#[derive(Debug)] +pub struct PoolJoinTxSuccess { + pub event: NominationPoolsEvents::Bonded, + pub events: ExtrinsicEvents, + pub tx_hash: BlockHash, + pub tx_index: u32, + pub block_hash: BlockHash, + pub block_number: u32, +} + +#[derive(Debug)] +pub struct PoolNominateTxSuccess { + pub events: ExtrinsicEvents, + pub tx_data: NominationPoolsCalls::Nominate, + pub tx_hash: BlockHash, + pub tx_index: u32, + pub block_hash: BlockHash, + pub block_number: u32, +} + +#[derive(Clone)] +pub struct NominationPools { + api: TxApi, + rpc_client: Rpc, + blocks: AvailBlocksClient, +} + +impl NominationPools { + pub fn new(api: TxApi, rpc_client: Rpc, blocks: AvailBlocksClient) -> Self { + Self { + api, + rpc_client, + blocks, + } + } + + pub async fn nominate( + &self, + pool_id: u32, + validators: Vec, + wait_for: WaitFor, + account: &Keypair, + options: Option, + ) -> Result { + let validators: Result, _> = validators + .into_iter() + .map(|v| AccountId::from_str(&v)) + .collect(); + let validators = validators.map_err(|e| e.to_string())?; + + let account_id = account.public_key().to_account_id(); + let params = + from_options_to_params(options, &self.rpc_client, account_id, &self.blocks).await?; + let call = avail::tx().nomination_pools().nominate(pool_id, validators); + + let maybe_tx_progress = self + .api + .sign_and_submit_then_watch(&call, account, params) + .await; + + let (events, data) = + progress_transaction_ex(maybe_tx_progress, wait_for, &self.blocks).await?; + let (block_hash, block_number, tx_hash, tx_index) = data; + + let tx_data = tx_data_pool_nominate(block_hash, tx_hash, &self.blocks).await?; + + Ok(PoolNominateTxSuccess { + events, + tx_data, + tx_hash, + tx_index, + block_hash, + block_number, + }) + } + + pub async fn join( + &self, + amount: u128, + pool_id: u32, + wait_for: WaitFor, + account: &Keypair, + options: Option, + ) -> Result { + let account_id = account.public_key().to_account_id(); + let params = + from_options_to_params(options, &self.rpc_client, account_id, &self.blocks).await?; + let call = avail::tx().nomination_pools().join(amount, pool_id); + + let maybe_tx_progress = self + .api + .sign_and_submit_then_watch(&call, account, params) + .await; + + let (events, data) = + progress_transaction_ex(maybe_tx_progress, wait_for, &self.blocks).await?; + let (block_hash, block_number, tx_hash, tx_index) = data; + + let event = events.find_first::(); + let Some(event) = event.ok().flatten() else { + return Err(String::from("Failed to find Created event")); + }; + + Ok(PoolJoinTxSuccess { + event, + events, + tx_hash, + tx_index, + block_hash, + block_number, + }) + } + + pub async fn create_with_pool_id( + &self, + amount: u128, + root: &str, + nominator: &str, + bouncer: &str, + pool_id: u32, + wait_for: WaitFor, + account: &Keypair, + options: Option, + ) -> Result { + let root = AccountId::from_str(root).map_err(|e| e.to_string())?; + let nominator = AccountId::from_str(nominator).map_err(|e| e.to_string())?; + let bouncer = AccountId::from_str(bouncer).map_err(|e| e.to_string())?; + + let account_id = account.public_key().to_account_id(); + let params = + from_options_to_params(options, &self.rpc_client, account_id, &self.blocks).await?; + let call = avail::tx().nomination_pools().create_with_pool_id( + amount, + root.into(), + nominator.into(), + bouncer.into(), + pool_id, + ); + + let maybe_tx_progress = self + .api + .sign_and_submit_then_watch(&call, account, params) + .await; + + let (events, data) = + progress_transaction_ex(maybe_tx_progress, wait_for, &self.blocks).await?; + let (block_hash, block_number, tx_hash, tx_index) = data; + + let event = events.find_first::(); + let Some(event) = event.ok().flatten() else { + return Err(String::from("Failed to find Created event")); + }; + + let event2 = events.find_first::(); + let Some(event2) = event2.ok().flatten() else { + return Err(String::from("Failed to find Bonded event")); + }; + + Ok(PoolCreateWithPoolIdTxSuccess { + event, + event2, + events, + tx_hash, + tx_index, + block_hash, + block_number, + }) + } + + pub async fn create( + &self, + amount: u128, + root: &str, + nominator: &str, + bouncer: &str, + wait_for: WaitFor, + account: &Keypair, + options: Option, + ) -> Result { + let root = AccountId::from_str(root).map_err(|e| e.to_string())?; + let nominator = AccountId::from_str(nominator).map_err(|e| e.to_string())?; + let bouncer = AccountId::from_str(bouncer).map_err(|e| e.to_string())?; + + let account_id = account.public_key().to_account_id(); + let params = + from_options_to_params(options, &self.rpc_client, account_id, &self.blocks).await?; + let call = avail::tx().nomination_pools().create( + amount, + root.into(), + nominator.into(), + bouncer.into(), + ); + + let maybe_tx_progress = self + .api + .sign_and_submit_then_watch(&call, account, params) + .await; + + let (events, data) = + progress_transaction_ex(maybe_tx_progress, wait_for, &self.blocks).await?; + let (block_hash, block_number, tx_hash, tx_index) = data; + + let event = events.find_first::(); + let Some(event) = event.ok().flatten() else { + return Err(String::from("Failed to find Created event")); + }; + + let event2 = events.find_first::(); + let Some(event2) = event2.ok().flatten() else { + return Err(String::from("Failed to find Bonded event")); + }; + + Ok(PoolCreateTxSuccess { + event, + event2, + events, + tx_hash, + tx_index, + block_hash, + block_number, + }) + } +} + +pub async fn tx_data_pool_nominate( + block_hash: BlockHash, + tx_hash: BlockHash, + blocks: &AvailBlocksClient, +) -> Result { + let transaction = + fetch_transaction::(block_hash, tx_hash, blocks).await; + let transaction = transaction.map_err(|err| err.to_string())?; + Ok(transaction.value) +} diff --git a/avail-rust/src/transactions/options.rs b/avail-rust/src/transactions/options.rs new file mode 100644 index 000000000..09ffb4f75 --- /dev/null +++ b/avail-rust/src/transactions/options.rs @@ -0,0 +1,118 @@ +use crate::rpcs::Rpc; +use crate::{AccountId, AvailBlocksClient, AvailExtrinsicParamsBuilder, BlockHash}; + +use super::Params; + +#[derive(Debug, Clone)] +pub struct Options { + pub app_id: Option, + pub mortality: Option, + pub nonce: Option, + pub tip: Option, +} +impl Options { + pub fn new() -> Self { + Self { + app_id: None, + mortality: None, + nonce: None, + tip: None, + } + } + + pub fn app_id(mut self, value: u32) -> Self { + self.app_id = Some(value); + self + } + + pub fn mortality(mut self, value: Mortality) -> Self { + self.mortality = Some(value); + self + } + + pub fn nonce(mut self, value: Nonce) -> Self { + self.nonce = Some(value); + self + } + + pub fn tip(mut self, value: u128) -> Self { + self.tip = Some(value); + self + } +} + +#[derive(Debug, Clone)] +pub struct Mortality { + pub period: u64, + pub block_hash: Option, +} +impl Mortality { + pub fn new(period: u64, block_hash: Option) -> Self { + Self { period, block_hash } + } +} + +#[derive(Debug, Clone)] +pub enum Nonce { + BestBlock, + FinalizedBlock, + BestBlockAndTxPool, + Custom(u32), +} + +pub async fn from_options_to_params( + options: Option, + client: &Rpc, + account: AccountId, + blocks: &AvailBlocksClient, +) -> Result { + let Some(options) = options else { + return Ok(AvailExtrinsicParamsBuilder::new().build()); + }; + + let mut builder = AvailExtrinsicParamsBuilder::new(); + builder = builder.app_id(options.app_id.unwrap_or_default()); + builder = builder.tip(options.tip.unwrap_or_default()); + + let mortality = options.mortality.unwrap_or_else(|| Mortality { + period: 32, + block_hash: None, + }); + let header = client.chain.get_header(mortality.block_hash); + let header = header.await.map_err(|e| e.to_string())?; + builder = builder.mortal(&header, mortality.period); + + if let Some(nonce) = options.nonce { + builder = match nonce { + Nonce::BestBlock => { + let hash = client.chain.get_block_hash(None).await.unwrap(); + let block = blocks.at(hash).await.map_err(|e| e.to_string())?; + let nonce = block + .account_nonce(&account) + .await + .map_err(|e| e.to_string())?; + builder.nonce(nonce) + }, + Nonce::FinalizedBlock => { + let hash = client.chain.get_finalized_head().await.unwrap(); + let block = blocks.at(hash).await.map_err(|e| e.to_string())?; + let nonce = block + .account_nonce(&account) + .await + .map_err(|e| e.to_string())?; + builder.nonce(nonce) + }, + Nonce::BestBlockAndTxPool => { + let nonce = client + .system + .account_next_index(account.to_string()) + .await + .map_err(|e| e.to_string())?; + builder.nonce(nonce as u64) + }, + Nonce::Custom(x) => builder.nonce(x as u64), + }; + } + + Ok(builder.build()) +} diff --git a/avail-rust/src/transactions/session.rs b/avail-rust/src/transactions/session.rs new file mode 100644 index 000000000..de2ceb546 --- /dev/null +++ b/avail-rust/src/transactions/session.rs @@ -0,0 +1,83 @@ +use crate::avail::runtime_types::da_runtime::primitives::SessionKeys; +use crate::rpcs::Rpc; +use crate::sdk::WaitFor; +use crate::utils_raw::fetch_transaction; +use crate::{avail, AvailBlocksClient, AvailConfig, BlockHash, TxApi}; + +use subxt::blocks::ExtrinsicEvents; +use subxt_signer::sr25519::Keypair; + +use super::options::from_options_to_params; +use super::{options::Options, progress_transaction_ex}; + +use avail::session::calls::types as SessionCalls; + +#[derive(Debug)] +pub struct SetKeysTxSuccess { + pub events: ExtrinsicEvents, + pub tx_data: SessionCalls::SetKeys, + pub tx_hash: BlockHash, + pub tx_index: u32, + pub block_hash: BlockHash, + pub block_number: u32, +} + +#[derive(Clone)] +pub struct Session { + api: TxApi, + rpc_client: Rpc, + blocks: AvailBlocksClient, +} + +impl Session { + pub fn new(api: TxApi, rpc_client: Rpc, blocks: AvailBlocksClient) -> Self { + Self { + api, + rpc_client, + blocks, + } + } + + pub async fn set_keys( + &self, + keys: SessionKeys, + wait_for: WaitFor, + account: &Keypair, + options: Option, + ) -> Result { + let account_id = account.public_key().to_account_id(); + let params = + from_options_to_params(options, &self.rpc_client, account_id, &self.blocks).await?; + let call = avail::tx().session().set_keys(keys, vec![]); + + let maybe_tx_progress = self + .api + .sign_and_submit_then_watch(&call, account, params) + .await; + + let (events, data) = + progress_transaction_ex(maybe_tx_progress, wait_for, &self.blocks).await?; + let (block_hash, block_number, tx_hash, tx_index) = data; + + let tx_data = tx_data_session_set_keys(block_hash, tx_hash, &self.blocks).await?; + + Ok(SetKeysTxSuccess { + events, + tx_data, + tx_hash, + tx_index, + block_hash, + block_number, + }) + } +} + +pub async fn tx_data_session_set_keys( + block_hash: BlockHash, + tx_hash: BlockHash, + blocks: &AvailBlocksClient, +) -> Result { + let transaction = fetch_transaction::(block_hash, tx_hash, blocks).await; + let transaction = transaction.map_err(|err| err.to_string())?; + Ok(transaction.value) +} diff --git a/avail-rust/src/transactions/staking.rs b/avail-rust/src/transactions/staking.rs new file mode 100644 index 000000000..e29f0e273 --- /dev/null +++ b/avail-rust/src/transactions/staking.rs @@ -0,0 +1,386 @@ +use crate::api_dev::api::runtime_types::pallet_staking::ValidatorPrefs; +use crate::api_dev::api::runtime_types::sp_arithmetic::per_things::Perbill; +use crate::rpcs::Rpc; +use crate::sdk::WaitFor; +use crate::utils_raw::fetch_transaction; +use crate::{ + avail, AccountId, AvailBlocksClient, AvailConfig, BlockHash, RewardDestination, TxApi, +}; + +use std::str::FromStr; +use subxt::blocks::ExtrinsicEvents; +use subxt_core::utils::MultiAddress; +use subxt_signer::sr25519::Keypair; + +use avail::staking::calls::types as StakingCalls; +use avail::staking::events as StakingEvents; + +use super::options::{from_options_to_params, Options}; +use super::progress_transaction_ex; + +#[derive(Debug)] +pub struct BondTxSuccess { + pub event: StakingEvents::Bonded, + pub events: ExtrinsicEvents, + pub tx_hash: BlockHash, + pub tx_index: u32, + pub block_hash: BlockHash, + pub block_number: u32, +} + +#[derive(Debug)] +pub struct BondExtraTxSuccess { + pub event: StakingEvents::Bonded, + pub events: ExtrinsicEvents, + pub tx_hash: BlockHash, + pub tx_index: u32, + pub block_hash: BlockHash, + pub block_number: u32, +} + +#[derive(Debug)] +pub struct ChillTxSuccess { + pub event: Option, + pub events: ExtrinsicEvents, + pub tx_hash: BlockHash, + pub tx_index: u32, + pub block_hash: BlockHash, + pub block_number: u32, +} + +#[derive(Debug)] +pub struct ChillOtherTxSuccess { + pub event: StakingEvents::Chilled, + pub events: ExtrinsicEvents, + pub tx_hash: BlockHash, + pub tx_index: u32, + pub block_hash: BlockHash, + pub block_number: u32, +} + +#[derive(Debug)] +pub struct NominateTxSuccess { + pub events: ExtrinsicEvents, + pub tx_data: StakingCalls::Nominate, + pub tx_hash: BlockHash, + pub tx_index: u32, + pub block_hash: BlockHash, + pub block_number: u32, +} + +#[derive(Debug)] +pub struct UnbondTxSuccess { + pub event: StakingEvents::Unbonded, + pub events: ExtrinsicEvents, + pub tx_hash: BlockHash, + pub tx_index: u32, + pub block_hash: BlockHash, + pub block_number: u32, +} + +#[derive(Debug)] +pub struct ValidateTxSuccess { + pub event: StakingEvents::ValidatorPrefsSet, + pub events: ExtrinsicEvents, + pub tx_hash: BlockHash, + pub tx_index: u32, + pub block_hash: BlockHash, + pub block_number: u32, +} + +#[derive(Clone)] +pub struct Staking { + api: TxApi, + rpc_client: Rpc, + blocks: AvailBlocksClient, +} + +impl Staking { + pub fn new(api: TxApi, rpc_client: Rpc, blocks: AvailBlocksClient) -> Self { + Self { + api, + rpc_client, + blocks, + } + } + + pub async fn bond( + &self, + value: u128, + payee: RewardDestination, + wait_for: WaitFor, + account: &Keypair, + options: Option, + ) -> Result { + let account_id = account.public_key().to_account_id(); + let params = + from_options_to_params(options, &self.rpc_client, account_id, &self.blocks).await?; + let call = avail::tx().staking().bond(value, payee); + + let maybe_tx_progress = self + .api + .sign_and_submit_then_watch(&call, account, params) + .await; + + let (events, data) = + progress_transaction_ex(maybe_tx_progress, wait_for, &self.blocks).await?; + let (block_hash, block_number, tx_hash, tx_index) = data; + + let event = events.find_first::(); + let Some(event) = event.ok().flatten() else { + return Err(String::from("Failed to find Bonded event")); + }; + + Ok(BondTxSuccess { + event, + events, + tx_hash, + tx_index, + block_hash, + block_number, + }) + } + + pub async fn bond_extra( + &self, + max_additional: u128, + wait_for: WaitFor, + account: &Keypair, + options: Option, + ) -> Result { + let account_id = account.public_key().to_account_id(); + let params = + from_options_to_params(options, &self.rpc_client, account_id, &self.blocks).await?; + let call = avail::tx().staking().bond_extra(max_additional); + + let maybe_tx_progress = self + .api + .sign_and_submit_then_watch(&call, account, params) + .await; + + let (events, data) = + progress_transaction_ex(maybe_tx_progress, wait_for, &self.blocks).await?; + let (block_hash, block_number, tx_hash, tx_index) = data; + + let event = events.find_first::(); + let Some(event) = event.ok().flatten() else { + return Err(String::from("Failed to find Bonded event")); + }; + + Ok(BondExtraTxSuccess { + event, + events, + tx_hash, + tx_index, + block_hash, + block_number, + }) + } + + pub async fn chill( + &self, + wait_for: WaitFor, + account: &Keypair, + options: Option, + ) -> Result { + let account_id = account.public_key().to_account_id(); + let params = + from_options_to_params(options, &self.rpc_client, account_id, &self.blocks).await?; + let call = avail::tx().staking().chill(); + + let maybe_tx_progress = self + .api + .sign_and_submit_then_watch(&call, account, params) + .await; + + let (events, data) = + progress_transaction_ex(maybe_tx_progress, wait_for, &self.blocks).await?; + let (block_hash, block_number, tx_hash, tx_index) = data; + + let event = events.find_first::().ok().flatten(); + + Ok(ChillTxSuccess { + event, + events, + tx_hash, + tx_index, + block_hash, + block_number, + }) + } + + pub async fn chill_other( + &self, + stash: &str, + wait_for: WaitFor, + account: &Keypair, + options: Option, + ) -> Result { + let stash = match AccountId::from_str(stash) { + Ok(stash) => stash, + Err(error) => return Err(std::format!("{:?}", error)), + }; + + let account_id = account.public_key().to_account_id(); + let params = + from_options_to_params(options, &self.rpc_client, account_id, &self.blocks).await?; + let call = avail::tx().staking().chill_other(stash); + + let maybe_tx_progress = self + .api + .sign_and_submit_then_watch(&call, account, params) + .await; + + let (events, data) = + progress_transaction_ex(maybe_tx_progress, wait_for, &self.blocks).await?; + let (block_hash, block_number, tx_hash, tx_index) = data; + + let event = events.find_first::(); + let Some(event) = event.ok().flatten() else { + return Err(String::from("Failed to find Chilled event")); + }; + + Ok(ChillOtherTxSuccess { + event, + events, + tx_hash, + tx_index, + block_hash, + block_number, + }) + } + + pub async fn nominate( + &self, + targets: &[String], + wait_for: WaitFor, + account: &Keypair, + options: Option, + ) -> Result { + let targets: Result, _> = targets + .iter() + .map(|address| AccountId::from_str(address)) + .collect(); + let targets = targets.map_err(|e| std::format!("{:?}", e))?; + let targets = targets.into_iter().map(|a| MultiAddress::Id(a)).collect(); + + let account_id = account.public_key().to_account_id(); + let params = + from_options_to_params(options, &self.rpc_client, account_id, &self.blocks).await?; + let call = avail::tx().staking().nominate(targets); + + let maybe_tx_progress = self + .api + .sign_and_submit_then_watch(&call, account, params) + .await; + + let (events, data) = + progress_transaction_ex(maybe_tx_progress, wait_for, &self.blocks).await?; + let (block_hash, block_number, tx_hash, tx_index) = data; + + let tx_data = tx_data_staking_nominate(block_hash, tx_hash, &self.blocks).await?; + + Ok(NominateTxSuccess { + events, + tx_data, + tx_hash, + tx_index, + block_hash, + block_number, + }) + } + + pub async fn unbond( + &self, + value: u128, + wait_for: WaitFor, + account: &Keypair, + options: Option, + ) -> Result { + let call = avail::tx().staking().unbond(value); + + let account_id = account.public_key().to_account_id(); + let params = + from_options_to_params(options, &self.rpc_client, account_id, &self.blocks).await?; + let maybe_tx_progress = self + .api + .sign_and_submit_then_watch(&call, account, params) + .await; + + let (events, data) = + progress_transaction_ex(maybe_tx_progress, wait_for, &self.blocks).await?; + let (block_hash, block_number, tx_hash, tx_index) = data; + + let event = events.find_first::(); + let Some(event) = event.ok().flatten() else { + return Err(String::from("Failed to find Unbonded event")); + }; + + Ok(UnbondTxSuccess { + event, + events, + tx_hash, + tx_index, + block_hash, + block_number, + }) + } + + pub async fn validate( + &self, + commission: u8, + blocked: bool, + wait_for: WaitFor, + account: &Keypair, + options: Option, + ) -> Result { + if commission > 100 { + return Err(String::from("Commission cannot be more than 100")); + } + + let commission = Perbill(commission as u32); + let perfs = ValidatorPrefs { + commission, + blocked, + }; + + let account_id = account.public_key().to_account_id(); + let params = + from_options_to_params(options, &self.rpc_client, account_id, &self.blocks).await?; + let call = avail::tx().staking().validate(perfs); + + let maybe_tx_progress = self + .api + .sign_and_submit_then_watch(&call, account, params) + .await; + + let (events, data) = + progress_transaction_ex(maybe_tx_progress, wait_for, &self.blocks).await?; + let (block_hash, block_number, tx_hash, tx_index) = data; + + let event = events.find_first::(); + let Some(event) = event.ok().flatten() else { + return Err(String::from("Failed to find ValidatorPrefsSet event")); + }; + + Ok(ValidateTxSuccess { + event, + events, + tx_hash, + tx_index, + block_hash, + block_number, + }) + } +} + +pub async fn tx_data_staking_nominate( + block_hash: BlockHash, + tx_hash: BlockHash, + blocks: &AvailBlocksClient, +) -> Result { + let transaction = + fetch_transaction::(block_hash, tx_hash, blocks).await; + let transaction = transaction.map_err(|err| err.to_string())?; + Ok(transaction.value) +} From 0fe020a2e77db36667351e952af32b01fa1677e1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Marko=20Petrli=C4=87?= Date: Wed, 11 Sep 2024 14:10:00 +0200 Subject: [PATCH 2/4] Added some storage calls to rust sdk (#656) --- .../docs/storage/da_app_keys/Cargo.toml | 9 ++++++ .../docs/storage/da_app_keys/src/main.rs | 30 ++++++++++++++++++ .../docs/storage/da_app_keys_iter/Cargo.toml | 9 ++++++ .../docs/storage/da_app_keys_iter/src/main.rs | 31 +++++++++++++++++++ .../docs/storage/da_next_app_id/Cargo.toml | 9 ++++++ .../docs/storage/da_next_app_id/src/main.rs | 25 +++++++++++++++ .../storage/staking_active_era/Cargo.toml | 9 ++++++ .../storage/staking_active_era/src/main.rs | 25 +++++++++++++++ .../docs/storage/staking_bonded/Cargo.toml | 9 ++++++ .../docs/storage/staking_bonded/src/main.rs | 29 +++++++++++++++++ .../storage/staking_bonded_iter/Cargo.toml | 9 ++++++ .../storage/staking_bonded_iter/src/main.rs | 31 +++++++++++++++++++ .../docs/storage/system_account/Cargo.toml | 9 ++++++ .../docs/storage/system_account/src/main.rs | 29 +++++++++++++++++ .../storage/system_account_iter/Cargo.toml | 9 ++++++ .../storage/system_account_iter/src/main.rs | 31 +++++++++++++++++++ avail-rust/src/lib.rs | 1 + 17 files changed, 304 insertions(+) create mode 100644 avail-rust/docs/storage/da_app_keys/Cargo.toml create mode 100644 avail-rust/docs/storage/da_app_keys/src/main.rs create mode 100644 avail-rust/docs/storage/da_app_keys_iter/Cargo.toml create mode 100644 avail-rust/docs/storage/da_app_keys_iter/src/main.rs create mode 100644 avail-rust/docs/storage/da_next_app_id/Cargo.toml create mode 100644 avail-rust/docs/storage/da_next_app_id/src/main.rs create mode 100644 avail-rust/docs/storage/staking_active_era/Cargo.toml create mode 100644 avail-rust/docs/storage/staking_active_era/src/main.rs create mode 100644 avail-rust/docs/storage/staking_bonded/Cargo.toml create mode 100644 avail-rust/docs/storage/staking_bonded/src/main.rs create mode 100644 avail-rust/docs/storage/staking_bonded_iter/Cargo.toml create mode 100644 avail-rust/docs/storage/staking_bonded_iter/src/main.rs create mode 100644 avail-rust/docs/storage/system_account/Cargo.toml create mode 100644 avail-rust/docs/storage/system_account/src/main.rs create mode 100644 avail-rust/docs/storage/system_account_iter/Cargo.toml create mode 100644 avail-rust/docs/storage/system_account_iter/src/main.rs diff --git a/avail-rust/docs/storage/da_app_keys/Cargo.toml b/avail-rust/docs/storage/da_app_keys/Cargo.toml new file mode 100644 index 000000000..9b4af3845 --- /dev/null +++ b/avail-rust/docs/storage/da_app_keys/Cargo.toml @@ -0,0 +1,9 @@ +[workspace] + +[package] +name = "storage-da-app-keys" +edition = "2021" + +[dependencies] +avail-rust = { git = "https://github.com/availproject/avail" } +tokio = { version = "1.38.0", features = ["rt-multi-thread"] } diff --git a/avail-rust/docs/storage/da_app_keys/src/main.rs b/avail-rust/docs/storage/da_app_keys/src/main.rs new file mode 100644 index 000000000..3f65a9151 --- /dev/null +++ b/avail-rust/docs/storage/da_app_keys/src/main.rs @@ -0,0 +1,30 @@ +use avail_rust::{ + avail::{self, runtime_types::bounded_collections::bounded_vec::BoundedVec}, + SDK, +}; + +#[tokio::main] +async fn main() -> Result<(), String> { + let sdk = SDK::new("ws://127.0.0.1:9944").await.unwrap(); + + let key = String::from("Reserved-1"); + let key = BoundedVec(key.as_bytes().to_vec()); + let storage_query = avail::storage().data_availability().app_keys(key); + let best_block_hash = sdk + .rpc + .chain + .get_block_hash(None) + .await + .map_err(|e| e.to_string())?; + let result = sdk + .api + .storage() + .at(best_block_hash) + .fetch(&storage_query) + .await + .map_err(|e| e.to_string())?; + + dbg!(result); + + Ok(()) +} diff --git a/avail-rust/docs/storage/da_app_keys_iter/Cargo.toml b/avail-rust/docs/storage/da_app_keys_iter/Cargo.toml new file mode 100644 index 000000000..803562567 --- /dev/null +++ b/avail-rust/docs/storage/da_app_keys_iter/Cargo.toml @@ -0,0 +1,9 @@ +[workspace] + +[package] +name = "storage-da-app-keys-iter" +edition = "2021" + +[dependencies] +avail-rust = { git = "https://github.com/availproject/avail" } +tokio = { version = "1.38.0", features = ["rt-multi-thread"] } diff --git a/avail-rust/docs/storage/da_app_keys_iter/src/main.rs b/avail-rust/docs/storage/da_app_keys_iter/src/main.rs new file mode 100644 index 000000000..fcaa7da82 --- /dev/null +++ b/avail-rust/docs/storage/da_app_keys_iter/src/main.rs @@ -0,0 +1,31 @@ +use avail_rust::{avail, SDK}; + +#[tokio::main] +async fn main() -> Result<(), String> { + let sdk = SDK::new("ws://127.0.0.1:9944").await.unwrap(); + + let storage_query = avail::storage().data_availability().app_keys_iter(); + let best_block_hash = sdk + .rpc + .chain + .get_block_hash(None) + .await + .map_err(|e| e.to_string())?; + let mut results = sdk + .api + .storage() + .at(best_block_hash) + .iter(storage_query) + .await + .map_err(|e| e.to_string())?; + + while let Some(Ok(kv)) = results.next().await { + let key = (&kv.key_bytes[49..]).to_vec(); + let key = String::from_utf8(key).unwrap(); + + println!("Key: {:?}", key); + println!("Value: {:?}", kv.value); + } + + Ok(()) +} diff --git a/avail-rust/docs/storage/da_next_app_id/Cargo.toml b/avail-rust/docs/storage/da_next_app_id/Cargo.toml new file mode 100644 index 000000000..f65fcb353 --- /dev/null +++ b/avail-rust/docs/storage/da_next_app_id/Cargo.toml @@ -0,0 +1,9 @@ +[workspace] + +[package] +name = "storage-da-next-app-id" +edition = "2021" + +[dependencies] +avail-rust = { git = "https://github.com/availproject/avail" } +tokio = { version = "1.38.0", features = ["rt-multi-thread"] } diff --git a/avail-rust/docs/storage/da_next_app_id/src/main.rs b/avail-rust/docs/storage/da_next_app_id/src/main.rs new file mode 100644 index 000000000..1e50d4b19 --- /dev/null +++ b/avail-rust/docs/storage/da_next_app_id/src/main.rs @@ -0,0 +1,25 @@ +use avail_rust::{avail, SDK}; + +#[tokio::main] +async fn main() -> Result<(), String> { + let sdk = SDK::new("ws://127.0.0.1:9944").await.unwrap(); + + let storage_query = avail::storage().data_availability().next_app_id(); + let best_block_hash = sdk + .rpc + .chain + .get_block_hash(None) + .await + .map_err(|e| e.to_string())?; + let result = sdk + .api + .storage() + .at(best_block_hash) + .fetch(&storage_query) + .await + .map_err(|e| e.to_string())?; + + dbg!(result); + + Ok(()) +} diff --git a/avail-rust/docs/storage/staking_active_era/Cargo.toml b/avail-rust/docs/storage/staking_active_era/Cargo.toml new file mode 100644 index 000000000..31f4cf5a2 --- /dev/null +++ b/avail-rust/docs/storage/staking_active_era/Cargo.toml @@ -0,0 +1,9 @@ +[workspace] + +[package] +name = "storage-staking-active-era" +edition = "2021" + +[dependencies] +avail-rust = { git = "https://github.com/availproject/avail" } +tokio = { version = "1.38.0", features = ["rt-multi-thread"] } diff --git a/avail-rust/docs/storage/staking_active_era/src/main.rs b/avail-rust/docs/storage/staking_active_era/src/main.rs new file mode 100644 index 000000000..bbda5341b --- /dev/null +++ b/avail-rust/docs/storage/staking_active_era/src/main.rs @@ -0,0 +1,25 @@ +use avail_rust::{avail, SDK}; + +#[tokio::main] +async fn main() -> Result<(), String> { + let sdk = SDK::new("ws://127.0.0.1:9944").await.unwrap(); + + let storage_query = avail::storage().staking().active_era(); + let best_block_hash = sdk + .rpc + .chain + .get_block_hash(None) + .await + .map_err(|e| e.to_string())?; + let result = sdk + .api + .storage() + .at(best_block_hash) + .fetch(&storage_query) + .await + .map_err(|e| e.to_string())?; + + dbg!(result); + + Ok(()) +} diff --git a/avail-rust/docs/storage/staking_bonded/Cargo.toml b/avail-rust/docs/storage/staking_bonded/Cargo.toml new file mode 100644 index 000000000..c6ca91fba --- /dev/null +++ b/avail-rust/docs/storage/staking_bonded/Cargo.toml @@ -0,0 +1,9 @@ +[workspace] + +[package] +name = "storage-staking-bonded" +edition = "2021" + +[dependencies] +avail-rust = { git = "https://github.com/availproject/avail" } +tokio = { version = "1.38.0", features = ["rt-multi-thread"] } diff --git a/avail-rust/docs/storage/staking_bonded/src/main.rs b/avail-rust/docs/storage/staking_bonded/src/main.rs new file mode 100644 index 000000000..a5ca47276 --- /dev/null +++ b/avail-rust/docs/storage/staking_bonded/src/main.rs @@ -0,0 +1,29 @@ +use avail_rust::{avail, AccountId, SDK}; +use core::str::FromStr; + +#[tokio::main] +async fn main() -> Result<(), String> { + let sdk = SDK::new("ws://127.0.0.1:9944").await.unwrap(); + + let account_id = + AccountId::from_str("5GNJqTPyNqANBkUVMN1LPPrxXnFouWXoe2wNSmmEoLctxiZY").unwrap(); // Alice_Stash + + let storage_query = avail::storage().staking().bonded(account_id); + let best_block_hash = sdk + .rpc + .chain + .get_block_hash(None) + .await + .map_err(|e| e.to_string())?; + let result = sdk + .api + .storage() + .at(best_block_hash) + .fetch(&storage_query) + .await + .map_err(|e| e.to_string())?; + + dbg!(result); + + Ok(()) +} diff --git a/avail-rust/docs/storage/staking_bonded_iter/Cargo.toml b/avail-rust/docs/storage/staking_bonded_iter/Cargo.toml new file mode 100644 index 000000000..33a672772 --- /dev/null +++ b/avail-rust/docs/storage/staking_bonded_iter/Cargo.toml @@ -0,0 +1,9 @@ +[workspace] + +[package] +name = "storage-staking-bonded-iter" +edition = "2021" + +[dependencies] +avail-rust = { git = "https://github.com/availproject/avail" } +tokio = { version = "1.38.0", features = ["rt-multi-thread"] } diff --git a/avail-rust/docs/storage/staking_bonded_iter/src/main.rs b/avail-rust/docs/storage/staking_bonded_iter/src/main.rs new file mode 100644 index 000000000..e1c3d0aa2 --- /dev/null +++ b/avail-rust/docs/storage/staking_bonded_iter/src/main.rs @@ -0,0 +1,31 @@ +use avail_rust::{avail, AccountId, SDK}; + +#[tokio::main] +async fn main() -> Result<(), String> { + let sdk = SDK::new("ws://127.0.0.1:9944").await.unwrap(); + + let storage_query = avail::storage().staking().bonded_iter(); + let best_block_hash = sdk + .rpc + .chain + .get_block_hash(None) + .await + .map_err(|e| e.to_string())?; + let mut results = sdk + .api + .storage() + .at(best_block_hash) + .iter(storage_query) + .await + .map_err(|e| e.to_string())?; + + while let Some(Ok(kv)) = results.next().await { + let key: [u8; 32] = (&kv.key_bytes[40..]).try_into().unwrap(); + let key = AccountId::from(key); + + println!("Key: 0x{:?}", key.to_string()); + println!("Value: {:?}", kv.value); + } + + Ok(()) +} diff --git a/avail-rust/docs/storage/system_account/Cargo.toml b/avail-rust/docs/storage/system_account/Cargo.toml new file mode 100644 index 000000000..4ed411e86 --- /dev/null +++ b/avail-rust/docs/storage/system_account/Cargo.toml @@ -0,0 +1,9 @@ +[workspace] + +[package] +name = "storage-system-account" +edition = "2021" + +[dependencies] +avail-rust = { git = "https://github.com/availproject/avail" } +tokio = { version = "1.38.0", features = ["rt-multi-thread"] } diff --git a/avail-rust/docs/storage/system_account/src/main.rs b/avail-rust/docs/storage/system_account/src/main.rs new file mode 100644 index 000000000..e417a68a1 --- /dev/null +++ b/avail-rust/docs/storage/system_account/src/main.rs @@ -0,0 +1,29 @@ +use avail_rust::{avail, AccountId, SDK}; +use core::str::FromStr; + +#[tokio::main] +async fn main() -> Result<(), String> { + let sdk = SDK::new("ws://127.0.0.1:9944").await.unwrap(); + + let account_id = + AccountId::from_str("5GNJqTPyNqANBkUVMN1LPPrxXnFouWXoe2wNSmmEoLctxiZY").unwrap(); // Alice_Stash + + let storage_query = avail::storage().system().account(account_id); + let best_block_hash = sdk + .rpc + .chain + .get_block_hash(None) + .await + .map_err(|e| e.to_string())?; + let result = sdk + .api + .storage() + .at(best_block_hash) + .fetch(&storage_query) + .await + .map_err(|e| e.to_string())?; + + dbg!(result); + + Ok(()) +} diff --git a/avail-rust/docs/storage/system_account_iter/Cargo.toml b/avail-rust/docs/storage/system_account_iter/Cargo.toml new file mode 100644 index 000000000..8a9a3d3be --- /dev/null +++ b/avail-rust/docs/storage/system_account_iter/Cargo.toml @@ -0,0 +1,9 @@ +[workspace] + +[package] +name = "storage-system-account-iter" +edition = "2021" + +[dependencies] +avail-rust = { git = "https://github.com/availproject/avail" } +tokio = { version = "1.38.0", features = ["rt-multi-thread"] } diff --git a/avail-rust/docs/storage/system_account_iter/src/main.rs b/avail-rust/docs/storage/system_account_iter/src/main.rs new file mode 100644 index 000000000..99d3382ba --- /dev/null +++ b/avail-rust/docs/storage/system_account_iter/src/main.rs @@ -0,0 +1,31 @@ +use avail_rust::{avail, AccountId, SDK}; + +#[tokio::main] +async fn main() -> Result<(), String> { + let sdk = SDK::new("ws://127.0.0.1:9944").await.unwrap(); + + let storage_query = avail::storage().system().account_iter(); + let best_block_hash = sdk + .rpc + .chain + .get_block_hash(None) + .await + .map_err(|e| e.to_string())?; + let mut results = sdk + .api + .storage() + .at(best_block_hash) + .iter(storage_query) + .await + .map_err(|e| e.to_string())?; + + while let Some(Ok(kv)) = results.next().await { + let key: [u8; 32] = (&kv.key_bytes[48..]).try_into().unwrap(); + let key = AccountId::from(key); + + println!("Key: 0x{:?}", key.to_string()); + println!("Value: {:?}", kv.value); + } + + Ok(()) +} diff --git a/avail-rust/src/lib.rs b/avail-rust/src/lib.rs index bccf006dd..c9a79aece 100644 --- a/avail-rust/src/lib.rs +++ b/avail-rust/src/lib.rs @@ -24,6 +24,7 @@ pub use config::*; pub use sdk::{WaitFor, SDK}; pub use avail_core; +pub use hex; pub use kate_recovery; pub use primitives::block::{ AppUncheckedExtrinsic, AvailHeader, DefaultExtrinsicParams, DefaultExtrinsicParamsBuilder, From 74ef645bdcdb7c0ffe5c25f2f072fc3d392c65b9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Marko=20Petrli=C4=87?= Date: Wed, 11 Sep 2024 16:27:46 +0200 Subject: [PATCH 3/4] Added nomination pool txs to avail-deno. (#657) --- avail-deno/docs/README.md | 3 +- avail-deno/docs/advanced-examples/README.md | 4 +- avail-deno/docs/advanced-examples/connect.ts | 26 - .../advanced-examples/register_validator.json | 7 - .../advanced-examples/register_validator.ts | 141 ---- .../rpc_kate_query_block_length.ts | 54 -- .../rpc_kate_query_data_proof.ts | 53 -- .../advanced-examples/rpc_kate_query_proof.ts | 54 -- .../advanced-examples/rpc_kate_query_rows.ts | 54 -- .../advanced-examples/subscribe_to_header.ts | 28 - .../advanced-examples/tx_balance_transfer.ts | 59 -- ...ata_availability_create_application_key.ts | 70 -- .../tx_data_availability_submit_data.ts | 75 -- .../tx_staking_nominate_full_example.ts | 85 -- .../tx_staking_validate_full_example.ts | 115 --- avail-deno/docs/extrinsics/README.md | 762 +++++++++++++++--- .../docs/extrinsics/balances_tranfer_all.ts | 4 +- .../balances_tranfer_allow_death.ts | 4 +- .../extrinsics/balances_tranfer_keep_alive.ts | 3 +- .../extrinsics/da_create_application_key.ts | 3 +- .../da_submit_block_length_proposal.ts | 3 +- avail-deno/docs/extrinsics/da_submit_data.ts | 4 +- .../extrinsics/nomination_pools_create.ts | 22 + .../nomination_pools_create_with_pool_id.ts | 23 + .../docs/extrinsics/nomination_pools_join.ts | 19 + .../extrinsics/nomination_pools_nominate.ts | 19 + avail-deno/docs/extrinsics/staking_bond.ts | 3 +- .../docs/extrinsics/staking_bond_extra.ts | 3 +- avail-deno/docs/extrinsics/staking_chill.ts | 3 +- .../docs/extrinsics/staking_chill_other.ts | 3 +- .../docs/extrinsics/staking_nominate.ts | 3 +- avail-deno/docs/extrinsics/staking_unbond.ts | 3 +- .../docs/extrinsics/staking_validate.ts | 3 +- .../docs/extrinsics/webapp/account.html | 2 - .../docs/extrinsics/webapp/shared_state.ts | 18 - .../docs/extrinsics/webapp/submit_data.html | 10 - .../docs/extrinsics/webapp/submit_data.ts | 29 - avail-deno/docs/extrinsics/webapp/webapp.ts | 44 - avail-deno/docs/storage/README.md | 0 avail-deno/docs/storage/da_app_keys.ts | 10 + avail-deno/docs/storage/da_app_keys_iter.ts | 12 + avail-deno/docs/storage/da_next_app_id.ts | 9 + .../minimal_examples/staking_bonded.ts | 0 avail-deno/docs/storage/staking_active_era.ts | 9 + avail-deno/docs/storage/staking_bonded.ts | 10 + .../docs/storage/staking_bonded_iter.ts | 12 + avail-deno/docs/storage/system_account.ts | 10 + .../docs/storage/system_account_iter.ts | 12 + avail-deno/src/events.ts | 54 +- avail-deno/src/transactions.ts | 466 +++++++++-- avail-rust/docs/extrinsics/README.md | 4 +- 51 files changed, 1299 insertions(+), 1127 deletions(-) delete mode 100644 avail-deno/docs/advanced-examples/connect.ts delete mode 100644 avail-deno/docs/advanced-examples/register_validator.json delete mode 100644 avail-deno/docs/advanced-examples/register_validator.ts delete mode 100644 avail-deno/docs/advanced-examples/rpc_kate_query_block_length.ts delete mode 100644 avail-deno/docs/advanced-examples/rpc_kate_query_data_proof.ts delete mode 100644 avail-deno/docs/advanced-examples/rpc_kate_query_proof.ts delete mode 100644 avail-deno/docs/advanced-examples/rpc_kate_query_rows.ts delete mode 100644 avail-deno/docs/advanced-examples/subscribe_to_header.ts delete mode 100644 avail-deno/docs/advanced-examples/tx_balance_transfer.ts delete mode 100644 avail-deno/docs/advanced-examples/tx_data_availability_create_application_key.ts delete mode 100644 avail-deno/docs/advanced-examples/tx_data_availability_submit_data.ts delete mode 100644 avail-deno/docs/advanced-examples/tx_staking_nominate_full_example.ts delete mode 100644 avail-deno/docs/advanced-examples/tx_staking_validate_full_example.ts create mode 100644 avail-deno/docs/extrinsics/nomination_pools_create.ts create mode 100644 avail-deno/docs/extrinsics/nomination_pools_create_with_pool_id.ts create mode 100644 avail-deno/docs/extrinsics/nomination_pools_join.ts create mode 100644 avail-deno/docs/extrinsics/nomination_pools_nominate.ts delete mode 100644 avail-deno/docs/extrinsics/webapp/account.html delete mode 100644 avail-deno/docs/extrinsics/webapp/shared_state.ts delete mode 100644 avail-deno/docs/extrinsics/webapp/submit_data.html delete mode 100644 avail-deno/docs/extrinsics/webapp/submit_data.ts delete mode 100644 avail-deno/docs/extrinsics/webapp/webapp.ts delete mode 100644 avail-deno/docs/storage/README.md create mode 100644 avail-deno/docs/storage/da_app_keys.ts create mode 100644 avail-deno/docs/storage/da_app_keys_iter.ts create mode 100644 avail-deno/docs/storage/da_next_app_id.ts delete mode 100644 avail-deno/docs/storage/minimal_examples/staking_bonded.ts create mode 100644 avail-deno/docs/storage/staking_active_era.ts create mode 100644 avail-deno/docs/storage/staking_bonded.ts create mode 100644 avail-deno/docs/storage/staking_bonded_iter.ts create mode 100644 avail-deno/docs/storage/system_account.ts create mode 100644 avail-deno/docs/storage/system_account_iter.ts diff --git a/avail-deno/docs/README.md b/avail-deno/docs/README.md index 55f34e5ef..f5d592ac3 100644 --- a/avail-deno/docs/README.md +++ b/avail-deno/docs/README.md @@ -1,4 +1,5 @@ # Structure - `/extrinsics/` folder contains API reference and examples for SDK extrinsics -- `/advanced-examples/` folder contains advanced examples that showcase how to do things that are not already available through the SDK interface. \ No newline at end of file +- `/advanced-examples/` folder contains advanced examples that showcase how to do things that are not already available through the SDK + interface. diff --git a/avail-deno/docs/advanced-examples/README.md b/avail-deno/docs/advanced-examples/README.md index dc9bc90ec..71199f416 100644 --- a/avail-deno/docs/advanced-examples/README.md +++ b/avail-deno/docs/advanced-examples/README.md @@ -1,7 +1,7 @@ # Structure -If you are looking for the API reference and examples on how to use the SDK check out the `/extrinsic/` or other folders. This folder contains advanced -examples that showcase how to do things that are not already available through the SDK interface. +If you are looking for the API reference and examples on how to use the SDK check out the `/extrinsic/` or other folders. This folder +contains advanced examples that showcase how to do things that are not already available through the SDK interface. ## Examples diff --git a/avail-deno/docs/advanced-examples/connect.ts b/avail-deno/docs/advanced-examples/connect.ts deleted file mode 100644 index 401815726..000000000 --- a/avail-deno/docs/advanced-examples/connect.ts +++ /dev/null @@ -1,26 +0,0 @@ -/// The example showcases how to programmatically connect to a network -/// - -import { ApiPromise, WsProvider } from "https://deno.land/x/polkadot@0.2.45/api/mod.ts"; -import { API_EXTENSIONS, API_RPC, API_TYPES } from "../src/api_options.ts"; - -const endpoint = "wss://kate.avail.tools/ws"; -const api = await ApiPromise.create({ - provider: new WsProvider(endpoint), - rpc: API_RPC, - types: API_TYPES, - signedExtensions: API_EXTENSIONS, -}); - -// Retrieve the chain and node information via rpc calls -const [chain, nodeName, nodeVersion, runtimeVersion] = await Promise.all([ - api.rpc.system.chain(), - api.rpc.system.name(), - api.rpc.system.version(), - api.rpc.state.getRuntimeVersion(), -]); - -console.log( - `Connected to chain ${chain} using ${nodeName}, node version ${nodeVersion} and spec version ${runtimeVersion.specVersion}`, -); -Deno.exit(0); diff --git a/avail-deno/docs/advanced-examples/register_validator.json b/avail-deno/docs/advanced-examples/register_validator.json deleted file mode 100644 index f7bd3c3b7..000000000 --- a/avail-deno/docs/advanced-examples/register_validator.json +++ /dev/null @@ -1,7 +0,0 @@ -{ - "session_keys": null, - "stash_account_seed_hex": "0x2ac5823a490004013e1c7dc7ad3dd5beed2132279dbbec66747b52b97f609e9a", - "bond_amount": 100, - "commission": 5, - "endpoint": "ws://127.0.0.1:9944" -} diff --git a/avail-deno/docs/advanced-examples/register_validator.ts b/avail-deno/docs/advanced-examples/register_validator.ts deleted file mode 100644 index ae2b5ac6b..000000000 --- a/avail-deno/docs/advanced-examples/register_validator.ts +++ /dev/null @@ -1,141 +0,0 @@ -import { ApiPromise, Keyring, WsProvider } from "https://deno.land/x/polkadot@0.2.45/api/mod.ts"; -import { BN } from "https://deno.land/x/polkadot@0.2.45/util/mod.ts"; -import { API_EXTENSIONS, API_RPC, API_TYPES } from "../src/api_options.ts"; -import { ISubmittableResult } from "https://deno.land/x/polkadot@0.2.45/types/types/extrinsic.ts"; - -interface Config { - session_keys: string | undefined; - stash_account_seed_hex: string | undefined; - bond_amount: number | undefined; - commission: number | undefined; - endpoint: string | undefined; -} - -const config: Config = JSON.parse( - Deno.readTextFileSync("./register_validator.json"), -); - -if ( - config.stash_account_seed_hex == undefined || - config.bond_amount == undefined || config.endpoint == undefined || - config.commission == undefined -) { - console.log("Failed 1"); - Deno.exit(0); -} - -if (config.bond_amount < 1) { - console.log("bond_amount cannot less than 1"); - Deno.exit(0); -} - -if (Math.floor(config.bond_amount) != config.bond_amount) { - console.log("bond_amount needs to be a whole number (integer)"); - Deno.exit(0); -} - -if (config.commission < 0 || config.commission > 100) { - console.log( - "commission cannot be less than 0. commission cannot be more than 100", - ); - Deno.exit(0); -} - -if (Math.floor(config.commission) != config.commission) { - console.log("commission needs to be a whole number (integer)"); - Deno.exit(0); -} - -const api = await ApiPromise.create({ - provider: new WsProvider(config.endpoint), - rpc: API_RPC, - types: API_TYPES, - signedExtensions: API_EXTENSIONS, -}); -const stash = new Keyring({ type: "sr25519" }).addFromUri( - config.stash_account_seed_hex, -); - -let session_keys = config.session_keys; -if (session_keys == undefined) { - session_keys = (await api.rpc.author.rotateKeys()).toHuman()?.toString(); -} -if (session_keys == undefined) { - console.log("Failed to generate session keys."); - Deno.exit(0); -} - -const endpoint = config.endpoint; -const stash_address = stash.address; -const bond_value = new BN( - config.bond_amount.toString().concat("000000000000000000"), -); -let commission = config.commission.toString().concat("0000000"); -const already_bonded = (await api.query.staking.bonded(stash_address)).toHuman() != undefined; - -// For some reason 0 commission is not defined as "0" but as "1". -if (commission == "00000000") { - commission = "1"; -} - -const keys = session_keys.slice(2, undefined); -const babe_key = "0x".concat(keys.slice(0, 64)); -const grandpa_key = "0x".concat(keys.slice(64, 128)); -const imonline_key = "0x".concat(keys.slice(128, 192)); -const authority_discovery_key = "0x".concat(keys.slice(192, 256)); - -console.log(`Endpoint: ${endpoint}`); -console.log(`Stash Account: ${stash_address}`); -console.log(`Bond Value: ${bond_value}`); -console.log(`Commission: ${commission}`); -console.log(`Session Keys: ${session_keys}`); -console.log(`Babe Key (derived from Session Keys): ${babe_key}`); -console.log(`Grandpa Key (derived from Session Keys): ${grandpa_key}`); -console.log(`ImOnline Key (derived from Session Keys): ${imonline_key}`); -console.log( - `Authority Discovery Key (derived from Session Keys): ${authority_discovery_key}`, -); -if (already_bonded) { - console.log( - "Stash is already bonded. No new staking.bond call will be executed", - ); -} - -const tx = new Promise((res, _) => { - const keys = { - babe: babe_key, - grandpa: grandpa_key, - imOnline: imonline_key, - authorityDiscover: authority_discovery_key, - }; - const prefs = { - commission: commission, - block: false, - }; - - const calls = []; - if (!already_bonded) { - calls.push(api.tx.staking.bond(bond_value, "Staked")); - } - calls.push(api.tx.session.setKeys(keys, undefined)); - calls.push(api.tx.staking.validate(prefs)); - - api.tx.utility.batchAll(calls).signAndSend( - stash, - (result: ISubmittableResult) => { - console.log(`Tx status: ${result.status}`); - if (result.isInBlock) { - res(undefined); - } else if (result.isError) { - res(result.toHuman()?.toString()); - } - }, - ); -}); - -const tx_res = await tx; -if (tx_res != undefined) { - console.log(tx_res); -} - -Deno.exit(0); diff --git a/avail-deno/docs/advanced-examples/rpc_kate_query_block_length.ts b/avail-deno/docs/advanced-examples/rpc_kate_query_block_length.ts deleted file mode 100644 index 9f0297c74..000000000 --- a/avail-deno/docs/advanced-examples/rpc_kate_query_block_length.ts +++ /dev/null @@ -1,54 +0,0 @@ -/// The example showcases how to programmatically call query block length RPC. -/// - -import { ApiPromise, Keyring, WsProvider } from "https://deno.land/x/polkadot@0.2.45/api/mod.ts"; -import { ISubmittableResult } from "https://deno.land/x/polkadot@0.2.45/types/types/extrinsic.ts"; -import { H256 } from "https://deno.land/x/polkadot@0.2.45/types/interfaces/types.ts"; -import { API_EXTENSIONS, API_RPC, API_TYPES } from "../src/api_options.ts"; - -const api = await ApiPromise.create({ - provider: new WsProvider("ws://127.0.0.1:9944"), - rpc: API_RPC, - types: API_TYPES, - signedExtensions: API_EXTENSIONS, -}); -const account = new Keyring({ type: "sr25519" }).addFromUri("//Alice"); -// Change App Id to something that has meaning to you or leave it at one -const options = { app_id: 1, nonce: -1 }; - -// submit data transaction -const tx_result = await new Promise((res, _) => { - api.tx.dataAvailability.submitData("Hello World").signAndSend(account, options, (result: ISubmittableResult) => { - console.log(`Tx status: ${result.status}`); - if (result.isFinalized || result.isError) { - res(result); - } - }); -}); - -// Rejected Transaction handling -if (tx_result.isError) { - console.log(`Transaction was not executed`); - Deno.exit(1); -} - -const [tx_hash, block_hash] = [tx_result.txHash as H256, tx_result.status.asFinalized as H256]; -console.log(`Tx Hash: ${tx_hash}, Block Hash: ${block_hash}`); - -// Failed Transaction handling -const error = tx_result.dispatchError; -if (error != undefined) { - if (error.isModule) { - const decoded = api.registry.findMetaError(error.asModule); - const { docs, name, section } = decoded; - console.log(`${section}.${name}: ${docs.join(" ")}`); - } else { - console.log(error.toString()); - } - Deno.exit(1); -} - -const blockLength = await api.rpc.kate.blockLength(block_hash); -console.log(blockLength.toHuman()); - -Deno.exit(0); diff --git a/avail-deno/docs/advanced-examples/rpc_kate_query_data_proof.ts b/avail-deno/docs/advanced-examples/rpc_kate_query_data_proof.ts deleted file mode 100644 index 632024ac4..000000000 --- a/avail-deno/docs/advanced-examples/rpc_kate_query_data_proof.ts +++ /dev/null @@ -1,53 +0,0 @@ -/// The example showcases how to programmatically call query data proof RPC. -/// - -import { ApiPromise, Keyring, WsProvider } from "https://deno.land/x/polkadot@0.2.45/api/mod.ts"; -import { ISubmittableResult } from "https://deno.land/x/polkadot@0.2.45/types/types/extrinsic.ts"; -import { H256 } from "https://deno.land/x/polkadot@0.2.45/types/interfaces/types.ts"; -import { API_EXTENSIONS, API_RPC, API_TYPES } from "../src/api_options.ts"; -const api = await ApiPromise.create({ - provider: new WsProvider("ws://127.0.0.1:9944"), - rpc: API_RPC, - types: API_TYPES, - signedExtensions: API_EXTENSIONS, -}); -const account = new Keyring({ type: "sr25519" }).addFromUri("//Alice"); -// Change App Id to something that has meaning to you or leave it at one -const options = { app_id: 1, nonce: -1 }; - -// submit data transaction -const tx_result = await new Promise((res, _) => { - api.tx.dataAvailability.submitData("Hello World").signAndSend(account, options, (result: ISubmittableResult) => { - console.log(`Tx status: ${result.status}`); - if (result.isFinalized || result.isError) { - res(result); - } - }); -}); - -// Rejected Transaction handling -if (tx_result.isError) { - console.log(`Transaction was not executed`); - Deno.exit(1); -} - -const [tx_hash, block_hash] = [tx_result.txHash as H256, tx_result.status.asFinalized as H256]; -console.log(`Tx Hash: ${tx_hash}, Block Hash: ${block_hash}`); - -// Failed Transaction handling -const error = tx_result.dispatchError; -if (error != undefined) { - if (error.isModule) { - const decoded = api.registry.findMetaError(error.asModule); - const { docs, name, section } = decoded; - console.log(`${section}.${name}: ${docs.join(" ")}`); - } else { - console.log(error.toString()); - } - Deno.exit(1); -} - -const dataProof = await api.rpc.kate.queryDataProof(1, block_hash); -console.log(dataProof.toHuman()); - -Deno.exit(0); diff --git a/avail-deno/docs/advanced-examples/rpc_kate_query_proof.ts b/avail-deno/docs/advanced-examples/rpc_kate_query_proof.ts deleted file mode 100644 index 603cad87d..000000000 --- a/avail-deno/docs/advanced-examples/rpc_kate_query_proof.ts +++ /dev/null @@ -1,54 +0,0 @@ -/// The example showcases how to programmatically call query proof RPC. -/// - -import { ApiPromise, Keyring, WsProvider } from "https://deno.land/x/polkadot@0.2.45/api/mod.ts"; -import { ISubmittableResult } from "https://deno.land/x/polkadot@0.2.45/types/types/extrinsic.ts"; -import { H256 } from "https://deno.land/x/polkadot@0.2.45/types/interfaces/types.ts"; -import { API_EXTENSIONS, API_RPC, API_TYPES } from "../src/api_options.ts"; - -const api = await ApiPromise.create({ - provider: new WsProvider("ws://127.0.0.1:9944"), - rpc: API_RPC, - types: API_TYPES, - signedExtensions: API_EXTENSIONS, -}); -const account = new Keyring({ type: "sr25519" }).addFromUri("//Alice"); -// Change App Id to something that has meaning to you or leave it at one -const options = { app_id: 1, nonce: -1 }; - -// submit data transaction -const tx_result = await new Promise((res, _) => { - api.tx.dataAvailability.submitData("Hello World").signAndSend(account, options, (result: ISubmittableResult) => { - console.log(`Tx status: ${result.status}`); - if (result.isFinalized || result.isError) { - res(result); - } - }); -}); - -// Rejected Transaction handling -if (tx_result.isError) { - console.log(`Transaction was not executed`); - Deno.exit(1); -} - -const [tx_hash, block_hash] = [tx_result.txHash as H256, tx_result.status.asFinalized as H256]; -console.log(`Tx Hash: ${tx_hash}, Block Hash: ${block_hash}`); - -// Failed Transaction handling -const error = tx_result.dispatchError; -if (error != undefined) { - if (error.isModule) { - const decoded = api.registry.findMetaError(error.asModule); - const { docs, name, section } = decoded; - console.log(`${section}.${name}: ${docs.join(" ")}`); - } else { - console.log(error.toString()); - } - Deno.exit(1); -} - -const proof = await api.rpc.kate.queryProof([{ row: 0, col: 0 }], block_hash); -console.log(proof.toHuman()); - -Deno.exit(0); diff --git a/avail-deno/docs/advanced-examples/rpc_kate_query_rows.ts b/avail-deno/docs/advanced-examples/rpc_kate_query_rows.ts deleted file mode 100644 index 6a98bdc53..000000000 --- a/avail-deno/docs/advanced-examples/rpc_kate_query_rows.ts +++ /dev/null @@ -1,54 +0,0 @@ -/// The example showcases how to programmatically call query rows RPC. -/// - -import { ApiPromise, Keyring, WsProvider } from "https://deno.land/x/polkadot@0.2.45/api/mod.ts"; -import { ISubmittableResult } from "https://deno.land/x/polkadot@0.2.45/types/types/extrinsic.ts"; -import { H256 } from "https://deno.land/x/polkadot@0.2.45/types/interfaces/types.ts"; -import { API_EXTENSIONS, API_RPC, API_TYPES } from "../src/api_options.ts"; - -const api = await ApiPromise.create({ - provider: new WsProvider("ws://127.0.0.1:9944"), - rpc: API_RPC, - types: API_TYPES, - signedExtensions: API_EXTENSIONS, -}); -const account = new Keyring({ type: "sr25519" }).addFromUri("//Alice"); -// Change App Id to something that has meaning to you or leave it at one -const options = { app_id: 1, nonce: -1 }; - -// submit data transaction -const tx_result = await new Promise((res, _) => { - api.tx.dataAvailability.submitData("Hello World").signAndSend(account, options, (result: ISubmittableResult) => { - console.log(`Tx status: ${result.status}`); - if (result.isFinalized || result.isError) { - res(result); - } - }); -}); - -// Rejected Transaction handling -if (tx_result.isError) { - console.log(`Transaction was not executed`); - Deno.exit(1); -} - -const [tx_hash, block_hash] = [tx_result.txHash as H256, tx_result.status.asFinalized as H256]; -console.log(`Tx Hash: ${tx_hash}, Block Hash: ${block_hash}`); - -// Failed Transaction handling -const error = tx_result.dispatchError; -if (error != undefined) { - if (error.isModule) { - const decoded = api.registry.findMetaError(error.asModule); - const { docs, name, section } = decoded; - console.log(`${section}.${name}: ${docs.join(" ")}`); - } else { - console.log(error.toString()); - } - Deno.exit(1); -} - -const rows = await api.rpc.kate.queryRows([0], block_hash); -console.log(rows.toHuman()); - -Deno.exit(0); diff --git a/avail-deno/docs/advanced-examples/subscribe_to_header.ts b/avail-deno/docs/advanced-examples/subscribe_to_header.ts deleted file mode 100644 index 1442ebeaf..000000000 --- a/avail-deno/docs/advanced-examples/subscribe_to_header.ts +++ /dev/null @@ -1,28 +0,0 @@ -/// TODO DOC -/// -/// - -import { ApiPromise, WsProvider } from "https://deno.land/x/polkadot@0.2.45/api/mod.ts"; -import { API_EXTENSIONS, API_RPC, API_TYPES } from "../src/api_options.ts"; -import { UnsubscribePromise } from "https://deno.land/x/polkadot@0.2.45/api-base/types/base.ts"; - -const api = await ApiPromise.create({ - provider: new WsProvider("ws://127.0.0.1:9944"), - rpc: API_RPC, - types: API_TYPES, - signedExtensions: API_EXTENSIONS, -}); - -const block_target = (await api.rpc.chain.getHeader()).number.toNumber() + 2; -const readHeaders = new Promise((res, _) => { - const unsub = api.rpc.chain.subscribeNewHeads((header) => { - console.log(`Chain is at block: #${header.number}`); - if (header.number.toNumber() >= block_target) { - res(unsub); - } - }); -}); - -const unsub = await readHeaders; -unsub(); -Deno.exit(0); diff --git a/avail-deno/docs/advanced-examples/tx_balance_transfer.ts b/avail-deno/docs/advanced-examples/tx_balance_transfer.ts deleted file mode 100644 index 730f5ad0b..000000000 --- a/avail-deno/docs/advanced-examples/tx_balance_transfer.ts +++ /dev/null @@ -1,59 +0,0 @@ -/// The example showcases how to programmatically do balance transfer. -/// -/// The following transactions are being called: -/// Balance.transfer -/// -/// The following storage are being queried: -/// System.account -/// - -import { ApiPromise, Keyring, WsProvider } from "https://deno.land/x/polkadot@0.2.45/api/mod.ts"; -import { BN } from "https://deno.land/x/polkadot@0.2.45/util/mod.ts"; -import { ISubmittableResult } from "https://deno.land/x/polkadot@0.2.45/types/types/extrinsic.ts"; -import { H256 } from "https://deno.land/x/polkadot@0.2.45/types/interfaces/types.ts"; -import { API_EXTENSIONS, API_RPC, API_TYPES } from "../src/api_options.ts"; - -const api = await ApiPromise.create({ - provider: new WsProvider("ws://127.0.0.1:9944"), - rpc: API_RPC, - types: API_TYPES, - signedExtensions: API_EXTENSIONS, -}); - -const alice = new Keyring({ type: "sr25519" }).addFromUri("//Alice"); -const bob_address = "5FHneW46xGXgs5mUiveU4sbTyGBzmstUspZC92UhjJM694ty"; -const one_AVAIL = new BN("1000000000000000000"); - -const old_bobs_state: any = await api.query.system.account(bob_address); -console.log(`Bob's balance before the transfer call: ${old_bobs_state["data"]["free"].toHuman()}`); - -// Transaction call -const tx_result = await new Promise((res, _) => { - api.tx.balances.transferKeepAlive(bob_address, one_AVAIL).signAndSend(alice, (result: ISubmittableResult) => { - console.log(`Tx status: ${result.status}`); - if (result.isFinalized || result.isError) { - res(result); - } - }); -}); -console.log(`Tx Hash: ${tx_result.txHash as H256}, Block Hash: ${tx_result.status.asFinalized as H256}`); - -// Error handling -const error = tx_result.dispatchError; -if (tx_result.isError) { - console.log(`Transaction was not executed`); -} else if (error != undefined) { - if (error.isModule) { - const decoded = api.registry.findMetaError(error.asModule); - const { docs, name, section } = decoded; - console.log(`${section}.${name}: ${docs.join(" ")}`); - } else { - console.log(error.toString()); - } - Deno.exit(1); -} - -const new_bobs_state: any = await api.query.system.account(bob_address); -console.log(`Bob's balance after the transfer call: ${new_bobs_state["data"]["free"].toHuman()}`); - -Deno.exit(0); diff --git a/avail-deno/docs/advanced-examples/tx_data_availability_create_application_key.ts b/avail-deno/docs/advanced-examples/tx_data_availability_create_application_key.ts deleted file mode 100644 index 3051fd365..000000000 --- a/avail-deno/docs/advanced-examples/tx_data_availability_create_application_key.ts +++ /dev/null @@ -1,70 +0,0 @@ -/// The example showcases how to programmatically create application key. -/// -/// The following transactions are being called: -/// DataAvailability.createApplicationKey -/// - -import { ApiPromise, Keyring, WsProvider } from "https://deno.land/x/polkadot@0.2.45/api/mod.ts"; -import { ISubmittableResult } from "https://deno.land/x/polkadot@0.2.45/types/types/extrinsic.ts"; -import { H256 } from "https://deno.land/x/polkadot@0.2.45/types/interfaces/types.ts"; -import { API_EXTENSIONS, API_RPC, API_TYPES } from "../src/api_options.ts"; - -const api = await ApiPromise.create({ - provider: new WsProvider("ws://127.0.0.1:9944"), - rpc: API_RPC, - types: API_TYPES, - signedExtensions: API_EXTENSIONS, -}); - -// Use your secret seed or mnemonic here -const account = new Keyring({ type: "sr25519" }).addFromUri("//Alice"); - -// Transaction call -const key = "My Key"; -const tx_result = await new Promise((res, _) => { - api.tx.dataAvailability.createApplicationKey(key).signAndSend(account, (result: ISubmittableResult) => { - console.log(`Tx status: ${result.status}`); - if (result.isFinalized || result.isError) { - res(result); - } - }); -}); - -// Rejected Transaction handling -if (tx_result.isError) { - console.log(`Transaction was not executed`); - Deno.exit(1); -} - -const [tx_hash, block_hash] = [tx_result.txHash as H256, tx_result.status.asFinalized as H256]; -console.log(`Tx Hash: ${tx_hash}, Block Hash: ${block_hash}`); - -// Failed Transaction handling -const error = tx_result.dispatchError; -if (error != undefined) { - if (error.isModule) { - const decoded = api.registry.findMetaError(error.asModule); - const { docs, name, section } = decoded; - console.log(`${section}.${name}: ${docs.join(" ")}`); - } else { - console.log(error.toString()); - } - Deno.exit(1); -} - -const e = tx_result.events.find((e) => e.event.method == "ApplicationKeyCreated"); -if (e == undefined) { - console.log(`Missing ApplicationKeyCreated method.`); - Deno.exit(1); -} -const data: any = e.event.data; -const read_key = data["key"].toString(); -const read_owner = data["owner"].toString(); -const read_app_id = data["id"].toString(); -console.log(` - key=${read_key}, - owner=${read_owner}, - id=${read_app_id}, -`); - -Deno.exit(0); diff --git a/avail-deno/docs/advanced-examples/tx_data_availability_submit_data.ts b/avail-deno/docs/advanced-examples/tx_data_availability_submit_data.ts deleted file mode 100644 index 86d5c5650..000000000 --- a/avail-deno/docs/advanced-examples/tx_data_availability_submit_data.ts +++ /dev/null @@ -1,75 +0,0 @@ -/// The example showcases how to programmatically do data submission. -/// -/// The following transactions are being called: -/// DataAvailability.submitData -/// - -import { ApiPromise, Keyring, WsProvider } from "https://deno.land/x/polkadot@0.2.45/api/mod.ts"; -import { ISubmittableResult } from "https://deno.land/x/polkadot@0.2.45/types/types/extrinsic.ts"; -import { H256 } from "https://deno.land/x/polkadot@0.2.45/types/interfaces/types.ts"; -import { API_EXTENSIONS, API_RPC, API_TYPES } from "../src/api_options.ts"; - -const api = await ApiPromise.create({ - provider: new WsProvider("ws://127.0.0.1:9944"), - rpc: API_RPC, - types: API_TYPES, - signedExtensions: API_EXTENSIONS, -}); - -// Use your secret seed or mnemonic here -const account = new Keyring({ type: "sr25519" }).addFromUri("//Alice"); - -// Transaction call -// Change "Hello World" to something that has meaning to you -const data = "Hello World"; -// Change App Id to something that has meaning to you or leave it at one -const options = { app_id: 1, nonce: -1 }; -const tx_result = await new Promise((res, _) => { - api.tx.dataAvailability.submitData(data).signAndSend(account, options, (result: ISubmittableResult) => { - console.log(`Tx status: ${result.status}`); - if (result.isFinalized || result.isError) { - res(result); - } - }); -}); - -// Rejected Transaction handling -if (tx_result.isError) { - console.log(`Transaction was not executed`); - Deno.exit(1); -} - -const [tx_hash, block_hash] = [tx_result.txHash as H256, tx_result.status.asFinalized as H256]; -console.log(`Tx Hash: ${tx_hash}, Block Hash: ${block_hash}`); - -// Failed Transaction handling -const error = tx_result.dispatchError; -if (error != undefined) { - if (error.isModule) { - const decoded = api.registry.findMetaError(error.asModule); - const { docs, name, section } = decoded; - console.log(`${section}.${name}: ${docs.join(" ")}`); - } else { - console.log(error.toString()); - } - Deno.exit(1); -} - -// Extracting data -const block = await api.rpc.chain.getBlock(block_hash); -const tx = block.block.extrinsics.find((tx) => tx.hash.toHex() == tx_hash.toHex()); -if (tx == undefined) { - console.log("Failed to find the Submit Data transaction"); - Deno.exit(1); -} - -console.log(tx.toHuman()); -const dataHex = tx.method.args.map((a) => a.toString()).join(", "); -// Data retrieved from the extrinsic data -let str = ""; -for (let n = 0; n < dataHex.length; n += 2) { - str += String.fromCharCode(parseInt(dataHex.substring(n, n + 2), 16)); -} -console.log(`submitted data: ${str}`); - -Deno.exit(0); diff --git a/avail-deno/docs/advanced-examples/tx_staking_nominate_full_example.ts b/avail-deno/docs/advanced-examples/tx_staking_nominate_full_example.ts deleted file mode 100644 index ee44fad4a..000000000 --- a/avail-deno/docs/advanced-examples/tx_staking_nominate_full_example.ts +++ /dev/null @@ -1,85 +0,0 @@ -/// The example showcases how to programmatically become a nominator. -/// -/// The following transactions are being called: -/// Utility.batchAll -/// Staking.bond -/// Session.nominate -/// -/// The following storage are being queried: -/// Staking.bonded -/// Staking.ledger -/// Staking.nominators -/// - -import { ApiPromise, Keyring, WsProvider } from "https://deno.land/x/polkadot@0.2.45/api/mod.ts"; -import { BN } from "https://deno.land/x/polkadot@0.2.45/util/mod.ts"; -import { H256 } from "https://deno.land/x/polkadot@0.2.45/types/interfaces/types.ts"; -import { API_EXTENSIONS, API_RPC, API_TYPES } from "../src/api_options.ts"; -import { ISubmittableResult } from "https://deno.land/x/polkadot@0.2.45/types/types/extrinsic.ts"; - -const api = await ApiPromise.create({ - provider: new WsProvider("ws://127.0.0.1:9944"), - rpc: API_RPC, - types: API_TYPES, - signedExtensions: API_EXTENSIONS, -}); - -// Use your secret seed or mnemonic here -const account = new Keyring({ type: "sr25519" }).addFromUri("//Bob"); -const min_nominator_bond = (await api.query.staking.minNominatorBond()).toString(); -// You can bond any amount of tokens as long as it is at least more or equal than the minimum -// In this case we either bond the minimum amount or if there is no minimum we bond 1k AVAIL -const bond_amount = new BN(min_nominator_bond == "0" ? "1000000000000000000000" : min_nominator_bond); -// Here you can specify what targets will be nominated -const targets = ["5GNJqTPyNqANBkUVMN1LPPrxXnFouWXoe2wNSmmEoLctxiZY"]; - -const staking_bond = api.tx.staking.bond(bond_amount, "Staked"); -const staking_nominate = api.tx.staking.nominate(targets); - -// Transaction call -const tx_result = await new Promise((res, _) => { - api.tx.utility.batchAll([staking_bond, staking_nominate]).signAndSend(account, (result: ISubmittableResult) => { - console.log(`Tx status: ${result.status}`); - if (result.isFinalized || result.isError) { - res(result); - } - }); -}); - -// Rejected Transaction handling -if (tx_result.isError) { - console.log(`Transaction was not executed`); - Deno.exit(1); -} - -const [tx_hash, block_hash] = [tx_result.txHash as H256, tx_result.status.asFinalized as H256]; -console.log(`Tx Hash: ${tx_hash}, Block Hash: ${block_hash}`); - -// Failed Transaction handling -const error = tx_result.dispatchError; -if (error != undefined) { - if (error.isModule) { - // for module errors, we have the section indexed, lookup - const decoded = api.registry.findMetaError(error.asModule); - const { docs, name, section } = decoded; - console.log(`${section}.${name}: ${docs.join(" ")}`); - } else { - // Other, CannotLookup, BadOrigin, no extra info - console.log(error.toString()); - } - Deno.exit(1); -} - -// Reading Nomination related information from storage -const is_bonded = (await api.query.staking.bonded(account.address)).toHuman(); -const ledger = await api.query.staking.ledger(account.address); -const nominators = await api.query.staking.nominators(account.address); -if (is_bonded == undefined) { - console.log("Something went wrong :("); - Deno.exit(1); -} - -console.log(`Staking.ledger: ${ledger}`); -console.log(`Staking.nominators: ${nominators}`); - -Deno.exit(0); diff --git a/avail-deno/docs/advanced-examples/tx_staking_validate_full_example.ts b/avail-deno/docs/advanced-examples/tx_staking_validate_full_example.ts deleted file mode 100644 index 97c0b0abe..000000000 --- a/avail-deno/docs/advanced-examples/tx_staking_validate_full_example.ts +++ /dev/null @@ -1,115 +0,0 @@ -/// The example showcases how to programmatically become a validator. -/// -/// The following transactions are being called: -/// Utility.batchAll -/// Staking.bond -/// Session.set_key -/// Staking.validate -/// -/// The following storage are being queried: -/// Staking.bonded -/// Staking.ledger -/// Staking.validators -/// - -import { ApiPromise, Keyring, WsProvider } from "https://deno.land/x/polkadot@0.2.45/api/mod.ts"; -import { BN } from "https://deno.land/x/polkadot@0.2.45/util/mod.ts"; -import { H256 } from "https://deno.land/x/polkadot@0.2.45/types/interfaces/types.ts"; -import { API_EXTENSIONS, API_RPC, API_TYPES } from "../src/api_options.ts"; -import { ISubmittableResult } from "https://deno.land/x/polkadot@0.2.45/types/types/extrinsic.ts"; - -function deconstruct_session_keys(deconstruct_session_keys: string) { - const keys = deconstruct_session_keys.slice(2, undefined); - const babe_key = "0x".concat(keys.slice(0, 64)); - const grandpa_key = "0x".concat(keys.slice(64, 128)); - const imonline_key = "0x".concat(keys.slice(128, 192)); - const authority_discovery_key = "0x".concat(keys.slice(192, 256)); - - return { - babe: babe_key, - grandpa: grandpa_key, - imOnline: imonline_key, - authorityDiscover: authority_discovery_key, - }; -} - -function define_validator_preference() { - // "5" means 5 percent. - let commission = "5".concat("0000000"); - // For some reason 0 commission is not defined as "0" but as "1". - if (commission == "00000000") { - commission = "1"; - } - return { commission: commission, block: false }; -} - -const api = await ApiPromise.create({ - provider: new WsProvider("ws://127.0.0.1:9944"), - rpc: API_RPC, - types: API_TYPES, - signedExtensions: API_EXTENSIONS, -}); - -// Use your secret seed or mnemonic here -const account = new Keyring({ type: "sr25519" }).addFromUri("//Bob"); -const min_validator_bond = (await api.query.staking.minValidatorBond()).toString(); -// You can bond any amount of tokens as long as it is at least more or equal than the minimum -// In this case we either bond the minimum amount or if there is no minimum we bond 1k AVAIL -const bond_amount = new BN(min_validator_bond == "0" ? "1000000000000000000000" : min_validator_bond); -// You need to generate the session keys yourself and put the value in here -const session_keys = - "0xcce44c3da975792242a278a90e1557ee2059ae14a6c6104a50045e13afdaea490028ae395391cba3e7aa5219802a04a0c1833b0814ed5bfae7e5b9c453a69bbedc69835386108accc1f191b82b40d92568b5e0863243cbe0351d36d5fc823b09187d3992202265cdce9d1b95481a402c9ca39fb041615ca71992d92066841534"; -const keys = deconstruct_session_keys(session_keys); -const prefs = define_validator_preference(); - -const staking_bond = api.tx.staking.bond(bond_amount, "Staked"); -const session_set_keys = api.tx.session.setKeys(keys, undefined); -const staking_validate = api.tx.staking.validate(prefs); - -// Transaction call -const tx_result = await new Promise((res, _) => { - api.tx.utility.batchAll([staking_bond, session_set_keys, staking_validate]).signAndSend(account, (result: ISubmittableResult) => { - console.log(`Tx status: ${result.status}`); - if (result.isFinalized || result.isError) { - res(result); - } - }); -}); - -// Rejected Transaction handling -if (tx_result.isError) { - console.log(`Transaction was not executed`); - Deno.exit(1); -} - -const [tx_hash, block_hash] = [tx_result.txHash as H256, tx_result.status.asFinalized as H256]; -console.log(`Tx Hash: ${tx_hash}, Block Hash: ${block_hash}`); - -// Failed Transaction handling -const error = tx_result.dispatchError; -if (error != undefined) { - if (error.isModule) { - // for module errors, we have the section indexed, lookup - const decoded = api.registry.findMetaError(error.asModule); - const { docs, name, section } = decoded; - console.log(`${section}.${name}: ${docs.join(" ")}`); - } else { - // Other, CannotLookup, BadOrigin, no extra info - console.log(error.toString()); - } - Deno.exit(1); -} - -// Reading Validator related information from storage -const is_bonded = (await api.query.staking.bonded(account.address)).toHuman(); -const ledger = await api.query.staking.ledger(account.address); -const validators = await api.query.staking.validators(account.address); -if (is_bonded == undefined) { - console.log("Something went wrong :("); - Deno.exit(1); -} - -console.log(`Staking.ledger: ${ledger}`); -console.log(`Staking.validators: ${validators}`); - -Deno.exit(0); diff --git a/avail-deno/docs/extrinsics/README.md b/avail-deno/docs/extrinsics/README.md index 1d595ae6b..82b059b18 100644 --- a/avail-deno/docs/extrinsics/README.md +++ b/avail-deno/docs/extrinsics/README.md @@ -23,10 +23,6 @@ function createApplicationKey(key: string, waitFor: WaitFor, account: KeyringPai | account | KeyringPair | false | account that will send and sign the transaction | | options | SignerOptions | true | used to overwrite existing signer options | -#### Return value - -On failure, a reason of failure is returned. On Success, ApplicationKeyCreated event, transaction hash and block hash is returned. - ### Minimal Example ```js @@ -45,12 +41,37 @@ if (result.isErr) { Deno.exit(1); } -console.log("Key=" + result.event.key + ", Owner=" + result.event.owner + ", Id=" + result.event.id); -console.log("TxHash=" + result.txHash + ", BlockHash=" + result.blockHash); +console.log(JSON.stringify(result, null, 4)); Deno.exit(); ``` +### Example Output + +#### On Failure + +If the operation fails, the function will return an error message indicating the nature of the issue. + +#### On Success + +If the operation is successful, the function will return a object of type `CreateApplicationKeyTxSuccess`. + +```js +{ + "isErr": false, + "event": { + "key": "0x4d79417765736f6d654b6579", + "owner": "5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY", + "id": "10" + }, + "events": [...], + "txHash": "0x5ae9edbd2a2da96eeffc14cf9050d711082890fa6bfb8749ad2c4947565f3bd2", + "txIndex": 1, + "blockHash": "0x152338c1b0696d12664cf3d4c159af3d54beca151ba1ea8b00989a66dc8050b0", + "blockNumber": 1 +} +``` + ## Submit Data Origin Level: Signed @@ -70,10 +91,6 @@ function submitData(data: string, waitFor: WaitFor, account: KeyringPair, option | account | KeyringPair | false | account that will send and sign the transaction | | options | SignerOptions | true | used to overwrite existing signer options | -#### Return value - -On failure, a reason of failure is returned. On Success, DataSubmitted event, transaction data, transaction hash and block hash is returned. - ### Minimal Example ```js @@ -92,13 +109,39 @@ if (result.isErr) { Deno.exit(1); } -console.log("Data=" + result.txData.data); -console.log("Who=" + result.event.who + ", DataHash=" + result.event.dataHash); -console.log("TxHash=" + result.txHash + ", BlockHash=" + result.blockHash); +console.log(JSON.stringify(result, null, 4)); Deno.exit(); ``` +### Example Output + +#### On Failure + +If the operation fails, the function will return an error message indicating the nature of the issue. + +#### On Success + +If the operation is successful, the function will return a object of type `SubmitDataTxSuccess`. + +```js +{ + "isErr": false, + "txData": { + "data": "4d7920417765736f6d652044617461" + }, + "event": { + "who": "5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY", + "dataHash": "0x8846d900ea89aab9bce96402846c0ac74a853acc00cb99ff5ddb1a0f052594bd" + }, + "events": [...], + "txHash": "0xec6f9fd5e002c9ddbcd24764380f57a014de7f2007cc0e2ae11a4dda17ab8062", + "txIndex": 1, + "blockHash": "0x043c2b88ff960f2f7042521b55a943676938948febefe8684022b524795340d9", + "blockNumber": 9 +} +``` + ## Submit Block Length Proposal Origin Level: Root @@ -119,10 +162,6 @@ function submitBlockLengthProposal(rows: number, cols: number, waitFor: WaitFor, | account | KeyringPair | false | account that will send and sign the transaction | | options | SignerOptions | true | used to overwrite existing signer options | -#### Return value - -On failure, a reason of failure is returned. On Success, BlockLengthProposalSubmitted event, transaction hash and block hash is returned. - ### Minimal Example ```js @@ -142,12 +181,24 @@ if (result.isErr) { Deno.exit(1); } -console.log("Rows=" + result.event.rows + ", Cols=" + result.event.cols); -console.log("TxHash=" + result.txHash + ", BlockHash=" + result.blockHash); +console.log(JSON.stringify(result, null, 4)); Deno.exit(); ``` +### Example Output + +#### On Failure + +If the operation fails, the function will return an error message indicating the nature of the issue. + +#### On Success + +If the operation is successful, the function will return a object of type `SubmitBlockLengthProposalTxSuccess`. + +```js +``` + ## Set Application Key Origin Level: Root @@ -168,10 +219,6 @@ function setApplicationKey(oldKey: string, newKey: string, waitFor: WaitFor, acc | account | KeyringPair | false | account that will send and sign the transaction | | options | SignerOptions | true | used to overwrite existing signer options | -#### Return value - -On failure, a reason of failure is returned. On Success, ApplicationKeySet event, transaction hash and block hash is returned. - ### Minimal Example ```js @@ -191,13 +238,25 @@ if (result.isErr) { Deno.exit(1); } -console.log("OldKey=" + result.event.oldKey + ", NewKey=" + result.event.newKey); -console.log("TxHash=" + result.txHash + ", BlockHash=" + result.blockHash); +console.log(JSON.stringify(result, null, 4)); Deno.exit(); ``` -## Set Submit Data Fee Modifer +### Example Output + +#### On Failure + +If the operation fails, the function will return an error message indicating the nature of the issue. + +#### On Success + +If the operation is successful, the function will return a object of type `SetApplicationKeyTxSuccess`. + +```js +``` + +## Set Submit Data Fee Modifier Origin Level: Root @@ -216,10 +275,6 @@ function setSubmitDataFeeModifier(modifier: DispatchFeeModifier, waitFor: WaitFo | account | KeyringPair | false | account that will send and sign the transaction | | options | SignerOptions | true | used to overwrite existing signer options | -#### Return value - -On failure, a reason of failure is returned. On Success, SubmitDataFeeModifierSet event, transaction hash and block hash is returned. - ### Minimal Example ```js @@ -238,15 +293,24 @@ if (result.isErr) { Deno.exit(1); } -console.log( - "WeightMaximumFee=" + result.event.weightMaximumFee + ", WeightFeeMultiplier=" + result.event.weightFeeMultiplier + - ", WeightFeeDivider=" + result.event.weightFeeDivider, -); -console.log("TxHash=" + result.txHash + ", BlockHash=" + result.blockHash); +console.log(JSON.stringify(result, null, 4)) Deno.exit(); ``` +### Example Output + +#### On Failure + +If the operation fails, the function will return an error message indicating the nature of the issue. + +#### On Success + +If the operation is successful, the function will return a object of type `SetSubmitDataFeeModifierTxSuccess`. + +```js +``` + ## Type Definitions ```js @@ -286,10 +350,6 @@ function transferKeepAlive(dest: string, value: BN, waitFor: WaitFor, account: | account | KeyringPair | false | account that will send and sign the transaction | | options | SignerOptions | true | used to overwrite existing signer options | -#### Return value - -On failure, a reason of failure is returned. On Success, TransferEvent event, transaction hash and block hash is returned. - ### Minimal Example ```js @@ -309,12 +369,37 @@ if (result.isErr) { Deno.exit(1); } -console.log("From=" + result.event.from + ", To=" + result.event.to + ", Amount=" + result.event.amount); -console.log("TxHash=" + result.txHash + ", BlockHash=" + result.blockHash); +console.log(JSON.stringify(result, null, 4)); Deno.exit(); ``` +### Example Output + +#### On Failure + +If the operation fails, the function will return an error message indicating the nature of the issue. + +#### On Success + +If the operation is successful, the function will return a object of type `TransferKeepAliveTxSuccess`. + +```js +{ + "isErr": false, + "event": { + "from": "5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY", + "to": "5HGjWAeFDfFCWPsjFQdVV2Msvz2XtMktvgocEZcCj68kUMaw", + "amount": "1000000000000000000" + }, + "events": [...], + "txHash": "0x812a3f3960afb8df72de0e5b86ff564c8ce7d93c837182c24d1796fb68a7f5f4", + "txIndex": 1, + "blockHash": "0xfdee1faced02696d692df1d896fa2822f4eb02f260c95e11041df86b2c229dfb", + "blockNumber": 1 +} +``` + ## Transfer Allow Death Origin Level: Signed @@ -335,11 +420,6 @@ function transferAllowDeath(dest: string, value: BN, waitFor: WaitFor, account: | account | KeyringPair | false | account that will send and sign the transaction | | options | SignerOptions | true | used to overwrite existing signer options | -#### Return value - -On failure, a reason of failure is returned. On Success, TransferEvent event, KilledAccount (optionally) event, transaction hash and block -hash is returned. - ### Minimal Example ```js @@ -359,13 +439,37 @@ if (result.isErr) { Deno.exit(1); } -console.log("From=" + result.event.from + ", To=" + result.event.to + ", Amount=" + result.event.amount); -console.log("MaybeKilled=" + result.event2?.account); -console.log("TxHash=" + result.txHash + ", BlockHash=" + result.blockHash); +console.log(JSON.stringify(result, null, 4)); Deno.exit(); ``` +### Example Output + +#### On Failure + +If the operation fails, the function will return an error message indicating the nature of the issue. + +#### On Success + +If the operation is successful, the function will return a object of type `TransferAllowDeathTxSuccess`. + +```js +{ + "isErr": false, + "event": { + "from": "5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY", + "to": "5HGjWAeFDfFCWPsjFQdVV2Msvz2XtMktvgocEZcCj68kUMaw", + "amount": "1000000000000000000" + }, + "events": [...], + "txHash": "0x63a73d2d1210ab9840341506788cca9592fd968609fecb5106cf0370c611061c", + "txIndex": 1, + "blockHash": "0xde2e95b63a4ca5927f9105931e4676b0634d12f524d4fff1048b403393419489", + "blockNumber": 2 +} +``` + ## Transfer All Origin Level: Signed @@ -386,11 +490,6 @@ function transferAll(dest: string, keepAlive: boolean, waitFor: WaitFor, account | account | KeyringPair | false | account that will send and sign the transaction | | options | SignerOptions | true | used to overwrite existing signer options | -#### Return value - -On failure, a reason of failure is returned. On Success, TransferEvent event, KilledAccount (optionally) event, transaction hash and block -hash is returned. - ### Minimal Example ```js @@ -410,13 +509,37 @@ if (result.isErr) { Deno.exit(1); } -console.log("From=" + result.event.from + ", To=" + result.event.to + ", Amount=" + result.event.amount); -console.log("MaybeKilled=" + result.event2?.account); -console.log("TxHash=" + result.txHash + ", BlockHash=" + result.blockHash); +console.log(JSON.stringify(result, null, 4)); Deno.exit(); ``` +### Example Output + +#### On Failure + +If the operation fails, the function will return an error message indicating the nature of the issue. + +#### On Success + +If the operation is successful, the function will return a object of type `TransferAllTxSuccess`. + +```js +{ + "isErr": false, + "event": { + "from": "5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY", + "to": "5HGjWAeFDfFCWPsjFQdVV2Msvz2XtMktvgocEZcCj68kUMaw", + "amount": "9999999873433871068464733" + }, + "events": [...], + "txHash": "0x343d3e8890bd479b4619cb7b0f2dfa91b7b91c0cedc0646247215f85baf1f63e", + "txIndex": 1, + "blockHash": "0xaec4adfad11f8aa902e1a985abb62737fc02445072b168238a956c3a0d8820f2", + "blockNumber": 2 +} +``` + # Staking Runtime Component: Staking\ @@ -443,10 +566,6 @@ function bond(value: BN, payee: StakingRewardDestination, waitFor: WaitFor, acco | account | KeyringPair | false | account that will send and sign the transaction | | options | SignerOptions | true | used to overwrite existing signer options | -#### Return value - -On failure, a reason of failure is returned. On Success, Bonded event, transaction hash and block hash is returned. - ### Minimal Example ```js @@ -466,12 +585,36 @@ if (result.isErr) { Deno.exit(1); } -console.log("Stash=" + result.event.stash + ", Amount=" + result.event.amount); -console.log("TxHash=" + result.txHash + ", BlockHash=" + result.blockHash); +console.log(JSON.stringify(result, null, 4)); Deno.exit(); ``` +### Example Output + +#### On Failure + +If the operation fails, the function will return an error message indicating the nature of the issue. + +#### On Success + +If the operation is successful, the function will return a object of type `BondTxSuccess`. + +```js +{ + "isErr": false, + "event": { + "stash": "5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY", + "amount": "100000" + }, + "events": [...], + "txHash": "0x3e1cc48207b02ca5d680cf1beeb270ce7cbf0d18a6191844bc963d4081a0ca90", + "txIndex": 1, + "blockHash": "0xf854e74cb428d0baf22454cb15007731a84263e57c64d019a304c0ca1bd30276", + "blockNumber": 2 +} +``` + ## Bond Extra Origin Level: Signed @@ -491,10 +634,6 @@ function bondExtra(maxAdditional: BN, waitFor: WaitFor, account: KeyringPair, op | account | KeyringPair | false | account that will send and sign the transaction | | options | SignerOptions | true | used to overwrite existing signer options | -#### Return value - -On failure, a reason of failure is returned. On Success, Bonded event, transaction hash and block hash is returned. - ### Minimal Example ```js @@ -513,12 +652,36 @@ if (result.isErr) { Deno.exit(1); } -console.log("Stash=" + result.event.stash + ", Amount=" + result.event.amount); -console.log("TxHash=" + result.txHash + ", BlockHash=" + result.blockHash); +console.log(JSON.stringify(result, null, 4)); Deno.exit(); ``` +### Example Output + +#### On Failure + +If the operation fails, the function will return an error message indicating the nature of the issue. + +#### On Success + +If the operation is successful, the function will return a object of type `BondExtraTxSuccess`. + +```js +{ + "isErr": false, + "event": { + "stash": "5GNJqTPyNqANBkUVMN1LPPrxXnFouWXoe2wNSmmEoLctxiZY", + "amount": "1" + }, + "events": [...], + "txHash": "0x940df5141925aeef2ab9aa767f6870689426de533f5f1d84b6d7be203e68ee77", + "txIndex": 1, + "blockHash": "0xc2a8375be07956586833f497a429ca2e29bafbb78ee5e051d5157df0ad5c8cb6", + "blockNumber": 7 +} +``` + ## Chill Origin Level: Signed @@ -537,10 +700,6 @@ function chill(waitFor: WaitFor, account: KeyringPair, options?: Partial): Promise; +function validate(commission: number, blocked: boolean, waitFor: WaitFor, account: KeyringPair, options?: Partial): Promise; ``` #### Parameters @@ -728,10 +960,6 @@ function validate(commission: number, blocked: boolean, waitFor: WaitFor, accoun | account | KeyringPair | false | account that will send and sign the transaction | | options | SignerOptions | true | used to overwrite existing signer options | -#### Return value - -On failure, a reason of failure is returned. On Success, ValidatorPrefsSet event, transaction hash and block hash is returned. - ### Minimal Example ```js @@ -751,8 +979,342 @@ if (result.isErr) { Deno.exit(1); } -console.log("Stash=" + result.event.stash + ", Commission=" + result.event.commission + ", Blocked=" + result.event.blocked); -console.log("TxHash=" + result.txHash + ", BlockHash=" + result.blockHash); +console.log(JSON.stringify(result, null, 4)); Deno.exit(); ``` + +### Example Output + +#### On Failure + +If the operation fails, the function will return an error message indicating the nature of the issue. + +#### On Success + +If the operation is successful, the function will return a object of type `ValidateTxSuccess`. + +```js +{ + "isErr": false, + "event": { + "stash": "5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY", + "commission": "50000000", + "blocked": "false" + }, + "events": [...], + "txHash": "0x31f047da16a350e32b832cc73d3351c8d5e5991625fde6e8c36fc45ebb9d2735", + "txIndex": 1, + "blockHash": "0xa7735804f52602d4b73e1dd7f718cf0ab5cc00d111c927a9f8a2b3d02b66e09a", + "blockNumber": 14 +} +``` + +# Nomination Pools + +Runtime Component: Nomination Pools\ +Runtime Index: 36\ +Interface Module Name: nominationPools + +## Create + +Origin Level: Signed + +### Interface + +```js +function create(amount: BN, root: string, nominator: string, bouncer: string, waitFor: WaitFor, account: KeyringPair, options?: Partial): Promise; +``` + +#### Parameters + +| parameter | type | optional | description | +| --------- | ------------- | -------- | -------------------------------------------------- | +| amount | BN | false | The amount of funds to delegate to the pool | +| root | string | false | The account to set as [`PoolRoles::root`] | +| nominator | string | false | The account to set as the [`PoolRoles::nominator`] | +| bouncer | string | false | The account to set as the [`PoolRoles::bouncer`] | +| waitFor | WaitFor | false | wait for block inclusion or finalization | +| account | KeyringPair | false | account that will send and sign the transaction | +| options | SignerOptions | true | used to overwrite existing signer options | + +### Minimal Example + +```js +import { BN, Keyring, SDK, WaitFor } from "https://raw.githubusercontent.com/availproject/avail/main/avail-deno/src/sdk.ts"; + +const providerEndpoint = "ws://127.0.0.1:9944"; +const sdk = await SDK.New(providerEndpoint); + +// Input +const account = new Keyring({ type: "sr25519" }).addFromUri("//Alice"); +const amount = new BN(10).pow(new BN(18)).mul(new BN(10000)); // 10_000 Avail + +const root: string = "5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY"; // Alice +const nominator: string = "5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY"; // Alice +const bouncer: string = "5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY"; // Alice + +const result = await sdk.tx.nomination_pools.create(amount, root, nominator, bouncer, WaitFor.BlockInclusion, account); +if (result.isErr) { + console.log(result.reason); + Deno.exit(1); +} + +console.log(JSON.stringify(result, null, 4)); + +Deno.exit(); +``` + +### Example Output + +#### On Failure + +If the operation fails, the function will return an error message indicating the nature of the issue. + +#### On Success + +If the operation is successful, the function will return a object of type `PoolCreateTxSuccess`. + +```js +{ + "isErr": false, + "event": { + "depositor": "5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY", + "poolId": "1" + }, + "event2": { + "member": "5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY", + "poolId": "1", + "bonded": "10000", + "joined": "true" + }, + "event": { + "key": "0x4d79417765736f6d654b6579", + "owner": "5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY", + "id": "10" + }, + "events": [...], + "txHash": "0x5ae9edbd2a2da96eeffc14cf9050d711082890fa6bfb8749ad2c4947565f3bd2", + "txIndex": 1, + "blockHash": "0x152338c1b0696d12664cf3d4c159af3d54beca151ba1ea8b00989a66dc8050b0", + "blockNumber": 1 +} +``` + +## Create with Pool Id + +Origin Level: Signed + +### Interface + +```js +function createWithPoolId(amount: BN, root: string, nominator: string, bouncer: string, poolId: number, waitFor: WaitFor, account: KeyringPair, options?: Partial): Promise; +``` + +#### Parameters + +| parameter | type | optional | description | +| --------- | ------------- | -------- | -------------------------------------------------- | +| amount | BN | false | The amount of funds to delegate to the pool | +| root | string | false | The account to set as [`PoolRoles::root`] | +| nominator | string | false | The account to set as the [`PoolRoles::nominator`] | +| bouncer | string | false | The account to set as the [`PoolRoles::bouncer`] | +| poolId | number | false | pool id | +| waitFor | WaitFor | false | wait for block inclusion or finalization | +| account | KeyringPair | false | account that will send and sign the transaction | +| options | SignerOptions | true | used to overwrite existing signer options | + +### Minimal Example + +```js +import { BN, Keyring, SDK, WaitFor } from "https://raw.githubusercontent.com/availproject/avail/main/avail-deno/src/sdk.ts"; + +const providerEndpoint = "ws://127.0.0.1:9944"; +const sdk = await SDK.New(providerEndpoint); + +// Input +const account = new Keyring({ type: "sr25519" }).addFromUri("//Bob"); +const amount = new BN(10).pow(new BN(18)).mul(new BN(10000)); // 10_000 Avail + +const root: string = "5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY"; // Alice +const nominator: string = "5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY"; // Alice +const bouncer: string = "5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY"; // Alice +const poolId = 0; + +const result = await sdk.tx.nomination_pools.createWithPoolId(amount, root, nominator, bouncer, poolId, WaitFor.BlockInclusion, account); +if (result.isErr) { + console.log(result.reason); + Deno.exit(1); +} + +console.log(JSON.stringify(result, null, 4)); + +Deno.exit(); +``` + +### Example Output + +#### On Failure + +If the operation fails, the function will return an error message indicating the nature of the issue. + +#### On Success + +If the operation is successful, the function will return a object of type `PoolCreateWithPoolIdTxSuccess`. + +```js +{ + "isErr": false, + "event": { + "depositor": "5FHneW46xGXgs5mUiveU4sbTyGBzmstUspZC92UhjJM694ty", + "poolId": "0" + }, + "event2": { + "member": "5FHneW46xGXgs5mUiveU4sbTyGBzmstUspZC92UhjJM694ty", + "poolId": "0", + "bonded": "10000", + "joined": "true" + }, + "events": [...], + "txHash": "0x6b50caed7950e67934cabbf88a1f7dc2e7e995ac608402f91a4db19be0da5c41", + "txIndex": 1, + "blockHash": "0xc06df7dbb1e404f54499f942479ddcffc92665c021ea07c2798fc2f354f403d3", + "blockNumber": 6 +} +``` + +## Join + +Origin Level: Signed + +### Interface + +```js +function join(amount: BN, poolId: number, waitFor: WaitFor, account: KeyringPair, options?: Partial): Promise; +``` + +#### Parameters + +| parameter | type | optional | description | +| --------- | ------------- | -------- | ----------------------------------------------- | +| amount | BN | false | The amount of funds to delegate to the pool | +| poolId | number | false | pool id | +| waitFor | WaitFor | false | wait for block inclusion or finalization | +| account | KeyringPair | false | account that will send and sign the transaction | +| options | SignerOptions | true | used to overwrite existing signer options | + +### Minimal Example + +```js +import { BN, Keyring, SDK, WaitFor } from "https://raw.githubusercontent.com/availproject/avail/main/avail-deno/src/sdk.ts"; + +const providerEndpoint = "ws://127.0.0.1:9944"; +const sdk = await SDK.New(providerEndpoint); + +// Input +const account = new Keyring({ type: "sr25519" }).addFromUri("//Bob"); +const amount = new BN(10).pow(new BN(18)).mul(new BN(10000)); // 10_000 Avail +const poolId = 1; + +const result = await sdk.tx.nomination_pools.join(amount, poolId, WaitFor.BlockInclusion, account); +if (result.isErr) { + console.log(result.reason); + Deno.exit(1); +} + +console.log(JSON.stringify(result, null, 4)); + +Deno.exit(); +``` + +### Example Output + +#### On Failure + +If the operation fails, the function will return an error message indicating the nature of the issue. + +#### On Success + +If the operation is successful, the function will return a object of type `PoolJoinTxSuccess`. + +```js +{ + "isErr": false, + "event": { + "member": "5FHneW46xGXgs5mUiveU4sbTyGBzmstUspZC92UhjJM694ty", + "poolId": "1", + "bonded": "10000", + "joined": "true" + }, + "events": [...], + "txHash": "0x06baecbb8680e90d025d1fd08044d0d251054a89e82dd460022bdf3796020050", + "txIndex": 1, + "blockHash": "0x82078130da46adacf5bdff86618ab6e1c443fda6d883d9fcf967a41a2e29d612", + "blockNumber": 19 +} +``` + +## Nominate + +Origin Level: Signed + +### Interface + +```js +function nominate(poolId: number, validators: string[], waitFor: WaitFor, account: KeyringPair, options?: Partial): Promise; +``` + +#### Parameters + +| parameter | type | optional | description | +| ---------- | ------------- | -------- | ----------------------------------------------- | +| poolId | number | false | pool id | +| validators | string[] | false | list of validators to nominate | +| waitFor | WaitFor | false | wait for block inclusion or finalization | +| account | KeyringPair | false | account that will send and sign the transaction | +| options | SignerOptions | true | used to overwrite existing signer options | + +### Minimal Example + +```js +import { Keyring, SDK, WaitFor } from "https://raw.githubusercontent.com/availproject/avail/main/avail-deno/src/sdk.ts"; + +const providerEndpoint = "ws://127.0.0.1:9944"; +const sdk = await SDK.New(providerEndpoint); + +// Input +const account = new Keyring({ type: "sr25519" }).addFromUri("//Alice"); +const validators: string[] = ["5GNJqTPyNqANBkUVMN1LPPrxXnFouWXoe2wNSmmEoLctxiZY", "5DAAnrj7VHTznn2AWBemMuyBwZWs6FNFjdyVXUeYum3PTXFy"]; +const poolId = 1; + +const result = await sdk.tx.nomination_pools.nominate(poolId, validators, WaitFor.BlockInclusion, account); +if (result.isErr) { + console.log(result.reason); + Deno.exit(1); +} + +console.log(JSON.stringify(result, null, 4)); + +Deno.exit(); +``` + +### Example Output + +#### On Failure + +If the operation fails, the function will return an error message indicating the nature of the issue. + +#### On Success + +If the operation is successful, the function will return a object of type `PoolNominateTxSuccess`. + +```js +{ + "isErr": false, + "events": [...], + "txHash": "0x98b993baf90183d85dece9357d3bc32311f4201b015b63845a13dbc22bf22370", + "txIndex": 1, + "blockHash": "0x84ef5a0ada4af71358ee701a2500bce7f6688efb554c32ba1a30c459f64d5370", + "blockNumber": 48 +} +``` diff --git a/avail-deno/docs/extrinsics/balances_tranfer_all.ts b/avail-deno/docs/extrinsics/balances_tranfer_all.ts index 8dc51b713..7d7c1131d 100644 --- a/avail-deno/docs/extrinsics/balances_tranfer_all.ts +++ b/avail-deno/docs/extrinsics/balances_tranfer_all.ts @@ -14,8 +14,6 @@ if (result.isErr) { Deno.exit(1); } -console.log("From=" + result.event.from + ", To=" + result.event.to + ", Amount=" + result.event.amount); -console.log("MaybeKilled=" + result.event2?.account); -console.log("TxHash=" + result.txHash + ", BlockHash=" + result.blockHash); +console.log(JSON.stringify(result, null, 4)); Deno.exit(); diff --git a/avail-deno/docs/extrinsics/balances_tranfer_allow_death.ts b/avail-deno/docs/extrinsics/balances_tranfer_allow_death.ts index 31ed3dc5c..1daa019d4 100644 --- a/avail-deno/docs/extrinsics/balances_tranfer_allow_death.ts +++ b/avail-deno/docs/extrinsics/balances_tranfer_allow_death.ts @@ -14,8 +14,6 @@ if (result.isErr) { Deno.exit(1); } -console.log("From=" + result.event.from + ", To=" + result.event.to + ", Amount=" + result.event.amount); -console.log("MaybeKilled=" + result.event2?.account); -console.log("TxHash=" + result.txHash + ", BlockHash=" + result.blockHash); +console.log(JSON.stringify(result, null, 4)); Deno.exit(); diff --git a/avail-deno/docs/extrinsics/balances_tranfer_keep_alive.ts b/avail-deno/docs/extrinsics/balances_tranfer_keep_alive.ts index bcbaf1ba8..924eb551a 100644 --- a/avail-deno/docs/extrinsics/balances_tranfer_keep_alive.ts +++ b/avail-deno/docs/extrinsics/balances_tranfer_keep_alive.ts @@ -14,7 +14,6 @@ if (result.isErr) { Deno.exit(1); } -console.log("From=" + result.event.from + ", To=" + result.event.to + ", Amount=" + result.event.amount); -console.log("TxHash=" + result.txHash + ", BlockHash=" + result.blockHash); +console.log(JSON.stringify(result, null, 4)); Deno.exit(); diff --git a/avail-deno/docs/extrinsics/da_create_application_key.ts b/avail-deno/docs/extrinsics/da_create_application_key.ts index 60ff2fb05..2edfa7b47 100644 --- a/avail-deno/docs/extrinsics/da_create_application_key.ts +++ b/avail-deno/docs/extrinsics/da_create_application_key.ts @@ -13,7 +13,6 @@ if (result.isErr) { Deno.exit(1); } -console.log("Key=" + result.event.key + ", Owner=" + result.event.owner + ", Id=" + result.event.id); -console.log("TxHash=" + result.txHash + ", BlockHash=" + result.blockHash); +console.log(JSON.stringify(result, null, 4)); Deno.exit(); diff --git a/avail-deno/docs/extrinsics/da_submit_block_length_proposal.ts b/avail-deno/docs/extrinsics/da_submit_block_length_proposal.ts index dd5442798..e700bf3d7 100644 --- a/avail-deno/docs/extrinsics/da_submit_block_length_proposal.ts +++ b/avail-deno/docs/extrinsics/da_submit_block_length_proposal.ts @@ -14,7 +14,6 @@ if (result.isErr) { Deno.exit(1); } -console.log("Rows=" + result.event.rows + ", Cols=" + result.event.cols); -console.log("TxHash=" + result.txHash + ", BlockHash=" + result.blockHash); +console.log(JSON.stringify(result, null, 4)); Deno.exit(); diff --git a/avail-deno/docs/extrinsics/da_submit_data.ts b/avail-deno/docs/extrinsics/da_submit_data.ts index 078b5fc99..882dc5a67 100644 --- a/avail-deno/docs/extrinsics/da_submit_data.ts +++ b/avail-deno/docs/extrinsics/da_submit_data.ts @@ -13,8 +13,6 @@ if (result.isErr) { Deno.exit(1); } -console.log("Data=" + result.txData.data); -console.log("Who=" + result.event.who + ", DataHash=" + result.event.dataHash); -console.log("TxHash=" + result.txHash + ", BlockHash=" + result.blockHash); +console.log(JSON.stringify(result, null, 4)); Deno.exit(); diff --git a/avail-deno/docs/extrinsics/nomination_pools_create.ts b/avail-deno/docs/extrinsics/nomination_pools_create.ts new file mode 100644 index 000000000..c1cf35571 --- /dev/null +++ b/avail-deno/docs/extrinsics/nomination_pools_create.ts @@ -0,0 +1,22 @@ +import { BN, Keyring, SDK, WaitFor } from "https://raw.githubusercontent.com/availproject/avail/main/avail-deno/src/sdk.ts"; + +const providerEndpoint = "ws://127.0.0.1:9944"; +const sdk = await SDK.New(providerEndpoint); + +// Input +const account = new Keyring({ type: "sr25519" }).addFromUri("//Alice"); +const amount = new BN(10).pow(new BN(18)).mul(new BN(10000)); // 10_000 Avail + +const root: string = "5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY"; // Alice +const nominator: string = "5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY"; // Alice +const bouncer: string = "5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY"; // Alice + +const result = await sdk.tx.nomination_pools.create(amount, root, nominator, bouncer, WaitFor.BlockInclusion, account); +if (result.isErr) { + console.log(result.reason); + Deno.exit(1); +} + +console.log(JSON.stringify(result, null, 4)); + +Deno.exit(); diff --git a/avail-deno/docs/extrinsics/nomination_pools_create_with_pool_id.ts b/avail-deno/docs/extrinsics/nomination_pools_create_with_pool_id.ts new file mode 100644 index 000000000..fb1eaebee --- /dev/null +++ b/avail-deno/docs/extrinsics/nomination_pools_create_with_pool_id.ts @@ -0,0 +1,23 @@ +import { BN, Keyring, SDK, WaitFor } from "https://raw.githubusercontent.com/availproject/avail/main/avail-deno/src/sdk.ts"; + +const providerEndpoint = "ws://127.0.0.1:9944"; +const sdk = await SDK.New(providerEndpoint); + +// Input +const account = new Keyring({ type: "sr25519" }).addFromUri("//Bob"); +const amount = new BN(10).pow(new BN(18)).mul(new BN(10000)); // 10_000 Avail + +const root: string = "5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY"; // Alice +const nominator: string = "5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY"; // Alice +const bouncer: string = "5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY"; // Alice +const poolId = 0; + +const result = await sdk.tx.nomination_pools.createWithPoolId(amount, root, nominator, bouncer, poolId, WaitFor.BlockInclusion, account); +if (result.isErr) { + console.log(result.reason); + Deno.exit(1); +} + +console.log(JSON.stringify(result, null, 4)); + +Deno.exit(); diff --git a/avail-deno/docs/extrinsics/nomination_pools_join.ts b/avail-deno/docs/extrinsics/nomination_pools_join.ts new file mode 100644 index 000000000..36b23cc48 --- /dev/null +++ b/avail-deno/docs/extrinsics/nomination_pools_join.ts @@ -0,0 +1,19 @@ +import { BN, Keyring, SDK, WaitFor } from "https://raw.githubusercontent.com/availproject/avail/main/avail-deno/src/sdk.ts"; + +const providerEndpoint = "ws://127.0.0.1:9944"; +const sdk = await SDK.New(providerEndpoint); + +// Input +const account = new Keyring({ type: "sr25519" }).addFromUri("//Bob"); +const amount = new BN(10).pow(new BN(18)).mul(new BN(10000)); // 10_000 Avail +const poolId = 1; + +const result = await sdk.tx.nomination_pools.join(amount, poolId, WaitFor.BlockInclusion, account); +if (result.isErr) { + console.log(result.reason); + Deno.exit(1); +} + +console.log(JSON.stringify(result, null, 4)); + +Deno.exit(); diff --git a/avail-deno/docs/extrinsics/nomination_pools_nominate.ts b/avail-deno/docs/extrinsics/nomination_pools_nominate.ts new file mode 100644 index 000000000..ca8704795 --- /dev/null +++ b/avail-deno/docs/extrinsics/nomination_pools_nominate.ts @@ -0,0 +1,19 @@ +import { Keyring, SDK, WaitFor } from "https://raw.githubusercontent.com/availproject/avail/main/avail-deno/src/sdk.ts"; + +const providerEndpoint = "ws://127.0.0.1:9944"; +const sdk = await SDK.New(providerEndpoint); + +// Input +const account = new Keyring({ type: "sr25519" }).addFromUri("//Alice"); +const validators: string[] = ["5GNJqTPyNqANBkUVMN1LPPrxXnFouWXoe2wNSmmEoLctxiZY", "5DAAnrj7VHTznn2AWBemMuyBwZWs6FNFjdyVXUeYum3PTXFy"]; +const poolId = 1; + +const result = await sdk.tx.nomination_pools.nominate(poolId, validators, WaitFor.BlockInclusion, account); +if (result.isErr) { + console.log(result.reason); + Deno.exit(1); +} + +console.log(JSON.stringify(result, null, 4)); + +Deno.exit(); diff --git a/avail-deno/docs/extrinsics/staking_bond.ts b/avail-deno/docs/extrinsics/staking_bond.ts index 7a95feecc..c48141333 100644 --- a/avail-deno/docs/extrinsics/staking_bond.ts +++ b/avail-deno/docs/extrinsics/staking_bond.ts @@ -14,7 +14,6 @@ if (result.isErr) { Deno.exit(1); } -console.log("Stash=" + result.event.stash + ", Amount=" + result.event.amount); -console.log("TxHash=" + result.txHash + ", BlockHash=" + result.blockHash); +console.log(JSON.stringify(result, null, 4)); Deno.exit(); diff --git a/avail-deno/docs/extrinsics/staking_bond_extra.ts b/avail-deno/docs/extrinsics/staking_bond_extra.ts index 42bb07fc5..dc52bed4d 100644 --- a/avail-deno/docs/extrinsics/staking_bond_extra.ts +++ b/avail-deno/docs/extrinsics/staking_bond_extra.ts @@ -13,7 +13,6 @@ if (result.isErr) { Deno.exit(1); } -console.log("Stash=" + result.event.stash + ", Amount=" + result.event.amount); -console.log("TxHash=" + result.txHash + ", BlockHash=" + result.blockHash); +console.log(JSON.stringify(result, null, 4)); Deno.exit(); diff --git a/avail-deno/docs/extrinsics/staking_chill.ts b/avail-deno/docs/extrinsics/staking_chill.ts index a30820b16..ee2a94094 100644 --- a/avail-deno/docs/extrinsics/staking_chill.ts +++ b/avail-deno/docs/extrinsics/staking_chill.ts @@ -12,7 +12,6 @@ if (result.isErr) { Deno.exit(1); } -console.log("Stash=" + result.event.stash); -console.log("TxHash=" + result.txHash + ", BlockHash=" + result.blockHash); +console.log(JSON.stringify(result, null, 4)); Deno.exit(); diff --git a/avail-deno/docs/extrinsics/staking_chill_other.ts b/avail-deno/docs/extrinsics/staking_chill_other.ts index e192bc4bb..a4a8676a6 100644 --- a/avail-deno/docs/extrinsics/staking_chill_other.ts +++ b/avail-deno/docs/extrinsics/staking_chill_other.ts @@ -13,7 +13,6 @@ if (result.isErr) { Deno.exit(1); } -console.log("Stash=" + result.event.stash); -console.log("TxHash=" + result.txHash + ", BlockHash=" + result.blockHash); +console.log(JSON.stringify(result, null, 4)); Deno.exit(); diff --git a/avail-deno/docs/extrinsics/staking_nominate.ts b/avail-deno/docs/extrinsics/staking_nominate.ts index 1eeaddca2..f769f889e 100644 --- a/avail-deno/docs/extrinsics/staking_nominate.ts +++ b/avail-deno/docs/extrinsics/staking_nominate.ts @@ -16,7 +16,6 @@ if (result.isErr) { Deno.exit(1); } -console.log("TxDataTargets=" + result.txData.targets); -console.log("TxHash=" + result.txHash + ", BlockHash=" + result.blockHash); +console.log(JSON.stringify(result, null, 4)); Deno.exit(); diff --git a/avail-deno/docs/extrinsics/staking_unbond.ts b/avail-deno/docs/extrinsics/staking_unbond.ts index e495ba96c..f275ca642 100644 --- a/avail-deno/docs/extrinsics/staking_unbond.ts +++ b/avail-deno/docs/extrinsics/staking_unbond.ts @@ -13,7 +13,6 @@ if (result.isErr) { Deno.exit(1); } -console.log("Stash=" + result.event.stash + ", Amount=" + result.event.amount); -console.log("TxHash=" + result.txHash + ", BlockHash=" + result.blockHash); +console.log(JSON.stringify(result, null, 4)); Deno.exit(); diff --git a/avail-deno/docs/extrinsics/staking_validate.ts b/avail-deno/docs/extrinsics/staking_validate.ts index f39584f7c..09d8a1d8b 100644 --- a/avail-deno/docs/extrinsics/staking_validate.ts +++ b/avail-deno/docs/extrinsics/staking_validate.ts @@ -14,7 +14,6 @@ if (result.isErr) { Deno.exit(1); } -console.log("Stash=" + result.event.stash + ", Commission=" + result.event.commission + ", Blocked=" + result.event.blocked); -console.log("TxHash=" + result.txHash + ", BlockHash=" + result.blockHash); +console.log(JSON.stringify(result, null, 4)); Deno.exit(); diff --git a/avail-deno/docs/extrinsics/webapp/account.html b/avail-deno/docs/extrinsics/webapp/account.html deleted file mode 100644 index 3adf1d64b..000000000 --- a/avail-deno/docs/extrinsics/webapp/account.html +++ /dev/null @@ -1,2 +0,0 @@ -
- \ No newline at end of file diff --git a/avail-deno/docs/extrinsics/webapp/shared_state.ts b/avail-deno/docs/extrinsics/webapp/shared_state.ts deleted file mode 100644 index d138e4ef1..000000000 --- a/avail-deno/docs/extrinsics/webapp/shared_state.ts +++ /dev/null @@ -1,18 +0,0 @@ -import { KeyringPair } from "https://deno.land/x/polkadot@0.2.45/keyring/types.ts"; -import { Keyring, SDK, WaitFor } from "https://raw.githubusercontent.com/availproject/avail/main/avail-deno/src/sdk.ts"; - -export class SharedState { - sdk: SDK; - account: KeyringPair; - waitFor: WaitFor = WaitFor.BlockInclusion; - - constructor(sdk: SDK) { - this.sdk = sdk; - this.account = new Keyring({ type: "sr25519" }).addFromUri("//Alice"); - } -} - -export enum ExecutionState { - Idle, - Busy, -} diff --git a/avail-deno/docs/extrinsics/webapp/submit_data.html b/avail-deno/docs/extrinsics/webapp/submit_data.html deleted file mode 100644 index 0f5ff3eae..000000000 --- a/avail-deno/docs/extrinsics/webapp/submit_data.html +++ /dev/null @@ -1,10 +0,0 @@ -
- - -
-
-
-

-
- -
\ No newline at end of file diff --git a/avail-deno/docs/extrinsics/webapp/submit_data.ts b/avail-deno/docs/extrinsics/webapp/submit_data.ts deleted file mode 100644 index 67801ccfd..000000000 --- a/avail-deno/docs/extrinsics/webapp/submit_data.ts +++ /dev/null @@ -1,29 +0,0 @@ -import { ExecutionState, SharedState } from "./shared_state.ts"; - -export class SubmitDataView { - private sharedState: SharedState; - private executionState: ExecutionState = ExecutionState.Idle; - - constructor(sharedState: SharedState) { - this.sharedState = sharedState; - } - - async execute(data: string): Promise { - if (this.executionState != ExecutionState.Idle) { - return null; - } - - this.executionState = ExecutionState.Busy; - const result = await this.sharedState.sdk.tx.dataAvailability.submitData(data, this.sharedState.waitFor, this.sharedState.account); - this.executionState = ExecutionState.Idle; - if (result.isErr) { - return result.reason; - } else { - return `TxHash: ${result.txHash}
BlockHash: ${result.blockHash}
Event: { who: ${result.event.who}, dataHash: ${result.event.dataHash} }
TX Data: ${result.txData}`; - } - } - - static generateHtml(): string { - return Deno.readTextFileSync("./submit_data.html"); - } -} diff --git a/avail-deno/docs/extrinsics/webapp/webapp.ts b/avail-deno/docs/extrinsics/webapp/webapp.ts deleted file mode 100644 index 6b79e7b2d..000000000 --- a/avail-deno/docs/extrinsics/webapp/webapp.ts +++ /dev/null @@ -1,44 +0,0 @@ -import { Application, Router, Status } from "https://deno.land/x/oak/mod.ts"; -import { SDK } from "https://raw.githubusercontent.com/availproject/avail/main/avail-deno/src/sdk.ts"; -import { SubmitDataView } from "./submit_data.ts"; -import { SharedState } from "./shared_state.ts"; - -const sdk = await SDK.new("ws://127.0.0.1:9944"); -const sharedState = new SharedState(sdk); -const submitDataView = new SubmitDataView(sharedState); - -const submitDataViewHtml = SubmitDataView.generateHtml(); -const htmlBoilerplate = - ``; -const server_app = new Application(); -const router = new Router(); -router - .get("/", (context) => { - context.response.type = "html"; - context.response.body = `${htmlBoilerplate} ${submitDataViewHtml}`; - }) - .post("/submitDataExecute", async (context) => { - context.response.type = "html"; - const body = await context.request.body({ type: "form" }).value; - const data = body.get("Data"); - if (data != null && data != "") { - const result = await submitDataView.execute(data); - if (result) { - context.response.body = result; - } else { - context.response.status = Status.NoContent; - } - } else { - context.response.body = "Something went wrong :("; - } - }) - .get("/accounts", async (context) => { - context.response.type = "html"; - context.response.body = ` - - - `; - }); - -server_app.use(router.routes()); -await server_app.listen({ port: 8000 }); diff --git a/avail-deno/docs/storage/README.md b/avail-deno/docs/storage/README.md deleted file mode 100644 index e69de29bb..000000000 diff --git a/avail-deno/docs/storage/da_app_keys.ts b/avail-deno/docs/storage/da_app_keys.ts new file mode 100644 index 000000000..d17e64140 --- /dev/null +++ b/avail-deno/docs/storage/da_app_keys.ts @@ -0,0 +1,10 @@ +import { SDK } from "https://raw.githubusercontent.com/availproject/avail/main/avail-deno/src/sdk.ts"; + +const providerEndpoint = "ws://127.0.0.1:9944"; +const sdk = await SDK.New(providerEndpoint); + +const key = "Reserved-2"; +const value = await sdk.api.query.dataAvailability.appKeys(key); +console.log(value.toHuman()); + +Deno.exit(); diff --git a/avail-deno/docs/storage/da_app_keys_iter.ts b/avail-deno/docs/storage/da_app_keys_iter.ts new file mode 100644 index 000000000..83e89c093 --- /dev/null +++ b/avail-deno/docs/storage/da_app_keys_iter.ts @@ -0,0 +1,12 @@ +import { SDK } from "https://raw.githubusercontent.com/availproject/avail/main/avail-deno/src/sdk.ts"; + +const providerEndpoint = "ws://127.0.0.1:9944"; +const sdk = await SDK.New(providerEndpoint); + +const appKeys = await sdk.api.query.dataAvailability.appKeys.entries(); +for (const [key, value] of appKeys) { + console.log(key.toHuman()); + console.log(value.toHuman()); +} + +Deno.exit(); diff --git a/avail-deno/docs/storage/da_next_app_id.ts b/avail-deno/docs/storage/da_next_app_id.ts new file mode 100644 index 000000000..34f5992bb --- /dev/null +++ b/avail-deno/docs/storage/da_next_app_id.ts @@ -0,0 +1,9 @@ +import { SDK } from "https://raw.githubusercontent.com/availproject/avail/main/avail-deno/src/sdk.ts"; + +const providerEndpoint = "ws://127.0.0.1:9944"; +const sdk = await SDK.New(providerEndpoint); + +const value = await sdk.api.query.dataAvailability.nextAppId(); +console.log(value.toHuman()); + +Deno.exit(); diff --git a/avail-deno/docs/storage/minimal_examples/staking_bonded.ts b/avail-deno/docs/storage/minimal_examples/staking_bonded.ts deleted file mode 100644 index e69de29bb..000000000 diff --git a/avail-deno/docs/storage/staking_active_era.ts b/avail-deno/docs/storage/staking_active_era.ts new file mode 100644 index 000000000..0c3081c4e --- /dev/null +++ b/avail-deno/docs/storage/staking_active_era.ts @@ -0,0 +1,9 @@ +import { SDK } from "https://raw.githubusercontent.com/availproject/avail/main/avail-deno/src/sdk.ts"; + +const providerEndpoint = "ws://127.0.0.1:9944"; +const sdk = await SDK.New(providerEndpoint); + +const value = await sdk.api.query.staking.activeEra(); +console.log(value.toHuman()); + +Deno.exit(); diff --git a/avail-deno/docs/storage/staking_bonded.ts b/avail-deno/docs/storage/staking_bonded.ts new file mode 100644 index 000000000..e62c208a7 --- /dev/null +++ b/avail-deno/docs/storage/staking_bonded.ts @@ -0,0 +1,10 @@ +import { SDK } from "https://raw.githubusercontent.com/availproject/avail/main/avail-deno/src/sdk.ts"; + +const providerEndpoint = "ws://127.0.0.1:9944"; +const sdk = await SDK.New(providerEndpoint); + +const key = "5EYCAe5ijiYfAXEth5DCfmQ9jnv4BFmdonKpbxwrc2nAw5uj"; +const value = await sdk.api.query.staking.bonded(key); +console.log(value.toHuman()); + +Deno.exit(); diff --git a/avail-deno/docs/storage/staking_bonded_iter.ts b/avail-deno/docs/storage/staking_bonded_iter.ts new file mode 100644 index 000000000..134539add --- /dev/null +++ b/avail-deno/docs/storage/staking_bonded_iter.ts @@ -0,0 +1,12 @@ +import { SDK } from "https://raw.githubusercontent.com/availproject/avail/main/avail-deno/src/sdk.ts"; + +const providerEndpoint = "ws://127.0.0.1:9944"; +const sdk = await SDK.New(providerEndpoint); + +const accounts = await sdk.api.query.staking.bonded.entries(); +for (const [key, value] of accounts) { + console.log(key.toHuman()); + console.log(value.toHuman()); +} + +Deno.exit(); diff --git a/avail-deno/docs/storage/system_account.ts b/avail-deno/docs/storage/system_account.ts new file mode 100644 index 000000000..eb7d967e2 --- /dev/null +++ b/avail-deno/docs/storage/system_account.ts @@ -0,0 +1,10 @@ +import { SDK } from "https://raw.githubusercontent.com/availproject/avail/main/avail-deno/src/sdk.ts"; + +const providerEndpoint = "ws://127.0.0.1:9944"; +const sdk = await SDK.New(providerEndpoint); + +const key = "5HKPmK9GYtE1PSLsS1qiYU9xQ9Si1NcEhdeCq9sw5bqu4ns8"; +const value = await sdk.api.query.system.account(key); +console.log(value.toHuman()); + +Deno.exit(); diff --git a/avail-deno/docs/storage/system_account_iter.ts b/avail-deno/docs/storage/system_account_iter.ts new file mode 100644 index 000000000..e19d72aca --- /dev/null +++ b/avail-deno/docs/storage/system_account_iter.ts @@ -0,0 +1,12 @@ +import { SDK } from "https://raw.githubusercontent.com/availproject/avail/main/avail-deno/src/sdk.ts"; + +const providerEndpoint = "ws://127.0.0.1:9944"; +const sdk = await SDK.New(providerEndpoint); + +const accounts = await sdk.api.query.system.account.entries(); +for (const [key, value] of accounts) { + console.log(key.toHuman()); + console.log(value.toHuman()); +} + +Deno.exit(); diff --git a/avail-deno/src/events.ts b/avail-deno/src/events.ts index 678a25a51..df4e87764 100644 --- a/avail-deno/src/events.ts +++ b/avail-deno/src/events.ts @@ -8,7 +8,7 @@ export namespace DataAvailability { export class DataSubmittedEvent { constructor(public who: string, public dataHash: string) {} static New(events: EventRecord[]): DataSubmittedEvent | undefined { - const ed: any = events.find((e) => e.event.method == "DataSubmitted")?.event.data; + const ed: any = events.find((e) => e.event.method == "DataSubmitted" && e.event.section == "dataAvailability")?.event.data; if (ed == undefined) { return undefined; } @@ -20,7 +20,8 @@ export namespace DataAvailability { export class ApplicationKeyCreatedEvent { constructor(public key: string, public owner: string, public id: string) {} static New(events: EventRecord[]): ApplicationKeyCreatedEvent | undefined { - const ed: any = events.find((e) => e.event.method == "ApplicationKeyCreated")?.event.data; + const ed: any = events.find((e) => e.event.method == "ApplicationKeyCreated" && e.event.section == "dataAvailability")?.event + .data; if (ed == undefined) { return undefined; } @@ -32,7 +33,7 @@ export namespace DataAvailability { export class ApplicationKeySetEvent { constructor(public oldKey: string, public newKey: string) {} static New(events: EventRecord[]): ApplicationKeySetEvent | undefined { - const ed: any = events.find((e) => e.event.method == "ApplicationKeySet")?.event.data; + const ed: any = events.find((e) => e.event.method == "ApplicationKeySet" && e.event.section == "dataAvailability")?.event.data; if (ed == undefined) { return undefined; } @@ -44,7 +45,8 @@ export namespace DataAvailability { export class BlockLengthProposalSubmittedEvent { constructor(public rows: string, public cols: string) {} static New(events: EventRecord[]): BlockLengthProposalSubmittedEvent | undefined { - const ed: any = events.find((e) => e.event.method == "BlockLengthProposalSubmitted")?.event.data; + const ed: any = events.find((e) => e.event.method == "BlockLengthProposalSubmitted" && e.event.section == "dataAvailability") + ?.event.data; if (ed == undefined) { return undefined; } @@ -60,7 +62,8 @@ export namespace DataAvailability { public weightFeeMultiplier: string | null, ) {} static New(events: EventRecord[]): SubmitDataFeeModifierSetEvent | undefined { - const ed: any = events.find((e) => e.event.method == "SubmitDataFeeModifierSet")?.event.data; + const ed: any = events.find((e) => e.event.method == "SubmitDataFeeModifierSet" && e.event.section == "dataAvailability")?.event + .data; if (ed == undefined) { return undefined; } @@ -78,7 +81,7 @@ export namespace Balances { export class TransferEvent { constructor(public from: string, public to: string, public amount: string) {} static New(events: EventRecord[]): TransferEvent | undefined { - const ed: any = events.find((e) => e.event.method == "Transfer")?.event.data; + const ed: any = events.find((e) => e.event.method == "Transfer" && e.event.section == "balances")?.event.data; if (ed == undefined) { return undefined; } @@ -92,7 +95,7 @@ export namespace System { export class KilledAccount { constructor(public account: string) {} static New(events: EventRecord[]): KilledAccount | undefined { - const ed: any = events.find((e) => e.event.method == "KilledAccount")?.event.data; + const ed: any = events.find((e) => e.event.method == "KilledAccount" && e.event.section == "system")?.event.data; if (ed == undefined) { return undefined; } @@ -106,7 +109,7 @@ export namespace Staking { export class Bonded { constructor(public stash: string, public amount: string) {} static New(events: EventRecord[]): Bonded | undefined { - const ed: any = events.find((e) => e.event.method == "Bonded")?.event.data; + const ed: any = events.find((e) => e.event.method == "Bonded" && e.event.section == "staking")?.event.data; if (ed == undefined) { return undefined; } @@ -121,7 +124,7 @@ export namespace Staking { export class Chilled { constructor(public stash: string) {} static New(events: EventRecord[]): Chilled | undefined { - const ed: any = events.find((e) => e.event.method == "Chilled")?.event.data; + const ed: any = events.find((e) => e.event.method == "Chilled" && e.event.section == "staking")?.event.data; if (ed == undefined) { return undefined; } @@ -133,7 +136,7 @@ export namespace Staking { export class Unbonded { constructor(public stash: string, public amount: string) {} static New(events: EventRecord[]): Unbonded | undefined { - const ed: any = events.find((e) => e.event.method == "Unbonded")?.event.data; + const ed: any = events.find((e) => e.event.method == "Unbonded" && e.event.section == "staking")?.event.data; if (ed == undefined) { return undefined; } @@ -145,7 +148,7 @@ export namespace Staking { export class ValidatorPrefsSet { constructor(public stash: string, public commission: string, public blocked: string) {} static New(events: EventRecord[]): ValidatorPrefsSet | undefined { - const ed: any = events.find((e) => e.event.method == "ValidatorPrefsSet")?.event.data; + const ed: any = events.find((e) => e.event.method == "ValidatorPrefsSet" && e.event.section == "staking")?.event.data; if (ed == undefined) { return undefined; } @@ -158,3 +161,32 @@ export namespace Staking { } } } + +export namespace NominationPools { + export class Created { + constructor(public depositor: string, public poolId: string) {} + static New(events: EventRecord[]): Created | undefined { + const ed: any = events.find((e) => e.event.method == "Created" && e.event.section == "nominationPools")?.event.data; + if (ed == undefined) { + return undefined; + } + + return new Created(ed["depositor"].toString(), ed["poolId"].toString()); + } + } + + export class Bonded { + constructor(public member: string, public poolId: string, public bonded: string, public joined: string) {} + static New(events: EventRecord[]): Bonded | undefined { + const ed: any = events.find((e) => e.event.method == "Bonded" && e.event.section == "nominationPools")?.event.data; + if (ed == undefined) { + return undefined; + } + + const bondedString = ed["bonded"].toString(); + const bonded = new BN(bondedString).div(new BN(10).pow(new BN(18))).toString(); + + return new Bonded(ed["member"].toString(), ed["poolId"].toString(), bonded, ed["joined"].toString()); + } + } +} diff --git a/avail-deno/src/transactions.ts b/avail-deno/src/transactions.ts index 5b544303a..0d308e74e 100644 --- a/avail-deno/src/transactions.ts +++ b/avail-deno/src/transactions.ts @@ -2,7 +2,7 @@ import { ApiPromise } from "https://deno.land/x/polkadot@0.2.45/api/mod.ts"; import { KeyringPair } from "https://deno.land/x/polkadot@0.2.45/keyring/types.ts"; import { ISubmittableResult } from "https://deno.land/x/polkadot@0.2.45/types/types/extrinsic.ts"; import { SignerOptions } from "https://deno.land/x/polkadot@0.2.45/api/submittable/types.ts"; -import { H256 } from "https://deno.land/x/polkadot@0.2.45/types/interfaces/types.ts"; +import { EventRecord, H256 } from "https://deno.land/x/polkadot@0.2.45/types/interfaces/types.ts"; import { BN } from "https://deno.land/x/polkadot@0.2.45/util/mod.ts"; import { err, ok, Result } from "npm:neverthrow@6.2.2"; @@ -20,71 +20,208 @@ type ValidatorPerfs = { commission: string; blocked: boolean }; type GenericFailure = { isErr: true; reason: string }; +// DA Struct type SubmitDataTxSuccess = { isErr: false; txData: TransactionData.DataAvailability.SubmitData; event: Events.DataAvailability.DataSubmittedEvent; + events: EventRecord[]; txHash: H256; + txIndex: number; blockHash: H256; + blockNumber: number; }; type CreateApplicationKeyTxSuccess = { isErr: false; event: Events.DataAvailability.ApplicationKeyCreatedEvent; + events: EventRecord[]; txHash: H256; + txIndex: number; blockHash: H256; + blockNumber: number; }; type SetApplicationKeyTxSuccess = { isErr: false; event: Events.DataAvailability.ApplicationKeySetEvent; + events: EventRecord[]; txHash: H256; + txIndex: number; blockHash: H256; + blockNumber: number; }; type SubmitBlockLengthProposalTxSuccess = { isErr: false; event: Events.DataAvailability.BlockLengthProposalSubmittedEvent; + events: EventRecord[]; txHash: H256; + txIndex: number; blockHash: H256; + blockNumber: number; }; type SetSubmitDataFeeModifierTxSuccess = { isErr: false; event: Events.DataAvailability.SubmitDataFeeModifierSetEvent; + events: EventRecord[]; txHash: H256; + txIndex: number; blockHash: H256; + blockNumber: number; +}; + +// Balances struct +type TransferKeepAliveTxSuccess = { + isErr: false; + event: Events.Balances.TransferEvent; + events: EventRecord[]; + txHash: H256; + txIndex: number; + blockHash: H256; + blockNumber: number; }; -type TransferKeepAliveTxSuccess = { isErr: false; event: Events.Balances.TransferEvent; txHash: H256; blockHash: H256 }; type TransferAllowDeathTxSuccess = { isErr: false; event: Events.Balances.TransferEvent; event2?: Events.System.KilledAccount; + events: EventRecord[]; txHash: H256; + txIndex: number; blockHash: H256; + blockNumber: number; }; type TransferAllTxSuccess = { isErr: false; event: Events.Balances.TransferEvent; event2?: Events.System.KilledAccount; + events: EventRecord[]; + txHash: H256; + txIndex: number; + blockHash: H256; + blockNumber: number; +}; + +// Staking struct +type BondTxSuccess = { + isErr: false; + event: Events.Staking.Bonded; + events: EventRecord[]; + txHash: H256; + txIndex: number; + blockHash: H256; + blockNumber: number; +}; +type BondExtraTxSuccess = { + isErr: false; + event: Events.Staking.Bonded; + events: EventRecord[]; + txHash: H256; + txIndex: number; + blockHash: H256; + blockNumber: number; +}; +type ChillTxSuccess = { + isErr: false; + event: Events.Staking.Chilled; + events: EventRecord[]; + txHash: H256; + txIndex: number; + blockHash: H256; + blockNumber: number; +}; +type ChillOtherTxSuccess = { + isErr: false; + event: Events.Staking.Chilled; + events: EventRecord[]; + txHash: H256; + txIndex: number; + blockHash: H256; + blockNumber: number; +}; +type UnbondTxSuccess = { + isErr: false; + event: Events.Staking.Unbonded; + events: EventRecord[]; + txHash: H256; + txIndex: number; + blockHash: H256; + blockNumber: number; +}; +type ValidateTxSuccess = { + isErr: false; + event: Events.Staking.ValidatorPrefsSet; + events: EventRecord[]; + txHash: H256; + txIndex: number; + blockHash: H256; + blockNumber: number; +}; +type NominateTxSuccess = { + isErr: false; + txData: TransactionData.Staking.Nominate; + events: EventRecord[]; + txHash: H256; + txIndex: number; + blockHash: H256; + blockNumber: number; +}; + +// Session struct +// todo + +// Nomination Pools struct +type PoolCreateTxSuccess = { + isErr: false; + event: Events.NominationPools.Created; + event2: Events.NominationPools.Bonded; + events: EventRecord[]; + txHash: H256; + txIndex: number; + blockHash: H256; + blockNumber: number; +}; + +type PoolCreateWithPoolIdTxSuccess = { + isErr: false; + event: Events.NominationPools.Created; + event2: Events.NominationPools.Bonded; + events: EventRecord[]; + txHash: H256; + txIndex: number; + blockHash: H256; + blockNumber: number; +}; + +type PoolJoinTxSuccess = { + isErr: false; + event: Events.NominationPools.Bonded; + events: EventRecord[]; txHash: H256; + txIndex: number; blockHash: H256; + blockNumber: number; +}; + +type PoolNominateTxSuccess = { + isErr: false; + events: EventRecord[]; + txHash: H256; + txIndex: number; + blockHash: H256; + blockNumber: number; }; -type BondTxSuccess = { isErr: false; event: Events.Staking.Bonded; txHash: H256; blockHash: H256 }; -type BondExtraTxSuccess = { isErr: false; event: Events.Staking.Bonded; txHash: H256; blockHash: H256 }; -type ChillTxSuccess = { isErr: false; event: Events.Staking.Chilled; txHash: H256; blockHash: H256 }; -type ChillOtherTxSuccess = { isErr: false; event: Events.Staking.Chilled; txHash: H256; blockHash: H256 }; -type UnbondTxSuccess = { isErr: false; event: Events.Staking.Unbonded; txHash: H256; blockHash: H256 }; -type ValidatexSuccess = { isErr: false; event: Events.Staking.ValidatorPrefsSet; txHash: H256; blockHash: H256 }; -type NominateTxSuccess = { isErr: false; txData: TransactionData.Staking.Nominate; txHash: H256; blockHash: H256 }; export class Transactions { private api: ApiPromise; dataAvailability: DataAvailability; balances: Balances; staking: Staking; + nomination_pools: NominationPools; constructor(api: ApiPromise) { this.api = api; this.dataAvailability = new DataAvailability(api); this.balances = new Balances(api); this.staking = new Staking(api); + this.nomination_pools = new NominationPools(api); } } @@ -106,11 +243,209 @@ function standardCallback( } } -function getBlockHashAndTxHash(result: ISubmittableResult, waitFor: WaitFor): [H256, H256] { - if (waitFor == WaitFor.BlockInclusion) { - return [result.txHash as H256, result.status.asInBlock as H256]; +async function getBlockHashAndTxHash(result: ISubmittableResult, waitFor: WaitFor, api: ApiPromise): Promise<[H256, number, H256, number]> { + const txHash = result.txHash as H256; + const txIndex: number = result.txIndex || 22; + let blockHash = txHash; + if (waitFor == WaitFor.BlockFinalization) { + blockHash = result.status.asFinalized as H256; } else { - return [result.txHash as H256, result.status.asFinalized as H256]; + blockHash = result.status.asInBlock as H256; + } + + const header = await api.rpc.chain.getHeader(blockHash); + const blockNumber: number = header.number.toNumber(); + + return [txHash, txIndex, blockHash, blockNumber]; +} + +export class NominationPools { + private api: ApiPromise; + + constructor(api: ApiPromise) { + this.api = api; + } + + async create( + amount: BN, + root: string, + nominator: string, + bouncer: string, + waitFor: WaitFor, + account: KeyringPair, + options?: Partial, + ): Promise { + const optionWrapper = options || {}; + const maybeTxResult = await new Promise>((res, _) => { + this.api.tx.nominationPools.create(amount, root, nominator, bouncer).signAndSend( + account, + optionWrapper, + (result: ISubmittableResult) => { + standardCallback(result, res, waitFor); + }, + ).catch((reason) => { + res(err(reason)); + }); + }); + + if (maybeTxResult.isErr()) { + return { isErr: true, reason: maybeTxResult.error } as GenericFailure; + } + const txResult = maybeTxResult.value; + + if (txResult.isError) { + return { isErr: true, reason: "The transaction was dropped or something." } as GenericFailure; + } + + const events = txResult.events; + const failed = events.find((e) => this.api.events.system.ExtrinsicFailed.is(e.event)); + if (failed != undefined) { + return { isErr: true, reason: decodeError(this.api, failed.event.data[0]) } as GenericFailure; + } + + const event = Events.NominationPools.Created.New(txResult.events); + if (event == undefined) { + return { isErr: true, reason: "Failed to find Created event." } as GenericFailure; + } + + const event2 = Events.NominationPools.Bonded.New(txResult.events); + if (event2 == undefined) { + return { isErr: true, reason: "Failed to find Bonded event." } as GenericFailure; + } + + const [txHash, txIndex, blockHash, blockNumber] = await getBlockHashAndTxHash(txResult, waitFor, this.api); + + return { isErr: false, event, event2, events, txHash, txIndex, blockHash, blockNumber } as PoolCreateTxSuccess; + } + + async createWithPoolId( + amount: BN, + root: string, + nominator: string, + bouncer: string, + poolId: number, + waitFor: WaitFor, + account: KeyringPair, + options?: Partial, + ): Promise { + const optionWrapper = options || {}; + const maybeTxResult = await new Promise>((res, _) => { + this.api.tx.nominationPools.createWithPoolId(amount, root, nominator, bouncer, poolId).signAndSend( + account, + optionWrapper, + (result: ISubmittableResult) => { + standardCallback(result, res, waitFor); + }, + ).catch((reason) => { + res(err(reason)); + }); + }); + + if (maybeTxResult.isErr()) { + return { isErr: true, reason: maybeTxResult.error } as GenericFailure; + } + const txResult = maybeTxResult.value; + + if (txResult.isError) { + return { isErr: true, reason: "The transaction was dropped or something." } as GenericFailure; + } + + const events = txResult.events; + const failed = events.find((e) => this.api.events.system.ExtrinsicFailed.is(e.event)); + if (failed != undefined) { + return { isErr: true, reason: decodeError(this.api, failed.event.data[0]) } as GenericFailure; + } + + const event = Events.NominationPools.Created.New(txResult.events); + if (event == undefined) { + return { isErr: true, reason: "Failed to find Created event." } as GenericFailure; + } + + const event2 = Events.NominationPools.Bonded.New(txResult.events); + if (event2 == undefined) { + return { isErr: true, reason: "Failed to find Bonded event." } as GenericFailure; + } + + const [txHash, txIndex, blockHash, blockNumber] = await getBlockHashAndTxHash(txResult, waitFor, this.api); + + return { isErr: false, event, event2, events, txHash, txIndex, blockHash, blockNumber } as PoolCreateWithPoolIdTxSuccess; + } + + async join( + amount: BN, + poolId: number, + waitFor: WaitFor, + account: KeyringPair, + options?: Partial, + ): Promise { + const optionWrapper = options || {}; + const maybeTxResult = await new Promise>((res, _) => { + this.api.tx.nominationPools.join(amount, poolId).signAndSend(account, optionWrapper, (result: ISubmittableResult) => { + standardCallback(result, res, waitFor); + }).catch((reason) => { + res(err(reason)); + }); + }); + + if (maybeTxResult.isErr()) { + return { isErr: true, reason: maybeTxResult.error } as GenericFailure; + } + const txResult = maybeTxResult.value; + + if (txResult.isError) { + return { isErr: true, reason: "The transaction was dropped or something." } as GenericFailure; + } + + const events = txResult.events; + const failed = events.find((e) => this.api.events.system.ExtrinsicFailed.is(e.event)); + if (failed != undefined) { + return { isErr: true, reason: decodeError(this.api, failed.event.data[0]) } as GenericFailure; + } + + const event = Events.NominationPools.Bonded.New(txResult.events); + if (event == undefined) { + return { isErr: true, reason: "Failed to find Bonded event." } as GenericFailure; + } + + const [txHash, txIndex, blockHash, blockNumber] = await getBlockHashAndTxHash(txResult, waitFor, this.api); + + return { isErr: false, event, events, txHash, txIndex, blockHash, blockNumber } as PoolJoinTxSuccess; + } + + async nominate( + poolId: number, + validators: string[], + waitFor: WaitFor, + account: KeyringPair, + options?: Partial, + ): Promise { + const optionWrapper = options || {}; + const maybeTxResult = await new Promise>((res, _) => { + this.api.tx.nominationPools.nominate(poolId, validators).signAndSend(account, optionWrapper, (result: ISubmittableResult) => { + standardCallback(result, res, waitFor); + }).catch((reason) => { + res(err(reason)); + }); + }); + + if (maybeTxResult.isErr()) { + return { isErr: true, reason: maybeTxResult.error } as GenericFailure; + } + const txResult = maybeTxResult.value; + + if (txResult.isError) { + return { isErr: true, reason: "The transaction was dropped or something." } as GenericFailure; + } + + const events = txResult.events; + const failed = events.find((e) => this.api.events.system.ExtrinsicFailed.is(e.event)); + if (failed != undefined) { + return { isErr: true, reason: decodeError(this.api, failed.event.data[0]) } as GenericFailure; + } + + const [txHash, txIndex, blockHash, blockNumber] = await getBlockHashAndTxHash(txResult, waitFor, this.api); + + return { isErr: false, events, txHash, txIndex, blockHash, blockNumber } as PoolNominateTxSuccess; } } @@ -146,7 +481,8 @@ export class Staking { return { isErr: true, reason: "The transaction was dropped or something." } as GenericFailure; } - const failed = txResult.events.find((e) => this.api.events.system.ExtrinsicFailed.is(e.event)); + const events = txResult.events; + const failed = events.find((e) => this.api.events.system.ExtrinsicFailed.is(e.event)); if (failed != undefined) { return { isErr: true, reason: decodeError(this.api, failed.event.data[0]) } as GenericFailure; } @@ -156,9 +492,9 @@ export class Staking { return { isErr: true, reason: "Failed to find Bonded event." } as GenericFailure; } - const [txHash, blockHash] = getBlockHashAndTxHash(txResult, waitFor); + const [txHash, txIndex, blockHash, blockNumber] = await getBlockHashAndTxHash(txResult, waitFor, this.api); - return { isErr: false, event, txHash, blockHash } as BondTxSuccess; + return { isErr: false, event, events, txHash, txIndex, blockHash, blockNumber } as BondTxSuccess; } async bondExtra( @@ -185,7 +521,8 @@ export class Staking { return { isErr: true, reason: "The transaction was dropped or something." } as GenericFailure; } - const failed = txResult.events.find((e) => this.api.events.system.ExtrinsicFailed.is(e.event)); + const events = txResult.events; + const failed = events.find((e) => this.api.events.system.ExtrinsicFailed.is(e.event)); if (failed != undefined) { return { isErr: true, reason: decodeError(this.api, failed.event.data[0]) } as GenericFailure; } @@ -195,9 +532,9 @@ export class Staking { return { isErr: true, reason: "Failed to find Bonded event." } as GenericFailure; } - const [txHash, blockHash] = getBlockHashAndTxHash(txResult, waitFor); + const [txHash, txIndex, blockHash, blockNumber] = await getBlockHashAndTxHash(txResult, waitFor, this.api); - return { isErr: false, event, txHash, blockHash } as BondExtraTxSuccess; + return { isErr: false, event, events, txHash, txIndex, blockHash, blockNumber } as BondExtraTxSuccess; } async chill(waitFor: WaitFor, account: KeyringPair, options?: Partial): Promise { @@ -219,7 +556,8 @@ export class Staking { return { isErr: true, reason: "The transaction was dropped or something." } as GenericFailure; } - const failed = txResult.events.find((e) => this.api.events.system.ExtrinsicFailed.is(e.event)); + const events = txResult.events; + const failed = events.find((e) => this.api.events.system.ExtrinsicFailed.is(e.event)); if (failed != undefined) { return { isErr: true, reason: decodeError(this.api, failed.event.data[0]) } as GenericFailure; } @@ -229,9 +567,9 @@ export class Staking { return { isErr: true, reason: "Failed to find Chilled event." } as GenericFailure; } - const [txHash, blockHash] = getBlockHashAndTxHash(txResult, waitFor); + const [txHash, txIndex, blockHash, blockNumber] = await getBlockHashAndTxHash(txResult, waitFor, this.api); - return { isErr: false, event, txHash, blockHash } as ChillTxSuccess; + return { isErr: false, event, events, txHash, txIndex, blockHash, blockNumber } as ChillTxSuccess; } async chillOther( @@ -258,7 +596,8 @@ export class Staking { return { isErr: true, reason: "The transaction was dropped or something." } as GenericFailure; } - const failed = txResult.events.find((e) => this.api.events.system.ExtrinsicFailed.is(e.event)); + const events = txResult.events; + const failed = events.find((e) => this.api.events.system.ExtrinsicFailed.is(e.event)); if (failed != undefined) { return { isErr: true, reason: decodeError(this.api, failed.event.data[0]) } as GenericFailure; } @@ -268,9 +607,9 @@ export class Staking { return { isErr: true, reason: "Failed to find Chilled event." } as GenericFailure; } - const [txHash, blockHash] = getBlockHashAndTxHash(txResult, waitFor); + const [txHash, txIndex, blockHash, blockNumber] = await getBlockHashAndTxHash(txResult, waitFor, this.api); - return { isErr: false, event, txHash, blockHash } as ChillOtherTxSuccess; + return { isErr: false, event, events, txHash, txIndex, blockHash, blockNumber } as ChillOtherTxSuccess; } async nominate( @@ -297,18 +636,19 @@ export class Staking { return { isErr: true, reason: "The transaction was dropped or something." } as GenericFailure; } - const failed = txResult.events.find((e) => this.api.events.system.ExtrinsicFailed.is(e.event)); + const events = txResult.events; + const failed = events.find((e) => this.api.events.system.ExtrinsicFailed.is(e.event)); if (failed != undefined) { return { isErr: true, reason: decodeError(this.api, failed.event.data[0]) } as GenericFailure; } - const [txHash, blockHash] = getBlockHashAndTxHash(txResult, waitFor); + const [txHash, txIndex, blockHash, blockNumber] = await getBlockHashAndTxHash(txResult, waitFor, this.api); const maybeTxData = await TransactionData.Staking.Nominate.New(this.api, txHash, blockHash); if (maybeTxData.isErr()) { return { isErr: true, reason: maybeTxData.error } as GenericFailure; } - return { isErr: false, txData: maybeTxData.value, txHash, blockHash } as NominateTxSuccess; + return { isErr: false, txData: maybeTxData.value, events, txHash, txIndex, blockHash, blockNumber } as NominateTxSuccess; } async unbond( @@ -335,7 +675,8 @@ export class Staking { return { isErr: true, reason: "The transaction was dropped or something." } as GenericFailure; } - const failed = txResult.events.find((e) => this.api.events.system.ExtrinsicFailed.is(e.event)); + const events = txResult.events; + const failed = events.find((e) => this.api.events.system.ExtrinsicFailed.is(e.event)); if (failed != undefined) { return { isErr: true, reason: decodeError(this.api, failed.event.data[0]) } as GenericFailure; } @@ -345,9 +686,9 @@ export class Staking { return { isErr: true, reason: "Failed to find Unbonded event." } as GenericFailure; } - const [txHash, blockHash] = getBlockHashAndTxHash(txResult, waitFor); + const [txHash, txIndex, blockHash, blockNumber] = await getBlockHashAndTxHash(txResult, waitFor, this.api); - return { isErr: false, event, txHash, blockHash } as UnbondTxSuccess; + return { isErr: false, event, events, txHash, txIndex, blockHash, blockNumber } as UnbondTxSuccess; } async validate( @@ -356,7 +697,7 @@ export class Staking { waitFor: WaitFor, account: KeyringPair, options?: Partial, - ): Promise { + ): Promise { const maybeCommission = commissionNumberToPerbill(commission); if (maybeCommission.isErr()) { return { isErr: true, reason: maybeCommission.error } as GenericFailure; @@ -381,7 +722,8 @@ export class Staking { return { isErr: true, reason: "The transaction was dropped or something." } as GenericFailure; } - const failed = txResult.events.find((e) => this.api.events.system.ExtrinsicFailed.is(e.event)); + const events = txResult.events; + const failed = events.find((e) => this.api.events.system.ExtrinsicFailed.is(e.event)); if (failed != undefined) { return { isErr: true, reason: decodeError(this.api, failed.event.data[0]) } as GenericFailure; } @@ -391,9 +733,9 @@ export class Staking { return { isErr: true, reason: "Failed to find ValidatorPrefsSet event." } as GenericFailure; } - const [txHash, blockHash] = getBlockHashAndTxHash(txResult, waitFor); + const [txHash, txIndex, blockHash, blockNumber] = await getBlockHashAndTxHash(txResult, waitFor, this.api); - return { isErr: false, event, txHash, blockHash } as ValidatexSuccess; + return { isErr: false, event, events, txHash, txIndex, blockHash, blockNumber } as ValidateTxSuccess; } } @@ -429,7 +771,8 @@ export class Balances { return { isErr: true, reason: "The transaction was dropped or something." } as GenericFailure; } - const failed = txResult.events.find((e) => this.api.events.system.ExtrinsicFailed.is(e.event)); + const events = txResult.events; + const failed = events.find((e) => this.api.events.system.ExtrinsicFailed.is(e.event)); if (failed != undefined) { return { isErr: true, reason: decodeError(this.api, failed.event.data[0]) } as GenericFailure; } @@ -440,9 +783,9 @@ export class Balances { } const event2 = Events.System.KilledAccount.New(txResult.events); - const [txHash, blockHash] = getBlockHashAndTxHash(txResult, waitFor); + const [txHash, txIndex, blockHash, blockNumber] = await getBlockHashAndTxHash(txResult, waitFor, this.api); - return { isErr: false, event, event2, txHash, blockHash } as TransferAllTxSuccess; + return { isErr: false, event, event2, events, txHash, txIndex, blockHash, blockNumber } as TransferAllTxSuccess; } async transferAllowDeath( @@ -470,7 +813,8 @@ export class Balances { return { isErr: true, reason: "The transaction was dropped or something." } as GenericFailure; } - const failed = txResult.events.find((e) => this.api.events.system.ExtrinsicFailed.is(e.event)); + const events = txResult.events; + const failed = events.find((e) => this.api.events.system.ExtrinsicFailed.is(e.event)); if (failed != undefined) { return { isErr: true, reason: decodeError(this.api, failed.event.data[0]) } as GenericFailure; } @@ -481,9 +825,9 @@ export class Balances { } const event2 = Events.System.KilledAccount.New(txResult.events); - const [txHash, blockHash] = getBlockHashAndTxHash(txResult, waitFor); + const [txHash, txIndex, blockHash, blockNumber] = await getBlockHashAndTxHash(txResult, waitFor, this.api); - return { isErr: false, event, event2, txHash, blockHash } as TransferAllowDeathTxSuccess; + return { isErr: false, event, event2, events, txHash, txIndex, blockHash, blockNumber } as TransferAllowDeathTxSuccess; } async transferKeepAlive( @@ -511,7 +855,8 @@ export class Balances { return { isErr: true, reason: "The transaction was dropped or something." } as GenericFailure; } - const failed = txResult.events.find((e) => this.api.events.system.ExtrinsicFailed.is(e.event)); + const events = txResult.events; + const failed = events.find((e) => this.api.events.system.ExtrinsicFailed.is(e.event)); if (failed != undefined) { return { isErr: true, reason: decodeError(this.api, failed.event.data[0]) } as GenericFailure; } @@ -521,9 +866,9 @@ export class Balances { return { isErr: true, reason: "Failed to find Transfer event." } as GenericFailure; } - const [txHash, blockHash] = getBlockHashAndTxHash(txResult, waitFor); + const [txHash, txIndex, blockHash, blockNumber] = await getBlockHashAndTxHash(txResult, waitFor, this.api); - return { isErr: false, event, txHash, blockHash } as TransferKeepAliveTxSuccess; + return { isErr: false, event, events, txHash, txIndex, blockHash, blockNumber } as TransferKeepAliveTxSuccess; } } @@ -558,7 +903,8 @@ export class DataAvailability { return { isErr: true, reason: "The transaction was dropped or something." } as GenericFailure; } - const failed = txResult.events.find((e) => this.api.events.system.ExtrinsicFailed.is(e.event)); + const events = txResult.events; + const failed = events.find((e) => this.api.events.system.ExtrinsicFailed.is(e.event)); if (failed != undefined) { return { isErr: true, reason: decodeError(this.api, failed.event.data[0]) } as GenericFailure; } @@ -568,14 +914,14 @@ export class DataAvailability { return { isErr: true, reason: "Failed to find DataSubmitted event." } as GenericFailure; } - const [txHash, blockHash] = getBlockHashAndTxHash(txResult, waitFor); + const [txHash, txIndex, blockHash, blockNumber] = await getBlockHashAndTxHash(txResult, waitFor, this.api); const maybeTxData = await TransactionData.DataAvailability.SubmitData.New(this.api, txHash, blockHash); if (maybeTxData.isErr()) { return { isErr: true, reason: maybeTxData.error } as GenericFailure; } - return { isErr: false, txData: maybeTxData.value, event, txHash, blockHash } as SubmitDataTxSuccess; + return { isErr: false, txData: maybeTxData.value, event, events, txHash, txIndex, blockHash, blockNumber } as SubmitDataTxSuccess; } async createApplicationKey( @@ -602,7 +948,8 @@ export class DataAvailability { return { isErr: true, reason: "The transaction was dropped or something." } as GenericFailure; } - const failed = txResult.events.find((e) => this.api.events.system.ExtrinsicFailed.is(e.event)); + const events = txResult.events; + const failed = events.find((e) => this.api.events.system.ExtrinsicFailed.is(e.event)); if (failed != undefined) { return { isErr: true, reason: decodeError(this.api, failed.event.data[0]) } as GenericFailure; } @@ -612,9 +959,9 @@ export class DataAvailability { return { isErr: true, reason: "Failed to find ApplicationKeyCreated event." } as GenericFailure; } - const [txHash, blockHash] = getBlockHashAndTxHash(txResult, waitFor); + const [txHash, txIndex, blockHash, blockNumber] = await getBlockHashAndTxHash(txResult, waitFor, this.api); - return { isErr: false, event, txHash, blockHash } as CreateApplicationKeyTxSuccess; + return { isErr: false, event, events, txHash, txIndex, blockHash, blockNumber } as CreateApplicationKeyTxSuccess; } async setApplicationKey( @@ -643,7 +990,8 @@ export class DataAvailability { return { isErr: true, reason: "The transaction was dropped or something." } as GenericFailure; } - const failed = txResult.events.find((e) => this.api.events.system.ExtrinsicFailed.is(e.event)); + const events = txResult.events; + const failed = events.find((e) => this.api.events.system.ExtrinsicFailed.is(e.event)); if (failed != undefined) { return { isErr: true, reason: decodeError(this.api, failed.event.data[0]) } as GenericFailure; } @@ -663,9 +1011,9 @@ export class DataAvailability { return { isErr: true, reason: "Failed to find ApplicationKeySet event." } as GenericFailure; } - const [txHash, blockHash] = getBlockHashAndTxHash(txResult, waitFor); + const [txHash, txIndex, blockHash, blockNumber] = await getBlockHashAndTxHash(txResult, waitFor, this.api); - return { isErr: false, event, txHash, blockHash } as SetApplicationKeyTxSuccess; + return { isErr: false, event, events, txHash, txIndex, blockHash, blockNumber } as SetApplicationKeyTxSuccess; } async submitBlockLengthProposal( @@ -694,7 +1042,8 @@ export class DataAvailability { return { isErr: true, reason: "The transaction was dropped or something." } as GenericFailure; } - const failed = txResult.events.find((e) => this.api.events.system.ExtrinsicFailed.is(e.event)); + const events = txResult.events; + const failed = events.find((e) => this.api.events.system.ExtrinsicFailed.is(e.event)); if (failed != undefined) { return { isErr: true, reason: decodeError(this.api, failed.event.data[0]) } as GenericFailure; } @@ -714,9 +1063,9 @@ export class DataAvailability { return { isErr: true, reason: "Failed to find BlockLengthProposalSubmitted event." } as GenericFailure; } - const [txHash, blockHash] = getBlockHashAndTxHash(txResult, waitFor); + const [txHash, txIndex, blockHash, blockNumber] = await getBlockHashAndTxHash(txResult, waitFor, this.api); - return { isErr: false, event, txHash, blockHash } as SubmitBlockLengthProposalTxSuccess; + return { isErr: false, event, events, txHash, txIndex, blockHash, blockNumber } as SubmitBlockLengthProposalTxSuccess; } async setSubmitDataFeeModifier( @@ -744,6 +1093,7 @@ export class DataAvailability { return { isErr: true, reason: "The transaction was dropped or something." } as GenericFailure; } + const events = txResult.events; const failed = txResult.events.find((e) => this.api.events.system.ExtrinsicFailed.is(e.event)); if (failed != undefined) { return { isErr: true, reason: decodeError(this.api, failed.event.data[0]) } as GenericFailure; @@ -764,8 +1114,8 @@ export class DataAvailability { return { isErr: true, reason: "Failed to find SubmitDataFeeModifierSet event." } as GenericFailure; } - const [txHash, blockHash] = getBlockHashAndTxHash(txResult, waitFor); + const [txHash, txIndex, blockHash, blockNumber] = await getBlockHashAndTxHash(txResult, waitFor, this.api); - return { isErr: false, event, txHash, blockHash } as SetSubmitDataFeeModifierTxSuccess; + return { isErr: false, event, events, txHash, txIndex, blockHash, blockNumber } as SetSubmitDataFeeModifierTxSuccess; } } diff --git a/avail-rust/docs/extrinsics/README.md b/avail-rust/docs/extrinsics/README.md index 5bd97c804..fba8acc00 100644 --- a/avail-rust/docs/extrinsics/README.md +++ b/avail-rust/docs/extrinsics/README.md @@ -1544,7 +1544,7 @@ async fn create(&self, amount: u128, root: &str, nominator: &str, bouncer: &str, | parameter | type | optional | description | | --------- | ----------- | -------- | -------------------------------------------------- | | amount | u128 | false | The amount of funds to delegate to the pool | -| root | WaitFor | false | The account to set as [`PoolRoles::root`] | +| root | &str | false | The account to set as [`PoolRoles::root`] | | nominator | &str | false | The account to set as the [`PoolRoles::nominator`] | | bouncer | &str | false | The account to set as the [`PoolRoles::bouncer`] | | waitFor | WaitFor | false | wait for block inclusion or finalization | @@ -1658,7 +1658,7 @@ async fn create_with_pool_id(&self, amount: u128, root: &str, nominator: &str, b | parameter | type | optional | description | | --------- | ----------- | -------- | -------------------------------------------------- | | amount | u128 | false | The amount of funds to delegate to the pool | -| root | WaitFor | false | The account to set as [`PoolRoles::root`] | +| root | &str | false | The account to set as [`PoolRoles::root`] | | nominator | &str | false | The account to set as the [`PoolRoles::nominator`] | | bouncer | &str | false | The account to set as the [`PoolRoles::bouncer`] | | pool id | u32 | false | pool id | From 383fb7214d38b782c29a1514ed52d8479285c5ec Mon Sep 17 00:00:00 2001 From: Toufeeq Pasha <47236805+ToufeeqP@users.noreply.github.com> Date: Thu, 12 Sep 2024 14:45:59 +0530 Subject: [PATCH 4/4] updated actions/upload-artifact to v4 (#659) --- .github/workflows/default.yml | 2 +- .github/workflows/weights.yml | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/default.yml b/.github/workflows/default.yml index 6486530ed..9e2f3ca11 100644 --- a/.github/workflows/default.yml +++ b/.github/workflows/default.yml @@ -97,7 +97,7 @@ jobs: run: cargo build --release -p avail-node - name: Upload avail-node binary - uses: actions/upload-artifact@v2 + uses: actions/upload-artifact@v4 with: name: avail-node path: target/release/avail-node diff --git a/.github/workflows/weights.yml b/.github/workflows/weights.yml index b892ac71c..07c35b650 100644 --- a/.github/workflows/weights.yml +++ b/.github/workflows/weights.yml @@ -60,7 +60,7 @@ jobs: $EXTRA $OUR_PALLETS ./scripts/run_benchmarks.sh - name: Upload output as artifact - uses: actions/upload-artifact@v2 + uses: actions/upload-artifact@v4 with: name: weights-result path: ./output/ \ No newline at end of file