From 0536cd3294c2726cbd57dedc13f990b08f179736 Mon Sep 17 00:00:00 2001 From: Marko Petrlic Date: Wed, 16 Oct 2024 13:18:15 +0200 Subject: [PATCH 1/8] Added multisig example --- avail-js/docs/advanced_examples/multisig.ts | 146 +++++++++++++ avail-js/package-lock.json | 4 +- avail-js/src/sdk/index.ts | 7 + avail-js/src/sdk/utils.ts | 26 --- avail-js/src/sdk/utils/index.ts | 223 ++++++++++++++++++++ 5 files changed, 378 insertions(+), 28 deletions(-) create mode 100644 avail-js/docs/advanced_examples/multisig.ts delete mode 100644 avail-js/src/sdk/utils.ts create mode 100644 avail-js/src/sdk/utils/index.ts diff --git a/avail-js/docs/advanced_examples/multisig.ts b/avail-js/docs/advanced_examples/multisig.ts new file mode 100644 index 000000000..959411bfa --- /dev/null +++ b/avail-js/docs/advanced_examples/multisig.ts @@ -0,0 +1,146 @@ +import { SDK, WaitFor, Keyring, BN, KeyringPair, Weight, ParsedTxResult, MultisigTimepoint } from "./../../src/index" + +const main = async () => { + const providerEndpoint = "ws://127.0.0.1:9944" + const sdk = await SDK.New(providerEndpoint) + + // Multisig Signatures + const alice = new Keyring({ type: "sr25519" }).addFromUri("//Alice") + const bob = new Keyring({ type: "sr25519" }).addFromUri("//Bob") + const charlie = new Keyring({ type: "sr25519" }).addFromUri("//Charlie") + + // Create Multisig Account + const threshold = 3 + const multisigAddress = sdk.util.generateMultisig([alice.address, bob.address, charlie.address], threshold) + await fundMultisigAccount(sdk, alice, multisigAddress) + + // Define what action will be taken by the multisig account + const amount = new BN(10).pow(new BN(18)) // one Avail + const call = sdk.api.tx.balances.transferKeepAlive(multisigAddress, amount) + // Data needed for multisig approval and execution + const callHash = call.method.hash.toString() + const callData = call.unwrap().toHex() + const maxWeight = (await call.paymentInfo(alice.address)).weight + + /* + The first signature creates and approves the multisig transaction. All the next signatures (besides the last one) should + use the `nextApproval` function to approve the tx. The last signature should use the `lastApproval` function to approve + and execute the multisig tx. + + In practice it means the following: + - If the threshold is 2 do the following: + - firstApproval + - lastApproval + - If the threshold is 4 do the following: + - firstApproval + - nextApproval + - nextApproval + - lastApproval + */ + + // Create New Multisig + const call1signatures = sdk.util.sortMultisigAddresses([bob.address, charlie.address]) + const firstResult = await firstApproval(sdk, alice, callHash, threshold, call1signatures, maxWeight) + + // Approve existing Multisig + const timepoint: MultisigTimepoint = { height: firstResult.blockNumber, index: firstResult.txIndex } + const call2signatures = sdk.util.sortMultisigAddresses([alice.address, charlie.address]) + const _secondResult = await nextApproval(sdk, bob, callHash, threshold, call2signatures, timepoint) + + // Execute Multisig + const call3signatures = sdk.util.sortMultisigAddresses([alice.address, bob.address]) + const _thirdResult = await lastApproval(sdk, charlie, threshold, call3signatures, timepoint, callData, maxWeight) + + process.exit() +} + +async function fundMultisigAccount(sdk: SDK, alice: KeyringPair, multisigAddress: string): Promise { + console.log("Funding multisig account...") + const amount = new BN(10).pow(new BN(18)).mul(new BN(100)) // 100 Avail + const result = await sdk.tx.balances.transferKeepAlive(multisigAddress, amount, WaitFor.BlockInclusion, alice) + if (result.isErr) { + console.log(result.reason) + process.exit(1) + } + + return multisigAddress +} + +async function firstApproval( + sdk: SDK, + account: KeyringPair, + callHash: string, + threshold: number, + otherSignatures: string[], + maxWeight: Weight, +): Promise { + console.log("Alice is creating a Multisig Transaction...") + + const maybeTxResult = await sdk.util.firstMultisigApproval( + callHash, + threshold, + otherSignatures, + maxWeight, + WaitFor.BlockInclusion, + account, + ) + if (maybeTxResult.isErr()) { + console.log(maybeTxResult.error) + process.exit(1) + } + return maybeTxResult.value +} + +async function nextApproval( + sdk: SDK, + account: KeyringPair, + callHash: string, + threshold: number, + otherSignatures: string[], + timepoint: MultisigTimepoint, +): Promise { + console.log("Bob is approving the existing Multisig Transaction...") + + const maybeTxResult = await sdk.util.nextMultisigApproval( + callHash, + threshold, + otherSignatures, + timepoint, + WaitFor.BlockInclusion, + account, + ) + if (maybeTxResult.isErr()) { + console.log(maybeTxResult.error) + process.exit(1) + } + return maybeTxResult.value +} + +async function lastApproval( + sdk: SDK, + account: KeyringPair, + threshold: number, + otherSignatures: string[], + timepoint: MultisigTimepoint, + callData: string, + maxWeight: Weight, +): Promise { + console.log("Charlie is approving and executing the existing Multisig Transaction...") + + const maybeTxResult = await sdk.util.lastMultisigApproval( + threshold, + otherSignatures, + timepoint, + callData, + maxWeight, + WaitFor.BlockInclusion, + account, + ) + if (maybeTxResult.isErr()) { + console.log(maybeTxResult.error) + process.exit(1) + } + return maybeTxResult.value +} + +main() diff --git a/avail-js/package-lock.json b/avail-js/package-lock.json index 9087c1e43..eaf13a764 100644 --- a/avail-js/package-lock.json +++ b/avail-js/package-lock.json @@ -1,12 +1,12 @@ { "name": "avail-js-sdk", - "version": "0.2.17", + "version": "0.2.18", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "avail-js-sdk", - "version": "0.2.17", + "version": "0.2.18", "license": "ISC", "dependencies": { "@polkadot/api": "^10.11.3", diff --git a/avail-js/src/sdk/index.ts b/avail-js/src/sdk/index.ts index a06ac9425..baef63a51 100644 --- a/avail-js/src/sdk/index.ts +++ b/avail-js/src/sdk/index.ts @@ -1,13 +1,18 @@ import { ApiPromise } from "@polkadot/api" import { initialize } from "../chain" import { Transactions } from "./transactions" +import { Utils } from "./utils" export * as sdkTransactions from "./transactions" export * as sdkTransactionData from "./transaction_data" export { BN } from "@polkadot/util" export { Keyring } from "@polkadot/api" +export { KeyringPair } from "@polkadot/keyring/types" export { Bytes } from "@polkadot/types-codec" +export { H256, Weight } from "@polkadot/types/interfaces" +export { ParsedTxResult, MultisigTimepoint } from "./utils" + export { WaitFor, StakingRewardDestination, @@ -21,6 +26,7 @@ export { export class SDK { api: ApiPromise tx: Transactions + util: Utils static async New(endpoint: string): Promise { const api = await initialize(endpoint) @@ -30,5 +36,6 @@ export class SDK { private constructor(api: ApiPromise) { this.api = api this.tx = new Transactions(api) + this.util = new Utils(api) } } diff --git a/avail-js/src/sdk/utils.ts b/avail-js/src/sdk/utils.ts deleted file mode 100644 index e6beb5258..000000000 --- a/avail-js/src/sdk/utils.ts +++ /dev/null @@ -1,26 +0,0 @@ -import { err, ok, Result } from "neverthrow" - -/** - * Converts a commission percentage to a perbill format. - * - * @param {number} value - The commission percentage (0-100). - * @return {string} The commission value in perbill format. - * @throws {Error} If the value is not an integer or is out of the 0-100 range. - */ -export function commissionNumberToPerbill(value: number): Result { - if (!Number.isInteger(value)) { - return err("Commission cannot have decimal place. It needs to be a whole number.") - } - - if (value < 0 || value > 100) { - return err("Commission is limited to the following range: 0 - 100. It cannot be less than 0 or more than 100.") - } - - let commission = value.toString().concat("0000000") - // For some reason 0 commission is not defined as "0" but as "1". - if (commission == "00000000") { - commission = "1" - } - - return ok(commission) -} diff --git a/avail-js/src/sdk/utils/index.ts b/avail-js/src/sdk/utils/index.ts new file mode 100644 index 000000000..abbf942ce --- /dev/null +++ b/avail-js/src/sdk/utils/index.ts @@ -0,0 +1,223 @@ +import { ApiPromise } from "@polkadot/api" +import { err, ok, Result } from "neverthrow" +import { ISubmittableResult } from "@polkadot/types/types/extrinsic" +import { EventRecord, H256, Weight } from "@polkadot/types/interfaces" +import { decodeError } from "../../helpers" +import { getBlockHashAndTxHash, standardCallback, WaitFor } from "../transactions/common" +import { createKeyMulti, encodeAddress, sortAddresses } from "@polkadot/util-crypto" +import { KeyringPair } from "@polkadot/keyring/types" +import { SignerOptions } from "@polkadot/api/types" + +export class ParsedTxResult { + constructor( + public txResult: ISubmittableResult, + public events: EventRecord[], + public txHash: H256, + public txIndex: number, + public blockHash: H256, + public blockNumber: number, + ) {} +} + +export interface MultisigTimepoint { + height: number + index: number +} + +export class Utils { + private api: ApiPromise + + constructor(api: ApiPromise) { + this.api = api + } + + /// Parses a transaction result. Helper function to get transaction details on + /// transaction success or an error if the transaction failed + async parseTransactionResult( + txResult: ISubmittableResult, + waitFor: WaitFor, + ): Promise> { + return await parseTransactionResult(this.api, txResult, waitFor) + } + + /** + * Converts a commission percentage to a perbill format. + * + * @param {number} value - The commission percentage (0-100). + * @return {string} The commission value in perbill format. + * @throws {Error} If the value is not an integer or is out of the 0-100 range. + */ + commissionNumberToPerbill(value: number): Result { + return commissionNumberToPerbill(value) + } + + /// Generates a multisig account + generateMultisig(addresses: string[], threshold: number): string { + return generateMultisig(addresses, threshold) + } + + /// Creates and approves a multisig transaction + async firstMultisigApproval( + callHash: string, + threshold: number, + otherSignatures: string[], + maxWeight: Weight, + waitFor: WaitFor, + account: KeyringPair, + options?: Partial, + ): Promise> { + const optionWrapper = options || {} + const maybeTxResult = await new Promise>((res, _) => { + this.api.tx.multisig + .approveAsMulti(threshold, otherSignatures, null, callHash, maxWeight) + .signAndSend(account, optionWrapper, (result: ISubmittableResult) => { + standardCallback(result, res, waitFor) + }) + .catch((reason) => { + res(err(reason)) + }) + }) + + if (maybeTxResult.isErr()) { + return err(maybeTxResult.error) + } + const txResult = maybeTxResult.value + const maybeParsed = await this.parseTransactionResult(txResult, waitFor) + if (maybeParsed.isErr()) { + return err(maybeParsed.error) + } + const parsed = maybeParsed.value + + return ok(parsed) + } + + /// Approves an existing multisig transaction + async nextMultisigApproval( + callHash: string, + threshold: number, + otherSignatures: string[], + timepoint: MultisigTimepoint, + waitFor: WaitFor, + account: KeyringPair, + options?: Partial, + ): Promise> { + const maxWeight = { refTime: 0, proofSize: 0 } + const optionWrapper = options || {} + const maybeTxResult = await new Promise>((res, _) => { + this.api.tx.multisig + .approveAsMulti(threshold, otherSignatures, timepoint, callHash, maxWeight) + .signAndSend(account, optionWrapper, (result: ISubmittableResult) => { + standardCallback(result, res, waitFor) + }) + .catch((reason) => { + res(err(reason)) + }) + }) + + if (maybeTxResult.isErr()) { + return err(maybeTxResult.error) + } + const txResult = maybeTxResult.value + const maybeParsed = await this.parseTransactionResult(txResult, waitFor) + if (maybeParsed.isErr()) { + return err(maybeParsed.error) + } + const parsed = maybeParsed.value + + return ok(parsed) + } + + /// Approves and executes an existing multisig transaction + async lastMultisigApproval( + threshold: number, + otherSignatures: string[], + timepoint: MultisigTimepoint, + callData: string, + maxWeight: Weight, + waitFor: WaitFor, + account: KeyringPair, + options?: Partial, + ): Promise> { + const optionWrapper = options || {} + const maybeTxResult = await new Promise>((res, _) => { + this.api.tx.multisig + .asMulti(threshold, otherSignatures, timepoint, callData, maxWeight) + .signAndSend(account, optionWrapper, (result: ISubmittableResult) => { + standardCallback(result, res, waitFor) + }) + .catch((reason) => { + res(err(reason)) + }) + }) + + if (maybeTxResult.isErr()) { + return err(maybeTxResult.error) + } + const txResult = maybeTxResult.value + const maybeParsed = await this.parseTransactionResult(txResult, waitFor) + if (maybeParsed.isErr()) { + return err(maybeParsed.error) + } + const parsed = maybeParsed.value + + return ok(parsed) + } + + /// Sorts multisig address so that ce be used for other multisig functions + sortMultisigAddresses(addresses: string[]): string[] { + return sortMultisigAddresses(addresses) + } +} + +export async function parseTransactionResult( + api: ApiPromise, + txResult: ISubmittableResult, + waitFor: WaitFor, +): Promise> { + if (txResult.isError) { + return err("The transaction was dropped or something.") + } + + const failed = txResult.events.find((e) => api.events.system.ExtrinsicFailed.is(e.event)) + if (failed != undefined) { + return err(decodeError(api, failed.event.data[0])) + } + + const events = txResult.events + const [txHash, txIndex, blockHash, blockNumber] = await getBlockHashAndTxHash(txResult, waitFor, api) + + return ok(new ParsedTxResult(txResult, events, txHash, txIndex, blockHash, blockNumber)) +} + +export function commissionNumberToPerbill(value: number): Result { + if (!Number.isInteger(value)) { + return err("Commission cannot have decimal place. It needs to be a whole number.") + } + + if (value < 0 || value > 100) { + return err("Commission is limited to the following range: 0 - 100. It cannot be less than 0 or more than 100.") + } + + let commission = value.toString().concat("0000000") + // For some reason 0 commission is not defined as "0" but as "1". + if (commission == "00000000") { + commission = "1" + } + + return ok(commission) +} + +export function generateMultisig(addresses: string[], threshold: number): string { + const SS58Prefix = 42 + + const multiAddress = createKeyMulti(addresses, threshold) + const Ss58Address = encodeAddress(multiAddress, SS58Prefix) + + return Ss58Address +} + +export function sortMultisigAddresses(addresses: string[]): string[] { + const SS58Prefix = 42 + + return sortAddresses(addresses, SS58Prefix) +} From 4cdf3a9ea8e144d2cc531b9b5fed9f5739da3904 Mon Sep 17 00:00:00 2001 From: Marko Petrlic Date: Wed, 16 Oct 2024 14:58:50 +0200 Subject: [PATCH 2/8] Existing structs are now simpler --- avail-js/docs/advanced_examples/multisig.ts | 8 +- avail-js/src/sdk/index.ts | 2 +- avail-js/src/sdk/transactions/balances.ts | 139 ++--- avail-js/src/sdk/transactions/common.ts | 8 +- avail-js/src/sdk/transactions/da.ts | 230 +++----- avail-js/src/sdk/transactions/multisig.ts | 0 .../src/sdk/transactions/nomination_pools.ts | 536 ++++++------------ avail-js/src/sdk/transactions/staking.ts | 279 ++++----- avail-js/src/sdk/utils/index.ts | 40 +- 9 files changed, 460 insertions(+), 782 deletions(-) create mode 100644 avail-js/src/sdk/transactions/multisig.ts diff --git a/avail-js/docs/advanced_examples/multisig.ts b/avail-js/docs/advanced_examples/multisig.ts index 959411bfa..6b7d61f86 100644 --- a/avail-js/docs/advanced_examples/multisig.ts +++ b/avail-js/docs/advanced_examples/multisig.ts @@ -1,4 +1,4 @@ -import { SDK, WaitFor, Keyring, BN, KeyringPair, Weight, ParsedTxResult, MultisigTimepoint } from "./../../src/index" +import { SDK, WaitFor, Keyring, BN, KeyringPair, Weight, TxResultDetails, MultisigTimepoint } from "./../../src/index" const main = async () => { const providerEndpoint = "ws://127.0.0.1:9944" @@ -73,7 +73,7 @@ async function firstApproval( threshold: number, otherSignatures: string[], maxWeight: Weight, -): Promise { +): Promise { console.log("Alice is creating a Multisig Transaction...") const maybeTxResult = await sdk.util.firstMultisigApproval( @@ -98,7 +98,7 @@ async function nextApproval( threshold: number, otherSignatures: string[], timepoint: MultisigTimepoint, -): Promise { +): Promise { console.log("Bob is approving the existing Multisig Transaction...") const maybeTxResult = await sdk.util.nextMultisigApproval( @@ -124,7 +124,7 @@ async function lastApproval( timepoint: MultisigTimepoint, callData: string, maxWeight: Weight, -): Promise { +): Promise { console.log("Charlie is approving and executing the existing Multisig Transaction...") const maybeTxResult = await sdk.util.lastMultisigApproval( diff --git a/avail-js/src/sdk/index.ts b/avail-js/src/sdk/index.ts index baef63a51..8bcada9b6 100644 --- a/avail-js/src/sdk/index.ts +++ b/avail-js/src/sdk/index.ts @@ -11,7 +11,7 @@ export { Keyring } from "@polkadot/api" export { KeyringPair } from "@polkadot/keyring/types" export { Bytes } from "@polkadot/types-codec" export { H256, Weight } from "@polkadot/types/interfaces" -export { ParsedTxResult, MultisigTimepoint } from "./utils" +export { TxResultDetails, MultisigTimepoint } from "./utils" export { WaitFor, diff --git a/avail-js/src/sdk/transactions/balances.ts b/avail-js/src/sdk/transactions/balances.ts index 2112b3db4..34573ace5 100644 --- a/avail-js/src/sdk/transactions/balances.ts +++ b/avail-js/src/sdk/transactions/balances.ts @@ -1,42 +1,35 @@ import { ApiPromise } from "@polkadot/api" import { ISubmittableResult } from "@polkadot/types/types/extrinsic" -import { H256, EventRecord } from "@polkadot/types/interfaces/types" +import { EventRecord } from "@polkadot/types/interfaces/types" import { BN } from "@polkadot/util" import { KeyringPair } from "@polkadot/keyring/types" -import { err, Result } from "neverthrow" +import { err, Result, ok } from "neverthrow" import { SignerOptions } from "@polkadot/api/types" -import { decodeError } from "../../helpers" -import { WaitFor, GenericFailure, standardCallback, getBlockHashAndTxHash } from "./common" - -type TransferKeepAliveTxSuccess = { - isErr: false - event: Events.TransferEvent - events: EventRecord[] - txHash: H256 - txIndex: number - blockHash: H256 - blockNumber: number +import { WaitFor, standardCallback, TransactionFailed } from "./common" +import { parseTransactionResult, TxResultDetails } from "../utils" + +export class TransferKeepAliveTx { + constructor( + public event: Events.TransferEvent, + public details: TxResultDetails, + ) {} } -type TransferAllowDeathTxSuccess = { - isErr: false - event: Events.TransferEvent - event2?: Events.KilledAccount - events: EventRecord[] - txHash: H256 - txIndex: number - blockHash: H256 - blockNumber: number + +export class TransferAllowDeathTx { + constructor( + public event: Events.TransferEvent, + public event2: Events.KilledAccount | undefined, + public details: TxResultDetails, + ) {} } -type TransferAllTxSuccess = { - isErr: false - event: Events.TransferEvent - event2?: Events.KilledAccount - events: EventRecord[] - txHash: H256 - txIndex: number - blockHash: H256 - blockNumber: number + +export class TransferAllTx { + constructor( + public event: Events.TransferEvent, + public event2: Events.KilledAccount | undefined, + public details: TxResultDetails, + ) {} } export class Balances { @@ -52,7 +45,7 @@ export class Balances { waitFor: WaitFor, account: KeyringPair, options?: Partial, - ): Promise { + ): Promise> { const optionWrapper = options || {} const maybeTxResult = await new Promise>((res, _) => { this.api.tx.balances @@ -66,29 +59,22 @@ export class Balances { }) if (maybeTxResult.isErr()) { - return { isErr: true, reason: maybeTxResult.error } as GenericFailure + return err(new TransactionFailed(maybeTxResult.error, null)) } const txResult = maybeTxResult.value - - if (txResult.isError) { - return { isErr: true, reason: "The transaction was dropped or something." } as GenericFailure + const maybeParsed = await parseTransactionResult(this.api, txResult, waitFor) + if (maybeParsed.isErr()) { + return err(maybeParsed.error) } + const details = maybeParsed.value - 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 - } - - const event = Events.TransferEvent.New(txResult.events) + const event = Events.TransferEvent.New(details.events) if (event == undefined) { - return { isErr: true, reason: "Failed to find Transfer event." } as GenericFailure + return err(new TransactionFailed("Failed to find Transfer event", details)) } const event2 = Events.KilledAccount.New(txResult.events) - const events = txResult.events - const [txHash, txIndex, blockHash, blockNumber] = await getBlockHashAndTxHash(txResult, waitFor, this.api) - - return { isErr: false, event, event2, events, txHash, txIndex, blockHash, blockNumber } as TransferAllTxSuccess + return ok(new TransferAllTx(event, event2, details)) } async transferAllowDeath( @@ -97,7 +83,7 @@ export class Balances { waitFor: WaitFor, account: KeyringPair, options?: Partial, - ): Promise { + ): Promise> { const optionWrapper = options || {} const maybeTxResult = await new Promise>((res, _) => { this.api.tx.balances @@ -111,38 +97,22 @@ export class Balances { }) if (maybeTxResult.isErr()) { - return { isErr: true, reason: maybeTxResult.error } as GenericFailure + return err(new TransactionFailed(maybeTxResult.error, null)) } const txResult = maybeTxResult.value - - if (txResult.isError) { - return { isErr: true, reason: "The transaction was dropped or something." } as GenericFailure + const maybeParsed = await parseTransactionResult(this.api, txResult, waitFor) + if (maybeParsed.isErr()) { + return err(maybeParsed.error) } + const details = maybeParsed.value - 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 - } - - const event = Events.TransferEvent.New(txResult.events) + const event = Events.TransferEvent.New(details.events) if (event == undefined) { - return { isErr: true, reason: "Failed to find Transfer event." } as GenericFailure + return err(new TransactionFailed("Failed to find Transfer event", details)) } const event2 = Events.KilledAccount.New(txResult.events) - const events = txResult.events - const [txHash, txIndex, blockHash, blockNumber] = await getBlockHashAndTxHash(txResult, waitFor, this.api) - - return { - isErr: false, - event, - event2, - events, - txHash, - txIndex, - blockHash, - blockNumber, - } as TransferAllowDeathTxSuccess + return ok(new TransferAllowDeathTx(event, event2, details)) } async transferKeepAlive( @@ -151,7 +121,7 @@ export class Balances { waitFor: WaitFor, account: KeyringPair, options?: Partial, - ): Promise { + ): Promise> { const optionWrapper = options || {} const maybeTxResult = await new Promise>((res, _) => { this.api.tx.balances @@ -165,28 +135,21 @@ export class Balances { }) if (maybeTxResult.isErr()) { - return { isErr: true, reason: maybeTxResult.error } as GenericFailure + return err(new TransactionFailed(maybeTxResult.error, null)) } const txResult = maybeTxResult.value - - if (txResult.isError) { - return { isErr: true, reason: "The transaction was dropped or something." } as GenericFailure + const maybeParsed = await parseTransactionResult(this.api, txResult, waitFor) + if (maybeParsed.isErr()) { + return err(maybeParsed.error) } + const details = maybeParsed.value - 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 - } - - const event = Events.TransferEvent.New(txResult.events) + const event = Events.TransferEvent.New(details.events) if (event == undefined) { - return { isErr: true, reason: "Failed to find Transfer event." } as GenericFailure + return err(new TransactionFailed("Failed to find Transfer event", details)) } - const events = txResult.events - const [txHash, txIndex, blockHash, blockNumber] = await getBlockHashAndTxHash(txResult, waitFor, this.api) - - return { isErr: false, event, events, txHash, txIndex, blockHash, blockNumber } as TransferKeepAliveTxSuccess + return ok(new TransferKeepAliveTx(event, details)) } } diff --git a/avail-js/src/sdk/transactions/common.ts b/avail-js/src/sdk/transactions/common.ts index 4383b968d..73d979143 100644 --- a/avail-js/src/sdk/transactions/common.ts +++ b/avail-js/src/sdk/transactions/common.ts @@ -2,6 +2,7 @@ import { ApiPromise } from "@polkadot/api" import { ISubmittableResult } from "@polkadot/types/types/extrinsic" import { H256 } from "@polkadot/types/interfaces/types" import { ok, Result } from "neverthrow" +import { TxResultDetails } from "../utils" export enum WaitFor { BlockInclusion, @@ -46,4 +47,9 @@ export async function getBlockHashAndTxHash( return [txHash, txIndex, blockHash, blockNumber] } -export type GenericFailure = { isErr: true; reason: string } +export class TransactionFailed { + constructor( + public reason: string, + public details: TxResultDetails | null, + ) {} +} diff --git a/avail-js/src/sdk/transactions/da.ts b/avail-js/src/sdk/transactions/da.ts index bfa48cacc..b7f14b873 100644 --- a/avail-js/src/sdk/transactions/da.ts +++ b/avail-js/src/sdk/transactions/da.ts @@ -1,14 +1,15 @@ import { ApiPromise } from "@polkadot/api" import { ISubmittableResult } from "@polkadot/types/types/extrinsic" -import { H256, EventRecord } from "@polkadot/types/interfaces/types" +import { EventRecord } from "@polkadot/types/interfaces/types" import { BN } from "@polkadot/util" import { KeyringPair } from "@polkadot/keyring/types" -import { err, Result } from "neverthrow" +import { err, Result, ok } from "neverthrow" import * as TransactionData from "./../transaction_data" import { SignerOptions } from "@polkadot/api/types" import { decodeError, fromHexToAscii } from "../../helpers" -import { WaitFor, GenericFailure, standardCallback, getBlockHashAndTxHash } from "./common" +import { WaitFor, standardCallback, TransactionFailed } from "./common" +import { parseTransactionResult, TxResultDetails } from "../utils" export type DispatchFeeModifier = { weightMaximumFee: BN | null @@ -16,51 +17,40 @@ export type DispatchFeeModifier = { weightFeeMultiplier: number | null } -type SubmitDataTxSuccess = { - isErr: false - txData: TransactionData.DataAvailability.SubmitData - event: Events.DataSubmittedEvent - events: EventRecord[] - txHash: H256 - txIndex: number - blockHash: H256 - blockNumber: number +export class SubmitDataTx { + constructor( + public txData: TransactionData.DataAvailability.SubmitData, + public event: Events.DataSubmittedEvent, + public details: TxResultDetails, + ) {} } -type CreateApplicationKeyTxSuccess = { - isErr: false - event: Events.ApplicationKeyCreatedEvent - events: EventRecord[] - txHash: H256 - txIndex: number - blockHash: H256 - blockNumber: number + +export class CreateApplicationKeyTx { + constructor( + public event: Events.ApplicationKeyCreatedEvent, + public details: TxResultDetails, + ) {} } -type SetApplicationKeyTxSuccess = { - isErr: false - event: Events.ApplicationKeySetEvent - events: EventRecord[] - txHash: H256 - txIndex: number - blockHash: H256 - blockNumber: number + +export class SetApplicationKeyTx { + constructor( + public event: Events.ApplicationKeySetEvent, + public details: TxResultDetails, + ) {} } -type SubmitBlockLengthProposalTxSuccess = { - isErr: false - event: Events.BlockLengthProposalSubmittedEvent - events: EventRecord[] - txHash: H256 - txIndex: number - blockHash: H256 - blockNumber: number + +export class SubmitBlockLengthProposalTx { + constructor( + public event: Events.BlockLengthProposalSubmittedEvent, + public details: TxResultDetails, + ) {} } -type SetSubmitDataFeeModifierTxSuccess = { - isErr: false - event: Events.SubmitDataFeeModifierSetEvent - events: EventRecord[] - txHash: H256 - txIndex: number - blockHash: H256 - blockNumber: number + +export class SetSubmitDataFeeModifierTx { + constructor( + public event: Events.SubmitDataFeeModifierSetEvent, + public details: TxResultDetails, + ) {} } export class DataAvailability { @@ -75,7 +65,7 @@ export class DataAvailability { waitFor: WaitFor, account: KeyringPair, options?: Partial, - ): Promise { + ): Promise> { const optionWrapper = options || {} const maybeTxResult = await new Promise>((res, _) => { this.api.tx.dataAvailability @@ -89,42 +79,30 @@ export class DataAvailability { }) if (maybeTxResult.isErr()) { - return { isErr: true, reason: maybeTxResult.error } as GenericFailure + return err(new TransactionFailed(maybeTxResult.error, null)) } const txResult = maybeTxResult.value - - if (txResult.isError) { - 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)) - if (failed != undefined) { - return { isErr: true, reason: decodeError(this.api, failed.event.data[0]) } as GenericFailure + const maybeParsed = await parseTransactionResult(this.api, txResult, waitFor) + if (maybeParsed.isErr()) { + return err(maybeParsed.error) } + const details = maybeParsed.value const event = Events.DataSubmittedEvent.New(txResult.events) if (event == undefined) { - return { isErr: true, reason: "Failed to find DataSubmitted event." } as GenericFailure + return err(new TransactionFailed("Failed to find DataSubmitted Event", details)) } - const events = txResult.events - const [txHash, txIndex, blockHash, blockNumber] = await getBlockHashAndTxHash(txResult, waitFor, this.api) - - const maybeTxData = await TransactionData.DataAvailability.SubmitData.New(this.api, txHash, blockHash) + const maybeTxData = await TransactionData.DataAvailability.SubmitData.New( + this.api, + details.txHash, + details.blockHash, + ) if (maybeTxData.isErr()) { - return { isErr: true, reason: maybeTxData.error } as GenericFailure + return err(new TransactionFailed(maybeTxData.error, details)) } - return { - isErr: false, - txData: maybeTxData.value, - event, - events, - txHash, - txIndex, - blockHash, - blockNumber, - } as SubmitDataTxSuccess + return ok(new SubmitDataTx(maybeTxData.value, event, details)) } async createApplicationKey( @@ -132,7 +110,7 @@ export class DataAvailability { waitFor: WaitFor, account: KeyringPair, options?: Partial, - ): Promise { + ): Promise> { const optionWrapper = options || {} const maybeTxResult = await new Promise>((res, _) => { this.api.tx.dataAvailability @@ -146,28 +124,21 @@ export class DataAvailability { }) if (maybeTxResult.isErr()) { - return { isErr: true, reason: maybeTxResult.error } as GenericFailure + return err(new TransactionFailed(maybeTxResult.error, null)) } const txResult = maybeTxResult.value - - if (txResult.isError) { - 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)) - if (failed != undefined) { - return { isErr: true, reason: decodeError(this.api, failed.event.data[0]) } as GenericFailure + const maybeParsed = await parseTransactionResult(this.api, txResult, waitFor) + if (maybeParsed.isErr()) { + return err(maybeParsed.error) } + const details = maybeParsed.value const event = Events.ApplicationKeyCreatedEvent.New(txResult.events) if (event == undefined) { - return { isErr: true, reason: "Failed to find ApplicationKeyCreated event." } as GenericFailure + return err(new TransactionFailed("Failed to find ApplicationKeyCreated Event", details)) } - const events = txResult.events - const [txHash, txIndex, blockHash, blockNumber] = await getBlockHashAndTxHash(txResult, waitFor, this.api) - - return { isErr: false, event, events, txHash, txIndex, blockHash, blockNumber } as CreateApplicationKeyTxSuccess + return ok(new CreateApplicationKeyTx(event, details)) } async setApplicationKey( @@ -176,7 +147,7 @@ export class DataAvailability { waitFor: WaitFor, account: KeyringPair, options?: Partial, - ): Promise { + ): Promise> { const optionWrapper = options || {} const maybeTxResult = await new Promise>((res, _) => { const call = this.api.tx.dataAvailability.setApplicationKey(oldKey, newKey) @@ -191,38 +162,31 @@ export class DataAvailability { }) if (maybeTxResult.isErr()) { - return { isErr: true, reason: maybeTxResult.error } as GenericFailure + return err(new TransactionFailed(maybeTxResult.error, null)) } const txResult = maybeTxResult.value - - if (txResult.isError) { - 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)) - if (failed != undefined) { - return { isErr: true, reason: decodeError(this.api, failed.event.data[0]) } as GenericFailure + const maybeParsed = await parseTransactionResult(this.api, txResult, waitFor) + if (maybeParsed.isErr()) { + return err(maybeParsed.error) } + const details = maybeParsed.value const sudoEvent = txResult.events.find((e) => e.event.method == "Sudid") if (sudoEvent == undefined) { - return { isErr: true, reason: "Failed to find Sudid event." } as GenericFailure + return err(new TransactionFailed("Failed to find Sudid Event", details)) } const sudoResult: any = (sudoEvent.event.data as any).sudoResult if (sudoResult.isErr) { - return { isErr: true, isFailure: true, reason: decodeError(this.api, sudoResult.asErr) } as GenericFailure + return err(new TransactionFailed(decodeError(this.api, sudoResult.asErr), details)) } const event = Events.ApplicationKeySetEvent.New(txResult.events) if (event == undefined) { - return { isErr: true, reason: "Failed to find ApplicationKeySet event." } as GenericFailure + return err(new TransactionFailed("Failed to find ApplicationKeySet Event", details)) } - const events = txResult.events - const [txHash, txIndex, blockHash, blockNumber] = await getBlockHashAndTxHash(txResult, waitFor, this.api) - - return { isErr: false, event, events, txHash, txIndex, blockHash, blockNumber } as SetApplicationKeyTxSuccess + return ok(new SetApplicationKeyTx(event, details)) } async submitBlockLengthProposal( @@ -231,7 +195,7 @@ export class DataAvailability { waitFor: WaitFor, account: KeyringPair, options?: Partial, - ): Promise { + ): Promise> { const optionWrapper = options || {} const maybeTxResult = await new Promise>((res, _) => { const call = this.api.tx.dataAvailability.submitBlockLengthProposal(rows, cols) @@ -246,46 +210,31 @@ export class DataAvailability { }) if (maybeTxResult.isErr()) { - return { isErr: true, reason: maybeTxResult.error } as GenericFailure + return err(new TransactionFailed(maybeTxResult.error, null)) } const txResult = maybeTxResult.value - - if (txResult.isError) { - 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)) - if (failed != undefined) { - return { isErr: true, reason: decodeError(this.api, failed.event.data[0]) } as GenericFailure + const maybeParsed = await parseTransactionResult(this.api, txResult, waitFor) + if (maybeParsed.isErr()) { + return err(maybeParsed.error) } + const details = maybeParsed.value const sudoEvent = txResult.events.find((e) => e.event.method == "Sudid") if (sudoEvent == undefined) { - return { isErr: true, reason: "Failed to find Sudid event." } as GenericFailure + return err(new TransactionFailed("Failed to find Sudid Event", details)) } const sudoResult: any = (sudoEvent.event.data as any).sudoResult if (sudoResult.isErr) { - return { isErr: true, isFailure: true, reason: decodeError(this.api, sudoResult.asErr) } as GenericFailure + return err(new TransactionFailed(decodeError(this.api, sudoResult.asErr), details)) } const event = Events.BlockLengthProposalSubmittedEvent.New(txResult.events) if (event == undefined) { - return { isErr: true, reason: "Failed to find BlockLengthProposalSubmitted event." } as GenericFailure + return err(new TransactionFailed("Failed to find BlockLengthProposalSubmitted Event", details)) } - const events = txResult.events - const [txHash, txIndex, blockHash, blockNumber] = await getBlockHashAndTxHash(txResult, waitFor, this.api) - - return { - isErr: false, - event, - events, - txHash, - txIndex, - blockHash, - blockNumber, - } as SubmitBlockLengthProposalTxSuccess + return ok(new SubmitBlockLengthProposalTx(event, details)) } async setSubmitDataFeeModifier( @@ -293,7 +242,7 @@ export class DataAvailability { waitFor: WaitFor, account: KeyringPair, options?: Partial, - ): Promise { + ): Promise> { const optionWrapper = options || {} const maybeTxResult = await new Promise>((res, _) => { const call = this.api.tx.dataAvailability.setSubmitDataFeeModifier(modifier) @@ -308,38 +257,31 @@ export class DataAvailability { }) if (maybeTxResult.isErr()) { - return { isErr: true, reason: maybeTxResult.error } as GenericFailure + return err(new TransactionFailed(maybeTxResult.error, null)) } const txResult = maybeTxResult.value - - if (txResult.isError) { - 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)) - if (failed != undefined) { - return { isErr: true, reason: decodeError(this.api, failed.event.data[0]) } as GenericFailure + const maybeParsed = await parseTransactionResult(this.api, txResult, waitFor) + if (maybeParsed.isErr()) { + return err(maybeParsed.error) } + const details = maybeParsed.value const sudoEvent = txResult.events.find((e) => e.event.method == "Sudid") if (sudoEvent == undefined) { - return { isErr: true, reason: "Failed to find Sudid event." } as GenericFailure + return err(new TransactionFailed("Failed to find Sudid Event", details)) } const sudoResult: any = (sudoEvent.event.data as any).sudoResult if (sudoResult.isErr) { - return { isErr: true, isFailure: true, reason: decodeError(this.api, sudoResult.asErr) } as GenericFailure + return err(new TransactionFailed(decodeError(this.api, sudoResult.asErr), details)) } const event = Events.SubmitDataFeeModifierSetEvent.New(txResult.events) if (event == undefined) { - return { isErr: true, reason: "Failed to find SubmitDataFeeModifierSet event." } as GenericFailure + return err(new TransactionFailed("Failed to find SubmitDataFeeModifierSet Event", details)) } - const events = txResult.events - const [txHash, txIndex, blockHash, blockNumber] = await getBlockHashAndTxHash(txResult, waitFor, this.api) - - return { isErr: false, event, events, txHash, txIndex, blockHash, blockNumber } as SetSubmitDataFeeModifierTxSuccess + return ok(new SetSubmitDataFeeModifierTx(event, details)) } } diff --git a/avail-js/src/sdk/transactions/multisig.ts b/avail-js/src/sdk/transactions/multisig.ts new file mode 100644 index 000000000..e69de29bb diff --git a/avail-js/src/sdk/transactions/nomination_pools.ts b/avail-js/src/sdk/transactions/nomination_pools.ts index 5d6947e80..9d6cde8fa 100644 --- a/avail-js/src/sdk/transactions/nomination_pools.ts +++ b/avail-js/src/sdk/transactions/nomination_pools.ts @@ -1,14 +1,13 @@ import { ApiPromise } from "@polkadot/api" import { ISubmittableResult } from "@polkadot/types/types/extrinsic" -import { H256, EventRecord } from "@polkadot/types/interfaces/types" +import { EventRecord } from "@polkadot/types/interfaces/types" import { BN } from "@polkadot/util" import { KeyringPair } from "@polkadot/keyring/types" -import { err, Result } from "neverthrow" +import { err, Result, ok } from "neverthrow" import { SignerOptions } from "@polkadot/api/types" -import { decodeError } from "../../helpers" -import { WaitFor, GenericFailure, standardCallback, getBlockHashAndTxHash } from "./common" -import { commissionNumberToPerbill } from "../utils" +import { WaitFor, standardCallback, TransactionFailed } from "./common" +import { commissionNumberToPerbill, parseTransactionResult, TxResultDetails } from "../utils" export interface BondExtra { FreeBalance?: BN @@ -23,152 +22,99 @@ export interface NewCommission { payee: string } -type PoolCreateTxSuccess = { - isErr: false - event: Events.Created - event2: Events.Bonded - events: EventRecord[] - txHash: H256 - txIndex: number - blockHash: H256 - blockNumber: number +export class CreateTx { + constructor( + public event: Events.Created, + public event2: Events.Bonded, + public details: TxResultDetails, + ) {} } -type PoolCreateWithPoolIdTxSuccess = { - isErr: false - event: Events.Created - event2: Events.Bonded - events: EventRecord[] - txHash: H256 - txIndex: number - blockHash: H256 - blockNumber: number +export class CreateWithPoolIdTx { + constructor( + public event: Events.Created, + public event2: Events.Bonded, + public details: TxResultDetails, + ) {} } -type PoolJoinTxSuccess = { - isErr: false - event: Events.Bonded - events: EventRecord[] - txHash: H256 - txIndex: number - blockHash: H256 - blockNumber: number +export class JoinTx { + constructor( + public event: Events.Bonded, + public details: TxResultDetails, + ) {} } -type PoolNominateTxSuccess = { - isErr: false - events: EventRecord[] - txHash: H256 - txIndex: number - blockHash: H256 - blockNumber: number +export class NominateTx { + constructor(public details: TxResultDetails) {} } -type PoolBondExtraTxSuccess = { - isErr: false - event: Events.Bonded - events: EventRecord[] - txHash: H256 - txIndex: number - blockHash: H256 - blockNumber: number +export class BondExtraTx { + constructor( + public event: Events.Bonded, + public details: TxResultDetails, + ) {} } -type PoolSetMetadataTxSuccess = { - isErr: false - events: EventRecord[] - txHash: H256 - txIndex: number - blockHash: H256 - blockNumber: number +export class SetMetadataTx { + constructor(public details: TxResultDetails) {} } -type PoolUnbondTxSuccess = { - isErr: false - event?: Events.Unbonded - events: EventRecord[] - txHash: H256 - txIndex: number - blockHash: H256 - blockNumber: number +export class UnbondTx { + constructor( + public event: Events.Unbonded | undefined, + public details: TxResultDetails, + ) {} } -type PoolChillTxSuccess = { - isErr: false - events: EventRecord[] - txHash: H256 - txIndex: number - blockHash: H256 - blockNumber: number +export class ChillTx { + constructor(public details: TxResultDetails) {} } -type PoolClaimCommissionTxSuccess = { - isErr: false - event: Events.PoolCommissionClaimed - events: EventRecord[] - txHash: H256 - txIndex: number - blockHash: H256 - blockNumber: number +export class ClaimCommissionTx { + constructor( + public event: Events.PoolCommissionClaimed, + public details: TxResultDetails, + ) {} } -type PoolClaimPayoutTxSuccess = { - isErr: false - event?: Events.PaidOut - events: EventRecord[] - txHash: H256 - txIndex: number - blockHash: H256 - blockNumber: number +export class ClaimPayoutTx { + constructor( + public event: Events.PaidOut | undefined, + public details: TxResultDetails, + ) {} } -type PoolClaimPayoutOtherTxSuccess = { - isErr: false - event?: Events.PaidOut - events: EventRecord[] - txHash: H256 - txIndex: number - blockHash: H256 - blockNumber: number +export class ClaimPayoutOtherTx { + constructor( + public event: Events.PaidOut | undefined, + public details: TxResultDetails, + ) {} } -type PoolSetClaimPermissionOtherTxSuccess = { - isErr: false - events: EventRecord[] - txHash: H256 - txIndex: number - blockHash: H256 - blockNumber: number +export class SetClaimPermissionTx { + constructor(public details: TxResultDetails) {} } -type PoolSetCommissionTxSuccess = { - isErr: false - event: Events.PoolCommissionUpdated - events: EventRecord[] - txHash: H256 - txIndex: number - blockHash: H256 - blockNumber: number +export class CommissionTx { + constructor( + public event: Events.PoolCommissionUpdated, + public details: TxResultDetails, + ) {} } -type PoolWithdrawUnbodedTxSuccess = { - isErr: false - event: Events.Withdrawn - events: EventRecord[] - txHash: H256 - txIndex: number - blockHash: H256 - blockNumber: number +export class WithdrawUnbodedTx { + constructor( + public event: Events.Withdrawn, + public details: TxResultDetails, + ) {} } -type PoolSetStateTxSuccess = { - isErr: false - event?: Events.StateChanged - events: EventRecord[] - txHash: H256 - txIndex: number - blockHash: H256 - blockNumber: number +export class SetStateTx { + constructor( + public event: Events.StateChanged | undefined, + public details: TxResultDetails, + ) {} } export class NominationPools { @@ -186,7 +132,7 @@ export class NominationPools { waitFor: WaitFor, account: KeyringPair, options?: Partial, - ): Promise { + ): Promise> { const optionWrapper = options || {} const maybeTxResult = await new Promise>((res, _) => { this.api.tx.nominationPools @@ -200,33 +146,25 @@ export class NominationPools { }) if (maybeTxResult.isErr()) { - return { isErr: true, reason: maybeTxResult.error } as GenericFailure + return err(new TransactionFailed(maybeTxResult.error, null)) } 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 maybeParsed = await parseTransactionResult(this.api, txResult, waitFor) + if (maybeParsed.isErr()) { + return err(maybeParsed.error) } + const details = maybeParsed.value const event = Events.Created.New(txResult.events) if (event == undefined) { - return { isErr: true, reason: "Failed to find Created event." } as GenericFailure + return err(new TransactionFailed("Failed to find Created event", details)) } - const event2 = Events.Bonded.New(txResult.events) if (event2 == undefined) { - return { isErr: true, reason: "Failed to find Bonded event." } as GenericFailure + return err(new TransactionFailed("Failed to find Bonded event", details)) } - const [txHash, txIndex, blockHash, blockNumber] = await getBlockHashAndTxHash(txResult, waitFor, this.api) - - return { isErr: false, event, event2, events, txHash, txIndex, blockHash, blockNumber } as PoolCreateTxSuccess + return ok(new CreateTx(event, event2, details)) } async createWithPoolId( @@ -238,7 +176,7 @@ export class NominationPools { waitFor: WaitFor, account: KeyringPair, options?: Partial, - ): Promise { + ): Promise> { const optionWrapper = options || {} const maybeTxResult = await new Promise>((res, _) => { this.api.tx.nominationPools @@ -252,42 +190,26 @@ export class NominationPools { }) if (maybeTxResult.isErr()) { - return { isErr: true, reason: maybeTxResult.error } as GenericFailure + return err(new TransactionFailed(maybeTxResult.error, null)) } 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 maybeParsed = await parseTransactionResult(this.api, txResult, waitFor) + if (maybeParsed.isErr()) { + return err(maybeParsed.error) } + const details = maybeParsed.value const event = Events.Created.New(txResult.events) if (event == undefined) { - return { isErr: true, reason: "Failed to find Created event." } as GenericFailure + return err(new TransactionFailed("Failed to find Created event", details)) } const event2 = Events.Bonded.New(txResult.events) if (event2 == undefined) { - return { isErr: true, reason: "Failed to find Bonded event." } as GenericFailure + return err(new TransactionFailed("Failed to find Bonded event", details)) } - const [txHash, txIndex, blockHash, blockNumber] = await getBlockHashAndTxHash(txResult, waitFor, this.api) - - return { - isErr: false, - event, - event2, - events, - txHash, - txIndex, - blockHash, - blockNumber, - } as PoolCreateWithPoolIdTxSuccess + return ok(new CreateWithPoolIdTx(event, event2, details)) } async join( @@ -296,7 +218,7 @@ export class NominationPools { waitFor: WaitFor, account: KeyringPair, options?: Partial, - ): Promise { + ): Promise> { const optionWrapper = options || {} const maybeTxResult = await new Promise>((res, _) => { this.api.tx.nominationPools @@ -310,28 +232,21 @@ export class NominationPools { }) if (maybeTxResult.isErr()) { - return { isErr: true, reason: maybeTxResult.error } as GenericFailure + return err(new TransactionFailed(maybeTxResult.error, null)) } 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 maybeParsed = await parseTransactionResult(this.api, txResult, waitFor) + if (maybeParsed.isErr()) { + return err(maybeParsed.error) } + const details = maybeParsed.value const event = Events.Bonded.New(txResult.events) if (event == undefined) { - return { isErr: true, reason: "Failed to find Bonded event." } as GenericFailure + return err(new TransactionFailed("Failed to find Bonded event", details)) } - const [txHash, txIndex, blockHash, blockNumber] = await getBlockHashAndTxHash(txResult, waitFor, this.api) - - return { isErr: false, event, events, txHash, txIndex, blockHash, blockNumber } as PoolJoinTxSuccess + return ok(new JoinTx(event, details)) } async nominate( @@ -340,7 +255,7 @@ export class NominationPools { waitFor: WaitFor, account: KeyringPair, options?: Partial, - ): Promise { + ): Promise> { const optionWrapper = options || {} const maybeTxResult = await new Promise>((res, _) => { this.api.tx.nominationPools @@ -354,23 +269,16 @@ export class NominationPools { }) if (maybeTxResult.isErr()) { - return { isErr: true, reason: maybeTxResult.error } as GenericFailure + return err(new TransactionFailed(maybeTxResult.error, null)) } 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 maybeParsed = await parseTransactionResult(this.api, txResult, waitFor) + if (maybeParsed.isErr()) { + return err(maybeParsed.error) } + const details = maybeParsed.value - const [txHash, txIndex, blockHash, blockNumber] = await getBlockHashAndTxHash(txResult, waitFor, this.api) - - return { isErr: false, events, txHash, txIndex, blockHash, blockNumber } as PoolNominateTxSuccess + return ok(new NominateTx(details)) } async bondExtra( @@ -378,7 +286,7 @@ export class NominationPools { waitFor: WaitFor, account: KeyringPair, options?: Partial, - ): Promise { + ): Promise> { const optionWrapper = options || {} const maybeTxResult = await new Promise>((res, _) => { this.api.tx.nominationPools @@ -392,28 +300,21 @@ export class NominationPools { }) if (maybeTxResult.isErr()) { - return { isErr: true, reason: maybeTxResult.error } as GenericFailure + return err(new TransactionFailed(maybeTxResult.error, null)) } 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 maybeParsed = await parseTransactionResult(this.api, txResult, waitFor) + if (maybeParsed.isErr()) { + return err(maybeParsed.error) } + const details = maybeParsed.value const event = Events.Bonded.New(txResult.events) if (event == undefined) { - return { isErr: true, reason: "Failed to find Bonded event." } as GenericFailure + return err(new TransactionFailed("Failed to find Bonded event", details)) } - const [txHash, txIndex, blockHash, blockNumber] = await getBlockHashAndTxHash(txResult, waitFor, this.api) - - return { isErr: false, event, events, txHash, txIndex, blockHash, blockNumber } as PoolBondExtraTxSuccess + return ok(new BondExtraTx(event, details)) } async setMetadata( @@ -422,7 +323,7 @@ export class NominationPools { waitFor: WaitFor, account: KeyringPair, options?: Partial, - ): Promise { + ): Promise> { const optionWrapper = options || {} const maybeTxResult = await new Promise>((res, _) => { this.api.tx.nominationPools @@ -436,23 +337,16 @@ export class NominationPools { }) if (maybeTxResult.isErr()) { - return { isErr: true, reason: maybeTxResult.error } as GenericFailure + return err(new TransactionFailed(maybeTxResult.error, null)) } const txResult = maybeTxResult.value - - if (txResult.isError) { - return { isErr: true, reason: "The transaction was dropped or something." } as GenericFailure + const maybeParsed = await parseTransactionResult(this.api, txResult, waitFor) + if (maybeParsed.isErr()) { + return err(maybeParsed.error) } + const details = maybeParsed.value - 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 PoolSetMetadataTxSuccess + return ok(new SetMetadataTx(details)) } async unbond( @@ -461,7 +355,7 @@ export class NominationPools { waitFor: WaitFor, account: KeyringPair, options?: Partial, - ): Promise { + ): Promise> { const optionWrapper = options || {} const maybeTxResult = await new Promise>((res, _) => { this.api.tx.nominationPools @@ -475,24 +369,18 @@ export class NominationPools { }) if (maybeTxResult.isErr()) { - return { isErr: true, reason: maybeTxResult.error } as GenericFailure + return err(new TransactionFailed(maybeTxResult.error, null)) } 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 maybeParsed = await parseTransactionResult(this.api, txResult, waitFor) + if (maybeParsed.isErr()) { + return err(maybeParsed.error) } + const details = maybeParsed.value const event = Events.Unbonded.New(txResult.events) - const [txHash, txIndex, blockHash, blockNumber] = await getBlockHashAndTxHash(txResult, waitFor, this.api) - return { isErr: false, event, events, txHash, txIndex, blockHash, blockNumber } as PoolUnbondTxSuccess + return ok(new UnbondTx(event, details)) } async chill( @@ -500,7 +388,7 @@ export class NominationPools { waitFor: WaitFor, account: KeyringPair, options?: Partial, - ): Promise { + ): Promise> { const optionWrapper = options || {} const maybeTxResult = await new Promise>((res, _) => { this.api.tx.nominationPools @@ -514,23 +402,16 @@ export class NominationPools { }) if (maybeTxResult.isErr()) { - return { isErr: true, reason: maybeTxResult.error } as GenericFailure + return err(new TransactionFailed(maybeTxResult.error, null)) } 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 maybeParsed = await parseTransactionResult(this.api, txResult, waitFor) + if (maybeParsed.isErr()) { + return err(maybeParsed.error) } + const details = maybeParsed.value - const [txHash, txIndex, blockHash, blockNumber] = await getBlockHashAndTxHash(txResult, waitFor, this.api) - - return { isErr: false, events, txHash, txIndex, blockHash, blockNumber } as PoolChillTxSuccess + return ok(new ChillTx(details)) } async claimCommission( @@ -538,7 +419,7 @@ export class NominationPools { waitFor: WaitFor, account: KeyringPair, options?: Partial, - ): Promise { + ): Promise> { const optionWrapper = options || {} const maybeTxResult = await new Promise>((res, _) => { this.api.tx.nominationPools @@ -552,35 +433,28 @@ export class NominationPools { }) if (maybeTxResult.isErr()) { - return { isErr: true, reason: maybeTxResult.error } as GenericFailure + return err(new TransactionFailed(maybeTxResult.error, null)) } 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 maybeParsed = await parseTransactionResult(this.api, txResult, waitFor) + if (maybeParsed.isErr()) { + return err(maybeParsed.error) } + const details = maybeParsed.value const event = Events.PoolCommissionClaimed.New(txResult.events) if (event == undefined) { - return { isErr: true, reason: "Failed to find PoolCommissionClaimed event." } as GenericFailure + return err(new TransactionFailed("Failed to find PoolCommissionClaimed event", details)) } - const [txHash, txIndex, blockHash, blockNumber] = await getBlockHashAndTxHash(txResult, waitFor, this.api) - - return { isErr: false, event, events, txHash, txIndex, blockHash, blockNumber } as PoolClaimCommissionTxSuccess + return ok(new ClaimCommissionTx(event, details)) } async claimPayout( waitFor: WaitFor, account: KeyringPair, options?: Partial, - ): Promise { + ): Promise> { const optionWrapper = options || {} const maybeTxResult = await new Promise>((res, _) => { this.api.tx.nominationPools @@ -594,24 +468,17 @@ export class NominationPools { }) if (maybeTxResult.isErr()) { - return { isErr: true, reason: maybeTxResult.error } as GenericFailure + return err(new TransactionFailed(maybeTxResult.error, null)) } const txResult = maybeTxResult.value - - if (txResult.isError) { - return { isErr: true, reason: "The transaction was dropped or something." } as GenericFailure + const maybeParsed = await parseTransactionResult(this.api, txResult, waitFor) + if (maybeParsed.isErr()) { + return err(maybeParsed.error) } - - 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 details = maybeParsed.value const event = Events.PaidOut.New(txResult.events) - const [txHash, txIndex, blockHash, blockNumber] = await getBlockHashAndTxHash(txResult, waitFor, this.api) - return { isErr: false, event, events, txHash, txIndex, blockHash, blockNumber } as PoolClaimPayoutTxSuccess + return ok(new ClaimPayoutTx(event, details)) } async claimPayoutOther( @@ -619,7 +486,7 @@ export class NominationPools { waitFor: WaitFor, account: KeyringPair, options?: Partial, - ): Promise { + ): Promise> { const optionWrapper = options || {} const maybeTxResult = await new Promise>((res, _) => { this.api.tx.nominationPools @@ -633,24 +500,17 @@ export class NominationPools { }) if (maybeTxResult.isErr()) { - return { isErr: true, reason: maybeTxResult.error } as GenericFailure + return err(new TransactionFailed(maybeTxResult.error, null)) } const txResult = maybeTxResult.value - - if (txResult.isError) { - return { isErr: true, reason: "The transaction was dropped or something." } as GenericFailure + const maybeParsed = await parseTransactionResult(this.api, txResult, waitFor) + if (maybeParsed.isErr()) { + return err(maybeParsed.error) } - - 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 details = maybeParsed.value const event = Events.PaidOut.New(txResult.events) - const [txHash, txIndex, blockHash, blockNumber] = await getBlockHashAndTxHash(txResult, waitFor, this.api) - return { isErr: false, event, events, txHash, txIndex, blockHash, blockNumber } as PoolClaimPayoutOtherTxSuccess + return ok(new ClaimPayoutOtherTx(event, details)) } async setClaimPermission( @@ -658,7 +518,7 @@ export class NominationPools { waitFor: WaitFor, account: KeyringPair, options?: Partial, - ): Promise { + ): Promise> { const optionWrapper = options || {} const maybeTxResult = await new Promise>((res, _) => { this.api.tx.nominationPools @@ -672,23 +532,16 @@ export class NominationPools { }) if (maybeTxResult.isErr()) { - return { isErr: true, reason: maybeTxResult.error } as GenericFailure + return err(new TransactionFailed(maybeTxResult.error, null)) } const txResult = maybeTxResult.value - - if (txResult.isError) { - return { isErr: true, reason: "The transaction was dropped or something." } as GenericFailure + const maybeParsed = await parseTransactionResult(this.api, txResult, waitFor) + if (maybeParsed.isErr()) { + return err(maybeParsed.error) } + const details = maybeParsed.value - 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 PoolSetClaimPermissionOtherTxSuccess + return ok(new SetClaimPermissionTx(details)) } async setCommission( @@ -697,14 +550,14 @@ export class NominationPools { waitFor: WaitFor, account: KeyringPair, options?: Partial, - ): Promise { + ): Promise> { const optionWrapper = options || {} let commission: string[] | null = null if (newCommission != null) { const amount = commissionNumberToPerbill(newCommission.amount) if (amount.isErr()) { - return { isErr: true, reason: amount.error } as GenericFailure + return err(new TransactionFailed(amount.error, null)) } commission = [amount.value, newCommission.payee] } @@ -720,28 +573,21 @@ export class NominationPools { }) if (maybeTxResult.isErr()) { - return { isErr: true, reason: maybeTxResult.error } as GenericFailure + return err(new TransactionFailed(maybeTxResult.error, null)) } 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 maybeParsed = await parseTransactionResult(this.api, txResult, waitFor) + if (maybeParsed.isErr()) { + return err(maybeParsed.error) } + const details = maybeParsed.value const event = Events.PoolCommissionUpdated.New(txResult.events) if (event == undefined) { - return { isErr: true, reason: "Failed to find PoolCommissionUpdated event." } as GenericFailure + return err(new TransactionFailed("Failed to find PoolCommissionUpdated event", details)) } - const [txHash, txIndex, blockHash, blockNumber] = await getBlockHashAndTxHash(txResult, waitFor, this.api) - - return { isErr: false, event, events, txHash, txIndex, blockHash, blockNumber } as PoolSetCommissionTxSuccess + return ok(new CommissionTx(event, details)) } async withdrawUnbonded( @@ -750,7 +596,7 @@ export class NominationPools { waitFor: WaitFor, account: KeyringPair, options?: Partial, - ): Promise { + ): Promise> { const optionWrapper = options || {} const maybeTxResult = await new Promise>((res, _) => { this.api.tx.nominationPools @@ -764,28 +610,21 @@ export class NominationPools { }) if (maybeTxResult.isErr()) { - return { isErr: true, reason: maybeTxResult.error } as GenericFailure + return err(new TransactionFailed(maybeTxResult.error, null)) } 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 maybeParsed = await parseTransactionResult(this.api, txResult, waitFor) + if (maybeParsed.isErr()) { + return err(maybeParsed.error) } + const details = maybeParsed.value const event = Events.Withdrawn.New(txResult.events) if (event == undefined) { - return { isErr: true, reason: "Failed to find Withdraw event." } as GenericFailure + return err(new TransactionFailed("Failed to find Withdrawn event", details)) } - const [txHash, txIndex, blockHash, blockNumber] = await getBlockHashAndTxHash(txResult, waitFor, this.api) - - return { isErr: false, event, events, txHash, txIndex, blockHash, blockNumber } as PoolWithdrawUnbodedTxSuccess + return ok(new WithdrawUnbodedTx(event, details)) } async setState( @@ -794,7 +633,7 @@ export class NominationPools { waitFor: WaitFor, account: KeyringPair, options?: Partial, - ): Promise { + ): Promise> { const optionWrapper = options || {} const maybeTxResult = await new Promise>((res, _) => { this.api.tx.nominationPools @@ -808,24 +647,17 @@ export class NominationPools { }) if (maybeTxResult.isErr()) { - return { isErr: true, reason: maybeTxResult.error } as GenericFailure + return err(new TransactionFailed(maybeTxResult.error, null)) } const txResult = maybeTxResult.value - - if (txResult.isError) { - return { isErr: true, reason: "The transaction was dropped or something." } as GenericFailure + const maybeParsed = await parseTransactionResult(this.api, txResult, waitFor) + if (maybeParsed.isErr()) { + return err(maybeParsed.error) } - - 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 details = maybeParsed.value const event = Events.StateChanged.New(txResult.events) - const [txHash, txIndex, blockHash, blockNumber] = await getBlockHashAndTxHash(txResult, waitFor, this.api) - return { isErr: false, event, events, txHash, txIndex, blockHash, blockNumber } as PoolSetStateTxSuccess + return ok(new SetStateTx(event, details)) } } diff --git a/avail-js/src/sdk/transactions/staking.ts b/avail-js/src/sdk/transactions/staking.ts index 3719f0195..acd220e74 100644 --- a/avail-js/src/sdk/transactions/staking.ts +++ b/avail-js/src/sdk/transactions/staking.ts @@ -1,81 +1,65 @@ import { ApiPromise } from "@polkadot/api" import { ISubmittableResult } from "@polkadot/types/types/extrinsic" -import { H256, EventRecord } from "@polkadot/types/interfaces/types" +import { EventRecord } from "@polkadot/types/interfaces/types" import { BN } from "@polkadot/util" import { KeyringPair } from "@polkadot/keyring/types" -import { err, Result } from "neverthrow" +import { err, Result, ok } from "neverthrow" import * as TransactionData from "./../transaction_data" import { SignerOptions } from "@polkadot/api/types" -import { decodeError } from "../../helpers" -import { WaitFor, GenericFailure, standardCallback, getBlockHashAndTxHash } from "./common" -import { commissionNumberToPerbill } from "../utils" +import { WaitFor, standardCallback, TransactionFailed } from "./common" +import { commissionNumberToPerbill, parseTransactionResult, TxResultDetails } from "../utils" type ValidatorPerfs = { commission: string; blocked: boolean } export type StakingRewardDestination = "Staked" | "Stash" | "None" | { account: string } -type BondTxSuccess = { - isErr: false - event: Events.Bonded - events: EventRecord[] - txHash: H256 - txIndex: number - blockHash: H256 - blockNumber: number +export class BondTx { + constructor( + public event: Events.Bonded, + public details: TxResultDetails, + ) {} } -type BondExtraTxSuccess = { - isErr: false - event: Events.Bonded - events: EventRecord[] - txHash: H256 - txIndex: number - blockHash: H256 - blockNumber: number + +export class BondExtraTx { + constructor( + public event: Events.Bonded, + public details: TxResultDetails, + ) {} } -type ChillTxSuccess = { - isErr: false - event: Events.Chilled - events: EventRecord[] - txHash: H256 - txIndex: number - blockHash: H256 - blockNumber: number + +export class ChillTx { + constructor( + public event: Events.Chilled, + public details: TxResultDetails, + ) {} } -type ChillOtherTxSuccess = { - isErr: false - event: Events.Chilled - events: EventRecord[] - txHash: H256 - txIndex: number - blockHash: H256 - blockNumber: number + +export class ChillOtherTx { + constructor( + public event: Events.Chilled, + public details: TxResultDetails, + ) {} } -type UnbondTxSuccess = { - isErr: false - event: Events.Unbonded - events: EventRecord[] - txHash: H256 - txIndex: number - blockHash: H256 - blockNumber: number + +export class UnbondTx { + constructor( + public event: Events.Unbonded, + public details: TxResultDetails, + ) {} } -type ValidatexSuccess = { - isErr: false - event: Events.ValidatorPrefsSet - events: EventRecord[] - txHash: H256 - txIndex: number - blockHash: H256 - blockNumber: number + +export class ValidateTx { + constructor( + public event: Events.ValidatorPrefsSet, + public details: TxResultDetails, + ) {} } -type NominateTxSuccess = { - isErr: false - txData: TransactionData.Staking.Nominate - events: EventRecord[] - txHash: H256 - txIndex: number - blockHash: H256 - blockNumber: number + +export class NominateTx { + constructor( + public txData: TransactionData.Staking.Nominate, + public details: TxResultDetails, + ) {} } export class Staking { @@ -91,7 +75,7 @@ export class Staking { waitFor: WaitFor, account: KeyringPair, options?: Partial, - ): Promise { + ): Promise> { const optionWrapper = options || {} const maybeTxResult = await new Promise>((res, _) => { this.api.tx.staking @@ -105,28 +89,21 @@ export class Staking { }) if (maybeTxResult.isErr()) { - return { isErr: true, reason: maybeTxResult.error } as GenericFailure + return err(new TransactionFailed(maybeTxResult.error, null)) } const txResult = maybeTxResult.value - - if (txResult.isError) { - 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)) - if (failed != undefined) { - return { isErr: true, reason: decodeError(this.api, failed.event.data[0]) } as GenericFailure + const maybeParsed = await parseTransactionResult(this.api, txResult, waitFor) + if (maybeParsed.isErr()) { + return err(maybeParsed.error) } + const details = maybeParsed.value const event = Events.Bonded.New(txResult.events) if (event == undefined) { - return { isErr: true, reason: "Failed to find Bonded event." } as GenericFailure + return err(new TransactionFailed("Failed to find Bonded event", details)) } - const events = txResult.events - const [txHash, txIndex, blockHash, blockNumber] = await getBlockHashAndTxHash(txResult, waitFor, this.api) - - return { isErr: false, event, events, txHash, txIndex, blockHash, blockNumber } as BondTxSuccess + return ok(new BondTx(event, details)) } async bondExtra( @@ -134,7 +111,7 @@ export class Staking { waitFor: WaitFor, account: KeyringPair, options?: Partial, - ): Promise { + ): Promise> { const optionWrapper = options || {} const maybeTxResult = await new Promise>((res, _) => { this.api.tx.staking @@ -148,35 +125,28 @@ export class Staking { }) if (maybeTxResult.isErr()) { - return { isErr: true, reason: maybeTxResult.error } as GenericFailure + return err(new TransactionFailed(maybeTxResult.error, null)) } const txResult = maybeTxResult.value - - if (txResult.isError) { - 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)) - if (failed != undefined) { - return { isErr: true, reason: decodeError(this.api, failed.event.data[0]) } as GenericFailure + const maybeParsed = await parseTransactionResult(this.api, txResult, waitFor) + if (maybeParsed.isErr()) { + return err(maybeParsed.error) } + const details = maybeParsed.value const event = Events.Bonded.New(txResult.events) if (event == undefined) { - return { isErr: true, reason: "Failed to find Bonded event." } as GenericFailure + return err(new TransactionFailed("Failed to find Bonded event", details)) } - const events = txResult.events - const [txHash, txIndex, blockHash, blockNumber] = await getBlockHashAndTxHash(txResult, waitFor, this.api) - - return { isErr: false, event, events, txHash, txIndex, blockHash, blockNumber } as BondExtraTxSuccess + return ok(new BondExtraTx(event, details)) } async chill( waitFor: WaitFor, account: KeyringPair, options?: Partial, - ): Promise { + ): Promise> { const optionWrapper = options || {} const maybeTxResult = await new Promise>((res, _) => { this.api.tx.staking @@ -190,28 +160,21 @@ export class Staking { }) if (maybeTxResult.isErr()) { - return { isErr: true, reason: maybeTxResult.error } as GenericFailure + return err(new TransactionFailed(maybeTxResult.error, null)) } const txResult = maybeTxResult.value - - if (txResult.isError) { - 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)) - if (failed != undefined) { - return { isErr: true, reason: decodeError(this.api, failed.event.data[0]) } as GenericFailure + const maybeParsed = await parseTransactionResult(this.api, txResult, waitFor) + if (maybeParsed.isErr()) { + return err(maybeParsed.error) } + const details = maybeParsed.value const event = Events.Chilled.New(txResult.events) if (event == undefined) { - return { isErr: true, reason: "Failed to find Chilled event." } as GenericFailure + return err(new TransactionFailed("Failed to find Chilled event", details)) } - const events = txResult.events - const [txHash, txIndex, blockHash, blockNumber] = await getBlockHashAndTxHash(txResult, waitFor, this.api) - - return { isErr: false, event, events, txHash, txIndex, blockHash, blockNumber } as ChillTxSuccess + return ok(new ChillTx(event, details)) } async chillOther( @@ -219,7 +182,7 @@ export class Staking { waitFor: WaitFor, account: KeyringPair, options?: Partial, - ): Promise { + ): Promise> { const optionWrapper = options || {} const maybeTxResult = await new Promise>((res, _) => { this.api.tx.staking @@ -233,28 +196,21 @@ export class Staking { }) if (maybeTxResult.isErr()) { - return { isErr: true, reason: maybeTxResult.error } as GenericFailure + return err(new TransactionFailed(maybeTxResult.error, null)) } const txResult = maybeTxResult.value - - if (txResult.isError) { - 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)) - if (failed != undefined) { - return { isErr: true, reason: decodeError(this.api, failed.event.data[0]) } as GenericFailure + const maybeParsed = await parseTransactionResult(this.api, txResult, waitFor) + if (maybeParsed.isErr()) { + return err(maybeParsed.error) } + const details = maybeParsed.value const event = Events.Chilled.New(txResult.events) if (event == undefined) { - return { isErr: true, reason: "Failed to find Chilled event." } as GenericFailure + return err(new TransactionFailed("Failed to find Chilled event", details)) } - const events = txResult.events - const [txHash, txIndex, blockHash, blockNumber] = await getBlockHashAndTxHash(txResult, waitFor, this.api) - - return { isErr: false, event, events, txHash, txIndex, blockHash, blockNumber } as ChillOtherTxSuccess + return ok(new ChillOtherTx(event, details)) } async nominate( @@ -262,7 +218,7 @@ export class Staking { waitFor: WaitFor, account: KeyringPair, options?: Partial, - ): Promise { + ): Promise> { const optionWrapper = options || {} const maybeTxResult = await new Promise>((res, _) => { this.api.tx.staking @@ -276,36 +232,21 @@ export class Staking { }) if (maybeTxResult.isErr()) { - return { isErr: true, reason: maybeTxResult.error } as GenericFailure + return err(new TransactionFailed(maybeTxResult.error, null)) } const txResult = maybeTxResult.value - - if (txResult.isError) { - 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)) - if (failed != undefined) { - return { isErr: true, reason: decodeError(this.api, failed.event.data[0]) } as GenericFailure + const maybeParsed = await parseTransactionResult(this.api, txResult, waitFor) + if (maybeParsed.isErr()) { + return err(maybeParsed.error) } + const details = maybeParsed.value - const events = txResult.events - const [txHash, txIndex, blockHash, blockNumber] = await getBlockHashAndTxHash(txResult, waitFor, this.api) - - const maybeTxData = await TransactionData.Staking.Nominate.New(this.api, txHash, blockHash) + const maybeTxData = await TransactionData.Staking.Nominate.New(this.api, details.txHash, details.blockHash) if (maybeTxData.isErr()) { - return { isErr: true, reason: maybeTxData.error } as GenericFailure + return err(new TransactionFailed(maybeTxData.error, details)) } - return { - isErr: false, - txData: maybeTxData.value, - events, - txHash, - txIndex, - blockHash, - blockNumber, - } as NominateTxSuccess + return ok(new NominateTx(maybeTxData.value, details)) } async unbond( @@ -313,7 +254,7 @@ export class Staking { waitFor: WaitFor, account: KeyringPair, options?: Partial, - ): Promise { + ): Promise> { const optionWrapper = options || {} const maybeTxResult = await new Promise>((res, _) => { this.api.tx.staking @@ -327,28 +268,21 @@ export class Staking { }) if (maybeTxResult.isErr()) { - return { isErr: true, reason: maybeTxResult.error } as GenericFailure + return err(new TransactionFailed(maybeTxResult.error, null)) } const txResult = maybeTxResult.value - - if (txResult.isError) { - 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)) - if (failed != undefined) { - return { isErr: true, reason: decodeError(this.api, failed.event.data[0]) } as GenericFailure + const maybeParsed = await parseTransactionResult(this.api, txResult, waitFor) + if (maybeParsed.isErr()) { + return err(maybeParsed.error) } + const details = maybeParsed.value const event = Events.Unbonded.New(txResult.events) if (event == undefined) { - return { isErr: true, reason: "Failed to find Unbonded event." } as GenericFailure + return err(new TransactionFailed("Failed to find Unbonded event", details)) } - const events = txResult.events - const [txHash, txIndex, blockHash, blockNumber] = await getBlockHashAndTxHash(txResult, waitFor, this.api) - - return { isErr: false, event, events, txHash, txIndex, blockHash, blockNumber } as UnbondTxSuccess + return ok(new UnbondTx(event, details)) } async validate( @@ -357,10 +291,10 @@ 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 + return err(new TransactionFailed(maybeCommission.error, null)) } const validatorPerfs = { commission: maybeCommission.value, blocked } as ValidatorPerfs @@ -377,28 +311,21 @@ export class Staking { }) if (maybeTxResult.isErr()) { - return { isErr: true, reason: maybeTxResult.error } as GenericFailure + return err(new TransactionFailed(maybeTxResult.error, null)) } const txResult = maybeTxResult.value - - if (txResult.isError) { - 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)) - if (failed != undefined) { - return { isErr: true, reason: decodeError(this.api, failed.event.data[0]) } as GenericFailure + const maybeParsed = await parseTransactionResult(this.api, txResult, waitFor) + if (maybeParsed.isErr()) { + return err(maybeParsed.error) } + const details = maybeParsed.value const event = Events.ValidatorPrefsSet.New(txResult.events) if (event == undefined) { - return { isErr: true, reason: "Failed to find ValidatorPrefsSet event." } as GenericFailure + return err(new TransactionFailed("Failed to find ValidatorPrefsSet event.", null)) } - const events = txResult.events - const [txHash, txIndex, blockHash, blockNumber] = await getBlockHashAndTxHash(txResult, waitFor, this.api) - - return { isErr: false, event, events, txHash, txIndex, blockHash, blockNumber } as ValidatexSuccess + return ok(new ValidateTx(event, details)) } } diff --git a/avail-js/src/sdk/utils/index.ts b/avail-js/src/sdk/utils/index.ts index abbf942ce..86ef4aed2 100644 --- a/avail-js/src/sdk/utils/index.ts +++ b/avail-js/src/sdk/utils/index.ts @@ -8,7 +8,7 @@ import { createKeyMulti, encodeAddress, sortAddresses } from "@polkadot/util-cry import { KeyringPair } from "@polkadot/keyring/types" import { SignerOptions } from "@polkadot/api/types" -export class ParsedTxResult { +export class TxResultDetails { constructor( public txResult: ISubmittableResult, public events: EventRecord[], @@ -19,6 +19,13 @@ export class ParsedTxResult { ) {} } +export class FailedTxResult { + constructor( + public reason: string, + public details: TxResultDetails | null, + ) {} +} + export interface MultisigTimepoint { height: number index: number @@ -31,12 +38,12 @@ export class Utils { this.api = api } - /// Parses a transaction result. Helper function to get transaction details on + /// Parses a transaction result. Helper function to get transaction details on /// transaction success or an error if the transaction failed async parseTransactionResult( txResult: ISubmittableResult, waitFor: WaitFor, - ): Promise> { + ): Promise> { return await parseTransactionResult(this.api, txResult, waitFor) } @@ -65,7 +72,7 @@ export class Utils { waitFor: WaitFor, account: KeyringPair, options?: Partial, - ): Promise> { + ): Promise> { const optionWrapper = options || {} const maybeTxResult = await new Promise>((res, _) => { this.api.tx.multisig @@ -84,7 +91,7 @@ export class Utils { const txResult = maybeTxResult.value const maybeParsed = await this.parseTransactionResult(txResult, waitFor) if (maybeParsed.isErr()) { - return err(maybeParsed.error) + return err(maybeParsed.error.reason) } const parsed = maybeParsed.value @@ -100,7 +107,7 @@ export class Utils { waitFor: WaitFor, account: KeyringPair, options?: Partial, - ): Promise> { + ): Promise> { const maxWeight = { refTime: 0, proofSize: 0 } const optionWrapper = options || {} const maybeTxResult = await new Promise>((res, _) => { @@ -120,7 +127,7 @@ export class Utils { const txResult = maybeTxResult.value const maybeParsed = await this.parseTransactionResult(txResult, waitFor) if (maybeParsed.isErr()) { - return err(maybeParsed.error) + return err(maybeParsed.error.reason) } const parsed = maybeParsed.value @@ -137,7 +144,7 @@ export class Utils { waitFor: WaitFor, account: KeyringPair, options?: Partial, - ): Promise> { + ): Promise> { const optionWrapper = options || {} const maybeTxResult = await new Promise>((res, _) => { this.api.tx.multisig @@ -156,7 +163,7 @@ export class Utils { const txResult = maybeTxResult.value const maybeParsed = await this.parseTransactionResult(txResult, waitFor) if (maybeParsed.isErr()) { - return err(maybeParsed.error) + return err(maybeParsed.error.reason) } const parsed = maybeParsed.value @@ -173,20 +180,21 @@ export async function parseTransactionResult( api: ApiPromise, txResult: ISubmittableResult, waitFor: WaitFor, -): Promise> { +): Promise> { if (txResult.isError) { - return err("The transaction was dropped or something.") + return err({ reason: "The transaction was dropped or something.", details: null }) } + const events = txResult.events + const [txHash, txIndex, blockHash, blockNumber] = await getBlockHashAndTxHash(txResult, waitFor, api) + const details = new TxResultDetails(txResult, events, txHash, txIndex, blockHash, blockNumber) + const failed = txResult.events.find((e) => api.events.system.ExtrinsicFailed.is(e.event)) if (failed != undefined) { - return err(decodeError(api, failed.event.data[0])) + return err({ reason: decodeError(api, failed.event.data[0]), details }) } - const events = txResult.events - const [txHash, txIndex, blockHash, blockNumber] = await getBlockHashAndTxHash(txResult, waitFor, api) - - return ok(new ParsedTxResult(txResult, events, txHash, txIndex, blockHash, blockNumber)) + return ok(details) } export function commissionNumberToPerbill(value: number): Result { From ce51806d04e092ce0fb2baf841c6fe179a19a1cb Mon Sep 17 00:00:00 2001 From: Marko Petrlic Date: Thu, 17 Oct 2024 09:47:24 +0200 Subject: [PATCH 3/8] Moved multisig interface from utils to tx --- avail-js/docs/advanced_examples/multisig.ts | 34 ++-- avail-js/src/sdk/transactions/index.ts | 3 + avail-js/src/sdk/transactions/multisig.ts | 184 ++++++++++++++++++++ avail-js/src/sdk/utils/index.ts | 107 ------------ 4 files changed, 207 insertions(+), 121 deletions(-) diff --git a/avail-js/docs/advanced_examples/multisig.ts b/avail-js/docs/advanced_examples/multisig.ts index 6b7d61f86..6655bf62b 100644 --- a/avail-js/docs/advanced_examples/multisig.ts +++ b/avail-js/docs/advanced_examples/multisig.ts @@ -40,12 +40,12 @@ const main = async () => { // Create New Multisig const call1signatures = sdk.util.sortMultisigAddresses([bob.address, charlie.address]) - const firstResult = await firstApproval(sdk, alice, callHash, threshold, call1signatures, maxWeight) + const firstResult = await firstApproval(sdk, alice, threshold, call1signatures, callHash, maxWeight) // Approve existing Multisig const timepoint: MultisigTimepoint = { height: firstResult.blockNumber, index: firstResult.txIndex } const call2signatures = sdk.util.sortMultisigAddresses([alice.address, charlie.address]) - const _secondResult = await nextApproval(sdk, bob, callHash, threshold, call2signatures, timepoint) + const _secondResult = await nextApproval(sdk, bob, threshold, call2signatures, timepoint, callHash, maxWeight) // Execute Multisig const call3signatures = sdk.util.sortMultisigAddresses([alice.address, bob.address]) @@ -58,8 +58,8 @@ async function fundMultisigAccount(sdk: SDK, alice: KeyringPair, multisigAddress console.log("Funding multisig account...") const amount = new BN(10).pow(new BN(18)).mul(new BN(100)) // 100 Avail const result = await sdk.tx.balances.transferKeepAlive(multisigAddress, amount, WaitFor.BlockInclusion, alice) - if (result.isErr) { - console.log(result.reason) + if (result.isErr()) { + console.log(result.error.reason) process.exit(1) } @@ -69,17 +69,18 @@ async function fundMultisigAccount(sdk: SDK, alice: KeyringPair, multisigAddress async function firstApproval( sdk: SDK, account: KeyringPair, - callHash: string, threshold: number, otherSignatures: string[], + callHash: string, maxWeight: Weight, ): Promise { console.log("Alice is creating a Multisig Transaction...") - const maybeTxResult = await sdk.util.firstMultisigApproval( - callHash, + const maybeTxResult = await sdk.tx.multisig.approveAsMulti( threshold, otherSignatures, + null, + callHash, maxWeight, WaitFor.BlockInclusion, account, @@ -88,24 +89,27 @@ async function firstApproval( console.log(maybeTxResult.error) process.exit(1) } - return maybeTxResult.value + + return maybeTxResult.value.details } async function nextApproval( sdk: SDK, account: KeyringPair, - callHash: string, threshold: number, otherSignatures: string[], timepoint: MultisigTimepoint, + callHash: string, + maxWeight: Weight, ): Promise { console.log("Bob is approving the existing Multisig Transaction...") - const maybeTxResult = await sdk.util.nextMultisigApproval( - callHash, + const maybeTxResult = await sdk.tx.multisig.approveAsMulti( threshold, otherSignatures, timepoint, + callHash, + maxWeight, WaitFor.BlockInclusion, account, ) @@ -113,7 +117,8 @@ async function nextApproval( console.log(maybeTxResult.error) process.exit(1) } - return maybeTxResult.value + + return maybeTxResult.value.details } async function lastApproval( @@ -127,7 +132,7 @@ async function lastApproval( ): Promise { console.log("Charlie is approving and executing the existing Multisig Transaction...") - const maybeTxResult = await sdk.util.lastMultisigApproval( + const maybeTxResult = await sdk.tx.multisig.asMulti( threshold, otherSignatures, timepoint, @@ -140,7 +145,8 @@ async function lastApproval( console.log(maybeTxResult.error) process.exit(1) } - return maybeTxResult.value + + return maybeTxResult.value.details } main() diff --git a/avail-js/src/sdk/transactions/index.ts b/avail-js/src/sdk/transactions/index.ts index 67223e244..addfa03ef 100644 --- a/avail-js/src/sdk/transactions/index.ts +++ b/avail-js/src/sdk/transactions/index.ts @@ -3,6 +3,7 @@ import { Balances } from "./balances" import { Staking } from "./staking" import { DataAvailability } from "./da" import { NominationPools } from "./nomination_pools" +import { Multisig } from "./multisig" export { WaitFor } from "./common" export { DispatchFeeModifier } from "./da" @@ -15,6 +16,7 @@ export class Transactions { balances: Balances staking: Staking nominationPools: NominationPools + multisig: Multisig constructor(api: ApiPromise) { this.api = api @@ -22,5 +24,6 @@ export class Transactions { this.balances = new Balances(api) this.staking = new Staking(api) this.nominationPools = new NominationPools(api) + this.multisig = new Multisig(api) } } diff --git a/avail-js/src/sdk/transactions/multisig.ts b/avail-js/src/sdk/transactions/multisig.ts index e69de29bb..e53c9ed59 100644 --- a/avail-js/src/sdk/transactions/multisig.ts +++ b/avail-js/src/sdk/transactions/multisig.ts @@ -0,0 +1,184 @@ +import { ApiPromise } from "@polkadot/api" +import { ISubmittableResult } from "@polkadot/types/types/extrinsic" +import { EventRecord, Weight } from "@polkadot/types/interfaces/types" +import { KeyringPair } from "@polkadot/keyring/types" +import { err, Result, ok } from "neverthrow" +import { SignerOptions } from "@polkadot/api/types" +import { WaitFor, standardCallback, TransactionFailed } from "./common" +import { MultisigTimepoint, parseTransactionResult, TxResultDetails } from "../utils" + +export class AsMultiTx { + constructor( + public event: Events.MultisigExecuted | undefined, + public event2: Events.MultisigApproval | undefined, + public details: TxResultDetails, + ) {} +} + +export class ApproveAsMultiTx { + constructor( + public event: Events.NewMultisig | undefined, + public event2: Events.MultisigApproval | undefined, + public details: TxResultDetails, + ) {} +} + +export class Multisig { + private api: ApiPromise + + constructor(api: ApiPromise) { + this.api = api + } + + async asMulti( + threshold: number, + otherSignatures: string[], + timepoint: MultisigTimepoint | null, + call: string, + maxWeight: Weight, + waitFor: WaitFor, + account: KeyringPair, + options?: Partial, + ): Promise> { + const optionWrapper = options || {} + const maybeTxResult = await new Promise>((res, _) => { + this.api.tx.multisig + .asMulti(threshold, otherSignatures, timepoint, call, maxWeight) + .signAndSend(account, optionWrapper, (result: ISubmittableResult) => { + standardCallback(result, res, waitFor) + }) + .catch((reason) => { + res(err(reason)) + }) + }) + + if (maybeTxResult.isErr()) { + return err(new TransactionFailed(maybeTxResult.error, null)) + } + const txResult = maybeTxResult.value + const maybeParsed = await parseTransactionResult(this.api, txResult, waitFor) + if (maybeParsed.isErr()) { + return err(maybeParsed.error) + } + const details = maybeParsed.value + + const event = Events.MultisigExecuted.New(details.events) + const event2 = Events.MultisigApproval.New(details.events) + + return ok(new AsMultiTx(event, event2, details)) + } + + async approveAsMulti( + threshold: number, + otherSignatures: string[], + timepoint: MultisigTimepoint | null, + callHash: string, + maxWeight: Weight, + waitFor: WaitFor, + account: KeyringPair, + options?: Partial, + ): Promise> { + const optionWrapper = options || {} + const maybeTxResult = await new Promise>((res, _) => { + this.api.tx.multisig + .approveAsMulti(threshold, otherSignatures, timepoint, callHash, maxWeight) + .signAndSend(account, optionWrapper, (result: ISubmittableResult) => { + standardCallback(result, res, waitFor) + }) + .catch((reason) => { + res(err(reason)) + }) + }) + + if (maybeTxResult.isErr()) { + return err(new TransactionFailed(maybeTxResult.error, null)) + } + const txResult = maybeTxResult.value + const maybeParsed = await parseTransactionResult(this.api, txResult, waitFor) + if (maybeParsed.isErr()) { + return err(maybeParsed.error) + } + const details = maybeParsed.value + + const event = Events.NewMultisig.New(details.events) + const event2 = Events.MultisigApproval.New(details.events) + + return ok(new ApproveAsMultiTx(event, event2, details)) + } +} + +export namespace Events { + export class MultisigApproval { + constructor( + public approving: string, + public timepoint: MultisigTimepoint, + public multisig: string, + public callHash: string, + ) {} + static New(events: EventRecord[]): MultisigApproval | undefined { + const ed: any = events.find((e) => e.event.method == "MultisigApproval" && e.event.section == "multisig")?.event + .data + if (ed == undefined) { + return undefined + } + + const timepoint = { + height: parseInt(ed["timepoint"].height.toString()), + index: parseInt(ed["timepoint"].index.toString()), + } + + return new MultisigApproval( + ed["approving"].toString(), + timepoint, + ed["multisig"].toString(), + ed["callHash"].toString(), + ) + } + } + + export class MultisigExecuted { + constructor( + public approving: string, + public timepoint: MultisigTimepoint, + public multisig: string, + public callHash: string, + public result: string, + ) {} + static New(events: EventRecord[]): MultisigExecuted | undefined { + const ed: any = events.find((e) => e.event.method == "MultisigExecuted" && e.event.section == "multisig")?.event + .data + if (ed == undefined) { + return undefined + } + + const timepoint = { + height: parseInt(ed["timepoint"].height.toString()), + index: parseInt(ed["timepoint"].index.toString()), + } + + return new MultisigExecuted( + ed["approving"].toString(), + timepoint, + ed["multisig"].toString(), + ed["callHash"].toString(), + ed["result"].toString(), + ) + } + } + + export class NewMultisig { + constructor( + public approving: string, + public multisig: string, + public callHash: string, + ) {} + static New(events: EventRecord[]): NewMultisig | undefined { + const ed: any = events.find((e) => e.event.method == "NewMultisig" && e.event.section == "multisig")?.event.data + if (ed == undefined) { + return undefined + } + + return new NewMultisig(ed["approving"].toString(), ed["multisig"].toString(), ed["callHash"].toString()) + } + } +} diff --git a/avail-js/src/sdk/utils/index.ts b/avail-js/src/sdk/utils/index.ts index 86ef4aed2..f6a355031 100644 --- a/avail-js/src/sdk/utils/index.ts +++ b/avail-js/src/sdk/utils/index.ts @@ -63,113 +63,6 @@ export class Utils { return generateMultisig(addresses, threshold) } - /// Creates and approves a multisig transaction - async firstMultisigApproval( - callHash: string, - threshold: number, - otherSignatures: string[], - maxWeight: Weight, - waitFor: WaitFor, - account: KeyringPair, - options?: Partial, - ): Promise> { - const optionWrapper = options || {} - const maybeTxResult = await new Promise>((res, _) => { - this.api.tx.multisig - .approveAsMulti(threshold, otherSignatures, null, callHash, maxWeight) - .signAndSend(account, optionWrapper, (result: ISubmittableResult) => { - standardCallback(result, res, waitFor) - }) - .catch((reason) => { - res(err(reason)) - }) - }) - - if (maybeTxResult.isErr()) { - return err(maybeTxResult.error) - } - const txResult = maybeTxResult.value - const maybeParsed = await this.parseTransactionResult(txResult, waitFor) - if (maybeParsed.isErr()) { - return err(maybeParsed.error.reason) - } - const parsed = maybeParsed.value - - return ok(parsed) - } - - /// Approves an existing multisig transaction - async nextMultisigApproval( - callHash: string, - threshold: number, - otherSignatures: string[], - timepoint: MultisigTimepoint, - waitFor: WaitFor, - account: KeyringPair, - options?: Partial, - ): Promise> { - const maxWeight = { refTime: 0, proofSize: 0 } - const optionWrapper = options || {} - const maybeTxResult = await new Promise>((res, _) => { - this.api.tx.multisig - .approveAsMulti(threshold, otherSignatures, timepoint, callHash, maxWeight) - .signAndSend(account, optionWrapper, (result: ISubmittableResult) => { - standardCallback(result, res, waitFor) - }) - .catch((reason) => { - res(err(reason)) - }) - }) - - if (maybeTxResult.isErr()) { - return err(maybeTxResult.error) - } - const txResult = maybeTxResult.value - const maybeParsed = await this.parseTransactionResult(txResult, waitFor) - if (maybeParsed.isErr()) { - return err(maybeParsed.error.reason) - } - const parsed = maybeParsed.value - - return ok(parsed) - } - - /// Approves and executes an existing multisig transaction - async lastMultisigApproval( - threshold: number, - otherSignatures: string[], - timepoint: MultisigTimepoint, - callData: string, - maxWeight: Weight, - waitFor: WaitFor, - account: KeyringPair, - options?: Partial, - ): Promise> { - const optionWrapper = options || {} - const maybeTxResult = await new Promise>((res, _) => { - this.api.tx.multisig - .asMulti(threshold, otherSignatures, timepoint, callData, maxWeight) - .signAndSend(account, optionWrapper, (result: ISubmittableResult) => { - standardCallback(result, res, waitFor) - }) - .catch((reason) => { - res(err(reason)) - }) - }) - - if (maybeTxResult.isErr()) { - return err(maybeTxResult.error) - } - const txResult = maybeTxResult.value - const maybeParsed = await this.parseTransactionResult(txResult, waitFor) - if (maybeParsed.isErr()) { - return err(maybeParsed.error.reason) - } - const parsed = maybeParsed.value - - return ok(parsed) - } - /// Sorts multisig address so that ce be used for other multisig functions sortMultisigAddresses(addresses: string[]): string[] { return sortMultisigAddresses(addresses) From d81e42b40a9e5e9c6c3ca9777dfae85031f805f2 Mon Sep 17 00:00:00 2001 From: Marko Petrlic Date: Thu, 17 Oct 2024 14:22:19 +0200 Subject: [PATCH 4/8] Added Account abstraction. Fixed tx options mess --- avail-js/docs/advanced_examples/multisig.ts | 2 +- avail-js/src/sdk/account.ts | 106 ++++++++++++++++++ avail-js/src/sdk/index.ts | 1 + avail-js/src/sdk/transactions/balances.ts | 40 ++++++- avail-js/src/sdk/transactions/common.ts | 7 ++ avail-js/src/sdk/transactions/da.ts | 29 +++-- avail-js/src/sdk/transactions/multisig.ts | 6 +- .../src/sdk/transactions/nomination_pools.ts | 32 +++--- avail-js/src/sdk/transactions/staking.ts | 16 +-- 9 files changed, 196 insertions(+), 43 deletions(-) create mode 100644 avail-js/src/sdk/account.ts diff --git a/avail-js/docs/advanced_examples/multisig.ts b/avail-js/docs/advanced_examples/multisig.ts index 6655bf62b..5af63525f 100644 --- a/avail-js/docs/advanced_examples/multisig.ts +++ b/avail-js/docs/advanced_examples/multisig.ts @@ -145,7 +145,7 @@ async function lastApproval( console.log(maybeTxResult.error) process.exit(1) } - + return maybeTxResult.value.details } diff --git a/avail-js/src/sdk/account.ts b/avail-js/src/sdk/account.ts new file mode 100644 index 000000000..f57179dba --- /dev/null +++ b/avail-js/src/sdk/account.ts @@ -0,0 +1,106 @@ +import { BN } from "@polkadot/util" +import { KeyringPair } from "@polkadot/keyring/types" +import { Result } from "neverthrow" +import { H256, SDK, WaitFor } from "." +import { TransferKeepAliveTx } from "./transactions/balances" +import { TransactionFailed } from "./transactions/common" +import { CreateApplicationKeyTx, SubmitDataTx } from "./transactions/da" +import { Bytes } from "@polkadot/types-codec" + +export interface AccountBalance { + free: BN + reserved: BN + frozen: BN + flags: BN +} + +export class Account { + waitFor: WaitFor.BlockInclusion = WaitFor.BlockInclusion + nonce: number | null = null + appId: number | null = null + + constructor( + public sdk: SDK, + public keyring: KeyringPair, + ) {} + + setNonce(nonce: number | null) { + this.nonce = nonce + } + + setAppId(appId: number | null) { + this.appId = appId + } + + async balanceTransfer(dest: string, value: BN): Promise> { + const options = this.buildOptions() + return await this.sdk.tx.balances.transferKeepAlive(dest, value, this.waitFor, this.keyring, options) + } + async balanceTransferNoWait(dest: string, value: BN): Promise { + const options = this.buildOptions() + return await this.sdk.tx.balances.transferKeepAliveNoWait(dest, value, this.keyring, options) + } + + async submitData(data: string | Bytes): Promise> { + const options = this.buildOptions() + return await this.sdk.tx.dataAvailability.submitData(data, this.waitFor, this.keyring, options) + } + + async submitDataNoWait(data: string | Bytes): Promise { + const options = this.buildOptions() + return await this.sdk.tx.dataAvailability.submitDataNoWait(data, this.keyring, options) + } + + async createApplicationKey(key: string): Promise> { + const options = this.buildOptions() + return await this.sdk.tx.dataAvailability.createApplicationKey(key, this.waitFor, this.keyring, options) + } + + async createApplicationKeyNoWait(key: string): Promise { + const options = this.buildOptions() + return await this.sdk.tx.dataAvailability.createApplicationKeyNoWait(key, this.keyring, options) + } + + async getBalance(): Promise { + const r: any = await this.sdk.api.query.system.account(this.keyring.address) + return { free: r.data.free, reserved: r.data.reserved, frozen: r.data.frozen, flags: r.data.flags } + } + + async getNonceState(): Promise { + const r: any = await this.sdk.api.query.system.account(this.keyring.address) + return parseInt(r.nonce.toString()) + } + + async getNonceNode(): Promise { + const r: any = await this.sdk.api.rpc.system.accountNextIndex(this.keyring.address) + return parseInt(r.toString()) + } + + async appKeys(): Promise { + const appKeys: number[] = [] + const entries = await this.sdk.api.query.dataAvailability.appKeys.entries() + entries.forEach((entry: any) => { + if (entry[1].isSome) { + let { owner, id } = entry[1].unwrap() + if (owner.toString() == this.keyring.address) { + appKeys.push(parseInt(id.toString())) + } + } + }) + + return appKeys.sort((a, b) => a - b) + } + + private buildOptions(): any { + let options: any = {} + if (this.nonce != null) { + options.nonce = this.nonce + } + + if (this.appId != null) { + options.app_id = this.appId + } + + return options + } +} diff --git a/avail-js/src/sdk/index.ts b/avail-js/src/sdk/index.ts index 8bcada9b6..2abfcbbb4 100644 --- a/avail-js/src/sdk/index.ts +++ b/avail-js/src/sdk/index.ts @@ -12,6 +12,7 @@ export { KeyringPair } from "@polkadot/keyring/types" export { Bytes } from "@polkadot/types-codec" export { H256, Weight } from "@polkadot/types/interfaces" export { TxResultDetails, MultisigTimepoint } from "./utils" +export { Account } from "./account" export { WaitFor, diff --git a/avail-js/src/sdk/transactions/balances.ts b/avail-js/src/sdk/transactions/balances.ts index 34573ace5..09ca05b8b 100644 --- a/avail-js/src/sdk/transactions/balances.ts +++ b/avail-js/src/sdk/transactions/balances.ts @@ -1,12 +1,12 @@ import { ApiPromise } from "@polkadot/api" import { ISubmittableResult } from "@polkadot/types/types/extrinsic" -import { EventRecord } from "@polkadot/types/interfaces/types" +import { EventRecord, H256 } from "@polkadot/types/interfaces/types" import { BN } from "@polkadot/util" import { KeyringPair } from "@polkadot/keyring/types" import { err, Result, ok } from "neverthrow" import { SignerOptions } from "@polkadot/api/types" -import { WaitFor, standardCallback, TransactionFailed } from "./common" +import { WaitFor, standardCallback, TransactionFailed, TransactionOptions } from "./common" import { parseTransactionResult, TxResultDetails } from "../utils" export class TransferKeepAliveTx { @@ -44,7 +44,7 @@ export class Balances { keepAlive: boolean, waitFor: WaitFor, account: KeyringPair, - options?: Partial, + options?: TransactionOptions, ): Promise> { const optionWrapper = options || {} const maybeTxResult = await new Promise>((res, _) => { @@ -77,12 +77,22 @@ export class Balances { return ok(new TransferAllTx(event, event2, details)) } + async transferAllNoWait( + dest: string, + keepAlive: boolean, + account: KeyringPair, + options?: TransactionOptions, + ): Promise { + const optionWrapper = options || {} + return this.api.tx.balances.transferAll(dest, keepAlive).signAndSend(account, optionWrapper) + } + async transferAllowDeath( dest: string, value: BN, waitFor: WaitFor, account: KeyringPair, - options?: Partial, + options?: TransactionOptions, ): Promise> { const optionWrapper = options || {} const maybeTxResult = await new Promise>((res, _) => { @@ -115,12 +125,22 @@ export class Balances { return ok(new TransferAllowDeathTx(event, event2, details)) } + async transferAllowDeathNoWait( + dest: string, + value: BN, + account: KeyringPair, + options?: TransactionOptions, + ): Promise { + const optionWrapper = options || {} + return this.api.tx.balances.transferAllowDeath(dest, value).signAndSend(account, optionWrapper) + } + async transferKeepAlive( dest: string, value: BN, waitFor: WaitFor, account: KeyringPair, - options?: Partial, + options?: TransactionOptions, ): Promise> { const optionWrapper = options || {} const maybeTxResult = await new Promise>((res, _) => { @@ -151,6 +171,16 @@ export class Balances { return ok(new TransferKeepAliveTx(event, details)) } + + async transferKeepAliveNoWait( + dest: string, + value: BN, + account: KeyringPair, + options?: TransactionOptions, + ): Promise { + const optionWrapper = options || {} + return this.api.tx.balances.transferKeepAlive(dest, value).signAndSend(account, optionWrapper) + } } export namespace Events { diff --git a/avail-js/src/sdk/transactions/common.ts b/avail-js/src/sdk/transactions/common.ts index 73d979143..6fd6ccd7a 100644 --- a/avail-js/src/sdk/transactions/common.ts +++ b/avail-js/src/sdk/transactions/common.ts @@ -53,3 +53,10 @@ export class TransactionFailed { public details: TxResultDetails | null, ) {} } + +export interface TransactionOptions { + app_id?: number + nonce?: number + era?: number + blockHash?: H256 +} diff --git a/avail-js/src/sdk/transactions/da.ts b/avail-js/src/sdk/transactions/da.ts index b7f14b873..1ca9fc6d6 100644 --- a/avail-js/src/sdk/transactions/da.ts +++ b/avail-js/src/sdk/transactions/da.ts @@ -1,15 +1,14 @@ import { ApiPromise } from "@polkadot/api" import { ISubmittableResult } from "@polkadot/types/types/extrinsic" -import { EventRecord } from "@polkadot/types/interfaces/types" +import { EventRecord, H256 } from "@polkadot/types/interfaces/types" import { BN } from "@polkadot/util" import { KeyringPair } from "@polkadot/keyring/types" import { err, Result, ok } from "neverthrow" - import * as TransactionData from "./../transaction_data" -import { SignerOptions } from "@polkadot/api/types" import { decodeError, fromHexToAscii } from "../../helpers" -import { WaitFor, standardCallback, TransactionFailed } from "./common" +import { WaitFor, standardCallback, TransactionFailed, TransactionOptions } from "./common" import { parseTransactionResult, TxResultDetails } from "../utils" +import { Bytes } from "@polkadot/types-codec" export type DispatchFeeModifier = { weightMaximumFee: BN | null @@ -61,10 +60,10 @@ export class DataAvailability { } async submitData( - data: string, + data: string | Bytes, waitFor: WaitFor, account: KeyringPair, - options?: Partial, + options?: TransactionOptions, ): Promise> { const optionWrapper = options || {} const maybeTxResult = await new Promise>((res, _) => { @@ -105,11 +104,16 @@ export class DataAvailability { return ok(new SubmitDataTx(maybeTxData.value, event, details)) } + async submitDataNoWait(data: string | Bytes, account: KeyringPair, options?: TransactionOptions): Promise { + const optionWrapper = options || {} + return this.api.tx.dataAvailability.submitData(data).signAndSend(account, optionWrapper) + } + async createApplicationKey( key: string, waitFor: WaitFor, account: KeyringPair, - options?: Partial, + options?: TransactionOptions, ): Promise> { const optionWrapper = options || {} const maybeTxResult = await new Promise>((res, _) => { @@ -141,12 +145,17 @@ export class DataAvailability { return ok(new CreateApplicationKeyTx(event, details)) } + async createApplicationKeyNoWait(key: string, account: KeyringPair, options?: TransactionOptions): Promise { + const optionWrapper = options || {} + return this.api.tx.dataAvailability.createApplicationKey(key).signAndSend(account, optionWrapper) + } + async setApplicationKey( oldKey: string, newKey: string, waitFor: WaitFor, account: KeyringPair, - options?: Partial, + options?: TransactionOptions, ): Promise> { const optionWrapper = options || {} const maybeTxResult = await new Promise>((res, _) => { @@ -194,7 +203,7 @@ export class DataAvailability { cols: number, waitFor: WaitFor, account: KeyringPair, - options?: Partial, + options?: TransactionOptions, ): Promise> { const optionWrapper = options || {} const maybeTxResult = await new Promise>((res, _) => { @@ -241,7 +250,7 @@ export class DataAvailability { modifier: DispatchFeeModifier, waitFor: WaitFor, account: KeyringPair, - options?: Partial, + options?: TransactionOptions, ): Promise> { const optionWrapper = options || {} const maybeTxResult = await new Promise>((res, _) => { diff --git a/avail-js/src/sdk/transactions/multisig.ts b/avail-js/src/sdk/transactions/multisig.ts index e53c9ed59..3be996095 100644 --- a/avail-js/src/sdk/transactions/multisig.ts +++ b/avail-js/src/sdk/transactions/multisig.ts @@ -4,7 +4,7 @@ import { EventRecord, Weight } from "@polkadot/types/interfaces/types" import { KeyringPair } from "@polkadot/keyring/types" import { err, Result, ok } from "neverthrow" import { SignerOptions } from "@polkadot/api/types" -import { WaitFor, standardCallback, TransactionFailed } from "./common" +import { WaitFor, standardCallback, TransactionFailed, TransactionOptions } from "./common" import { MultisigTimepoint, parseTransactionResult, TxResultDetails } from "../utils" export class AsMultiTx { @@ -38,7 +38,7 @@ export class Multisig { maxWeight: Weight, waitFor: WaitFor, account: KeyringPair, - options?: Partial, + options?: TransactionOptions, ): Promise> { const optionWrapper = options || {} const maybeTxResult = await new Promise>((res, _) => { @@ -76,7 +76,7 @@ export class Multisig { maxWeight: Weight, waitFor: WaitFor, account: KeyringPair, - options?: Partial, + options?: TransactionOptions, ): Promise> { const optionWrapper = options || {} const maybeTxResult = await new Promise>((res, _) => { diff --git a/avail-js/src/sdk/transactions/nomination_pools.ts b/avail-js/src/sdk/transactions/nomination_pools.ts index 9d6cde8fa..c258a0990 100644 --- a/avail-js/src/sdk/transactions/nomination_pools.ts +++ b/avail-js/src/sdk/transactions/nomination_pools.ts @@ -6,7 +6,7 @@ import { KeyringPair } from "@polkadot/keyring/types" import { err, Result, ok } from "neverthrow" import { SignerOptions } from "@polkadot/api/types" -import { WaitFor, standardCallback, TransactionFailed } from "./common" +import { WaitFor, standardCallback, TransactionFailed, TransactionOptions } from "./common" import { commissionNumberToPerbill, parseTransactionResult, TxResultDetails } from "../utils" export interface BondExtra { @@ -131,7 +131,7 @@ export class NominationPools { bouncer: string, waitFor: WaitFor, account: KeyringPair, - options?: Partial, + options?: TransactionOptions, ): Promise> { const optionWrapper = options || {} const maybeTxResult = await new Promise>((res, _) => { @@ -175,7 +175,7 @@ export class NominationPools { poolId: number, waitFor: WaitFor, account: KeyringPair, - options?: Partial, + options?: TransactionOptions, ): Promise> { const optionWrapper = options || {} const maybeTxResult = await new Promise>((res, _) => { @@ -217,7 +217,7 @@ export class NominationPools { poolId: number, waitFor: WaitFor, account: KeyringPair, - options?: Partial, + options?: TransactionOptions, ): Promise> { const optionWrapper = options || {} const maybeTxResult = await new Promise>((res, _) => { @@ -254,7 +254,7 @@ export class NominationPools { validators: string[], waitFor: WaitFor, account: KeyringPair, - options?: Partial, + options?: TransactionOptions, ): Promise> { const optionWrapper = options || {} const maybeTxResult = await new Promise>((res, _) => { @@ -285,7 +285,7 @@ export class NominationPools { extra: BondExtra, waitFor: WaitFor, account: KeyringPair, - options?: Partial, + options?: TransactionOptions, ): Promise> { const optionWrapper = options || {} const maybeTxResult = await new Promise>((res, _) => { @@ -322,7 +322,7 @@ export class NominationPools { metadata: string, waitFor: WaitFor, account: KeyringPair, - options?: Partial, + options?: TransactionOptions, ): Promise> { const optionWrapper = options || {} const maybeTxResult = await new Promise>((res, _) => { @@ -354,7 +354,7 @@ export class NominationPools { unbondingPoints: BN, waitFor: WaitFor, account: KeyringPair, - options?: Partial, + options?: TransactionOptions, ): Promise> { const optionWrapper = options || {} const maybeTxResult = await new Promise>((res, _) => { @@ -387,7 +387,7 @@ export class NominationPools { poolId: number, waitFor: WaitFor, account: KeyringPair, - options?: Partial, + options?: TransactionOptions, ): Promise> { const optionWrapper = options || {} const maybeTxResult = await new Promise>((res, _) => { @@ -418,7 +418,7 @@ export class NominationPools { poolId: number, waitFor: WaitFor, account: KeyringPair, - options?: Partial, + options?: TransactionOptions, ): Promise> { const optionWrapper = options || {} const maybeTxResult = await new Promise>((res, _) => { @@ -453,7 +453,7 @@ export class NominationPools { async claimPayout( waitFor: WaitFor, account: KeyringPair, - options?: Partial, + options?: TransactionOptions, ): Promise> { const optionWrapper = options || {} const maybeTxResult = await new Promise>((res, _) => { @@ -485,7 +485,7 @@ export class NominationPools { other: string, waitFor: WaitFor, account: KeyringPair, - options?: Partial, + options?: TransactionOptions, ): Promise> { const optionWrapper = options || {} const maybeTxResult = await new Promise>((res, _) => { @@ -517,7 +517,7 @@ export class NominationPools { permission: ClaimPermission, waitFor: WaitFor, account: KeyringPair, - options?: Partial, + options?: TransactionOptions, ): Promise> { const optionWrapper = options || {} const maybeTxResult = await new Promise>((res, _) => { @@ -549,7 +549,7 @@ export class NominationPools { newCommission: NewCommission | null, waitFor: WaitFor, account: KeyringPair, - options?: Partial, + options?: TransactionOptions, ): Promise> { const optionWrapper = options || {} @@ -595,7 +595,7 @@ export class NominationPools { numSlashingSpans: number, waitFor: WaitFor, account: KeyringPair, - options?: Partial, + options?: TransactionOptions, ): Promise> { const optionWrapper = options || {} const maybeTxResult = await new Promise>((res, _) => { @@ -632,7 +632,7 @@ export class NominationPools { state: PoolState, waitFor: WaitFor, account: KeyringPair, - options?: Partial, + options?: TransactionOptions, ): Promise> { const optionWrapper = options || {} const maybeTxResult = await new Promise>((res, _) => { diff --git a/avail-js/src/sdk/transactions/staking.ts b/avail-js/src/sdk/transactions/staking.ts index acd220e74..0e4c082b9 100644 --- a/avail-js/src/sdk/transactions/staking.ts +++ b/avail-js/src/sdk/transactions/staking.ts @@ -7,7 +7,7 @@ import { err, Result, ok } from "neverthrow" import * as TransactionData from "./../transaction_data" import { SignerOptions } from "@polkadot/api/types" -import { WaitFor, standardCallback, TransactionFailed } from "./common" +import { WaitFor, standardCallback, TransactionFailed, TransactionOptions } from "./common" import { commissionNumberToPerbill, parseTransactionResult, TxResultDetails } from "../utils" type ValidatorPerfs = { commission: string; blocked: boolean } @@ -74,7 +74,7 @@ export class Staking { payee: StakingRewardDestination, waitFor: WaitFor, account: KeyringPair, - options?: Partial, + options?: TransactionOptions, ): Promise> { const optionWrapper = options || {} const maybeTxResult = await new Promise>((res, _) => { @@ -110,7 +110,7 @@ export class Staking { maxAdditional: BN, waitFor: WaitFor, account: KeyringPair, - options?: Partial, + options?: TransactionOptions, ): Promise> { const optionWrapper = options || {} const maybeTxResult = await new Promise>((res, _) => { @@ -145,7 +145,7 @@ export class Staking { async chill( waitFor: WaitFor, account: KeyringPair, - options?: Partial, + options?: TransactionOptions, ): Promise> { const optionWrapper = options || {} const maybeTxResult = await new Promise>((res, _) => { @@ -181,7 +181,7 @@ export class Staking { stash: string, waitFor: WaitFor, account: KeyringPair, - options?: Partial, + options?: TransactionOptions, ): Promise> { const optionWrapper = options || {} const maybeTxResult = await new Promise>((res, _) => { @@ -217,7 +217,7 @@ export class Staking { targets: string[], waitFor: WaitFor, account: KeyringPair, - options?: Partial, + options?: TransactionOptions, ): Promise> { const optionWrapper = options || {} const maybeTxResult = await new Promise>((res, _) => { @@ -253,7 +253,7 @@ export class Staking { value: BN, waitFor: WaitFor, account: KeyringPair, - options?: Partial, + options?: TransactionOptions, ): Promise> { const optionWrapper = options || {} const maybeTxResult = await new Promise>((res, _) => { @@ -290,7 +290,7 @@ export class Staking { blocked: boolean, waitFor: WaitFor, account: KeyringPair, - options?: Partial, + options?: TransactionOptions, ): Promise> { const maybeCommission = commissionNumberToPerbill(commission) if (maybeCommission.isErr()) { From b54ebec936fb80ae96f2c32e756328e366d36313 Mon Sep 17 00:00:00 2001 From: Marko Petrlic Date: Thu, 17 Oct 2024 15:01:22 +0200 Subject: [PATCH 5/8] Added new extrinsic docs. Updated existing extrisnic docs --- avail-js/docs/advanced_examples/multisig.ts | 2 +- avail-js/docs/extrinsics/README.md | 180 +++++++++--------- .../docs/extrinsics/balances_tranfer_all.ts | 9 +- .../balances_tranfer_all_no_wait.ts | 17 ++ .../balances_tranfer_allow_death.ts | 11 +- .../balances_tranfer_allow_death_no_wait.ts | 17 ++ .../extrinsics/balances_tranfer_keep_alive.ts | 11 +- .../balances_tranfer_keep_alive_no_wait.ts | 17 ++ .../extrinsics/da_create_application_key.ts | 9 +- .../da_create_application_key_no_wait.ts | 16 ++ .../docs/extrinsics/da_set_aplication_key.ts | 9 +- .../da_set_submit_data_fee_modifier.ts | 11 +- .../da_submit_block_length_proposal.ts | 9 +- avail-js/docs/extrinsics/da_submit_data.ts | 11 +- .../docs/extrinsics/da_submit_data_no_wait.ts | 17 ++ .../extrinsics/nomination_pools_bond_extra.ts | 10 +- .../docs/extrinsics/nomination_pools_chill.ts | 8 +- .../nomination_pools_claim_commission.ts | 8 +- .../nomination_pools_claim_payout.ts | 8 +- .../nomination_pools_claim_payout_other.ts | 8 +- .../extrinsics/nomination_pools_create.ts | 10 +- .../nomination_pools_create_with_pool_id.ts | 10 +- .../docs/extrinsics/nomination_pools_join.ts | 10 +- .../extrinsics/nomination_pools_nominate.ts | 8 +- .../nomination_pools_set_claim_permission.ts | 8 +- .../nomination_pools_set_commission.ts | 8 +- .../nomination_pools_set_metadata.ts | 8 +- .../extrinsics/nomination_pools_set_state.ts | 8 +- .../extrinsics/nomination_pools_unbond.ts | 10 +- .../nomination_pools_withdraw_unbonded.ts | 8 +- avail-js/docs/extrinsics/staking_bond.ts | 11 +- .../docs/extrinsics/staking_bond_extra.ts | 11 +- avail-js/docs/extrinsics/staking_chill.ts | 9 +- .../docs/extrinsics/staking_chill_other.ts | 9 +- avail-js/docs/extrinsics/staking_nominate.ts | 9 +- avail-js/docs/extrinsics/staking_unbond.ts | 10 +- avail-js/docs/extrinsics/staking_validate.ts | 9 +- avail-js/docs/storage/da_app_keys.ts | 2 +- avail-js/docs/storage/da_app_keys_iter.ts | 2 +- avail-js/docs/storage/da_next_app_id.ts | 2 +- avail-js/docs/storage/staking_active_era.ts | 2 +- avail-js/docs/storage/staking_bonded.ts | 2 +- avail-js/docs/storage/staking_bonded_iter.ts | 2 +- avail-js/docs/storage/system_account.ts | 2 +- avail-js/docs/storage/system_account_iter.ts | 2 +- avail-js/src/sdk/account.ts | 19 +- avail-js/src/sdk/index.ts | 6 + avail-js/src/sdk/transactions/index.ts | 2 +- 48 files changed, 337 insertions(+), 250 deletions(-) create mode 100644 avail-js/docs/extrinsics/balances_tranfer_all_no_wait.ts create mode 100644 avail-js/docs/extrinsics/balances_tranfer_allow_death_no_wait.ts create mode 100644 avail-js/docs/extrinsics/balances_tranfer_keep_alive_no_wait.ts create mode 100644 avail-js/docs/extrinsics/da_create_application_key_no_wait.ts create mode 100644 avail-js/docs/extrinsics/da_submit_data_no_wait.ts diff --git a/avail-js/docs/advanced_examples/multisig.ts b/avail-js/docs/advanced_examples/multisig.ts index 5af63525f..645607825 100644 --- a/avail-js/docs/advanced_examples/multisig.ts +++ b/avail-js/docs/advanced_examples/multisig.ts @@ -15,7 +15,7 @@ const main = async () => { await fundMultisigAccount(sdk, alice, multisigAddress) // Define what action will be taken by the multisig account - const amount = new BN(10).pow(new BN(18)) // one Avail + const amount = SDK.oneAvail() const call = sdk.api.tx.balances.transferKeepAlive(multisigAddress, amount) // Data needed for multisig approval and execution const callHash = call.method.hash.toString() diff --git a/avail-js/docs/extrinsics/README.md b/avail-js/docs/extrinsics/README.md index 4fd093d66..03ce1231a 100644 --- a/avail-js/docs/extrinsics/README.md +++ b/avail-js/docs/extrinsics/README.md @@ -37,12 +37,12 @@ const main = async () => { const key = "MyAwesomeKey" const result = await sdk.tx.dataAvailability.createApplicationKey(key, WaitFor.BlockInclusion, account) - if (result.isErr) { - console.log(result.reason) + if (result.isErr()) { + console.log(result.error.reason) process.exit(1) } - console.log(JSON.stringify(result, null, 2)) + console.log(JSON.stringify(result.value, null, 2)) process.exit() } @@ -108,12 +108,12 @@ const main = async () => { const data = "My Awesome Data" const result = await sdk.tx.dataAvailability.submitData(data, WaitFor.BlockInclusion, account) - if (result.isErr) { - console.log(result.reason) + if (result.isErr()) { + console.log(result.error.reason) process.exit(1) } - console.log(JSON.stringify(result, null, 2)) + console.log(JSON.stringify(result.value, null, 2)) process.exit() } main() @@ -182,12 +182,12 @@ const main = async () => { const cols = 128 const result = await sdk.tx.dataAvailability.submitBlockLengthProposal(rows, cols, WaitFor.BlockInclusion, account) - if (result.isErr) { - console.log(result.reason) + if (result.isErr()) { + console.log(result.error.reason) process.exit(1) } - console.log(JSON.stringify(result, null, 2)) + console.log(JSON.stringify(result.value, null, 2)) process.exit() } @@ -243,12 +243,12 @@ const main = async () => { const newKey = "MyNewKeyAwesome2" const result = await sdk.tx.dataAvailability.setApplicationKey(oldKey, newKey, WaitFor.BlockInclusion, account) - if (result.isErr) { - console.log(result.reason) + if (result.isErr()) { + console.log(result.error.reason) process.exit(1) } - console.log(JSON.stringify(result, null, 2)) + console.log(JSON.stringify(result.value, null, 2)) process.exit() } @@ -305,12 +305,12 @@ const main = async () => { } as sdkTransactions.DispatchFeeModifier const result = await sdk.tx.dataAvailability.setSubmitDataFeeModifier(modifier, WaitFor.BlockInclusion, account) - if (result.isErr) { - console.log(result.reason) + if (result.isErr()) { + console.log(result.error.reason) process.exit(1) } - console.log(JSON.stringify(result, null, 2)) + console.log(JSON.stringify(result.value, null, 2)) process.exit() } @@ -385,12 +385,12 @@ const main = async () => { const amount = new BN(10).pow(new BN(18)) // one Avail const result = await sdk.tx.balances.transferKeepAlive(dest, amount, WaitFor.BlockInclusion, account) - if (result.isErr) { - console.log(result.reason) + if (result.isErr()) { + console.log(result.error.reason) process.exit(1) } - console.log(JSON.stringify(result, null, 2)) + console.log(JSON.stringify(result.value, null, 2)) process.exit() } @@ -458,12 +458,12 @@ const main = async () => { const amount = new BN(10).pow(new BN(18)) // one Avail const result = await sdk.tx.balances.transferAllowDeath(dest, amount, WaitFor.BlockInclusion, account) - if (result.isErr) { - console.log(result.reason) + if (result.isErr()) { + console.log(result.error.reason) process.exit(1) } - console.log(JSON.stringify(result, null, 2)) + console.log(JSON.stringify(result.value, null, 2)) process.exit() } @@ -531,12 +531,12 @@ const main = async () => { const keepAlive = true const result = await sdk.tx.balances.transferAll(dest, keepAlive, WaitFor.BlockInclusion, account) - if (result.isErr) { - console.log(result.reason) + if (result.isErr()) { + console.log(result.error.reason) process.exit(1) } - console.log(JSON.stringify(result, null, 2)) + console.log(JSON.stringify(result.value, null, 2)) process.exit() } @@ -610,12 +610,12 @@ const main = async () => { const payee = "Staked" const result = await sdk.tx.staking.bond(value, payee, WaitFor.BlockInclusion, account) - if (result.isErr) { - console.log(result.reason) + if (result.isErr()) { + console.log(result.error.reason) process.exit(1) } - console.log(JSON.stringify(result, null, 2)) + console.log(JSON.stringify(result.value, null, 2)) process.exit() } @@ -680,12 +680,12 @@ const main = async () => { const maxAdditional = new BN(10).pow(new BN(18)) // one Avail const result = await sdk.tx.staking.bondExtra(maxAdditional, WaitFor.BlockInclusion, account) - if (result.isErr) { - console.log(result.reason) + if (result.isErr()) { + console.log(result.error.reason) process.exit(1) } - console.log(JSON.stringify(result, null, 2)) + console.log(JSON.stringify(result.value, null, 2)) process.exit() } @@ -747,12 +747,12 @@ const main = async () => { const account = new Keyring({ type: "sr25519" }).addFromUri("//Alice//stash") const result = await sdk.tx.staking.chill(WaitFor.BlockInclusion, account) - if (result.isErr) { - console.log(result.reason) + if (result.isErr()) { + console.log(result.error.reason) process.exit(1) } - console.log(JSON.stringify(result, null, 2)) + console.log(JSON.stringify(result.value, null, 2)) process.exit() } @@ -815,12 +815,12 @@ const main = async () => { const stash = "5GNJqTPyNqANBkUVMN1LPPrxXnFouWXoe2wNSmmEoLctxiZY" // Alice Stash const result = await sdk.tx.staking.chillOther(stash, WaitFor.BlockInclusion, account) - if (result.isErr) { - console.log(result.reason) + if (result.isErr()) { + console.log(result.error.reason) process.exit(1) } - console.log(JSON.stringify(result, null, 2)) + console.log(JSON.stringify(result.value, null, 2)) process.exit() } @@ -877,12 +877,12 @@ const main = async () => { ] const result = await sdk.tx.staking.nominate(targets, WaitFor.BlockInclusion, account) - if (result.isErr) { - console.log(result.reason) + if (result.isErr()) { + console.log(result.error.reason) process.exit(1) } - console.log(JSON.stringify(result, null, 2)) + console.log(JSON.stringify(result.value, null, 2)) process.exit() } @@ -949,12 +949,12 @@ const main = async () => { const value = new BN(10).pow(new BN(18)) // one Avail const result = await sdk.tx.staking.unbond(value, WaitFor.BlockInclusion, account) - if (result.isErr) { - console.log(result.reason) + if (result.isErr()) { + console.log(result.error.reason) process.exit(1) } - console.log(JSON.stringify(result, null, 2)) + console.log(JSON.stringify(result.value, null, 2)) process.exit() } main() @@ -1020,12 +1020,12 @@ const main = async () => { const blocked = false const result = await sdk.tx.staking.validate(commission, blocked, WaitFor.BlockInclusion, account) - if (result.isErr) { - console.log(result.reason) + if (result.isErr()) { + console.log(result.error.reason) process.exit(1) } - console.log(JSON.stringify(result, null, 2)) + console.log(JSON.stringify(result.value, null, 2)) process.exit() } @@ -1104,12 +1104,12 @@ const main = async () => { const bouncer: string = "5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY" // Alice const result = await sdk.tx.nominationPools.create(amount, root, nominator, bouncer, WaitFor.BlockInclusion, account) - if (result.isErr) { - console.log(result.reason) + if (result.isErr()) { + console.log(result.error.reason) process.exit(1) } - console.log(JSON.stringify(result, null, 2)) + console.log(JSON.stringify(result.value, null, 2)) process.exit() } main() @@ -1196,12 +1196,12 @@ const main = async () => { WaitFor.BlockInclusion, account, ) - if (result.isErr) { - console.log(result.reason) + if (result.isErr()) { + console.log(result.error.reason) process.exit(1) } - console.log(JSON.stringify(result, null, 2)) + console.log(JSON.stringify(result.value, null, 2)) process.exit() } main() @@ -1273,12 +1273,12 @@ const main = async () => { const poolId = 1 const result = await sdk.tx.nominationPools.join(amount, poolId, WaitFor.BlockInclusion, account) - if (result.isErr) { - console.log(result.reason) + if (result.isErr()) { + console.log(result.error.reason) process.exit(1) } - console.log(JSON.stringify(result, null, 2)) + console.log(JSON.stringify(result.value, null, 2)) process.exit() } main() @@ -1349,12 +1349,12 @@ const main = async () => { const poolId = 1 const result = await sdk.tx.nominationPools.nominate(poolId, validators, WaitFor.BlockInclusion, account) - if (result.isErr) { - console.log(result.reason) + if (result.isErr()) { + console.log(result.error.reason) process.exit(1) } - console.log(JSON.stringify(result, null, 2)) + console.log(JSON.stringify(result.value, null, 2)) process.exit() } main() @@ -1415,12 +1415,12 @@ const main = async () => { const bondExtra = { FreeBalance: amount } as BondExtra const result = await sdk.tx.nominationPools.bondExtra(bondExtra, WaitFor.BlockInclusion, account) - if (result.isErr) { - console.log(result.reason) + if (result.isErr()) { + console.log(result.error.reason) process.exit(1) } - console.log(JSON.stringify(result, null, 2)) + console.log(JSON.stringify(result.value, null, 2)) process.exit() } main() @@ -1488,12 +1488,12 @@ const main = async () => { const metadata = "My Metadata" const result = await sdk.tx.nominationPools.setMetadata(poolId, metadata, WaitFor.BlockInclusion, account) - if (result.isErr) { - console.log(result.reason) + if (result.isErr()) { + console.log(result.error.reason) process.exit(1) } - console.log(JSON.stringify(result, null, 2)) + console.log(JSON.stringify(result.value, null, 2)) process.exit() } main() @@ -1555,12 +1555,12 @@ const main = async () => { const unbondingPoints = new BN(10).pow(new BN(18)).mul(new BN(100)) // 100 Avail const result = await sdk.tx.nominationPools.unbond(memberAccount, unbondingPoints, WaitFor.BlockInclusion, account) - if (result.isErr) { - console.log(result.reason) + if (result.isErr()) { + console.log(result.error.reason) process.exit(1) } - console.log(JSON.stringify(result, null, 2)) + console.log(JSON.stringify(result.value, null, 2)) process.exit() } main() @@ -1627,12 +1627,12 @@ const main = async () => { const poolId = 1 const result = await sdk.tx.nominationPools.chill(poolId, WaitFor.BlockInclusion, account) - if (result.isErr) { - console.log(result.reason) + if (result.isErr()) { + console.log(result.error.reason) process.exit(1) } - console.log(JSON.stringify(result, null, 2)) + console.log(JSON.stringify(result.value, null, 2)) process.exit() } main() @@ -1692,12 +1692,12 @@ const main = async () => { const permission: ClaimPermission = "PermissionlessAll" const result = await sdk.tx.nominationPools.setClaimPermission(permission, WaitFor.BlockInclusion, account) - if (result.isErr) { - console.log(result.reason) + if (result.isErr()) { + console.log(result.error.reason) process.exit(1) } - console.log(JSON.stringify(result, null, 2)) + console.log(JSON.stringify(result.value, null, 2)) process.exit() } main() @@ -1757,12 +1757,12 @@ const main = async () => { const poolId = 1 const result = await sdk.tx.nominationPools.claimCommission(poolId, WaitFor.BlockInclusion, account) - if (result.isErr) { - console.log(result.reason) + if (result.isErr()) { + console.log(result.error.reason) process.exit(1) } - console.log(JSON.stringify(result, null, 2)) + console.log(JSON.stringify(result.value, null, 2)) process.exit() } main() @@ -1824,12 +1824,12 @@ const main = async () => { const account = new Keyring({ type: "sr25519" }).addFromUri("//Alice") const result = await sdk.tx.nominationPools.claimPayout(WaitFor.BlockInclusion, account) - if (result.isErr) { - console.log(result.reason) + if (result.isErr()) { + console.log(result.error.reason) process.exit(1) } - console.log(JSON.stringify(result, null, 2)) + console.log(JSON.stringify(result.value, null, 2)) process.exit() } main() @@ -1894,12 +1894,12 @@ const main = async () => { const other = "5FHneW46xGXgs5mUiveU4sbTyGBzmstUspZC92UhjJM694ty" // Bob const result = await sdk.tx.nominationPools.claimPayoutOther(other, WaitFor.BlockInclusion, account) - if (result.isErr) { - console.log(result.reason) + if (result.isErr()) { + console.log(result.error.reason) process.exit(1) } - console.log(JSON.stringify(result, null, 2)) + console.log(JSON.stringify(result.value, null, 2)) process.exit() } main() @@ -1966,12 +1966,12 @@ const main = async () => { const newCommission: NewCommission = { amount: 25, payee: "5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY" } const result = await sdk.tx.nominationPools.setCommission(poolId, newCommission, WaitFor.BlockInclusion, account) - if (result.isErr) { - console.log(result.reason) + if (result.isErr()) { + console.log(result.error.reason) process.exit(1) } - console.log(JSON.stringify(result, null, 2)) + console.log(JSON.stringify(result.value, null, 2)) process.exit() } main() @@ -2042,12 +2042,12 @@ const main = async () => { WaitFor.BlockInclusion, account, ) - if (result.isErr) { - console.log(result.reason) + if (result.isErr()) { + console.log(result.error.reason) process.exit(1) } - console.log(JSON.stringify(result, null, 2)) + console.log(JSON.stringify(result.value, null, 2)) process.exit() } main() @@ -2115,12 +2115,12 @@ const main = async () => { const state: PoolState = "Blocked" const result = await sdk.tx.nominationPools.setState(poolId, state, WaitFor.BlockInclusion, account) - if (result.isErr) { - console.log(result.reason) + if (result.isErr()) { + console.log(result.error.reason) process.exit(1) } - console.log(JSON.stringify(result, null, 2)) + console.log(JSON.stringify(result.value, null, 2)) process.exit() } main() diff --git a/avail-js/docs/extrinsics/balances_tranfer_all.ts b/avail-js/docs/extrinsics/balances_tranfer_all.ts index fdb02777e..675a4d8d8 100644 --- a/avail-js/docs/extrinsics/balances_tranfer_all.ts +++ b/avail-js/docs/extrinsics/balances_tranfer_all.ts @@ -1,4 +1,4 @@ -import { SDK, WaitFor, Keyring } from "avail-js-sdk" +import { SDK, WaitFor, Keyring } from "../../src/index" const main = async () => { const providerEndpoint = "ws://127.0.0.1:9944" @@ -10,13 +10,12 @@ const main = async () => { const keepAlive = true const result = await sdk.tx.balances.transferAll(dest, keepAlive, WaitFor.BlockInclusion, account) - if (result.isErr) { - console.log(result.reason) + if (result.isErr()) { + console.log(result.error.reason) process.exit(1) } - console.log(JSON.stringify(result, null, 2)) - + console.log(JSON.stringify(result.value, null, 2)) process.exit() } main() diff --git a/avail-js/docs/extrinsics/balances_tranfer_all_no_wait.ts b/avail-js/docs/extrinsics/balances_tranfer_all_no_wait.ts new file mode 100644 index 000000000..5a3382477 --- /dev/null +++ b/avail-js/docs/extrinsics/balances_tranfer_all_no_wait.ts @@ -0,0 +1,17 @@ +import { SDK, Keyring } from "../../src/index" + +const main = async () => { + const providerEndpoint = "ws://127.0.0.1:9944" + const sdk = await SDK.New(providerEndpoint) + + // Input + const account = new Keyring({ type: "sr25519" }).addFromUri("//Alice") + const dest = "5HGjWAeFDfFCWPsjFQdVV2Msvz2XtMktvgocEZcCj68kUMaw" // Eve + const keepAlive = true + + const txHash = await sdk.tx.balances.transferAllNoWait(dest, keepAlive, account) + + console.log(txHash) + process.exit() +} +main() diff --git a/avail-js/docs/extrinsics/balances_tranfer_allow_death.ts b/avail-js/docs/extrinsics/balances_tranfer_allow_death.ts index 899175982..27cb3e965 100644 --- a/avail-js/docs/extrinsics/balances_tranfer_allow_death.ts +++ b/avail-js/docs/extrinsics/balances_tranfer_allow_death.ts @@ -1,4 +1,4 @@ -import { SDK, WaitFor, Keyring, BN } from "avail-js-sdk" +import { SDK, WaitFor, Keyring } from "../../src/index" const main = async () => { const providerEndpoint = "ws://127.0.0.1:9944" @@ -7,16 +7,15 @@ const main = async () => { // Input const account = new Keyring({ type: "sr25519" }).addFromUri("//Alice") const dest = "5HGjWAeFDfFCWPsjFQdVV2Msvz2XtMktvgocEZcCj68kUMaw" // Eve - const amount = new BN(10).pow(new BN(18)) // one Avail + const amount = SDK.oneAvail() const result = await sdk.tx.balances.transferAllowDeath(dest, amount, WaitFor.BlockInclusion, account) - if (result.isErr) { - console.log(result.reason) + if (result.isErr()) { + console.log(result.error.reason) process.exit(1) } - console.log(JSON.stringify(result, null, 2)) - + console.log(JSON.stringify(result.value, null, 2)) process.exit() } main() diff --git a/avail-js/docs/extrinsics/balances_tranfer_allow_death_no_wait.ts b/avail-js/docs/extrinsics/balances_tranfer_allow_death_no_wait.ts new file mode 100644 index 000000000..fd176bc72 --- /dev/null +++ b/avail-js/docs/extrinsics/balances_tranfer_allow_death_no_wait.ts @@ -0,0 +1,17 @@ +import { SDK, Keyring } from "../../src/index" + +const main = async () => { + const providerEndpoint = "ws://127.0.0.1:9944" + const sdk = await SDK.New(providerEndpoint) + + // Input + const account = new Keyring({ type: "sr25519" }).addFromUri("//Alice") + const dest = "5HGjWAeFDfFCWPsjFQdVV2Msvz2XtMktvgocEZcCj68kUMaw" // Eve + const amount = SDK.oneAvail() + + const txHash = await sdk.tx.balances.transferAllowDeathNoWait(dest, amount, account) + + console.log(txHash) + process.exit() +} +main() diff --git a/avail-js/docs/extrinsics/balances_tranfer_keep_alive.ts b/avail-js/docs/extrinsics/balances_tranfer_keep_alive.ts index ef163cddb..a03bf6321 100644 --- a/avail-js/docs/extrinsics/balances_tranfer_keep_alive.ts +++ b/avail-js/docs/extrinsics/balances_tranfer_keep_alive.ts @@ -1,4 +1,4 @@ -import { SDK, WaitFor, Keyring, BN } from "avail-js-sdk" +import { SDK, WaitFor, Keyring } from "../../src/index" const main = async () => { const providerEndpoint = "ws://127.0.0.1:9944" @@ -7,16 +7,15 @@ const main = async () => { // Input const account = new Keyring({ type: "sr25519" }).addFromUri("//Alice") const dest = "5HGjWAeFDfFCWPsjFQdVV2Msvz2XtMktvgocEZcCj68kUMaw" // Eve - const amount = new BN(10).pow(new BN(18)) // one Avail + const amount = SDK.oneAvail() const result = await sdk.tx.balances.transferKeepAlive(dest, amount, WaitFor.BlockInclusion, account) - if (result.isErr) { - console.log(result.reason) + if (result.isErr()) { + console.log(result.error.reason) process.exit(1) } - console.log(JSON.stringify(result, null, 2)) - + console.log(JSON.stringify(result.value, null, 2)) process.exit() } main() diff --git a/avail-js/docs/extrinsics/balances_tranfer_keep_alive_no_wait.ts b/avail-js/docs/extrinsics/balances_tranfer_keep_alive_no_wait.ts new file mode 100644 index 000000000..8a03fe912 --- /dev/null +++ b/avail-js/docs/extrinsics/balances_tranfer_keep_alive_no_wait.ts @@ -0,0 +1,17 @@ +import { SDK, Keyring } from "../../src/index" + +const main = async () => { + const providerEndpoint = "ws://127.0.0.1:9944" + const sdk = await SDK.New(providerEndpoint) + + // Input + const account = new Keyring({ type: "sr25519" }).addFromUri("//Alice") + const dest = "5HGjWAeFDfFCWPsjFQdVV2Msvz2XtMktvgocEZcCj68kUMaw" // Eve + const amount = SDK.oneAvail() + + const txHash = await sdk.tx.balances.transferKeepAliveNoWait(dest, amount, account) + + console.log(txHash) + process.exit() +} +main() diff --git a/avail-js/docs/extrinsics/da_create_application_key.ts b/avail-js/docs/extrinsics/da_create_application_key.ts index 3e0430346..5c42d4713 100644 --- a/avail-js/docs/extrinsics/da_create_application_key.ts +++ b/avail-js/docs/extrinsics/da_create_application_key.ts @@ -1,4 +1,4 @@ -import { SDK, WaitFor, Keyring } from "avail-js-sdk" +import { SDK, WaitFor, Keyring } from "../../src/index" const main = async () => { const providerEndpoint = "ws://127.0.0.1:9944" @@ -9,13 +9,12 @@ const main = async () => { const key = "MyAwesomeKey" const result = await sdk.tx.dataAvailability.createApplicationKey(key, WaitFor.BlockInclusion, account) - if (result.isErr) { - console.log(result.reason) + if (result.isErr()) { + console.log(result.error.reason) process.exit(1) } - console.log(JSON.stringify(result, null, 2)) - + console.log(JSON.stringify(result.value, null, 2)) process.exit() } main() diff --git a/avail-js/docs/extrinsics/da_create_application_key_no_wait.ts b/avail-js/docs/extrinsics/da_create_application_key_no_wait.ts new file mode 100644 index 000000000..7ebf33bd9 --- /dev/null +++ b/avail-js/docs/extrinsics/da_create_application_key_no_wait.ts @@ -0,0 +1,16 @@ +import { SDK, Keyring } from "../../src/index" + +const main = async () => { + const providerEndpoint = "ws://127.0.0.1:9944" + const sdk = await SDK.New(providerEndpoint) + + // Input + const account = new Keyring({ type: "sr25519" }).addFromUri("//Alice") + const key = "MyAwesomeKey" + + const txHash = await sdk.tx.dataAvailability.createApplicationKeyNoWait(key, account) + + console.log(txHash) + process.exit() +} +main() diff --git a/avail-js/docs/extrinsics/da_set_aplication_key.ts b/avail-js/docs/extrinsics/da_set_aplication_key.ts index c1cfdb3c7..105446c4e 100644 --- a/avail-js/docs/extrinsics/da_set_aplication_key.ts +++ b/avail-js/docs/extrinsics/da_set_aplication_key.ts @@ -1,4 +1,4 @@ -import { SDK, WaitFor, Keyring } from "avail-js-sdk" +import { SDK, WaitFor, Keyring } from "../../src/index" const main = async () => { const providerEndpoint = "ws://127.0.0.1:9944" @@ -10,13 +10,12 @@ const main = async () => { const newKey = "MyNewKeyAwesome2" const result = await sdk.tx.dataAvailability.setApplicationKey(oldKey, newKey, WaitFor.BlockInclusion, account) - if (result.isErr) { - console.log(result.reason) + if (result.isErr()) { + console.log(result.error.reason) process.exit(1) } - console.log(JSON.stringify(result, null, 2)) - + console.log(JSON.stringify(result.value, null, 2)) process.exit() } main() diff --git a/avail-js/docs/extrinsics/da_set_submit_data_fee_modifier.ts b/avail-js/docs/extrinsics/da_set_submit_data_fee_modifier.ts index f018c0623..107609a40 100644 --- a/avail-js/docs/extrinsics/da_set_submit_data_fee_modifier.ts +++ b/avail-js/docs/extrinsics/da_set_submit_data_fee_modifier.ts @@ -1,4 +1,4 @@ -import { SDK, WaitFor, Keyring, BN, sdkTransactions } from "avail-js-sdk" +import { SDK, WaitFor, Keyring, sdkTransactions } from "../../src/index" const main = async () => { const providerEndpoint = "ws://127.0.0.1:9944" @@ -7,18 +7,17 @@ const main = async () => { // Input const account = new Keyring({ type: "sr25519" }).addFromUri("//Alice") const modifier = { - weightMaximumFee: new BN("10").pow(new BN("18")), + weightMaximumFee: SDK.oneAvail(), weightFeeDivider: 20, } as sdkTransactions.DispatchFeeModifier const result = await sdk.tx.dataAvailability.setSubmitDataFeeModifier(modifier, WaitFor.BlockInclusion, account) - if (result.isErr) { - console.log(result.reason) + if (result.isErr()) { + console.log(result.error.reason) process.exit(1) } - console.log(JSON.stringify(result, null, 2)) - + console.log(JSON.stringify(result.value, null, 2)) process.exit() } main() diff --git a/avail-js/docs/extrinsics/da_submit_block_length_proposal.ts b/avail-js/docs/extrinsics/da_submit_block_length_proposal.ts index ea518096a..2bd95a2c8 100644 --- a/avail-js/docs/extrinsics/da_submit_block_length_proposal.ts +++ b/avail-js/docs/extrinsics/da_submit_block_length_proposal.ts @@ -1,4 +1,4 @@ -import { SDK, WaitFor, Keyring } from "avail-js-sdk" +import { SDK, WaitFor, Keyring } from "../../src/index" const main = async () => { const providerEndpoint = "ws://127.0.0.1:9944" @@ -10,13 +10,12 @@ const main = async () => { const cols = 128 const result = await sdk.tx.dataAvailability.submitBlockLengthProposal(rows, cols, WaitFor.BlockInclusion, account) - if (result.isErr) { - console.log(result.reason) + if (result.isErr()) { + console.log(result.error.reason) process.exit(1) } - console.log(JSON.stringify(result, null, 2)) - + console.log(JSON.stringify(result.value, null, 2)) process.exit() } main() diff --git a/avail-js/docs/extrinsics/da_submit_data.ts b/avail-js/docs/extrinsics/da_submit_data.ts index 41e14b894..5a67793d8 100644 --- a/avail-js/docs/extrinsics/da_submit_data.ts +++ b/avail-js/docs/extrinsics/da_submit_data.ts @@ -1,4 +1,4 @@ -import { SDK, WaitFor, Keyring } from "avail-js-sdk" +import { SDK, WaitFor, Keyring, TransactionOptions } from "../../src/index" const main = async () => { const providerEndpoint = "ws://127.0.0.1:9944" @@ -8,13 +8,14 @@ const main = async () => { const account = new Keyring({ type: "sr25519" }).addFromUri("//Alice") const data = "My Awesome Data" - const result = await sdk.tx.dataAvailability.submitData(data, WaitFor.BlockInclusion, account) - if (result.isErr) { - console.log(result.reason) + const options: TransactionOptions = { app_id: 1 } + const result = await sdk.tx.dataAvailability.submitData(data, WaitFor.BlockInclusion, account, options) + if (result.isErr()) { + console.log(result.error.reason) process.exit(1) } - console.log(JSON.stringify(result, null, 2)) + console.log(JSON.stringify(result.value, null, 2)) process.exit() } main() diff --git a/avail-js/docs/extrinsics/da_submit_data_no_wait.ts b/avail-js/docs/extrinsics/da_submit_data_no_wait.ts new file mode 100644 index 000000000..be39fc956 --- /dev/null +++ b/avail-js/docs/extrinsics/da_submit_data_no_wait.ts @@ -0,0 +1,17 @@ +import { SDK, Keyring, TransactionOptions } from "../../src/index" + +const main = async () => { + const providerEndpoint = "ws://127.0.0.1:9944" + const sdk = await SDK.New(providerEndpoint) + + // Input + const account = new Keyring({ type: "sr25519" }).addFromUri("//Alice") + const data = "My Awesome Data" + + const options: TransactionOptions = { app_id: 1 } + const txHash = await sdk.tx.dataAvailability.submitDataNoWait(data, account, options) + + console.log(txHash) + process.exit() +} +main() diff --git a/avail-js/docs/extrinsics/nomination_pools_bond_extra.ts b/avail-js/docs/extrinsics/nomination_pools_bond_extra.ts index 2fb5523d6..255c273e0 100644 --- a/avail-js/docs/extrinsics/nomination_pools_bond_extra.ts +++ b/avail-js/docs/extrinsics/nomination_pools_bond_extra.ts @@ -1,4 +1,4 @@ -import { SDK, WaitFor, Keyring, BondExtra, BN } from "avail-js-sdk" +import { SDK, WaitFor, Keyring, BondExtra, BN } from "../../src/index" const main = async () => { const providerEndpoint = "ws://127.0.0.1:9944" @@ -6,16 +6,16 @@ const main = async () => { // 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 amount = SDK.oneAvail().mul(new BN(10000)) // 10_000 Avail const bondExtra = { FreeBalance: amount } as BondExtra const result = await sdk.tx.nominationPools.bondExtra(bondExtra, WaitFor.BlockInclusion, account) - if (result.isErr) { - console.log(result.reason) + if (result.isErr()) { + console.log(result.error.reason) process.exit(1) } - console.log(JSON.stringify(result, null, 2)) + console.log(JSON.stringify(result.value, null, 2)) process.exit() } main() diff --git a/avail-js/docs/extrinsics/nomination_pools_chill.ts b/avail-js/docs/extrinsics/nomination_pools_chill.ts index 12ccacfe0..ccda267a4 100644 --- a/avail-js/docs/extrinsics/nomination_pools_chill.ts +++ b/avail-js/docs/extrinsics/nomination_pools_chill.ts @@ -1,4 +1,4 @@ -import { SDK, WaitFor, Keyring } from "avail-js-sdk" +import { SDK, WaitFor, Keyring } from "../../src/index" const main = async () => { const providerEndpoint = "ws://127.0.0.1:9944" @@ -9,12 +9,12 @@ const main = async () => { const poolId = 1 const result = await sdk.tx.nominationPools.chill(poolId, WaitFor.BlockInclusion, account) - if (result.isErr) { - console.log(result.reason) + if (result.isErr()) { + console.log(result.error.reason) process.exit(1) } - console.log(JSON.stringify(result, null, 2)) + console.log(JSON.stringify(result.value, null, 2)) process.exit() } main() diff --git a/avail-js/docs/extrinsics/nomination_pools_claim_commission.ts b/avail-js/docs/extrinsics/nomination_pools_claim_commission.ts index 84bba5c2f..930963ad2 100644 --- a/avail-js/docs/extrinsics/nomination_pools_claim_commission.ts +++ b/avail-js/docs/extrinsics/nomination_pools_claim_commission.ts @@ -1,4 +1,4 @@ -import { SDK, WaitFor, Keyring } from "avail-js-sdk" +import { SDK, WaitFor, Keyring } from "../../src/index" const main = async () => { const providerEndpoint = "ws://127.0.0.1:9944" @@ -9,12 +9,12 @@ const main = async () => { const poolId = 1 const result = await sdk.tx.nominationPools.claimCommission(poolId, WaitFor.BlockInclusion, account) - if (result.isErr) { - console.log(result.reason) + if (result.isErr()) { + console.log(result.error.reason) process.exit(1) } - console.log(JSON.stringify(result, null, 2)) + console.log(JSON.stringify(result.value, null, 2)) process.exit() } main() diff --git a/avail-js/docs/extrinsics/nomination_pools_claim_payout.ts b/avail-js/docs/extrinsics/nomination_pools_claim_payout.ts index 70c2a54a1..cd6981f6f 100644 --- a/avail-js/docs/extrinsics/nomination_pools_claim_payout.ts +++ b/avail-js/docs/extrinsics/nomination_pools_claim_payout.ts @@ -1,4 +1,4 @@ -import { SDK, WaitFor, Keyring } from "avail-js-sdk" +import { SDK, WaitFor, Keyring } from "../../src/index" const main = async () => { const providerEndpoint = "ws://127.0.0.1:9944" @@ -8,12 +8,12 @@ const main = async () => { const account = new Keyring({ type: "sr25519" }).addFromUri("//Alice") const result = await sdk.tx.nominationPools.claimPayout(WaitFor.BlockInclusion, account) - if (result.isErr) { - console.log(result.reason) + if (result.isErr()) { + console.log(result.error.reason) process.exit(1) } - console.log(JSON.stringify(result, null, 2)) + console.log(JSON.stringify(result.value, null, 2)) process.exit() } main() diff --git a/avail-js/docs/extrinsics/nomination_pools_claim_payout_other.ts b/avail-js/docs/extrinsics/nomination_pools_claim_payout_other.ts index c00df7a85..3cf069122 100644 --- a/avail-js/docs/extrinsics/nomination_pools_claim_payout_other.ts +++ b/avail-js/docs/extrinsics/nomination_pools_claim_payout_other.ts @@ -1,4 +1,4 @@ -import { SDK, WaitFor, Keyring } from "avail-js-sdk" +import { SDK, WaitFor, Keyring } from "../../src/index" const main = async () => { const providerEndpoint = "ws://127.0.0.1:9944" @@ -9,12 +9,12 @@ const main = async () => { const other = "5FHneW46xGXgs5mUiveU4sbTyGBzmstUspZC92UhjJM694ty" // Bob const result = await sdk.tx.nominationPools.claimPayoutOther(other, WaitFor.BlockInclusion, account) - if (result.isErr) { - console.log(result.reason) + if (result.isErr()) { + console.log(result.error.reason) process.exit(1) } - console.log(JSON.stringify(result, null, 2)) + console.log(JSON.stringify(result.value, null, 2)) process.exit() } main() diff --git a/avail-js/docs/extrinsics/nomination_pools_create.ts b/avail-js/docs/extrinsics/nomination_pools_create.ts index f1f2fe7c6..2ea8cbec1 100644 --- a/avail-js/docs/extrinsics/nomination_pools_create.ts +++ b/avail-js/docs/extrinsics/nomination_pools_create.ts @@ -1,4 +1,4 @@ -import { SDK, WaitFor, Keyring, BN } from "avail-js-sdk" +import { SDK, WaitFor, Keyring, BN } from "../../src/index" const main = async () => { const providerEndpoint = "ws://127.0.0.1:9944" @@ -6,19 +6,19 @@ const main = async () => { // 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 amount = SDK.oneAvail().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.nominationPools.create(amount, root, nominator, bouncer, WaitFor.BlockInclusion, account) - if (result.isErr) { - console.log(result.reason) + if (result.isErr()) { + console.log(result.error.reason) process.exit(1) } - console.log(JSON.stringify(result, null, 2)) + console.log(JSON.stringify(result.value, null, 2)) process.exit() } main() diff --git a/avail-js/docs/extrinsics/nomination_pools_create_with_pool_id.ts b/avail-js/docs/extrinsics/nomination_pools_create_with_pool_id.ts index d6953d5c2..d80ab49c1 100644 --- a/avail-js/docs/extrinsics/nomination_pools_create_with_pool_id.ts +++ b/avail-js/docs/extrinsics/nomination_pools_create_with_pool_id.ts @@ -1,4 +1,4 @@ -import { SDK, WaitFor, Keyring, BN } from "avail-js-sdk" +import { SDK, WaitFor, Keyring, BN } from "../../src/index" const main = async () => { const providerEndpoint = "ws://127.0.0.1:9944" @@ -6,7 +6,7 @@ const main = async () => { // 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 amount = SDK.oneAvail().mul(new BN(10000)) // 10_000 Avail const root: string = "5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY" // Alice const nominator: string = "5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY" // Alice @@ -22,12 +22,12 @@ const main = async () => { WaitFor.BlockInclusion, account, ) - if (result.isErr) { - console.log(result.reason) + if (result.isErr()) { + console.log(result.error.reason) process.exit(1) } - console.log(JSON.stringify(result, null, 2)) + console.log(JSON.stringify(result.value, null, 2)) process.exit() } main() diff --git a/avail-js/docs/extrinsics/nomination_pools_join.ts b/avail-js/docs/extrinsics/nomination_pools_join.ts index a65c30d54..e60933f08 100644 --- a/avail-js/docs/extrinsics/nomination_pools_join.ts +++ b/avail-js/docs/extrinsics/nomination_pools_join.ts @@ -1,4 +1,4 @@ -import { SDK, WaitFor, Keyring, BN } from "avail-js-sdk" +import { SDK, WaitFor, Keyring, BN } from "../../src/index" const main = async () => { const providerEndpoint = "ws://127.0.0.1:9944" @@ -6,16 +6,16 @@ const main = async () => { // 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 amount = SDK.oneAvail().mul(new BN(10000)) // 10_000 Avail const poolId = 1 const result = await sdk.tx.nominationPools.join(amount, poolId, WaitFor.BlockInclusion, account) - if (result.isErr) { - console.log(result.reason) + if (result.isErr()) { + console.log(result.error.reason) process.exit(1) } - console.log(JSON.stringify(result, null, 2)) + console.log(JSON.stringify(result.value, null, 2)) process.exit() } main() diff --git a/avail-js/docs/extrinsics/nomination_pools_nominate.ts b/avail-js/docs/extrinsics/nomination_pools_nominate.ts index c939de186..de2be576b 100644 --- a/avail-js/docs/extrinsics/nomination_pools_nominate.ts +++ b/avail-js/docs/extrinsics/nomination_pools_nominate.ts @@ -1,4 +1,4 @@ -import { SDK, WaitFor, Keyring } from "avail-js-sdk" +import { SDK, WaitFor, Keyring } from "../../src/index" const main = async () => { const providerEndpoint = "ws://127.0.0.1:9944" @@ -13,12 +13,12 @@ const main = async () => { const poolId = 1 const result = await sdk.tx.nominationPools.nominate(poolId, validators, WaitFor.BlockInclusion, account) - if (result.isErr) { - console.log(result.reason) + if (result.isErr()) { + console.log(result.error.reason) process.exit(1) } - console.log(JSON.stringify(result, null, 2)) + console.log(JSON.stringify(result.value, null, 2)) process.exit() } main() diff --git a/avail-js/docs/extrinsics/nomination_pools_set_claim_permission.ts b/avail-js/docs/extrinsics/nomination_pools_set_claim_permission.ts index bb891a08b..047bcf17e 100644 --- a/avail-js/docs/extrinsics/nomination_pools_set_claim_permission.ts +++ b/avail-js/docs/extrinsics/nomination_pools_set_claim_permission.ts @@ -1,4 +1,4 @@ -import { SDK, WaitFor, Keyring, ClaimPermission } from "avail-js-sdk" +import { SDK, WaitFor, Keyring, ClaimPermission } from "../../src/index" const main = async () => { const providerEndpoint = "ws://127.0.0.1:9944" @@ -9,12 +9,12 @@ const main = async () => { const permission: ClaimPermission = "PermissionlessAll" const result = await sdk.tx.nominationPools.setClaimPermission(permission, WaitFor.BlockInclusion, account) - if (result.isErr) { - console.log(result.reason) + if (result.isErr()) { + console.log(result.error.reason) process.exit(1) } - console.log(JSON.stringify(result, null, 2)) + console.log(JSON.stringify(result.value, null, 2)) process.exit() } main() diff --git a/avail-js/docs/extrinsics/nomination_pools_set_commission.ts b/avail-js/docs/extrinsics/nomination_pools_set_commission.ts index 74e3baf65..c03803ccd 100644 --- a/avail-js/docs/extrinsics/nomination_pools_set_commission.ts +++ b/avail-js/docs/extrinsics/nomination_pools_set_commission.ts @@ -1,4 +1,4 @@ -import { SDK, WaitFor, Keyring, NewCommission } from "avail-js-sdk" +import { SDK, WaitFor, Keyring, NewCommission } from "../../src/index" const main = async () => { const providerEndpoint = "ws://127.0.0.1:9944" @@ -10,12 +10,12 @@ const main = async () => { const newCommission: NewCommission = { amount: 25, payee: "5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY" } const result = await sdk.tx.nominationPools.setCommission(poolId, newCommission, WaitFor.BlockInclusion, account) - if (result.isErr) { - console.log(result.reason) + if (result.isErr()) { + console.log(result.error.reason) process.exit(1) } - console.log(JSON.stringify(result, null, 2)) + console.log(JSON.stringify(result.value, null, 2)) process.exit() } main() diff --git a/avail-js/docs/extrinsics/nomination_pools_set_metadata.ts b/avail-js/docs/extrinsics/nomination_pools_set_metadata.ts index 7192b5540..a568daef4 100644 --- a/avail-js/docs/extrinsics/nomination_pools_set_metadata.ts +++ b/avail-js/docs/extrinsics/nomination_pools_set_metadata.ts @@ -1,4 +1,4 @@ -import { SDK, WaitFor, Keyring } from "avail-js-sdk" +import { SDK, WaitFor, Keyring } from "../../src/index" const main = async () => { const providerEndpoint = "ws://127.0.0.1:9944" @@ -10,12 +10,12 @@ const main = async () => { const metadata = "My Metadata" const result = await sdk.tx.nominationPools.setMetadata(poolId, metadata, WaitFor.BlockInclusion, account) - if (result.isErr) { - console.log(result.reason) + if (result.isErr()) { + console.log(result.error.reason) process.exit(1) } - console.log(JSON.stringify(result, null, 2)) + console.log(JSON.stringify(result.value, null, 2)) process.exit() } main() diff --git a/avail-js/docs/extrinsics/nomination_pools_set_state.ts b/avail-js/docs/extrinsics/nomination_pools_set_state.ts index 8e8edbd70..d67ccf1ce 100644 --- a/avail-js/docs/extrinsics/nomination_pools_set_state.ts +++ b/avail-js/docs/extrinsics/nomination_pools_set_state.ts @@ -1,4 +1,4 @@ -import { SDK, WaitFor, Keyring, PoolState } from "avail-js-sdk" +import { SDK, WaitFor, Keyring, PoolState } from "../../src/index" const main = async () => { const providerEndpoint = "ws://127.0.0.1:9944" @@ -10,12 +10,12 @@ const main = async () => { const state: PoolState = "Blocked" const result = await sdk.tx.nominationPools.setState(poolId, state, WaitFor.BlockInclusion, account) - if (result.isErr) { - console.log(result.reason) + if (result.isErr()) { + console.log(result.error.reason) process.exit(1) } - console.log(JSON.stringify(result, null, 2)) + console.log(JSON.stringify(result.value, null, 2)) process.exit() } main() diff --git a/avail-js/docs/extrinsics/nomination_pools_unbond.ts b/avail-js/docs/extrinsics/nomination_pools_unbond.ts index dcb501990..6613c9f61 100644 --- a/avail-js/docs/extrinsics/nomination_pools_unbond.ts +++ b/avail-js/docs/extrinsics/nomination_pools_unbond.ts @@ -1,4 +1,4 @@ -import { SDK, WaitFor, Keyring, BN } from "avail-js-sdk" +import { SDK, WaitFor, Keyring, BN } from "../../src/index" const main = async () => { const providerEndpoint = "ws://127.0.0.1:9944" @@ -7,15 +7,15 @@ const main = async () => { // Input const account = new Keyring({ type: "sr25519" }).addFromUri("//Alice") const memberAccount = "5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY" // Alice - const unbondingPoints = new BN(10).pow(new BN(18)).mul(new BN(100)) // 100 Avail + const unbondingPoints = SDK.oneAvail().mul(new BN(100)) // 100 Avail const result = await sdk.tx.nominationPools.unbond(memberAccount, unbondingPoints, WaitFor.BlockInclusion, account) - if (result.isErr) { - console.log(result.reason) + if (result.isErr()) { + console.log(result.error.reason) process.exit(1) } - console.log(JSON.stringify(result, null, 2)) + console.log(JSON.stringify(result.value, null, 2)) process.exit() } main() diff --git a/avail-js/docs/extrinsics/nomination_pools_withdraw_unbonded.ts b/avail-js/docs/extrinsics/nomination_pools_withdraw_unbonded.ts index 310dd70c6..82a5dc51c 100644 --- a/avail-js/docs/extrinsics/nomination_pools_withdraw_unbonded.ts +++ b/avail-js/docs/extrinsics/nomination_pools_withdraw_unbonded.ts @@ -1,4 +1,4 @@ -import { SDK, WaitFor, Keyring } from "avail-js-sdk" +import { SDK, WaitFor, Keyring } from "../../src/index" const main = async () => { const providerEndpoint = "ws://127.0.0.1:9944" @@ -15,12 +15,12 @@ const main = async () => { WaitFor.BlockInclusion, account, ) - if (result.isErr) { - console.log(result.reason) + if (result.isErr()) { + console.log(result.error.reason) process.exit(1) } - console.log(JSON.stringify(result, null, 2)) + console.log(JSON.stringify(result.value, null, 2)) process.exit() } main() diff --git a/avail-js/docs/extrinsics/staking_bond.ts b/avail-js/docs/extrinsics/staking_bond.ts index 8f4d5b4f0..2334fb750 100644 --- a/avail-js/docs/extrinsics/staking_bond.ts +++ b/avail-js/docs/extrinsics/staking_bond.ts @@ -1,4 +1,4 @@ -import { SDK, WaitFor, Keyring, BN } from "avail-js-sdk" +import { SDK, WaitFor, Keyring, BN } from "../../src/index" const main = async () => { const providerEndpoint = "ws://127.0.0.1:9944" @@ -6,17 +6,16 @@ const main = async () => { // Input const account = new Keyring({ type: "sr25519" }).addFromUri("//Alice") - const value = new BN(100_000).mul(new BN(10).pow(new BN("18"))) // 100 000 Avail + const value = SDK.oneAvail().mul(new BN(100000)) // 100_000 Avail const payee = "Staked" const result = await sdk.tx.staking.bond(value, payee, WaitFor.BlockInclusion, account) - if (result.isErr) { - console.log(result.reason) + if (result.isErr()) { + console.log(result.error.reason) process.exit(1) } - console.log(JSON.stringify(result, null, 2)) - + console.log(JSON.stringify(result.value, null, 2)) process.exit() } main() diff --git a/avail-js/docs/extrinsics/staking_bond_extra.ts b/avail-js/docs/extrinsics/staking_bond_extra.ts index 662329e1c..b582da026 100644 --- a/avail-js/docs/extrinsics/staking_bond_extra.ts +++ b/avail-js/docs/extrinsics/staking_bond_extra.ts @@ -1,4 +1,4 @@ -import { SDK, WaitFor, Keyring, BN } from "avail-js-sdk" +import { SDK, WaitFor, Keyring } from "../../src/index" const main = async () => { const providerEndpoint = "ws://127.0.0.1:9944" @@ -6,16 +6,15 @@ const main = async () => { // Input const account = new Keyring({ type: "sr25519" }).addFromUri("//Alice//stash") - const maxAdditional = new BN(10).pow(new BN(18)) // one Avail + const maxAdditional = SDK.oneAvail() const result = await sdk.tx.staking.bondExtra(maxAdditional, WaitFor.BlockInclusion, account) - if (result.isErr) { - console.log(result.reason) + if (result.isErr()) { + console.log(result.error.reason) process.exit(1) } - console.log(JSON.stringify(result, null, 2)) - + console.log(JSON.stringify(result.value, null, 2)) process.exit() } main() diff --git a/avail-js/docs/extrinsics/staking_chill.ts b/avail-js/docs/extrinsics/staking_chill.ts index 8a1a171da..1e843e994 100644 --- a/avail-js/docs/extrinsics/staking_chill.ts +++ b/avail-js/docs/extrinsics/staking_chill.ts @@ -1,4 +1,4 @@ -import { SDK, WaitFor, Keyring } from "avail-js-sdk" +import { SDK, WaitFor, Keyring } from "../../src/index" const main = async () => { const providerEndpoint = "ws://127.0.0.1:9944" const sdk = await SDK.New(providerEndpoint) @@ -7,13 +7,12 @@ const main = async () => { const account = new Keyring({ type: "sr25519" }).addFromUri("//Alice//stash") const result = await sdk.tx.staking.chill(WaitFor.BlockInclusion, account) - if (result.isErr) { - console.log(result.reason) + if (result.isErr()) { + console.log(result.error.reason) process.exit(1) } - console.log(JSON.stringify(result, null, 2)) - + console.log(JSON.stringify(result.value, null, 2)) process.exit() } main() diff --git a/avail-js/docs/extrinsics/staking_chill_other.ts b/avail-js/docs/extrinsics/staking_chill_other.ts index 0bedff0d8..c85afbe9f 100644 --- a/avail-js/docs/extrinsics/staking_chill_other.ts +++ b/avail-js/docs/extrinsics/staking_chill_other.ts @@ -1,4 +1,4 @@ -import { SDK, WaitFor, Keyring } from "avail-js-sdk" +import { SDK, WaitFor, Keyring } from "../../src/index" const main = async () => { const providerEndpoint = "ws://127.0.0.1:9944" const sdk = await SDK.New(providerEndpoint) @@ -8,13 +8,12 @@ const main = async () => { const stash = "5GNJqTPyNqANBkUVMN1LPPrxXnFouWXoe2wNSmmEoLctxiZY" // Alice Stash const result = await sdk.tx.staking.chillOther(stash, WaitFor.BlockInclusion, account) - if (result.isErr) { - console.log(result.reason) + if (result.isErr()) { + console.log(result.error.reason) process.exit(1) } - console.log(JSON.stringify(result, null, 2)) - + console.log(JSON.stringify(result.value, null, 2)) process.exit() } main() diff --git a/avail-js/docs/extrinsics/staking_nominate.ts b/avail-js/docs/extrinsics/staking_nominate.ts index 32dd4c3f2..039ccd9e5 100644 --- a/avail-js/docs/extrinsics/staking_nominate.ts +++ b/avail-js/docs/extrinsics/staking_nominate.ts @@ -1,4 +1,4 @@ -import { SDK, WaitFor, Keyring } from "avail-js-sdk" +import { SDK, WaitFor, Keyring } from "../../src/index" const main = async () => { const providerEndpoint = "ws://127.0.0.1:9944" @@ -12,13 +12,12 @@ const main = async () => { ] const result = await sdk.tx.staking.nominate(targets, WaitFor.BlockInclusion, account) - if (result.isErr) { - console.log(result.reason) + if (result.isErr()) { + console.log(result.error.reason) process.exit(1) } - console.log(JSON.stringify(result, null, 2)) - + console.log(JSON.stringify(result.value, null, 2)) process.exit() } main() diff --git a/avail-js/docs/extrinsics/staking_unbond.ts b/avail-js/docs/extrinsics/staking_unbond.ts index 700f24b8c..3f321e222 100644 --- a/avail-js/docs/extrinsics/staking_unbond.ts +++ b/avail-js/docs/extrinsics/staking_unbond.ts @@ -1,4 +1,4 @@ -import { SDK, WaitFor, Keyring, BN } from "avail-js-sdk" +import { SDK, WaitFor, Keyring } from "../../src/index" const main = async () => { const providerEndpoint = "ws://127.0.0.1:9944" @@ -6,15 +6,15 @@ const main = async () => { // Input const account = new Keyring({ type: "sr25519" }).addFromUri("//Alice") - const value = new BN(10).pow(new BN(18)) // one Avail + const value = SDK.oneAvail() const result = await sdk.tx.staking.unbond(value, WaitFor.BlockInclusion, account) - if (result.isErr) { - console.log(result.reason) + if (result.isErr()) { + console.log(result.error.reason) process.exit(1) } - console.log(JSON.stringify(result, null, 2)) + console.log(JSON.stringify(result.value, null, 2)) process.exit() } main() diff --git a/avail-js/docs/extrinsics/staking_validate.ts b/avail-js/docs/extrinsics/staking_validate.ts index 2cbac4868..c930a1af9 100644 --- a/avail-js/docs/extrinsics/staking_validate.ts +++ b/avail-js/docs/extrinsics/staking_validate.ts @@ -1,4 +1,4 @@ -import { SDK, WaitFor, Keyring } from "avail-js-sdk" +import { SDK, WaitFor, Keyring } from "../../src/index" const main = async () => { const providerEndpoint = "ws://127.0.0.1:9944" @@ -10,13 +10,12 @@ const main = async () => { const blocked = false const result = await sdk.tx.staking.validate(commission, blocked, WaitFor.BlockInclusion, account) - if (result.isErr) { - console.log(result.reason) + if (result.isErr()) { + console.log(result.error.reason) process.exit(1) } - console.log(JSON.stringify(result, null, 2)) - + console.log(JSON.stringify(result.value, null, 2)) process.exit() } main() diff --git a/avail-js/docs/storage/da_app_keys.ts b/avail-js/docs/storage/da_app_keys.ts index 61cf942fa..cd28c3ed6 100644 --- a/avail-js/docs/storage/da_app_keys.ts +++ b/avail-js/docs/storage/da_app_keys.ts @@ -1,4 +1,4 @@ -import { SDK } from "avail-js-sdk" +import { SDK } from "../../src/index" const main = async () => { const providerEndpoint = "ws://127.0.0.1:9944" diff --git a/avail-js/docs/storage/da_app_keys_iter.ts b/avail-js/docs/storage/da_app_keys_iter.ts index ca62fc37a..f9d6bd363 100644 --- a/avail-js/docs/storage/da_app_keys_iter.ts +++ b/avail-js/docs/storage/da_app_keys_iter.ts @@ -1,4 +1,4 @@ -import { SDK } from "avail-js-sdk" +import { SDK } from "../../src/index" const main = async () => { const providerEndpoint = "ws://127.0.0.1:9944" diff --git a/avail-js/docs/storage/da_next_app_id.ts b/avail-js/docs/storage/da_next_app_id.ts index 51419c71f..96fd38f88 100644 --- a/avail-js/docs/storage/da_next_app_id.ts +++ b/avail-js/docs/storage/da_next_app_id.ts @@ -1,4 +1,4 @@ -import { SDK } from "avail-js-sdk" +import { SDK } from "../../src/index" const main = async () => { const providerEndpoint = "ws://127.0.0.1:9944" diff --git a/avail-js/docs/storage/staking_active_era.ts b/avail-js/docs/storage/staking_active_era.ts index b9bad52b2..51b4f8a47 100644 --- a/avail-js/docs/storage/staking_active_era.ts +++ b/avail-js/docs/storage/staking_active_era.ts @@ -1,4 +1,4 @@ -import { SDK } from "avail-js-sdk" +import { SDK } from "../../src/index" const main = async () => { const providerEndpoint = "ws://127.0.0.1:9944" diff --git a/avail-js/docs/storage/staking_bonded.ts b/avail-js/docs/storage/staking_bonded.ts index 0296ea8f6..e27a1d363 100644 --- a/avail-js/docs/storage/staking_bonded.ts +++ b/avail-js/docs/storage/staking_bonded.ts @@ -1,4 +1,4 @@ -import { SDK } from "avail-js-sdk" +import { SDK } from "../../src/index" const main = async () => { const providerEndpoint = "ws://127.0.0.1:9944" diff --git a/avail-js/docs/storage/staking_bonded_iter.ts b/avail-js/docs/storage/staking_bonded_iter.ts index 7b548f41b..369fb3243 100644 --- a/avail-js/docs/storage/staking_bonded_iter.ts +++ b/avail-js/docs/storage/staking_bonded_iter.ts @@ -1,4 +1,4 @@ -import { SDK } from "avail-js-sdk" +import { SDK } from "../../src/index" const main = async () => { const providerEndpoint = "ws://127.0.0.1:9944" diff --git a/avail-js/docs/storage/system_account.ts b/avail-js/docs/storage/system_account.ts index 051783a4f..4971e418f 100644 --- a/avail-js/docs/storage/system_account.ts +++ b/avail-js/docs/storage/system_account.ts @@ -1,4 +1,4 @@ -import { SDK } from "avail-js-sdk" +import { SDK } from "../../src/index" const main = async () => { const providerEndpoint = "ws://127.0.0.1:9944" diff --git a/avail-js/docs/storage/system_account_iter.ts b/avail-js/docs/storage/system_account_iter.ts index 3d03cb1fc..d4ffbe3eb 100644 --- a/avail-js/docs/storage/system_account_iter.ts +++ b/avail-js/docs/storage/system_account_iter.ts @@ -1,4 +1,4 @@ -import { SDK } from "avail-js-sdk" +import { SDK } from "../../src/index" const main = async () => { const providerEndpoint = "ws://127.0.0.1:9944" diff --git a/avail-js/src/sdk/account.ts b/avail-js/src/sdk/account.ts index f57179dba..7abce29a1 100644 --- a/avail-js/src/sdk/account.ts +++ b/avail-js/src/sdk/account.ts @@ -15,7 +15,7 @@ export interface AccountBalance { } export class Account { - waitFor: WaitFor.BlockInclusion = WaitFor.BlockInclusion + waitFor: WaitFor = WaitFor.BlockInclusion nonce: number | null = null appId: number | null = null @@ -24,18 +24,23 @@ export class Account { public keyring: KeyringPair, ) {} - setNonce(nonce: number | null) { - this.nonce = nonce + setNonce(value: number | null) { + this.nonce = value } - setAppId(appId: number | null) { - this.appId = appId + setAppId(value: number | null) { + this.appId = value + } + + setWaitFor(value: WaitFor) { + this.waitFor = value } async balanceTransfer(dest: string, value: BN): Promise> { const options = this.buildOptions() return await this.sdk.tx.balances.transferKeepAlive(dest, value, this.waitFor, this.keyring, options) } + async balanceTransferNoWait(dest: string, value: BN): Promise { const options = this.buildOptions() return await this.sdk.tx.balances.transferKeepAliveNoWait(dest, value, this.keyring, options) @@ -91,6 +96,10 @@ export class Account { return appKeys.sort((a, b) => a - b) } + oneAvail(): BN { + return SDK.oneAvail() + } + private buildOptions(): any { let options: any = {} if (this.nonce != null) { diff --git a/avail-js/src/sdk/index.ts b/avail-js/src/sdk/index.ts index 2abfcbbb4..28fc48bb6 100644 --- a/avail-js/src/sdk/index.ts +++ b/avail-js/src/sdk/index.ts @@ -2,6 +2,7 @@ import { ApiPromise } from "@polkadot/api" import { initialize } from "../chain" import { Transactions } from "./transactions" import { Utils } from "./utils" +import { BN } from "@polkadot/util" export * as sdkTransactions from "./transactions" export * as sdkTransactionData from "./transaction_data" @@ -22,6 +23,7 @@ export { ClaimPermission, NewCommission, PoolState, + TransactionOptions, } from "./transactions" export class SDK { @@ -39,4 +41,8 @@ export class SDK { this.tx = new Transactions(api) this.util = new Utils(api) } + + static oneAvail(): BN { + return new BN(10).pow(new BN(18)) + } } diff --git a/avail-js/src/sdk/transactions/index.ts b/avail-js/src/sdk/transactions/index.ts index addfa03ef..452c31d1e 100644 --- a/avail-js/src/sdk/transactions/index.ts +++ b/avail-js/src/sdk/transactions/index.ts @@ -5,7 +5,7 @@ import { DataAvailability } from "./da" import { NominationPools } from "./nomination_pools" import { Multisig } from "./multisig" -export { WaitFor } from "./common" +export { WaitFor, TransactionOptions } from "./common" export { DispatchFeeModifier } from "./da" export { StakingRewardDestination } from "./staking" export { BondExtra, ClaimPermission, NewCommission, PoolState } from "./nomination_pools" From 1d7d42638af59727ae9ccb91633e68eb828f0e09 Mon Sep 17 00:00:00 2001 From: Marko Petrlic Date: Thu, 17 Oct 2024 16:03:51 +0200 Subject: [PATCH 6/8] Added examples for nonce, tranasction options and account abstractions --- .../advanced_examples/account_abstraction.ts | 52 +++++++++++++++++++ avail-js/docs/advanced_examples/nonce.ts | 29 +++++++++++ .../advanced_examples/transaction_options.ts | 26 ++++++++++ avail-js/src/sdk/account.ts | 13 +++-- avail-js/src/sdk/transactions/balances.ts | 2 - avail-js/src/sdk/utils/index.ts | 20 ++++++- 6 files changed, 131 insertions(+), 11 deletions(-) create mode 100644 avail-js/docs/advanced_examples/account_abstraction.ts create mode 100644 avail-js/docs/advanced_examples/nonce.ts create mode 100644 avail-js/docs/advanced_examples/transaction_options.ts diff --git a/avail-js/docs/advanced_examples/account_abstraction.ts b/avail-js/docs/advanced_examples/account_abstraction.ts new file mode 100644 index 000000000..9aa4846fb --- /dev/null +++ b/avail-js/docs/advanced_examples/account_abstraction.ts @@ -0,0 +1,52 @@ +import { SDK, Keyring, BN, Weight, TxResultDetails, MultisigTimepoint, Account, WaitFor } from "./../../src/index" + +const main = async () => { + const providerEndpoint = "ws://127.0.0.1:9944" + const sdk = await SDK.New(providerEndpoint) + const alice = new Keyring({ type: "sr25519" }).addFromUri("//Alice") + + /* + Sometimes the existing sdk functions can see too low level and cumbersome to use. + The Account class tries to remedy that by providing a similar interface but + with less parameters. + + Account related data like balance, nonce and associated app keys can all be accessed + by calling `getBalance`, `getNonceState`, and `getAppKeys` respectively. + */ + const account = new Account(sdk, alice) + console.log((await account.getBalance()).free.toString()) + console.log(await account.getNonceNode()) + console.log(await account.getNonceState()) + console.log(await account.getAppKeys()) + + /* + Three most common transactions are as well part of the Account interface. + `balanceTransfer` (`balanceTransferNoWait`) + `createApplicationKey` (`createApplicationKeyNoWait`) + `submitData` (`submitDataNoWait`) + */ + const _r1 = await account.balanceTransfer("5HGjWAeFDfFCWPsjFQdVV2Msvz2XtMktvgocEZcCj68kUMaw", account.oneAvail()) + const r2 = await account.createApplicationKey("Alice Key") + + /* + Setting app id, nonce, and the waitfor method can be easily done by calling + `setAppId`, `setNonce`, and `setWaitFor` respectively. + + These values are sticky which means they will persist until you change them again. + */ + account.setAppId(parseInt(r2._unsafeUnwrap().event.id)) + account.setNonce(await account.getNonceNode()) + account.setWaitFor(WaitFor.BlockInclusion) + const _r3 = await account.submitData("My Data") + + /* + To make sure that we don't use the same app id and the same nonce for our next + call we reset them to null (default value) + */ + account.setAppId(null) + account.setNonce(null) + const _r4 = await account.submitDataNoWait("My Data") + + process.exit() +} +main() diff --git a/avail-js/docs/advanced_examples/nonce.ts b/avail-js/docs/advanced_examples/nonce.ts new file mode 100644 index 000000000..a59da103d --- /dev/null +++ b/avail-js/docs/advanced_examples/nonce.ts @@ -0,0 +1,29 @@ +import { SDK, WaitFor, Keyring, TransactionOptions } from "./../../src/index" + +const main = async () => { + const providerEndpoint = "ws://127.0.0.1:9944" + const sdk = await SDK.New(providerEndpoint) + + const alice = new Keyring({ type: "sr25519" }).addFromUri("//Alice") + + /* + The SDK provides two easy to use but slightly different nonce functions. + - `getNonceState` - Returns nonce from the state of network. This only changes + on a per block basis + - `getNonceNode` - Returns nonce from the node's storage. This gets the nonce + from the state and it updates it if there are existing + transactions already in the mem pool. + + If in doubt, use `getNonceNode`. + */ + let nonceState1 = await sdk.util.getNonceState(alice.address) + let nonceNode1 = await sdk.util.getNonceNode(alice.address) + console.log(`Nonce State: ${nonceState1}, Nonce Node: ${nonceNode1}`) + let _result = await sdk.tx.dataAvailability.submitDataNoWait("Data", alice) + let nonceState2 = await sdk.util.getNonceState(alice.address) + let nonceNode2 = await sdk.util.getNonceNode(alice.address) + console.log(`Nonce State: ${nonceState2}, Nonce Node: ${nonceNode2}`) + + process.exit() +} +main() diff --git a/avail-js/docs/advanced_examples/transaction_options.ts b/avail-js/docs/advanced_examples/transaction_options.ts new file mode 100644 index 000000000..ab9a1481d --- /dev/null +++ b/avail-js/docs/advanced_examples/transaction_options.ts @@ -0,0 +1,26 @@ +import { SDK, WaitFor, Keyring, TransactionOptions } from "./../../src/index" + +const main = async () => { + const providerEndpoint = "ws://127.0.0.1:9944" + const sdk = await SDK.New(providerEndpoint) + const alice = new Keyring({ type: "sr25519" }).addFromUri("//Alice") + + /* + Setting up application id and/or nonce for any transaction is as simple as just defining them + and passing them as the last argument to any sdk transaction call. + + TransactionOptions interface has the following fields: + - app_id?: number + - nonce?: number + - era?: number + - blockHash?: H256 + */ + let nonce = await sdk.util.getNonceNode(alice.address) + let options: TransactionOptions = { app_id: 1, nonce } + let result = await sdk.tx.dataAvailability.submitData("Data", WaitFor.BlockInclusion, alice, options) + + console.log(JSON.stringify(result, null, 2)) + + process.exit() +} +main() diff --git a/avail-js/src/sdk/account.ts b/avail-js/src/sdk/account.ts index 7abce29a1..2895e0603 100644 --- a/avail-js/src/sdk/account.ts +++ b/avail-js/src/sdk/account.ts @@ -6,6 +6,7 @@ import { TransferKeepAliveTx } from "./transactions/balances" import { TransactionFailed } from "./transactions/common" import { CreateApplicationKeyTx, SubmitDataTx } from "./transactions/da" import { Bytes } from "@polkadot/types-codec" +import { getNonceState, getNonceNode } from "./utils" export interface AccountBalance { free: BN @@ -72,21 +73,19 @@ export class Account { } async getNonceState(): Promise { - const r: any = await this.sdk.api.query.system.account(this.keyring.address) - return parseInt(r.nonce.toString()) + return await getNonceState(this.sdk.api, this.keyring.address) } async getNonceNode(): Promise { - const r: any = await this.sdk.api.rpc.system.accountNextIndex(this.keyring.address) - return parseInt(r.toString()) + return await getNonceNode(this.sdk.api, this.keyring.address) } - async appKeys(): Promise { + async getAppKeys(): Promise { const appKeys: number[] = [] const entries = await this.sdk.api.query.dataAvailability.appKeys.entries() entries.forEach((entry: any) => { if (entry[1].isSome) { - let { owner, id } = entry[1].unwrap() + const { owner, id } = entry[1].unwrap() if (owner.toString() == this.keyring.address) { appKeys.push(parseInt(id.toString())) } @@ -101,7 +100,7 @@ export class Account { } private buildOptions(): any { - let options: any = {} + const options: any = {} if (this.nonce != null) { options.nonce = this.nonce } diff --git a/avail-js/src/sdk/transactions/balances.ts b/avail-js/src/sdk/transactions/balances.ts index 09ca05b8b..194fe3696 100644 --- a/avail-js/src/sdk/transactions/balances.ts +++ b/avail-js/src/sdk/transactions/balances.ts @@ -4,8 +4,6 @@ import { EventRecord, H256 } from "@polkadot/types/interfaces/types" import { BN } from "@polkadot/util" import { KeyringPair } from "@polkadot/keyring/types" import { err, Result, ok } from "neverthrow" - -import { SignerOptions } from "@polkadot/api/types" import { WaitFor, standardCallback, TransactionFailed, TransactionOptions } from "./common" import { parseTransactionResult, TxResultDetails } from "../utils" diff --git a/avail-js/src/sdk/utils/index.ts b/avail-js/src/sdk/utils/index.ts index f6a355031..b82e18b12 100644 --- a/avail-js/src/sdk/utils/index.ts +++ b/avail-js/src/sdk/utils/index.ts @@ -5,8 +5,6 @@ import { EventRecord, H256, Weight } from "@polkadot/types/interfaces" import { decodeError } from "../../helpers" import { getBlockHashAndTxHash, standardCallback, WaitFor } from "../transactions/common" import { createKeyMulti, encodeAddress, sortAddresses } from "@polkadot/util-crypto" -import { KeyringPair } from "@polkadot/keyring/types" -import { SignerOptions } from "@polkadot/api/types" export class TxResultDetails { constructor( @@ -67,6 +65,14 @@ export class Utils { sortMultisigAddresses(addresses: string[]): string[] { return sortMultisigAddresses(addresses) } + + async getNonceState(address: string): Promise { + return await getNonceState(this.api, address) + } + + async getNonceNode(address: string): Promise { + return await getNonceNode(this.api, address) + } } export async function parseTransactionResult( @@ -122,3 +128,13 @@ export function sortMultisigAddresses(addresses: string[]): string[] { return sortAddresses(addresses, SS58Prefix) } + +export async function getNonceState(api: ApiPromise, address: string): Promise { + const r: any = await api.query.system.account(address) + return parseInt(r.nonce.toString()) +} + +export async function getNonceNode(api: ApiPromise, address: string): Promise { + const r: any = await api.rpc.system.accountNextIndex(address) + return parseInt(r.toString()) +} From f3d456d71cf249c783be53b7a0e82e24f6ee08fd Mon Sep 17 00:00:00 2001 From: Marko Petrlic Date: Thu, 17 Oct 2024 16:25:57 +0200 Subject: [PATCH 7/8] Added doc extrinsic examples for as_multi and approving_as_multi --- .../extrinsics/multisig_approving_as_multi.ts | 42 ++++++++++++++++++ avail-js/docs/extrinsics/multisig_as_multi.ts | 43 +++++++++++++++++++ avail-js/src/sdk/transactions/multisig.ts | 1 - .../src/sdk/transactions/nomination_pools.ts | 1 - avail-js/src/sdk/transactions/staking.ts | 1 - avail-js/src/sdk/utils/index.ts | 4 +- 6 files changed, 87 insertions(+), 5 deletions(-) create mode 100644 avail-js/docs/extrinsics/multisig_approving_as_multi.ts create mode 100644 avail-js/docs/extrinsics/multisig_as_multi.ts diff --git a/avail-js/docs/extrinsics/multisig_approving_as_multi.ts b/avail-js/docs/extrinsics/multisig_approving_as_multi.ts new file mode 100644 index 000000000..144475da3 --- /dev/null +++ b/avail-js/docs/extrinsics/multisig_approving_as_multi.ts @@ -0,0 +1,42 @@ +import { SDK, WaitFor, Keyring } from "./../../src/index" + +const main = async () => { + const providerEndpoint = "ws://127.0.0.1:9944" + const sdk = await SDK.New(providerEndpoint) + + // Multisig Signatures + const alice = new Keyring({ type: "sr25519" }).addFromUri("//Alice") + const bobAddress = "5FHneW46xGXgs5mUiveU4sbTyGBzmstUspZC92UhjJM694ty" + + // Create Multisig Account + const threshold = 2 + const multisigAddress = sdk.util.generateMultisig([alice.address, bobAddress], threshold) + + // Define what action will be taken by the multisig account + const amount = SDK.oneAvail() + const call = sdk.api.tx.balances.transferKeepAlive(multisigAddress, amount) + // Data needed for multisig approval and execution + const callHash = call.method.hash.toString() + const maxWeight = (await call.paymentInfo(alice.address)).weight + + // Create New Multisig + console.log("Alice is creating a Multisig Transaction...") + const call1signatures = sdk.util.sortMultisigAddresses([bobAddress]) + const result = await sdk.tx.multisig.approveAsMulti( + threshold, + call1signatures, + null, + callHash, + maxWeight, + WaitFor.BlockInclusion, + alice, + ) + if (result.isErr()) { + console.log(result.error) + process.exit(1) + } + + console.log(JSON.stringify(result.value, null, 2)) + process.exit() +} +main() diff --git a/avail-js/docs/extrinsics/multisig_as_multi.ts b/avail-js/docs/extrinsics/multisig_as_multi.ts new file mode 100644 index 000000000..d0885a962 --- /dev/null +++ b/avail-js/docs/extrinsics/multisig_as_multi.ts @@ -0,0 +1,43 @@ +import { SDK, WaitFor, Keyring, MultisigTimepoint } from "./../../src/index" + +const main = async () => { + const providerEndpoint = "ws://127.0.0.1:9944" + const sdk = await SDK.New(providerEndpoint) + + // Multisig Signatures + const bob = new Keyring({ type: "sr25519" }).addFromUri("//Bob") + const aliceAddress = "5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY" + + // Create Multisig Account + const threshold = 2 + const multisigAddress = sdk.util.generateMultisig([aliceAddress, bob.address], threshold) + + // Define what action will be taken by the multisig account + const amount = SDK.oneAvail() + const call = sdk.api.tx.balances.transferKeepAlive(multisigAddress, amount) + // Data needed for multisig approval and execution + const callData = call.unwrap().toHex() + const maxWeight = (await call.paymentInfo(aliceAddress)).weight + const timepoint: MultisigTimepoint = { height: 4, index: 1 } + + // Approving and executing Multisig transaction + console.log("Bob is approving and executing the existing Multisig Transaction...") + const call2signatures = sdk.util.sortMultisigAddresses([aliceAddress]) + const secondResult = await sdk.tx.multisig.asMulti( + threshold, + call2signatures, + timepoint, + callData, + maxWeight, + WaitFor.BlockInclusion, + bob, + ) + if (secondResult.isErr()) { + console.log(secondResult.error) + process.exit(1) + } + + console.log(JSON.stringify(secondResult.value, null, 2)) + process.exit() +} +main() diff --git a/avail-js/src/sdk/transactions/multisig.ts b/avail-js/src/sdk/transactions/multisig.ts index 3be996095..79c5f4221 100644 --- a/avail-js/src/sdk/transactions/multisig.ts +++ b/avail-js/src/sdk/transactions/multisig.ts @@ -3,7 +3,6 @@ import { ISubmittableResult } from "@polkadot/types/types/extrinsic" import { EventRecord, Weight } from "@polkadot/types/interfaces/types" import { KeyringPair } from "@polkadot/keyring/types" import { err, Result, ok } from "neverthrow" -import { SignerOptions } from "@polkadot/api/types" import { WaitFor, standardCallback, TransactionFailed, TransactionOptions } from "./common" import { MultisigTimepoint, parseTransactionResult, TxResultDetails } from "../utils" diff --git a/avail-js/src/sdk/transactions/nomination_pools.ts b/avail-js/src/sdk/transactions/nomination_pools.ts index c258a0990..85fe296e6 100644 --- a/avail-js/src/sdk/transactions/nomination_pools.ts +++ b/avail-js/src/sdk/transactions/nomination_pools.ts @@ -5,7 +5,6 @@ import { BN } from "@polkadot/util" import { KeyringPair } from "@polkadot/keyring/types" import { err, Result, ok } from "neverthrow" -import { SignerOptions } from "@polkadot/api/types" import { WaitFor, standardCallback, TransactionFailed, TransactionOptions } from "./common" import { commissionNumberToPerbill, parseTransactionResult, TxResultDetails } from "../utils" diff --git a/avail-js/src/sdk/transactions/staking.ts b/avail-js/src/sdk/transactions/staking.ts index 0e4c082b9..2f9c1156f 100644 --- a/avail-js/src/sdk/transactions/staking.ts +++ b/avail-js/src/sdk/transactions/staking.ts @@ -6,7 +6,6 @@ import { KeyringPair } from "@polkadot/keyring/types" import { err, Result, ok } from "neverthrow" import * as TransactionData from "./../transaction_data" -import { SignerOptions } from "@polkadot/api/types" import { WaitFor, standardCallback, TransactionFailed, TransactionOptions } from "./common" import { commissionNumberToPerbill, parseTransactionResult, TxResultDetails } from "../utils" diff --git a/avail-js/src/sdk/utils/index.ts b/avail-js/src/sdk/utils/index.ts index b82e18b12..10a2834ca 100644 --- a/avail-js/src/sdk/utils/index.ts +++ b/avail-js/src/sdk/utils/index.ts @@ -1,9 +1,9 @@ import { ApiPromise } from "@polkadot/api" import { err, ok, Result } from "neverthrow" import { ISubmittableResult } from "@polkadot/types/types/extrinsic" -import { EventRecord, H256, Weight } from "@polkadot/types/interfaces" +import { EventRecord, H256 } from "@polkadot/types/interfaces" import { decodeError } from "../../helpers" -import { getBlockHashAndTxHash, standardCallback, WaitFor } from "../transactions/common" +import { getBlockHashAndTxHash, WaitFor } from "../transactions/common" import { createKeyMulti, encodeAddress, sortAddresses } from "@polkadot/util-crypto" export class TxResultDetails { From 9076c33e9cd97988e36ab4181056fe571e024406 Mon Sep 17 00:00:00 2001 From: Marko Petrlic Date: Thu, 17 Oct 2024 17:47:34 +0200 Subject: [PATCH 8/8] Updated Readme --- avail-js/docs/extrinsics/README.md | 1816 ++++++++++------- .../balances_tranfer_all_no_wait.ts | 2 +- .../balances_tranfer_allow_death_no_wait.ts | 2 +- .../balances_tranfer_keep_alive_no_wait.ts | 2 +- .../da_create_application_key_no_wait.ts | 2 +- .../docs/extrinsics/da_submit_data_no_wait.ts | 2 +- 6 files changed, 1064 insertions(+), 762 deletions(-) diff --git a/avail-js/docs/extrinsics/README.md b/avail-js/docs/extrinsics/README.md index 03ce1231a..18773ad60 100644 --- a/avail-js/docs/extrinsics/README.md +++ b/avail-js/docs/extrinsics/README.md @@ -1,32 +1,33 @@ -# Data Availability +# Balances -Runtime Component: DataAvailability\ -Runtime Index: 29\ -Interface Module Name: dataAvailability +Runtime Component: Balances\ +Runtime Index: 6\ +Interface Module Name: balances -## Create Application Key +## Transfer All Origin Level: Signed ### Interface ```js -function createApplicationKey(key: string, waitFor: WaitFor, account: KeyringPair, options?: Partial): Promise; +function transferAll(dest: string, keepAlive: boolean, waitFor: WaitFor, account: KeyringPair, options?: TransactionOptions): Promise>; ``` #### Parameters -| parameter | type | optional | description | -| --------- | ------------- | -------- | ----------------------------------------------- | -| key | string | 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 | SignerOptions | true | used to overwrite existing signer options | +| parameter | type | optional | description | +| --------- | ------------------ | -------- | ------------------------------------------------------------- | +| dest | string | false | Account that will receive funds | +| keepAlive | boolean | 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 | TransactionOptions | true | Can be used to set nonce, app id or other transaction options | ### Minimal Example ```js -import { SDK, WaitFor, Keyring } from "avail-js-sdk" +import { SDK, WaitFor, Keyring } from "../../src/index" const main = async () => { const providerEndpoint = "ws://127.0.0.1:9944" @@ -34,16 +35,16 @@ const main = async () => { // Input const account = new Keyring({ type: "sr25519" }).addFromUri("//Alice") - const key = "MyAwesomeKey" + const dest = "5HGjWAeFDfFCWPsjFQdVV2Msvz2XtMktvgocEZcCj68kUMaw" // Eve + const keepAlive = true - const result = await sdk.tx.dataAvailability.createApplicationKey(key, WaitFor.BlockInclusion, account) + const result = await sdk.tx.balances.transferAll(dest, keepAlive, WaitFor.BlockInclusion, account) if (result.isErr()) { console.log(result.error.reason) process.exit(1) } console.log(JSON.stringify(result.value, null, 2)) - process.exit() } main() @@ -57,47 +58,49 @@ If the operation fails, the function will return an error message indicating the #### On Success -If the operation is successful, the function will return a object of type `CreateApplicationKeyTxSuccess`. +If the operation is successful, the function will return a object of type `TransferAllTx`. -```js +```json { - "isErr": false, "event": { - "key": "0x4d79417765736f6d654b6579", - "owner": "5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY", - "id": "10" + "from": "5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY", + "to": "5HGjWAeFDfFCWPsjFQdVV2Msvz2XtMktvgocEZcCj68kUMaw", + "amount": "9999999873433871068464733" }, - "events": [...], - "txHash": "0x5ae9edbd2a2da96eeffc14cf9050d711082890fa6bfb8749ad2c4947565f3bd2", - "txIndex": 1, - "blockHash": "0x152338c1b0696d12664cf3d4c159af3d54beca151ba1ea8b00989a66dc8050b0", - "blockNumber": 1 + "details": { + "txResult": {...}, + "events": [...], + "txHash": "0x48b0e56ad89280f9a94d1f1ab48af2a9cf25fe4c9b41b916e0efa983fa5726c4", + "txIndex": 1, + "blockHash": "0x3a4fe6a2618db91cd1786f853c6c0548bcefa15849c810a37bbfcfb7eedb5b7f", + "blockNumber": 2 + } } ``` -## Submit Data +## Transfer All No Wait Origin Level: Signed ### Interface ```js -function submitData(data: string, waitFor: WaitFor, account: KeyringPair, options?: Partial): Promise; +function transferAllNoWait(dest: string, keepAlive: boolean, account: KeyringPair, options?: TransactionOptions): Promise; ``` #### Parameters -| parameter | type | optional | description | -| --------- | ------------- | -------- | ----------------------------------------------- | -| data | string | 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 | SignerOptions | true | used to overwrite existing signer options | +| parameter | type | optional | description | +| --------- | ------------------ | -------- | ------------------------------------------------------------- | +| dest | string | false | Account that will receive funds | +| keepAlive | boolean | false | if set to false it will reap the account as well | +| account | KeyringPair | false | Account that will send and sign the transaction | +| options | TransactionOptions | true | Can be used to set nonce, app id or other transaction options | ### Minimal Example ```js -import { SDK, WaitFor, Keyring } from "avail-js-sdk" +import { SDK, Keyring } from "../../src/index" const main = async () => { const providerEndpoint = "ws://127.0.0.1:9944" @@ -105,9 +108,60 @@ const main = async () => { // Input const account = new Keyring({ type: "sr25519" }).addFromUri("//Alice") - const data = "My Awesome Data" + const dest = "5HGjWAeFDfFCWPsjFQdVV2Msvz2XtMktvgocEZcCj68kUMaw" // Eve + const keepAlive = true + + const txHash = await sdk.tx.balances.transferAllNoWait(dest, keepAlive, account) + + console.log(txHash) + process.exit() +} +main() +``` + +### Example Output + +The function will return a object of type `H256`. + +```json +"0x3481a87e6ebfd2af2fad83fb0305c93e8cf59b6eacc7fdc37d3cf4a6ab0929b1" +``` + +## Transfer Allow Death + +Origin Level: Signed + +### Interface + +```js +function transferAllowDeath(dest: string, value: BN, waitFor: WaitFor, account: KeyringPair, options?: TransactionOptions): Promise>; +``` + +#### Parameters + +| parameter | type | optional | description | +| --------- | ------------------ | -------- | ------------------------------------------------------------- | +| dest | string | false | Account that will receive funds | +| 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 | TransactionOptions | true | Can be used to set nonce, app id or other transaction options | + +### Minimal Example + +```js +import { SDK, WaitFor, Keyring } from "../../src/index" + +const main = async () => { + const providerEndpoint = "ws://127.0.0.1:9944" + const sdk = await SDK.New(providerEndpoint) + + // Input + const account = new Keyring({ type: "sr25519" }).addFromUri("//Alice") + const dest = "5HGjWAeFDfFCWPsjFQdVV2Msvz2XtMktvgocEZcCj68kUMaw" // Eve + const amount = SDK.oneAvail() - const result = await sdk.tx.dataAvailability.submitData(data, WaitFor.BlockInclusion, account) + const result = await sdk.tx.balances.transferAllowDeath(dest, amount, WaitFor.BlockInclusion, account) if (result.isErr()) { console.log(result.error.reason) process.exit(1) @@ -127,50 +181,49 @@ If the operation fails, the function will return an error message indicating the #### On Success -If the operation is successful, the function will return a object of type `SubmitDataTxSuccess`. +If the operation is successful, the function will return a object of type `TransferAllowDeathTx`. -```js +```json { - "isErr": false, - "txData": { - "data": "4d7920417765736f6d652044617461" - }, "event": { - "who": "5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY", - "dataHash": "0x8846d900ea89aab9bce96402846c0ac74a853acc00cb99ff5ddb1a0f052594bd" + "from": "5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY", + "to": "5HGjWAeFDfFCWPsjFQdVV2Msvz2XtMktvgocEZcCj68kUMaw", + "amount": "1000000000000000000" }, - "events": [...], - "txHash": "0xec6f9fd5e002c9ddbcd24764380f57a014de7f2007cc0e2ae11a4dda17ab8062", - "txIndex": 1, - "blockHash": "0x043c2b88ff960f2f7042521b55a943676938948febefe8684022b524795340d9", - "blockNumber": 9 + "details": { + "txResult": {...}, + "events": [...], + "txHash": "0x03218ef4ef981238f31ff83d369bbb020b5f3fd30a1009c42993c99069062731", + "txIndex": 1, + "blockHash": "0xf2f47bb6093e56a22bd23ff39c320e2c1282d397045240921546fd4dfe49fc49", + "blockNumber": 3 + } } ``` -## Submit Block Length Proposal +## Transfer Allow Death No Wait -Origin Level: Root +Origin Level: Signed ### Interface ```js -function submitBlockLengthProposal(rows: number, cols: number, waitFor: WaitFor, account: KeyringPair, options?: Partial): Promise; +function transferAllowDeathNoWait(dest: string, value: BN, account: KeyringPair, options?: TransactionOptions): Promise; ``` #### Parameters -| parameter | type | optional | description | -| --------- | ------------- | -------- | ----------------------------------------------- | -| rows | number | false | number of rows in block | -| cols | number | 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 | SignerOptions | true | used to overwrite existing signer options | +| parameter | type | optional | description | +| --------- | ------------------ | -------- | ------------------------------------------------------------- | +| dest | string | false | Account that will receive funds | +| value | BN | false | Amount that is send. 10^18 is equal to 1 AVL | +| account | KeyringPair | false | Account that will send and sign the transaction | +| options | TransactionOptions | true | Can be used to set nonce, app id or other transaction options | ### Minimal Example ```js -import { SDK, WaitFor, Keyring } from "avail-js-sdk" +import { SDK, Keyring } from "../../src/index" const main = async () => { const providerEndpoint = "ws://127.0.0.1:9944" @@ -178,17 +231,12 @@ const main = async () => { // Input const account = new Keyring({ type: "sr25519" }).addFromUri("//Alice") - const rows = 128 - const cols = 128 - - const result = await sdk.tx.dataAvailability.submitBlockLengthProposal(rows, cols, WaitFor.BlockInclusion, account) - if (result.isErr()) { - console.log(result.error.reason) - process.exit(1) - } + const dest = "5HGjWAeFDfFCWPsjFQdVV2Msvz2XtMktvgocEZcCj68kUMaw" // Eve + const amount = SDK.oneAvail() - console.log(JSON.stringify(result.value, null, 2)) + const txHash = await sdk.tx.balances.transferAllowDeathNoWait(dest, amount, account) + console.log(JSON.stringify(txHash, null, 2)) process.exit() } main() @@ -196,42 +244,36 @@ main() ### 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 +The function will return a object of type `H256`. +```json +"0x7ee1ba58c7e71a3222850e01d8fd3661b97935f38d959d0ad704ad632bd7e6b5" ``` -## Set Application Key +## Transfer Keep Alive -Origin Level: Root +Origin Level: Signed ### Interface ```js -function setApplicationKey(oldKey: string, newKey: string, waitFor: WaitFor, account: KeyringPair, options?: Partial): Promise; +function transferKeepAlive(dest: string, value: BN, waitFor: WaitFor, account: KeyringPair, options?: TransactionOptions): Promise>; ``` #### Parameters -| parameter | type | optional | description | -| --------- | ------------- | -------- | ----------------------------------------------- | -| oldKey | string | false | application key to be replaced | -| newKey | string | 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 | SignerOptions | true | used to overwrite existing signer options | +| parameter | type | optional | description | +| --------- | ------------------ | -------- | ------------------------------------------------------------- | +| dest | string | false | Account that will receive funds | +| 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 | TransactionOptions | true | Can be used to set nonce, app id or other transaction options | ### Minimal Example ```js -import { SDK, WaitFor, Keyring } from "avail-js-sdk" +import { SDK, WaitFor, Keyring } from "../../src/index" const main = async () => { const providerEndpoint = "ws://127.0.0.1:9944" @@ -239,17 +281,16 @@ const main = async () => { // Input const account = new Keyring({ type: "sr25519" }).addFromUri("//Alice") - const oldKey = "MyNewKeyAwesome1" - const newKey = "MyNewKeyAwesome2" + const dest = "5HGjWAeFDfFCWPsjFQdVV2Msvz2XtMktvgocEZcCj68kUMaw" // Eve + const amount = SDK.oneAvail() - const result = await sdk.tx.dataAvailability.setApplicationKey(oldKey, newKey, WaitFor.BlockInclusion, account) + const result = await sdk.tx.balances.transferKeepAlive(dest, amount, WaitFor.BlockInclusion, account) if (result.isErr()) { console.log(result.error.reason) process.exit(1) } console.log(JSON.stringify(result.value, null, 2)) - process.exit() } main() @@ -263,35 +304,104 @@ If the operation fails, the function will return an error message indicating the #### On Success -If the operation is successful, the function will return a object of type `SetApplicationKeyTxSuccess`. +If the operation is successful, the function will return a object of type `TransferKeepAliveTx`. + +```json +{ + "event": { + "from": "5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY", + "to": "5HGjWAeFDfFCWPsjFQdVV2Msvz2XtMktvgocEZcCj68kUMaw", + "amount": "1000000000000000000" + }, + "details": { + "txResult": {...}, + "events": [...], + "txHash": "0x84a745ebb9642dcf382935c882519bfa6b957898365fb56a3499543d157e4b08", + "txIndex": 1, + "blockHash": "0x79e32fd8129d052b90f2c01c60c5c81e08fe461bdef1d403712df20cee5b6303", + "blockNumber": 56 + } +} +``` + +## Transfer Keep Alive No Wait + +Origin Level: Signed + +### Interface + +```js +function transferKeepAliveNoWait(dest: string, value: BN, account: KeyringPair, options?: TransactionOptions): Promise; +``` + +#### Parameters + +| parameter | type | optional | description | +| --------- | ------------------ | -------- | ------------------------------------------------------------- | +| dest | string | false | Account that will receive funds | +| value | BN | false | Amount that is send. 10^18 is equal to 1 AVL | +| account | KeyringPair | false | Account that will send and sign the transaction | +| options | TransactionOptions | true | Can be used to set nonce, app id or other transaction options | + +### Minimal Example ```js +import { SDK, Keyring } from "../../src/index" + +const main = async () => { + const providerEndpoint = "ws://127.0.0.1:9944" + const sdk = await SDK.New(providerEndpoint) + // Input + const account = new Keyring({ type: "sr25519" }).addFromUri("//Alice") + const dest = "5HGjWAeFDfFCWPsjFQdVV2Msvz2XtMktvgocEZcCj68kUMaw" // Eve + const amount = SDK.oneAvail() + + const txHash = await sdk.tx.balances.transferKeepAliveNoWait(dest, amount, account) + + console.log(JSON.stringify(txHash, null, 2)) + process.exit() +} +main() ``` -## Set Submit Data Fee Modifier +### Example Output + +The function will return a object of type `H256`. + +```json +"0xa6700ad4a056b9096c940e464b41acc7ac13c4df9ea5e214a3549794916d789a" +``` + +# Data Availability + +Runtime Component: DataAvailability\ +Runtime Index: 29\ +Interface Module Name: dataAvailability -Origin Level: Root +## Create Application Key + +Origin Level: Signed ### Interface ```js -function setSubmitDataFeeModifier(modifier: DispatchFeeModifier, waitFor: WaitFor, account: KeyringPair, options?: Partial): Promise; +function createApplicationKey(key: string, waitFor: WaitFor, account: KeyringPair, options?: TransactionOptions): Promise>; ``` #### Parameters -| parameter | type | optional | description | -| --------- | ------------------- | -------- | ----------------------------------------------- | -| 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 | SignerOptions | true | used to overwrite existing signer options | +| parameter | type | optional | description | +| --------- | ------------------ | -------- | ------------------------------------------------------------- | +| key | string | 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 | TransactionOptions | true | Can be used to set nonce, app id or other transaction options | ### Minimal Example ```js -import { SDK, WaitFor, Keyring, BN, sdkTransactions } from "avail-js-sdk" +import { SDK, WaitFor, Keyring } from "../../src/index" const main = async () => { const providerEndpoint = "ws://127.0.0.1:9944" @@ -299,19 +409,15 @@ const main = async () => { // Input const account = new Keyring({ type: "sr25519" }).addFromUri("//Alice") - const modifier = { - weightMaximumFee: new BN("10").pow(new BN("18")), - weightFeeDivider: 20, - } as sdkTransactions.DispatchFeeModifier + const key = "MyAwesomeKey" - const result = await sdk.tx.dataAvailability.setSubmitDataFeeModifier(modifier, WaitFor.BlockInclusion, account) + const result = await sdk.tx.dataAvailability.createApplicationKey(key, WaitFor.BlockInclusion, account) if (result.isErr()) { console.log(result.error.reason) process.exit(1) } console.log(JSON.stringify(result.value, null, 2)) - process.exit() } main() @@ -325,55 +431,96 @@ If the operation fails, the function will return an error message indicating the #### On Success -If the operation is successful, the function will return a object of type `SetSubmitDataFeeModifierTxSuccess`. - -```js +If the operation is successful, the function will return a object of type `CreateApplicationKeyTx`. +```json +{ + "event": { + "key": "0x4d79417765736f6d654b6579", + "owner": "5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY", + "id": "10" + }, + "details": { + "txResult": {...}, + "events": [...], + "txHash": "0x8bb6e5167bb0808a0e12236ed89aba5b8147737e2f4e35580cc157a5a17f8ae3", + "txIndex": 1, + "blockHash": "0xba5cdf11ad6847617d58d16d931436a5e1fba2191bb50f08912107dcd8440189", + "blockNumber": 94 + } +} ``` -## Type Definitions +## Create Application Key No Wait + +Origin Level: Signed + +### Interface ```js -enum WaitFor { - BlockInclusion, - BlockFinalization, -} +function createApplicationKeyNoWait(key: string, account: KeyringPair, options?: TransactionOptions): Promise; ``` +#### Parameters + +| parameter | type | optional | description | +| --------- | ------------------ | -------- | ------------------------------------------------------------- | +| key | string | false | name of the application key | +| account | KeyringPair | false | Account that will send and sign the transaction | +| options | TransactionOptions | true | Can be used to set nonce, app id or other transaction options | + +### Minimal Example + ```js -type DispatchFeeModifier = { weightMaximumFee: BN | null, weightFeeDivider: number | null, weightFeeMultiplier: number | null }; +import { SDK, Keyring } from "../../src/index" + +const main = async () => { + const providerEndpoint = "ws://127.0.0.1:9944" + const sdk = await SDK.New(providerEndpoint) + + // Input + const account = new Keyring({ type: "sr25519" }).addFromUri("//Alice") + const key = "MyAwesomeKey" + + const txHash = await sdk.tx.dataAvailability.createApplicationKeyNoWait(key, account) + + console.log(JSON.stringify(txHash, null, 2)) + process.exit() +} +main() ``` -# Balances +### Example Output -Runtime Component: Balances\ -Runtime Index: 6\ -Interface Module Name: balances +The function will return a object of type `H256`. -## Transfer Keep Alive +```json +"0x8d523a3b36327651bb11e619d8a1fceaa205cb414b411e6cd00116272278042e" +``` + +## Submit Data Origin Level: Signed ### Interface ```js -function transferKeepAlive(dest: string, value: BN, waitFor: WaitFor, account: KeyringPair, options?: Partial): Promise; +function submitData(data: string | Bytes, waitFor: WaitFor, account: KeyringPair, options?: TransactionOptions): Promise>; ``` #### Parameters -| parameter | type | optional | description | -| --------- | ------------- | -------- | ----------------------------------------------- | -| dest | string | false | account that will receive funds | -| 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 | SignerOptions | true | used to overwrite existing signer options | +| parameter | type | optional | description | +| --------- | ------------------ | -------- | ------------------------------------------------------------- | +| data | string | 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 | TransactionOptions | true | Can be used to set nonce, app id or other transaction options | ### Minimal Example ```js -import { SDK, WaitFor, Keyring, BN } from "avail-js-sdk" +import { SDK, WaitFor, Keyring, TransactionOptions } from "../../src/index" const main = async () => { const providerEndpoint = "ws://127.0.0.1:9944" @@ -381,17 +528,16 @@ const main = async () => { // Input const account = new Keyring({ type: "sr25519" }).addFromUri("//Alice") - const dest = "5HGjWAeFDfFCWPsjFQdVV2Msvz2XtMktvgocEZcCj68kUMaw" // Eve - const amount = new BN(10).pow(new BN(18)) // one Avail + const data = "My Awesome Data" - const result = await sdk.tx.balances.transferKeepAlive(dest, amount, WaitFor.BlockInclusion, account) + const options: TransactionOptions = { app_id: 1 } + const result = await sdk.tx.dataAvailability.submitData(data, WaitFor.BlockInclusion, account, options) if (result.isErr()) { console.log(result.error.reason) process.exit(1) } console.log(JSON.stringify(result.value, null, 2)) - process.exit() } main() @@ -405,48 +551,50 @@ If the operation fails, the function will return an error message indicating the #### On Success -If the operation is successful, the function will return a object of type `TransferKeepAliveTxSuccess`. +If the operation is successful, the function will return a object of type `SubmitDataTx`. -```js +```json { - "isErr": false, + "txData": { + "data": "4d7920417765736f6d652044617461" + }, "event": { - "from": "5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY", - "to": "5HGjWAeFDfFCWPsjFQdVV2Msvz2XtMktvgocEZcCj68kUMaw", - "amount": "1000000000000000000" + "who": "5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY", + "dataHash": "0x8846d900ea89aab9bce96402846c0ac74a853acc00cb99ff5ddb1a0f052594bd" }, - "events": [...], - "txHash": "0x812a3f3960afb8df72de0e5b86ff564c8ce7d93c837182c24d1796fb68a7f5f4", - "txIndex": 1, - "blockHash": "0xfdee1faced02696d692df1d896fa2822f4eb02f260c95e11041df86b2c229dfb", - "blockNumber": 1 + "details": { + "txResult": {...}, + "events": [...], + "txHash": "0xc189150ae2a0ebe6df1ec20b8096bbffc44e2ec5c56045049ab92e3e0a781565", + "txIndex": 1, + "blockHash": "0x0221659ca85a47bb11a8926c52e9273b908193a2420644c59f65d9da3754535a", + "blockNumber": 2 + } } ``` -## Transfer Allow Death +## Submit Data No Wait Origin Level: Signed ### Interface ```js -function transferAllowDeath(dest: string, value: BN, waitFor: WaitFor, account: KeyringPair, options?: Partial): Promise; +function submitDataNoWait(data: string | Bytes, account: KeyringPair, options?: TransactionOptions): Promise; ``` #### Parameters -| parameter | type | optional | description | -| --------- | ------------- | -------- | ----------------------------------------------- | -| dest | string | false | account that will receive funds | -| 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 | SignerOptions | true | used to overwrite existing signer options | +| parameter | type | optional | description | +| --------- | ------------------ | -------- | ------------------------------------------------------------- | +| data | string | false | data to be submitted | +| account | KeyringPair | false | Account that will send and sign the transaction | +| options | TransactionOptions | true | Can be used to set nonce, app id or other transaction options | ### Minimal Example ```js -import { SDK, WaitFor, Keyring, BN } from "avail-js-sdk" +import { SDK, Keyring, TransactionOptions } from "../../src/index" const main = async () => { const providerEndpoint = "ws://127.0.0.1:9944" @@ -454,17 +602,102 @@ const main = async () => { // Input const account = new Keyring({ type: "sr25519" }).addFromUri("//Alice") - const dest = "5HGjWAeFDfFCWPsjFQdVV2Msvz2XtMktvgocEZcCj68kUMaw" // Eve - const amount = new BN(10).pow(new BN(18)) // one Avail + const data = "My Awesome Data" - const result = await sdk.tx.balances.transferAllowDeath(dest, amount, WaitFor.BlockInclusion, account) + const options: TransactionOptions = { app_id: 1 } + const txHash = await sdk.tx.dataAvailability.submitDataNoWait(data, account, options) + + console.log(JSON.stringify(txHash, null, 2)) + process.exit() +} +main() +``` + +### 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 `SubmitDataTx`. + +```json +"0x8643a0f94f1928eb542aaa44aacf943c7fe50ab4949c53a934debf006049bc7e" +``` + +# Multisig + +Runtime Component: Multisig\ +Runtime Index: 34\ +Interface Module Name: multisig + +## Approving As Multi + +Origin Level: Signed + +### Interface + +```js +function approveAsMulti(threshold: number, otherSignatures: string[], timepoint: MultisigTimepoint | null, callHash: string, maxWeight: Weight, waitFor: WaitFor, account: KeyringPair, options?: TransactionOptions): Promise>; +``` + +#### Parameters + +| parameter | type | optional | description | +| --------------- | ------------------------- | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | +| threshold | number | false | The total number of approvals for this dispatch before it is executed. | +| otherSignatures | string[] | false | The accounts (other than the sender) who can approve this dispatch. May not be empty. | +| timepoint | MultisigTimepoint or null | false | If this is the first approval, then this must be `None`. If it is not the first approval, then it must be `Some`, with the timepoint (block number and transaction index) of the first approval transaction. | +| callHash | string | false | The hash of the call to be executed | +| maxWeight | Weight | false | This should be equal to the weight of the call | +| waitFor | WaitFor | false | Wait for block inclusion or finalization | +| account | KeyringPair | false | Account that will send and sign the transaction | +| options | TransactionOptions | true | Can be used to set nonce, app id or other transaction options | + +### Minimal Example + +```js +import { SDK, WaitFor, Keyring } from "./../../src/index" + +const main = async () => { + const providerEndpoint = "ws://127.0.0.1:9944" + const sdk = await SDK.New(providerEndpoint) + + // Multisig Signatures + const alice = new Keyring({ type: "sr25519" }).addFromUri("//Alice") + const bobAddress = "5FHneW46xGXgs5mUiveU4sbTyGBzmstUspZC92UhjJM694ty" + + // Create Multisig Account + const threshold = 2 + const multisigAddress = sdk.util.generateMultisig([alice.address, bobAddress], threshold) + + // Define what action will be taken by the multisig account + const amount = SDK.oneAvail() + const call = sdk.api.tx.balances.transferKeepAlive(multisigAddress, amount) + // Data needed for multisig approval and execution + const callHash = call.method.hash.toString() + const maxWeight = (await call.paymentInfo(alice.address)).weight + + // Create New Multisig + console.log("Alice is creating a Multisig Transaction...") + const call1signatures = sdk.util.sortMultisigAddresses([bobAddress]) + const result = await sdk.tx.multisig.approveAsMulti( + threshold, + call1signatures, + null, + callHash, + maxWeight, + WaitFor.BlockInclusion, + alice, + ) if (result.isErr()) { - console.log(result.error.reason) + console.log(result.error) process.exit(1) } console.log(JSON.stringify(result.value, null, 2)) - process.exit() } main() @@ -478,66 +711,92 @@ If the operation fails, the function will return an error message indicating the #### On Success -If the operation is successful, the function will return a object of type `TransferAllowDeathTxSuccess`. +If the operation is successful, the function will return a object of type `ApproveAsMultiTx`. -```js +```json { - "isErr": false, "event": { - "from": "5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY", - "to": "5HGjWAeFDfFCWPsjFQdVV2Msvz2XtMktvgocEZcCj68kUMaw", - "amount": "1000000000000000000" + "approving": "5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY", + "multisig": "5F3QVbS78a4aTYLiRAD8N3czjqVoNyV42L19CXyhqUMCh4Ch", + "callHash": "0x239258ef81456d5dbf5bf8a37709c7cf14c74ea7ed89961f47c7f3701de1e86b" }, - "events": [...], - "txHash": "0x63a73d2d1210ab9840341506788cca9592fd968609fecb5106cf0370c611061c", - "txIndex": 1, - "blockHash": "0xde2e95b63a4ca5927f9105931e4676b0634d12f524d4fff1048b403393419489", - "blockNumber": 2 + "details": { + "txResult": {...}, + "events": [...], + "txHash": "0x7beb1e4edb785c57533e0793f0d9051bbe6290e9551ee7e907d9c34ba9cad1a2", + "txIndex": 1, + "blockHash": "0xb23ef6eada32c5c19e75d3c0713c62ec88153613ceab70b28cac9ccd743e6b60", + "blockNumber": 103 + } } ``` -## Transfer All +## As Multi Origin Level: Signed ### Interface ```js -function transferAll(dest: string, keepAlive: boolean, waitFor: WaitFor, account: KeyringPair, options?: Partial): Promise; +function asMulti(threshold: number, otherSignatures: string[], timepoint: MultisigTimepoint | null, call: string, maxWeight: Weight, waitFor: WaitFor, account: KeyringPair, options?: TransactionOptions): Promise>; ``` #### Parameters -| parameter | type | optional | description | -| --------- | ------------- | -------- | ------------------------------------------------ | -| dest | string | false | account that will receive funds | -| keepAlive | boolean | 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 | SignerOptions | true | used to overwrite existing signer options | +| parameter | type | optional | description | +| --------------- | ------------------------- | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | +| threshold | number | false | The total number of approvals for this dispatch before it is executed. | +| otherSignatures | string[] | false | The accounts (other than the sender) who can approve this dispatch. May not be empty. | +| timepoint | MultisigTimepoint or null | false | If this is the first approval, then this must be `None`. If it is not the first approval, then it must be `Some`, with the timepoint (block number and transaction index) of the first approval transaction. | +| call | string | false | The call to be executed. | +| maxWeight | Weight | false | This should be equal to the weight of the call | +| waitFor | WaitFor | false | Wait for block inclusion or finalization | +| account | KeyringPair | false | Account that will send and sign the transaction | +| options | TransactionOptions | true | Can be used to set nonce, app id or other transaction options | ### Minimal Example ```js -import { SDK, WaitFor, Keyring } from "avail-js-sdk" +import { SDK, WaitFor, Keyring, MultisigTimepoint } from "./../../src/index" const main = async () => { const providerEndpoint = "ws://127.0.0.1:9944" const sdk = await SDK.New(providerEndpoint) - // Input - const account = new Keyring({ type: "sr25519" }).addFromUri("//Alice") - const dest = "5HGjWAeFDfFCWPsjFQdVV2Msvz2XtMktvgocEZcCj68kUMaw" // Eve - const keepAlive = true - - const result = await sdk.tx.balances.transferAll(dest, keepAlive, WaitFor.BlockInclusion, account) - if (result.isErr()) { - console.log(result.error.reason) + // Multisig Signatures + const bob = new Keyring({ type: "sr25519" }).addFromUri("//Bob") + const aliceAddress = "5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY" + + // Create Multisig Account + const threshold = 2 + const multisigAddress = sdk.util.generateMultisig([aliceAddress, bob.address], threshold) + + // Define what action will be taken by the multisig account + const amount = SDK.oneAvail() + const call = sdk.api.tx.balances.transferKeepAlive(multisigAddress, amount) + // Data needed for multisig approval and execution + const callData = call.unwrap().toHex() + const maxWeight = (await call.paymentInfo(aliceAddress)).weight + const timepoint: MultisigTimepoint = { height: 4, index: 1 } + + // Approving and executing Multisig transaction + console.log("Bob is approving and executing the existing Multisig Transaction...") + const call2signatures = sdk.util.sortMultisigAddresses([aliceAddress]) + const secondResult = await sdk.tx.multisig.asMulti( + threshold, + call2signatures, + timepoint, + callData, + maxWeight, + WaitFor.BlockInclusion, + bob, + ) + if (secondResult.isErr()) { + console.log(secondResult.error) process.exit(1) } - console.log(JSON.stringify(result.value, null, 2)) - + console.log(JSON.stringify(secondResult.value, null, 2)) process.exit() } main() @@ -551,54 +810,60 @@ If the operation fails, the function will return an error message indicating the #### On Success -If the operation is successful, the function will return a object of type `TransferAllTxSuccess`. +If the operation is successful, the function will return a object of type `AsMultiTx`. -```js +```json { - "isErr": false, "event": { - "from": "5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY", - "to": "5HGjWAeFDfFCWPsjFQdVV2Msvz2XtMktvgocEZcCj68kUMaw", - "amount": "9999999873433871068464733" + "approving": "5FHneW46xGXgs5mUiveU4sbTyGBzmstUspZC92UhjJM694ty", + "timepoint": { + "height": 103, + "index": 1 + }, + "multisig": "5F3QVbS78a4aTYLiRAD8N3czjqVoNyV42L19CXyhqUMCh4Ch", + "callHash": "0x239258ef81456d5dbf5bf8a37709c7cf14c74ea7ed89961f47c7f3701de1e86b", + "result": "Ok" }, - "events": [...], - "txHash": "0x343d3e8890bd479b4619cb7b0f2dfa91b7b91c0cedc0646247215f85baf1f63e", - "txIndex": 1, - "blockHash": "0xaec4adfad11f8aa902e1a985abb62737fc02445072b168238a956c3a0d8820f2", - "blockNumber": 2 + "details": { + "txResult": {...}, + "events": [...], + "txHash": "0xada53aa3d7e7891404228c07251f51c86214143e57205be10b6f55b1dd63b933", + "txIndex": 1, + "blockHash": "0x84a33cb83078795f8be128835c5699f20a314119c8b6efa432cc626fa6ac8812", + "blockNumber": 150 + } } ``` -# Staking +# Nomination Pools -Runtime Component: Staking\ -Runtime Index: 10\ -Interface Module Name: staking +Runtime Component: Nomination Pools\ +Runtime Index: 36\ +Interface Module Name: nominationPools -## Bond +## Bond Extra Origin Level: Signed ### Interface ```js -function bond(value: BN, payee: StakingRewardDestination, waitFor: WaitFor, account: KeyringPair, options?: Partial): Promise; +function bondExtra(extra: BondExtra, waitFor: WaitFor, account: KeyringPair, options?: TransactionOptions): Promise>; ``` #### Parameters -| parameter | type | optional | description | -| --------- | ------------------------ | -------- | ------------------------------------------------------- | -| value | BN | false | amount that is bond. 10^18 is equal to 1 AVL | -| payee | StakingRewardDestination | 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 | SignerOptions | true | used to overwrite existing signer options | +| parameter | type | optional | description | +| --------- | ------------------ | -------- | ------------------------------------------------------------------------------------------------------ | +| extra | BondExtra | false | Additional funds can come from either the free balance of the account, of from the accumulated rewards | +| waitFor | WaitFor | false | Wait for block inclusion or finalization | +| account | KeyringPair | false | Account that will send and sign the transaction | +| options | TransactionOptions | true | Can be used to set nonce, app id or other transaction options | ### Minimal Example ```js -import { SDK, WaitFor, Keyring, BN } from "avail-js-sdk" +import { SDK, WaitFor, Keyring, BondExtra, BN } from "../../src/index" const main = async () => { const providerEndpoint = "ws://127.0.0.1:9944" @@ -606,17 +871,16 @@ const main = async () => { // Input const account = new Keyring({ type: "sr25519" }).addFromUri("//Alice") - const value = new BN(100_000).mul(new BN(10).pow(new BN("18"))) // 100 000 Avail - const payee = "Staked" + const amount = SDK.oneAvail().mul(new BN(10000)) // 10_000 Avail + const bondExtra = { FreeBalance: amount } as BondExtra - const result = await sdk.tx.staking.bond(value, payee, WaitFor.BlockInclusion, account) + const result = await sdk.tx.nominationPools.bondExtra(bondExtra, WaitFor.BlockInclusion, account) if (result.isErr()) { console.log(result.error.reason) process.exit(1) } console.log(JSON.stringify(result.value, null, 2)) - process.exit() } main() @@ -630,63 +894,66 @@ If the operation fails, the function will return an error message indicating the #### On Success -If the operation is successful, the function will return a object of type `BondTxSuccess`. +If the operation is successful, the function will return a object of type `BondExtraTx`. -```js +```json { - "isErr": false, "event": { - "stash": "5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY", - "amount": "100000" + "member": "5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY", + "poolId": "1", + "bonded": "10000000000000000000000", + "joined": "false" }, - "events": [...], - "txHash": "0x3e1cc48207b02ca5d680cf1beeb270ce7cbf0d18a6191844bc963d4081a0ca90", - "txIndex": 1, - "blockHash": "0xf854e74cb428d0baf22454cb15007731a84263e57c64d019a304c0ca1bd30276", - "blockNumber": 2 + "details": { + "txResult": {...}, + "events": [...], + "txHash": "0xc09bdfbc1703763850a2f4255ccb0dd7d7e9f4b793d2f9f05782b9e3c63682d9", + "txIndex": 1, + "blockHash": "0xe06e35e61e2b59900e22d627dd8cd9cab39c87a304a40aba0fce87936e921843", + "blockNumber": 112 + } } ``` -## Bond Extra +## Chill Origin Level: Signed ### Interface ```js -function bondExtra(maxAdditional: BN, waitFor: WaitFor, account: KeyringPair, options?: Partial): Promise; +function chill(poolId: number, waitFor: WaitFor, account: KeyringPair, options?: TransactionOptions): Promise>; ``` #### Parameters -| parameter | type | optional | description | -| ------------- | ------------- | -------- | ------------------------------------------------------- | -| maxAdditional | BN | false | additional amount that is bond. 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 | SignerOptions | true | used to overwrite existing signer options | +| parameter | type | optional | description | +| --------- | ------------------ | -------- | ------------------------------------------------------------- | +| 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 | TransactionOptions | true | Can be used to set nonce, app id or other transaction options | ### Minimal Example ```js -import { SDK, WaitFor, Keyring, BN } from "avail-js-sdk" +import { SDK, WaitFor, Keyring } from "../../src/index" const main = async () => { const providerEndpoint = "ws://127.0.0.1:9944" const sdk = await SDK.New(providerEndpoint) // Input - const account = new Keyring({ type: "sr25519" }).addFromUri("//Alice//stash") - const maxAdditional = new BN(10).pow(new BN(18)) // one Avail + const account = new Keyring({ type: "sr25519" }).addFromUri("//Alice") + const poolId = 1 - const result = await sdk.tx.staking.bondExtra(maxAdditional, WaitFor.BlockInclusion, account) + const result = await sdk.tx.nominationPools.chill(poolId, WaitFor.BlockInclusion, account) if (result.isErr()) { console.log(result.error.reason) process.exit(1) } console.log(JSON.stringify(result.value, null, 2)) - process.exit() } main() @@ -700,60 +967,60 @@ If the operation fails, the function will return an error message indicating the #### On Success -If the operation is successful, the function will return a object of type `BondExtraTxSuccess`. +If the operation is successful, the function will return a object of type `ChillTx`. -```js +```json { - "isErr": false, - "event": { - "stash": "5GNJqTPyNqANBkUVMN1LPPrxXnFouWXoe2wNSmmEoLctxiZY", - "amount": "1" - }, - "events": [...], - "txHash": "0x940df5141925aeef2ab9aa767f6870689426de533f5f1d84b6d7be203e68ee77", - "txIndex": 1, - "blockHash": "0xc2a8375be07956586833f497a429ca2e29bafbb78ee5e051d5157df0ad5c8cb6", - "blockNumber": 7 + "details": { + "txResult": {...}, + "events": [...], + "txHash": "0x678fd95154114bb899598f8ef4413e3fdb5a90317a132d5a49f868ffb029cecf", + "txIndex": 1, + "blockHash": "0xa66f5eacd4c4294ba6679c868d90df11fccf5c85c773e8554856882ac64b4be7", + "blockNumber": 1106 + } } ``` -## Chill +## Claim Commission Origin Level: Signed ### Interface ```js -function chill(waitFor: WaitFor, account: KeyringPair, options?: Partial): Promise; +function claimCommission(poolId: number, waitFor: WaitFor, account: KeyringPair, options?: TransactionOptions): Promise>; ``` #### Parameters -| parameter | type | optional | description | -| --------- | ------------- | -------- | ----------------------------------------------- | -| 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 | +| parameter | type | optional | description | +| --------- | ------------------ | -------- | ------------------------------------------------------------- | +| 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 | TransactionOptions | true | Can be used to set nonce, app id or other transaction options | ### Minimal Example ```js -import { SDK, WaitFor, Keyring } from "avail-js-sdk" +import { SDK, WaitFor, Keyring } from "../../src/index" + const main = async () => { const providerEndpoint = "ws://127.0.0.1:9944" const sdk = await SDK.New(providerEndpoint) // Input - const account = new Keyring({ type: "sr25519" }).addFromUri("//Alice//stash") + const account = new Keyring({ type: "sr25519" }).addFromUri("//Alice") + const poolId = 1 - const result = await sdk.tx.staking.chill(WaitFor.BlockInclusion, account) + const result = await sdk.tx.nominationPools.claimCommission(poolId, WaitFor.BlockInclusion, account) if (result.isErr()) { console.log(result.error.reason) process.exit(1) } console.log(JSON.stringify(result.value, null, 2)) - process.exit() } main() @@ -767,61 +1034,64 @@ If the operation fails, the function will return an error message indicating the #### On Success -If the operation is successful, the function will return a object of type `ChillTxSuccess`. +If the operation is successful, the function will return a object of type `ClaimCommissionTx`. -```js +```json { - "isErr": false, "event": { - "stash": "5GNJqTPyNqANBkUVMN1LPPrxXnFouWXoe2wNSmmEoLctxiZY" + "poolId": "1", + "commission": "7652149502759813012" }, - "events": [...], - "txHash": "0x4572681f19af32fdfb4759c914697697b0e82fde48a5dd7e28c2b3a263772b0d", - "txIndex": 1, - "blockHash": "0xad2e5376f53e6257e7bc0c842e5b6952f1d4af6f7499319b2d1ab59bdd742628", - "blockNumber": 13 + "details": { + "txResult": {...}, + "events": [...], + "txHash": "0x52292c2af7c2505c0bd39f5f1308bc10d92db7117f1b9fec208dc778e0c49654", + "txIndex": 1, + "blockHash": "0xdceaa5b12517f9634ad568e355061e8e13a8af25074e8966381c92fcea214285", + "blockNumber": 418 + } } ``` -## Chill Other +## Claim Payout Other Origin Level: Signed ### Interface ```js -function chillOther(stash: string, waitFor: WaitFor, account: KeyringPair, options?: Partial): Promise; +function claimPayoutOther(other: string, waitFor: WaitFor, account: KeyringPair, options?: TransactionOptions): Promise>; ``` #### Parameters -| parameter | type | optional | description | -| --------- | ------------- | -------- | ----------------------------------------------- | -| stash | string | 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 | SignerOptions | true | used to overwrite existing signer options | +| parameter | type | optional | description | +| --------- | ------------------ | -------- | ------------------------------------------------------------- | +| other | &str | false | other account to claim payout | +| waitFor | WaitFor | false | Wait for block inclusion or finalization | +| account | KeyringPair | false | Account that will send and sign the transaction | +| options | TransactionOptions | true | Can be used to set nonce, app id or other transaction options | ### Minimal Example ```js -import { SDK, WaitFor, Keyring } from "avail-js-sdk" +import { SDK, WaitFor, Keyring } from "../../src/index" + const main = async () => { const providerEndpoint = "ws://127.0.0.1:9944" const sdk = await SDK.New(providerEndpoint) // Input - const account = new Keyring({ type: "sr25519" }).addFromUri("//Alice//stash") - const stash = "5GNJqTPyNqANBkUVMN1LPPrxXnFouWXoe2wNSmmEoLctxiZY" // Alice Stash + const account = new Keyring({ type: "sr25519" }).addFromUri("//Alice") + const other = "5FHneW46xGXgs5mUiveU4sbTyGBzmstUspZC92UhjJM694ty" // Bob - const result = await sdk.tx.staking.chillOther(stash, WaitFor.BlockInclusion, account) + const result = await sdk.tx.nominationPools.claimPayoutOther(other, WaitFor.BlockInclusion, account) if (result.isErr()) { console.log(result.error.reason) process.exit(1) } console.log(JSON.stringify(result.value, null, 2)) - process.exit() } main() @@ -835,35 +1105,48 @@ If the operation fails, the function will return an error message indicating the #### On Success -If the operation is successful, the function will return a object of type `ChillOtherTxSuccess`. - -```js +If the operation is successful, the function will return a object of type `ClaimPayoutOtherTx`. +```json +{ + "event": { + "member": "5FHneW46xGXgs5mUiveU4sbTyGBzmstUspZC92UhjJM694ty", + "poolId": "1", + "payout": "8198513381719500000" + }, + "details": { + "txResult": {...}, + "events": [...], + "txHash": "0xe14015b25afc66c4954dda18631b3fd5efaeba80989070ed12712ca312dbec40", + "txIndex": 1, + "blockHash": "0x3abde836ab66ac38bc3ca260f081d370f1c15094f43048423e0995170569a51a", + "blockNumber": 594 + } +} ``` -## Nominate +## Claim Payout Origin Level: Signed ### Interface ```js -function nominate(targets: string[], waitFor: WaitFor, account: KeyringPair, options?: Partial): Promise; +function claimPayout(waitFor: WaitFor, account: KeyringPair, options?: TransactionOptions): Promise; ``` #### Parameters -| parameter | type | optional | description | -| --------- | ------------- | -------- | ----------------------------------------------- | -| 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 | SignerOptions | true | used to overwrite existing signer options | +| parameter | type | optional | description | +| --------- | ------------------ | -------- | ------------------------------------------------------------- | +| waitFor | WaitFor | false | Wait for block inclusion or finalization | +| account | KeyringPair | false | Account that will send and sign the transaction | +| options | TransactionOptions | true | Can be used to set nonce, app id or other transaction options | ### Minimal Example ```js -import { SDK, WaitFor, Keyring } from "avail-js-sdk" +import { SDK, WaitFor, Keyring } from "../../src/index" const main = async () => { const providerEndpoint = "ws://127.0.0.1:9944" @@ -871,19 +1154,14 @@ const main = async () => { // Input const account = new Keyring({ type: "sr25519" }).addFromUri("//Alice") - const targets = [ - "5GNJqTPyNqANBkUVMN1LPPrxXnFouWXoe2wNSmmEoLctxiZY", // Alice Stash - "5FHneW46xGXgs5mUiveU4sbTyGBzmstUspZC92UhjJM694ty", // Bob - ] - const result = await sdk.tx.staking.nominate(targets, WaitFor.BlockInclusion, account) + const result = await sdk.tx.nominationPools.claimPayout(WaitFor.BlockInclusion, account) if (result.isErr()) { console.log(result.error.reason) process.exit(1) } console.log(JSON.stringify(result.value, null, 2)) - process.exit() } main() @@ -897,58 +1175,76 @@ If the operation fails, the function will return an error message indicating the #### On Success -If the operation is successful, the function will return a object of type `NominateTxSuccess`. +If the operation is successful, the function will return a object of type `ClaimPayoutTx`. -```js +```json { - "isErr": false, - "txData": { - "targets": [ - "5GNJqTPyNqANBkUVMN1LPPrxXnFouWXoe2wNSmmEoLctxiZY", - "5FHneW46xGXgs5mUiveU4sbTyGBzmstUspZC92UhjJM694ty" - ] + "event": { + "member": "5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY", + "poolId": "1", + "payout": "4008268787159890000" }, - "events": [...], - "txHash": "0x2f81a34f59d36eb7ada96ec1070358043026d7bd7cfb6fa5a532cc474190880b", - "txIndex": 1, - "blockHash": "0x49a57953aa2b2ba508f1c6991515309a0fe89723a79f3831f9a9263ba8c7baa4", - "blockNumber": 4 + "details": { + "txResult": {...}, + "events": [...], + "txHash": "0x15b50cb2a3885432811ba1417b7715e69e05b8d4dd8f7c9951f0b4f7a8ba5a61", + "txIndex": 1, + "blockHash": "0xdd24eca2111c6b7eea4a34c9bed02cfa6effde65c65c3dc66fb13c88e2fe6985", + "blockNumber": 426 + } } ``` -## Unbond +## Create with Pool Id Origin Level: Signed ### Interface ```js -function unbond(value: BN, waitFor: WaitFor, account: KeyringPair, options?: Partial): Promise; +function createWithPoolId(amount: BN, root: string, nominator: string, bouncer: string, poolId: number, waitFor: WaitFor, account: KeyringPair, options?: TransactionOptions): Promise>; ``` #### Parameters -| parameter | type | optional | description | -| --------- | ------------- | -------- | ----------------------------------------------- | -| value | BN | 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 | +| 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 | TransactionOptions | true | Can be used to set nonce, app id or other transaction options | ### Minimal Example ```js -import { SDK, WaitFor, Keyring, BN } from "avail-js-sdk" +import { SDK, WaitFor, Keyring, BN } from "../../src/index" const main = async () => { const providerEndpoint = "ws://127.0.0.1:9944" const sdk = await SDK.New(providerEndpoint) // Input - const account = new Keyring({ type: "sr25519" }).addFromUri("//Alice") - const value = new BN(10).pow(new BN(18)) // one Avail + const account = new Keyring({ type: "sr25519" }).addFromUri("//Bob") + const amount = SDK.oneAvail().mul(new BN(10000)) // 10_000 Avail - const result = await sdk.tx.staking.unbond(value, WaitFor.BlockInclusion, account) + const root: string = "5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY" // Alice + const nominator: string = "5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY" // Alice + const bouncer: string = "5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY" // Alice + const poolId = 0 + + const result = await sdk.tx.nominationPools.createWithPoolId( + amount, + root, + nominator, + bouncer, + poolId, + WaitFor.BlockInclusion, + account, + ) if (result.isErr()) { console.log(result.error.reason) process.exit(1) @@ -968,47 +1264,57 @@ If the operation fails, the function will return an error message indicating the #### On Success -If the operation is successful, the function will return a object of type `UnbondTxSuccess`. +If the operation is successful, the function will return a object of type `CreateWithPoolIdTx`. -```js +```json { - "isErr": false, "event": { - "stash": "5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY", - "amount": "1000000000000000000" + "depositor": "5FHneW46xGXgs5mUiveU4sbTyGBzmstUspZC92UhjJM694ty", + "poolId": "0" + }, + "event2": { + "member": "5FHneW46xGXgs5mUiveU4sbTyGBzmstUspZC92UhjJM694ty", + "poolId": "0", + "bonded": "10000", + "joined": "true" }, - "events": [...], - "txHash": "0xbf264e0e95885fd64a35d5c64bd4e1cc17056a1e6b05fa9207d7c777395dffdf", - "txIndex": 1, - "blockHash": "0x9ef43aaca71ba7b91a53976de5170f80d8a1ed4fe3e95fae237f7ed91f953963", - "blockNumber": 9 + "details": { + "txResult": {...}, + "events": [...], + "txHash": "0x6b50caed7950e67934cabbf88a1f7dc2e7e995ac608402f91a4db19be0da5c41", + "txIndex": 1, + "blockHash": "0xc06df7dbb1e404f54499f942479ddcffc92665c021ea07c2798fc2f354f403d3", + "blockNumber": 6 + } } ``` -## Validate +## Create Origin Level: Signed ### Interface ```js -function validate(commission: number, blocked: boolean, waitFor: WaitFor, account: KeyringPair, options?: Partial): Promise; +function create(amount: BN, root: string, nominator: string, bouncer: string, waitFor: WaitFor, account: KeyringPair, options?: TransactionOptions): Promise>; ``` #### Parameters -| parameter | type | optional | description | -| ---------- | ------------- | -------- | ----------------------------------------------------- | -| commission | number | false | how much validator charge nominators in 0 - 100 range | -| blocked | boolean | 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 | SignerOptions | true | used to overwrite existing signer options | +| 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 | TransactionOptions | true | Can be used to set nonce, app id or other transaction options | ### Minimal Example ```js -import { SDK, WaitFor, Keyring } from "avail-js-sdk" +import { SDK, WaitFor, Keyring, BN } from "../../src/index" const main = async () => { const providerEndpoint = "ws://127.0.0.1:9944" @@ -1016,17 +1322,19 @@ const main = async () => { // Input const account = new Keyring({ type: "sr25519" }).addFromUri("//Alice") - const commission = 5 // 5% - const blocked = false + const amount = SDK.oneAvail().mul(new BN(10000)) // 10_000 Avail - const result = await sdk.tx.staking.validate(commission, blocked, WaitFor.BlockInclusion, account) + const root: string = "5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY" // Alice + const nominator: string = "5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY" // Alice + const bouncer: string = "5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY" // Alice + + const result = await sdk.tx.nominationPools.create(amount, root, nominator, bouncer, WaitFor.BlockInclusion, account) if (result.isErr()) { console.log(result.error.reason) process.exit(1) } console.log(JSON.stringify(result.value, null, 2)) - process.exit() } main() @@ -1040,70 +1348,66 @@ If the operation fails, the function will return an error message indicating the #### On Success -If the operation is successful, the function will return a object of type `ValidateTxSuccess`. +If the operation is successful, the function will return a object of type `PoolCreateTxSuccess`. -```js +```json { - "isErr": false, "event": { - "stash": "5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY", - "commission": "50000000", - "blocked": "false" + "depositor": "5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY", + "poolId": "1" + }, + "event2": { + "member": "5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY", + "poolId": "1", + "bonded": "10000", + "joined": "true" }, - "events": [...], - "txHash": "0x31f047da16a350e32b832cc73d3351c8d5e5991625fde6e8c36fc45ebb9d2735", - "txIndex": 1, - "blockHash": "0xa7735804f52602d4b73e1dd7f718cf0ab5cc00d111c927a9f8a2b3d02b66e09a", - "blockNumber": 14 + "details": { + "txResult": {...}, + "events": [...], + "txHash": "0x9f019464c676682d9cbfb62814d019a85738e01b0ce92b18fa77878f80e16f66", + "txIndex": 1, + "blockHash": "0xdaa49f09b8c519bbd4c52ed05652d3de3f777afa3ac85db5c697cf705907e2d2", + "blockNumber": 5 + } } ``` -# Nomination Pools - -Runtime Component: Nomination Pools\ -Runtime Index: 36\ -Interface Module Name: nominationPools - -## Create +## Join Origin Level: Signed ### Interface ```js -function create(amount: BN, root: string, nominator: string, bouncer: string, waitFor: WaitFor, account: KeyringPair, options?: Partial): Promise; +function join(amount: BN, poolId: number, waitFor: WaitFor, account: KeyringPair, options?: TransactionOptions): 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 | +| 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 | TransactionOptions | true | Can be used to set nonce, app id or other transaction options | ### Minimal Example ```js -import { SDK, WaitFor, Keyring, BN } from "avail-js-sdk" +import { SDK, WaitFor, Keyring, BN } from "../../src/index" const main = async () => { 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 account = new Keyring({ type: "sr25519" }).addFromUri("//Bob") + const amount = SDK.oneAvail().mul(new BN(10000)) // 10_000 Avail + const poolId = 1 - const result = await sdk.tx.nominationPools.create(amount, root, nominator, bouncer, WaitFor.BlockInclusion, account) + const result = await sdk.tx.nominationPools.join(amount, poolId, WaitFor.BlockInclusion, account) if (result.isErr()) { console.log(result.error.reason) process.exit(1) @@ -1123,79 +1427,65 @@ If the operation fails, the function will return an error message indicating the #### On Success -If the operation is successful, the function will return a object of type `PoolCreateTxSuccess`. +If the operation is successful, the function will return a object of type `JoinTx`. -```js +```json { - "isErr": false, "event": { - "depositor": "5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY", - "poolId": "1" - }, - "event2": { - "member": "5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY", + "member": "5FHneW46xGXgs5mUiveU4sbTyGBzmstUspZC92UhjJM694ty", "poolId": "1", "bonded": "10000", "joined": "true" }, - "events": [...], - "txHash": "0x9f019464c676682d9cbfb62814d019a85738e01b0ce92b18fa77878f80e16f66", - "txIndex": 1, - "blockHash": "0xdaa49f09b8c519bbd4c52ed05652d3de3f777afa3ac85db5c697cf705907e2d2", - "blockNumber": 5 + "details": { + "txResult": {...}, + "events": [...], + "txHash": "0x06baecbb8680e90d025d1fd08044d0d251054a89e82dd460022bdf3796020050", + "txIndex": 1, + "blockHash": "0x82078130da46adacf5bdff86618ab6e1c443fda6d883d9fcf967a41a2e29d612", + "blockNumber": 19 + } } ``` -## Create with Pool Id +## Nominate Origin Level: Signed ### Interface ```js -function createWithPoolId(amount: BN, root: string, nominator: string, bouncer: string, poolId: number, waitFor: WaitFor, account: KeyringPair, options?: Partial): Promise; +function nominate(poolId: number, validators: string[], waitFor: WaitFor, account: KeyringPair, options?: TransactionOptions): 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 | +| 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 | TransactionOptions | true | Can be used to set nonce, app id or other transaction options | ### Minimal Example ```js -import { SDK, WaitFor, Keyring, BN } from "avail-js-sdk" +import { SDK, WaitFor, Keyring } from "../../src/index" const main = async () => { 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 account = new Keyring({ type: "sr25519" }).addFromUri("//Alice") + const validators: string[] = [ + "5GNJqTPyNqANBkUVMN1LPPrxXnFouWXoe2wNSmmEoLctxiZY", + "5DAAnrj7VHTznn2AWBemMuyBwZWs6FNFjdyVXUeYum3PTXFy", + ] + const poolId = 1 - const result = await sdk.tx.nominationPools.createWithPoolId( - amount, - root, - nominator, - bouncer, - poolId, - WaitFor.BlockInclusion, - account, - ) + const result = await sdk.tx.nominationPools.nominate(poolId, validators, WaitFor.BlockInclusion, account) if (result.isErr()) { console.log(result.error.reason) process.exit(1) @@ -1215,53 +1505,44 @@ If the operation fails, the function will return an error message indicating the #### On Success -If the operation is successful, the function will return a object of type `PoolCreateWithPoolIdTxSuccess`. +If the operation is successful, the function will return a object of type `NominateTx`. -```js +```json { - "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 + "details": { + "txResult": {...}, + "events": [...], + "txHash": "0x98b993baf90183d85dece9357d3bc32311f4201b015b63845a13dbc22bf22370", + "txIndex": 1, + "blockHash": "0x84ef5a0ada4af71358ee701a2500bce7f6688efb554c32ba1a30c459f64d5370", + "blockNumber": 48 + } } ``` -## Join +## Set Claim Permission Origin Level: Signed ### Interface ```js -function join(amount: BN, poolId: number, waitFor: WaitFor, account: KeyringPair, options?: Partial): Promise; +function setClaimPermission(permission: ClaimPermission, waitFor: WaitFor, account: KeyringPair, options?: TransactionOptions): 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 | +| parameter | type | optional | description | +| ---------- | ------------------ | -------- | ------------------------------------------------------------- | +| permission | ClaimPermission | false | permission type | +| waitFor | WaitFor | false | Wait for block inclusion or finalization | +| account | KeyringPair | false | Account that will send and sign the transaction | +| options | TransactionOptions | true | Can be used to set nonce, app id or other transaction options | ### Minimal Example ```js -import { SDK, WaitFor, Keyring, BN } from "avail-js-sdk" +import { SDK, WaitFor, Keyring, ClaimPermission } from "../../src/index" const main = async () => { const providerEndpoint = "ws://127.0.0.1:9944" @@ -1269,10 +1550,9 @@ const main = async () => { // 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 permission: ClaimPermission = "PermissionlessAll" - const result = await sdk.tx.nominationPools.join(amount, poolId, WaitFor.BlockInclusion, account) + const result = await sdk.tx.nominationPools.setClaimPermission(permission, WaitFor.BlockInclusion, account) if (result.isErr()) { console.log(result.error.reason) process.exit(1) @@ -1292,49 +1572,45 @@ If the operation fails, the function will return an error message indicating the #### On Success -If the operation is successful, the function will return a object of type `PoolJoinTxSuccess`. +If the operation is successful, the function will return a object of type `SetClaimPermissionTx`. -```js +```json { - "isErr": false, - "event": { - "member": "5FHneW46xGXgs5mUiveU4sbTyGBzmstUspZC92UhjJM694ty", - "poolId": "1", - "bonded": "10000", - "joined": "true" - }, - "events": [...], - "txHash": "0x06baecbb8680e90d025d1fd08044d0d251054a89e82dd460022bdf3796020050", - "txIndex": 1, - "blockHash": "0x82078130da46adacf5bdff86618ab6e1c443fda6d883d9fcf967a41a2e29d612", - "blockNumber": 19 + "details": { + "txResult": {...}, + "events": [...], + "txHash": "0x3096fb312d22f2aa4fa51532fbae4b812a99d60c85a0750662816146bce997bc", + "txIndex": 1, + "blockHash": "0xfb41995f2e5aaa1b92126792dfc1e7b2863773fa4865eca2d96f458da17d6f82", + "blockNumber": 249 + } } ``` -## Nominate +## Set Commission Origin Level: Signed ### Interface ```js -function nominate(poolId: number, validators: string[], waitFor: WaitFor, account: KeyringPair, options?: Partial): Promise; +function setCommission(poolId: number, newCommission: NewCommission | null, waitFor: WaitFor, account: KeyringPair, options?: TransactionOptions): 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 | +| parameter | type | optional | description | +| ------------- | --------------------- | -------- | ---------------------------------------------------------------- | +| poolId | number | false | pool id | +| newCommission | NewCommission or Null | false | if empty it removes the existing commission otherwise it sets it | +| waitFor | WaitFor | false | Wait for block inclusion or finalization | +| account | KeyringPair | false | Account that will send and sign the transaction | +| options | TransactionOptions | true | Can be used to set nonce, app id or other transaction options | ### Minimal Example ```js -import { SDK, WaitFor, Keyring } from "avail-js-sdk" +import { SDK, WaitFor, Keyring, NewCommission } from "avail-js-sdk" const main = async () => { const providerEndpoint = "ws://127.0.0.1:9944" @@ -1342,13 +1618,10 @@ const main = async () => { // Input const account = new Keyring({ type: "sr25519" }).addFromUri("//Alice") - const validators: string[] = [ - "5GNJqTPyNqANBkUVMN1LPPrxXnFouWXoe2wNSmmEoLctxiZY", - "5DAAnrj7VHTznn2AWBemMuyBwZWs6FNFjdyVXUeYum3PTXFy", - ] const poolId = 1 + const newCommission: NewCommission = { amount: 25, payee: "5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY" } - const result = await sdk.tx.nominationPools.nominate(poolId, validators, WaitFor.BlockInclusion, account) + const result = await sdk.tx.nominationPools.setCommission(poolId, newCommission, WaitFor.BlockInclusion, account) if (result.isErr()) { console.log(result.error.reason) process.exit(1) @@ -1368,42 +1641,49 @@ If the operation fails, the function will return an error message indicating the #### On Success -If the operation is successful, the function will return a object of type `PoolNominateTxSuccess`. +If the operation is successful, the function will return a object of type `CommissionTx`. -```js +```json { - "isErr": false, - "events": [...], - "txHash": "0x98b993baf90183d85dece9357d3bc32311f4201b015b63845a13dbc22bf22370", - "txIndex": 1, - "blockHash": "0x84ef5a0ada4af71358ee701a2500bce7f6688efb554c32ba1a30c459f64d5370", - "blockNumber": 48 + "event": { + "poolId": "1", + "current": "[250000000,\"5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY\"]" + }, + "details": { + "txResult": {...}, + "events": [...], + "txHash": "0x8256693f9648abe0d47b12380cdcfcb56c3078080216a7487f0b34d7ff80e047", + "txIndex": 1, + "blockHash": "0xedf037ef9de56cba1a81a45bb5ed5b0ec3424725a521c6255976a68d5638015e", + "blockNumber": 552 + } } ``` -## Bond Extra +## Set Metadata Origin Level: Signed ### Interface ```js -function bondExtra(extra: BondExtra, waitFor: WaitFor, account: KeyringPair, options?: Partial): Promise; +function setMetadata(poolId: number, metadata: string, waitFor: WaitFor, account: KeyringPair, options?: TransactionOptions): Promise>; ``` #### Parameters -| parameter | type | optional | description | -| --------- | ------------- | -------- | ------------------------------------------------------------------------------------------------------ | -| extra | BondExtra | false | Additional funds can come from either the free balance of the account, of from the accumulated rewards | -| 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 | +| parameter | type | optional | description | +| --------- | ------------------ | -------- | ------------------------------------------------------------- | +| poolId | number | false | pool id | +| metadata | string | false | metadata | +| waitFor | WaitFor | false | Wait for block inclusion or finalization | +| account | KeyringPair | false | Account that will send and sign the transaction | +| options | TransactionOptions | true | Can be used to set nonce, app id or other transaction options | ### Minimal Example ```js -import { SDK, WaitFor, Keyring, BondExtra, BN } from "avail-js-sdk" +import { SDK, WaitFor, Keyring } from "../../src/index" const main = async () => { const providerEndpoint = "ws://127.0.0.1:9944" @@ -1411,10 +1691,10 @@ const main = async () => { // 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 bondExtra = { FreeBalance: amount } as BondExtra + const poolId = 1 + const metadata = "My Metadata" - const result = await sdk.tx.nominationPools.bondExtra(bondExtra, WaitFor.BlockInclusion, account) + const result = await sdk.tx.nominationPools.setMetadata(poolId, metadata, WaitFor.BlockInclusion, account) if (result.isErr()) { console.log(result.error.reason) process.exit(1) @@ -1434,49 +1714,45 @@ If the operation fails, the function will return an error message indicating the #### On Success -If the operation is successful, the function will return a object of type `PoolBondExtraTxSuccess`. +If the operation is successful, the function will return a object of type `SetMetadataTx`. -```js +```json { - "isErr": false, - "event": { - "member": "5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY", - "poolId": "1", - "bonded": "10000000000000000000000", - "joined": "false" - }, - "events": [...], - "txHash": "0xc09bdfbc1703763850a2f4255ccb0dd7d7e9f4b793d2f9f05782b9e3c63682d9", - "txIndex": 1, - "blockHash": "0xe06e35e61e2b59900e22d627dd8cd9cab39c87a304a40aba0fce87936e921843", - "blockNumber": 112 + "details": { + "txResult": {...}, + "events": [...], + "txHash": "0x59121cd7e320acab280a1ad0d8b8385581ca7e03d973477ae812b1d967e2cb1d", + "txIndex": 1, + "blockHash": "0x6f19a8c993dc33676605a1dfabbb5a1008929ee965772a3b3edd12f9fe1eb296", + "blockNumber": 369 + } } ``` -## Set Metadata +## Set State Origin Level: Signed ### Interface ```js -function setMetadata(poolId: number, metadata: string, waitFor: WaitFor, account: KeyringPair, options?: Partial): Promise; +function setState(poolId: number, state: PoolState, waitFor: WaitFor, account: KeyringPair, options?: TransactionOptions): Promise>; ``` #### Parameters -| parameter | type | optional | description | -| --------- | ------------- | -------- | ----------------------------------------------- | -| poolId | number | false | pool id | -| metadata | string | false | metadata | -| 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 | +| parameter | type | optional | description | +| --------- | ------------------ | -------- | ------------------------------------------------------------- | +| poolId | number | false | pool id | +| state | PoolState | false | "Open" or "Blocked" or "Destroying" | +| waitFor | WaitFor | false | Wait for block inclusion or finalization | +| account | KeyringPair | false | Account that will send and sign the transaction | +| options | TransactionOptions | true | Can be used to set nonce, app id or other transaction options | ### Minimal Example ```js -import { SDK, WaitFor, Keyring } from "avail-js-sdk" +import { SDK, WaitFor, Keyring, PoolState } from "../../src/index" const main = async () => { const providerEndpoint = "ws://127.0.0.1:9944" @@ -1484,10 +1760,10 @@ const main = async () => { // Input const account = new Keyring({ type: "sr25519" }).addFromUri("//Alice") - const poolId = 1 - const metadata = "My Metadata" + const poolId = 2 + const state: PoolState = "Blocked" - const result = await sdk.tx.nominationPools.setMetadata(poolId, metadata, WaitFor.BlockInclusion, account) + const result = await sdk.tx.nominationPools.setState(poolId, state, WaitFor.BlockInclusion, account) if (result.isErr()) { console.log(result.error.reason) process.exit(1) @@ -1507,16 +1783,22 @@ If the operation fails, the function will return an error message indicating the #### On Success -If the operation is successful, the function will return a object of type `PoolSetMetadataTxSuccess`. +If the operation is successful, the function will return a object of type `SetStateTx`. -```js +```json { - "isErr": false, - "events": [...], - "txHash": "0x59121cd7e320acab280a1ad0d8b8385581ca7e03d973477ae812b1d967e2cb1d", - "txIndex": 1, - "blockHash": "0x6f19a8c993dc33676605a1dfabbb5a1008929ee965772a3b3edd12f9fe1eb296", - "blockNumber": 369 + "event": { + "poolId": "1", + "newState": "Blocked" + }, + "details": { + "txResult": {...}, + "events": [...], + "txHash": "0x921a187171a1d15a0779be75b9ecadc62eb1446f798bd0f4f1542700f32c724c", + "txIndex": 1, + "blockHash": "0xf2b85aae8a41eb4a27c72dfb2c4bce258213b829ef5f97f416a24d3989e7b3da", + "blockNumber": 184 + } } ``` @@ -1527,23 +1809,23 @@ Origin Level: Signed ### Interface ```js -function unbond(memberAccount: string, unbondingPoints: BN, waitFor: WaitFor, account: KeyringPair, options?: Partial): Promise; +function unbond(memberAccount: string, unbondingPoints: BN, waitFor: WaitFor, account: KeyringPair, options?: TransactionOptions): Promise>; ``` #### Parameters -| parameter | type | optional | description | -| --------------- | ------------- | -------- | ----------------------------------------------- | -| memberAccount | string | false | member account | -| unbondingPoints | BN | false | defines how many tokens will be 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 | +| parameter | type | optional | description | +| --------------- | ------------------ | -------- | ------------------------------------------------------------- | +| memberAccount | string | false | member account | +| unbondingPoints | BN | false | defines how many tokens will be unbond | +| waitFor | WaitFor | false | Wait for block inclusion or finalization | +| account | KeyringPair | false | Account that will send and sign the transaction | +| options | TransactionOptions | true | Can be used to set nonce, app id or other transaction options | ### Minimal Example ```js -import { SDK, WaitFor, Keyring, BN } from "avail-js-sdk" +import { SDK, WaitFor, Keyring, BN } from "../../src/index" const main = async () => { const providerEndpoint = "ws://127.0.0.1:9944" @@ -1552,7 +1834,7 @@ const main = async () => { // Input const account = new Keyring({ type: "sr25519" }).addFromUri("//Alice") const memberAccount = "5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY" // Alice - const unbondingPoints = new BN(10).pow(new BN(18)).mul(new BN(100)) // 100 Avail + const unbondingPoints = SDK.oneAvail().mul(new BN(100)) // 100 Avail const result = await sdk.tx.nominationPools.unbond(memberAccount, unbondingPoints, WaitFor.BlockInclusion, account) if (result.isErr()) { @@ -1574,11 +1856,10 @@ If the operation fails, the function will return an error message indicating the #### On Success -If the operation is successful, the function will return a object of type `PoolUnbondTxSuccess`. +If the operation is successful, the function will return a object of type `UnbondTx`. -```js +```json { - "isErr": false, "event": { "member": "5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY", "poolId": "1", @@ -1586,32 +1867,36 @@ If the operation is successful, the function will return a object of type `PoolU "points": "100000000000000000000", "era": "23" }, - "events": [], - "txHash": "0x87eeadd1dcf643b898dd46a681704565741c428fffc0fbcd0f9f587d47b43c5d", - "txIndex": 1, - "blockHash": "0xb38d12ccdc7a5c8190b8948597d40008540574150ccd96426a611695f0969115", - "blockNumber": 1032 + "details": { + "txResult": {...}, + "events": [...], + "txHash": "0x87eeadd1dcf643b898dd46a681704565741c428fffc0fbcd0f9f587d47b43c5d", + "txIndex": 1, + "blockHash": "0xb38d12ccdc7a5c8190b8948597d40008540574150ccd96426a611695f0969115", + "blockNumber": 1032 + } } ``` -## Chill +## Withdraw Unbonded Origin Level: Signed ### Interface ```js -function chill(poolId: number, waitFor: WaitFor, account: KeyringPair, options?: Partial): Promise; +function withdrawUnbonded(memberAccount: string, numSlashingSpans: number, waitFor: WaitFor, account: KeyringPair, options?: TransactionOptions): Promise>; ``` #### Parameters -| parameter | type | optional | description | -| --------- | ------------- | -------- | ----------------------------------------------- | -| 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 | +| parameter | type | optional | description | +| ---------------- | ------------------ | -------- | ------------------------------------------------------------- | +| memberAccount | string | false | member account | +| numSlashingSpans | number | false | number of slashing spans | +| waitFor | WaitFor | false | Wait for block inclusion or finalization | +| account | KeyringPair | false | Account that will send and sign the transaction | +| options | TransactionOptions | true | Can be used to set nonce, app id or other transaction options | ### Minimal Example @@ -1624,9 +1909,15 @@ const main = async () => { // Input const account = new Keyring({ type: "sr25519" }).addFromUri("//Alice") - const poolId = 1 + const memberAccount = "5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY" // Alice + const numSlashingSpans = 0 - const result = await sdk.tx.nominationPools.chill(poolId, WaitFor.BlockInclusion, account) + const result = await sdk.tx.nominationPools.withdrawUnbonded( + memberAccount, + numSlashingSpans, + WaitFor.BlockInclusion, + account, + ) if (result.isErr()) { console.log(result.error.reason) process.exit(1) @@ -1646,52 +1937,66 @@ If the operation fails, the function will return an error message indicating the #### On Success -If the operation is successful, the function will return a object of type `PoolChillTxSuccess`. +If the operation is successful, the function will return a object of type `WithdrawUnbodedTx`. -```js +```json { - "isErr": false, - "events": [...], - "txHash": "0x678fd95154114bb899598f8ef4413e3fdb5a90317a132d5a49f868ffb029cecf", - "txIndex": 1, - "blockHash": "0xa66f5eacd4c4294ba6679c868d90df11fccf5c85c773e8554856882ac64b4be7", - "blockNumber": 1106 + "event": { + "member": "5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY", + "poolId": "1", + "balance": "100000000000000000000", + "points": "100000000000000000000" + }, + "details": { + "txResult": {...}, + "events": [...], + "txHash": "0xfaad26fc9bc45d02303772cbdddaf4866430fc72f1b52129aebda5fcbb50a964", + "txIndex": 1, + "blockHash": "0x1062735f5e11d1ffd1724d9d2892609dbb7b7065fadc3d0e7aa77618179016b7", + "blockNumber": 266 + } } ``` -## Set Claim Permission +# Staking + +Runtime Component: Staking\ +Runtime Index: 10\ +Interface Module Name: staking + +## Bond Extra Origin Level: Signed ### Interface ```js -function setClaimPermission(permission: ClaimPermission, waitFor: WaitFor, account: KeyringPair, options?: Partial): Promise; +function bondExtra(maxAdditional: BN, waitFor: WaitFor, account: KeyringPair, options?: TransactionOptions): Promise>; ``` #### Parameters -| parameter | type | optional | description | -| ---------- | --------------- | -------- | ----------------------------------------------- | -| permission | ClaimPermission | false | permission type | -| 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 | +| parameter | type | optional | description | +| ------------- | ------------------ | -------- | ------------------------------------------------------------- | +| maxAdditional | BN | false | Additional amount that is bond. 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 | TransactionOptions | true | Can be used to set nonce, app id or other transaction options | ### Minimal Example ```js -import { SDK, WaitFor, Keyring, ClaimPermission } from "avail-js-sdk" +import { SDK, WaitFor, Keyring } from "../../src/index" const main = async () => { const providerEndpoint = "ws://127.0.0.1:9944" const sdk = await SDK.New(providerEndpoint) // Input - const account = new Keyring({ type: "sr25519" }).addFromUri("//Bob") - const permission: ClaimPermission = "PermissionlessAll" + const account = new Keyring({ type: "sr25519" }).addFromUri("//Alice//stash") + const maxAdditional = SDK.oneAvail() - const result = await sdk.tx.nominationPools.setClaimPermission(permission, WaitFor.BlockInclusion, account) + const result = await sdk.tx.staking.bondExtra(maxAdditional, WaitFor.BlockInclusion, account) if (result.isErr()) { console.log(result.error.reason) process.exit(1) @@ -1711,42 +2016,49 @@ If the operation fails, the function will return an error message indicating the #### On Success -If the operation is successful, the function will return a object of type `PoolSetClaimPermissionOtherTxSuccess`. +If the operation is successful, the function will return a object of type `BondExtraTx`. -```js +```json { - "isErr": false, - "events": [...], - "txHash": "0x3096fb312d22f2aa4fa51532fbae4b812a99d60c85a0750662816146bce997bc", - "txIndex": 1, - "blockHash": "0xfb41995f2e5aaa1b92126792dfc1e7b2863773fa4865eca2d96f458da17d6f82", - "blockNumber": 249 + "event": { + "stash": "5GNJqTPyNqANBkUVMN1LPPrxXnFouWXoe2wNSmmEoLctxiZY", + "amount": "1" + }, + "details": { + "txResult": {...}, + "events": [...], + "txHash": "0x940df5141925aeef2ab9aa767f6870689426de533f5f1d84b6d7be203e68ee77", + "txIndex": 1, + "blockHash": "0xc2a8375be07956586833f497a429ca2e29bafbb78ee5e051d5157df0ad5c8cb6", + "blockNumber": 7 + } } ``` -## Claim Commission +## Bond Origin Level: Signed ### Interface ```js -function claimCommission(poolId: number, waitFor: WaitFor, account: KeyringPair, options?: Partial): Promise; +function bond(value: BN, payee: StakingRewardDestination, waitFor: WaitFor, account: KeyringPair, options?: TransactionOptions): Promise>; ``` #### Parameters -| parameter | type | optional | description | -| --------- | ------------- | -------- | ----------------------------------------------- | -| 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 | +| parameter | type | optional | description | +| --------- | ------------------------ | -------- | ------------------------------------------------------------- | +| value | BN | false | Amount that is bond. 10^18 is equal to 1 AVL | +| payee | StakingRewardDestination | false | Can be: "Staked", "Stash", "None" or an account address | +| waitFor | WaitFor | false | Wait for block inclusion or finalization | +| account | KeyringPair | false | ccount that will send and sign the transaction | +| options | TransactionOptions | true | Can be used to set nonce, app id or other transaction options | ### Minimal Example ```js -import { SDK, WaitFor, Keyring } from "avail-js-sdk" +import { SDK, WaitFor, Keyring, BN } from "../../src/index" const main = async () => { const providerEndpoint = "ws://127.0.0.1:9944" @@ -1754,9 +2066,10 @@ const main = async () => { // Input const account = new Keyring({ type: "sr25519" }).addFromUri("//Alice") - const poolId = 1 + const value = SDK.oneAvail().mul(new BN(100000)) // 100_000 Avail + const payee = "Staked" - const result = await sdk.tx.nominationPools.claimCommission(poolId, WaitFor.BlockInclusion, account) + const result = await sdk.tx.staking.bond(value, payee, WaitFor.BlockInclusion, account) if (result.isErr()) { console.log(result.error.reason) process.exit(1) @@ -1776,54 +2089,57 @@ If the operation fails, the function will return an error message indicating the #### On Success -If the operation is successful, the function will return a object of type `PoolClaimCommissionTxSuccess`. +If the operation is successful, the function will return a object of type `BondTx`. -```js +```json { - "isErr": false, "event": { - "poolId": "1", - "commission": "7652149502759813012" + "stash": "5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY", + "amount": "100000" }, - "events": [...], - "txHash": "0x52292c2af7c2505c0bd39f5f1308bc10d92db7117f1b9fec208dc778e0c49654", - "txIndex": 1, - "blockHash": "0xdceaa5b12517f9634ad568e355061e8e13a8af25074e8966381c92fcea214285", - "blockNumber": 418 + "details": { + "txResult": {...}, + "events": [...], + "txHash": "0x3e1cc48207b02ca5d680cf1beeb270ce7cbf0d18a6191844bc963d4081a0ca90", + "txIndex": 1, + "blockHash": "0xf854e74cb428d0baf22454cb15007731a84263e57c64d019a304c0ca1bd30276", + "blockNumber": 2 + } } ``` -## Claim Payout +## Chill Other Origin Level: Signed ### Interface ```js -function claimPayout(waitFor: WaitFor, account: KeyringPair, options?: Partial): Promise; +function chillOther(stash: string, waitFor: WaitFor, account: KeyringPair, options?: TransactionOptions): Promise>; ``` #### Parameters -| parameter | type | optional | description | -| --------- | ------------- | -------- | ----------------------------------------------- | -| 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 | +| parameter | type | optional | description | +| --------- | ------------------ | -------- | ------------------------------------------------------------- | +| stash | string | 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 | TransactionOptions | true | Can be used to set nonce, app id or other transaction options | ### Minimal Example ```js -import { SDK, WaitFor, Keyring } from "avail-js-sdk" - +import { SDK, WaitFor, Keyring } from "../../src/index" const main = async () => { const providerEndpoint = "ws://127.0.0.1:9944" const sdk = await SDK.New(providerEndpoint) // Input - const account = new Keyring({ type: "sr25519" }).addFromUri("//Alice") + const account = new Keyring({ type: "sr25519" }).addFromUri("//Alice//stash") + const stash = "5GNJqTPyNqANBkUVMN1LPPrxXnFouWXoe2wNSmmEoLctxiZY" // Alice Stash - const result = await sdk.tx.nominationPools.claimPayout(WaitFor.BlockInclusion, account) + const result = await sdk.tx.staking.chillOther(stash, WaitFor.BlockInclusion, account) if (result.isErr()) { console.log(result.error.reason) process.exit(1) @@ -1843,57 +2159,42 @@ If the operation fails, the function will return an error message indicating the #### On Success -If the operation is successful, the function will return a object of type `PoolClaimPayoutTxSuccess`. +If the operation is successful, the function will return a object of type `ChillOtherTx`. + +```json -```js -{ - "isErr": false, - "event": { - "member": "5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY", - "poolId": "1", - "payout": "4008268787159890000" - }, - "events": [...], - "txHash": "0x15b50cb2a3885432811ba1417b7715e69e05b8d4dd8f7c9951f0b4f7a8ba5a61", - "txIndex": 1, - "blockHash": "0xdd24eca2111c6b7eea4a34c9bed02cfa6effde65c65c3dc66fb13c88e2fe6985", - "blockNumber": 426 -} ``` -## Claim Payout Other +## Chill Origin Level: Signed ### Interface ```js -function claimPayoutOther(other: string, waitFor: WaitFor, account: KeyringPair, options?: Partial): Promise; +function chill( waitFor: WaitFor, account: KeyringPair, options?: TransactionOptions): Promise>; ``` #### Parameters -| parameter | type | optional | description | -| --------- | ------------- | -------- | ----------------------------------------------- | -| other | &str | false | other account to claim payout | -| 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 | +| parameter | type | optional | description | +| --------- | ------------------ | -------- | ------------------------------------------------------------- | +| waitFor | WaitFor | false | Wait for block inclusion or finalization | +| account | KeyringPair | false | Account that will send and sign the transaction | +| options | TransactionOptions | true | Can be used to set nonce, app id or other transaction options | ### Minimal Example ```js -import { SDK, WaitFor, Keyring } from "avail-js-sdk" - +import { SDK, WaitFor, Keyring } from "../../src/index" const main = async () => { const providerEndpoint = "ws://127.0.0.1:9944" const sdk = await SDK.New(providerEndpoint) // Input - const account = new Keyring({ type: "sr25519" }).addFromUri("//Alice") - const other = "5FHneW46xGXgs5mUiveU4sbTyGBzmstUspZC92UhjJM694ty" // Bob + const account = new Keyring({ type: "sr25519" }).addFromUri("//Alice//stash") - const result = await sdk.tx.nominationPools.claimPayoutOther(other, WaitFor.BlockInclusion, account) + const result = await sdk.tx.staking.chill(WaitFor.BlockInclusion, account) if (result.isErr()) { console.log(result.error.reason) process.exit(1) @@ -1913,48 +2214,47 @@ If the operation fails, the function will return an error message indicating the #### On Success -If the operation is successful, the function will return a object of type `PoolClaimPayoutOtherTxSuccess`. +If the operation is successful, the function will return a object of type `ChillTx`. -```js +```json { - "isErr": false, "event": { - "member": "5FHneW46xGXgs5mUiveU4sbTyGBzmstUspZC92UhjJM694ty", - "poolId": "1", - "payout": "8198513381719500000" + "stash": "5GNJqTPyNqANBkUVMN1LPPrxXnFouWXoe2wNSmmEoLctxiZY" }, - "events": [...], - "txHash": "0xe14015b25afc66c4954dda18631b3fd5efaeba80989070ed12712ca312dbec40", - "txIndex": 1, - "blockHash": "0x3abde836ab66ac38bc3ca260f081d370f1c15094f43048423e0995170569a51a", - "blockNumber": 594 + "details": { + "txResult": {...}, + "events": [...], + "txHash": "0x4572681f19af32fdfb4759c914697697b0e82fde48a5dd7e28c2b3a263772b0d", + "txIndex": 1, + "blockHash": "0xad2e5376f53e6257e7bc0c842e5b6952f1d4af6f7499319b2d1ab59bdd742628", + "blockNumber": 13 + } } ``` -## Set Commission +## Nominate Origin Level: Signed ### Interface ```js -function setCommission(poolId: number, newCommission: NewCommission | null, waitFor: WaitFor, account: KeyringPair, options?: Partial): Promise; +function nominate(targets: string[], waitFor: WaitFor, account: KeyringPair, options?: TransactionOptions): Promise>; ``` #### Parameters -| parameter | type | optional | description | -| ------------- | --------------------- | -------- | ---------------------------------------------------------------- | -| poolId | number | false | pool id | -| newCommission | NewCommission or Null | false | if empty it removes the existing commission otherwise it sets it | -| 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 | +| parameter | type | optional | description | +| --------- | ------------------ | -------- | ------------------------------------------------------------- | +| 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 | TransactionOptions | true | Can be used to set nonce, app id or other transaction options | ### Minimal Example ```js -import { SDK, WaitFor, Keyring, NewCommission } from "avail-js-sdk" +import { SDK, WaitFor, Keyring } from "../../src/index" const main = async () => { const providerEndpoint = "ws://127.0.0.1:9944" @@ -1962,10 +2262,12 @@ const main = async () => { // Input const account = new Keyring({ type: "sr25519" }).addFromUri("//Alice") - const poolId = 1 - const newCommission: NewCommission = { amount: 25, payee: "5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY" } + const targets = [ + "5GNJqTPyNqANBkUVMN1LPPrxXnFouWXoe2wNSmmEoLctxiZY", // Alice Stash + "5FHneW46xGXgs5mUiveU4sbTyGBzmstUspZC92UhjJM694ty", // Bob + ] - const result = await sdk.tx.nominationPools.setCommission(poolId, newCommission, WaitFor.BlockInclusion, account) + const result = await sdk.tx.staking.nominate(targets, WaitFor.BlockInclusion, account) if (result.isErr()) { console.log(result.error.reason) process.exit(1) @@ -1985,47 +2287,50 @@ If the operation fails, the function will return an error message indicating the #### On Success -If the operation is successful, the function will return a object of type `PoolSetCommissionTxSuccess`. +If the operation is successful, the function will return a object of type `NominateTxSuccess`. -```js +```json { - "isErr": false, - "event": { - "poolId": "1", - "current": "[250000000,\"5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY\"]" + "txData": { + "targets": [ + "5GNJqTPyNqANBkUVMN1LPPrxXnFouWXoe2wNSmmEoLctxiZY", + "5FHneW46xGXgs5mUiveU4sbTyGBzmstUspZC92UhjJM694ty" + ] }, - "events": [...], - "txHash": "0x8256693f9648abe0d47b12380cdcfcb56c3078080216a7487f0b34d7ff80e047", - "txIndex": 1, - "blockHash": "0xedf037ef9de56cba1a81a45bb5ed5b0ec3424725a521c6255976a68d5638015e", - "blockNumber": 552 + "details": { + "txResult": {...}, + "events": [...], + "txHash": "0x2f81a34f59d36eb7ada96ec1070358043026d7bd7cfb6fa5a532cc474190880b", + "txIndex": 1, + "blockHash": "0x49a57953aa2b2ba508f1c6991515309a0fe89723a79f3831f9a9263ba8c7baa4", + "blockNumber": 4 + } } ``` -## Withdraw Unbonded +## Unbond Origin Level: Signed ### Interface ```js -function withdrawUnbonded(memberAccount: string, numSlashingSpans: number, waitFor: WaitFor, account: KeyringPair, options?: Partial): Promise; +function unbond(value: BN, waitFor: WaitFor, account: KeyringPair, options?: TransactionOptions): Promise>; ``` #### Parameters -| parameter | type | optional | description | -| ---------------- | ------------- | -------- | ----------------------------------------------- | -| memberAccount | string | false | member account | -| numSlashingSpans | number | false | number of slashing spans | -| 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 | +| parameter | type | optional | description | +| --------- | ------------------ | -------- | ------------------------------------------------------------- | +| value | BN | 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 | TransactionOptions | true | Can be used to set nonce, app id or other transaction options | ### Minimal Example ```js -import { SDK, WaitFor, Keyring } from "avail-js-sdk" +import { SDK, WaitFor, Keyring } from "../../src/index" const main = async () => { const providerEndpoint = "ws://127.0.0.1:9944" @@ -2033,15 +2338,9 @@ const main = async () => { // Input const account = new Keyring({ type: "sr25519" }).addFromUri("//Alice") - const memberAccount = "5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY" // Alice - const numSlashingSpans = 0 + const value = SDK.oneAvail() - const result = await sdk.tx.nominationPools.withdrawUnbonded( - memberAccount, - numSlashingSpans, - WaitFor.BlockInclusion, - account, - ) + const result = await sdk.tx.staking.unbond(value, WaitFor.BlockInclusion, account) if (result.isErr()) { console.log(result.error.reason) process.exit(1) @@ -2061,49 +2360,49 @@ If the operation fails, the function will return an error message indicating the #### On Success -If the operation is successful, the function will return a object of type `PoolWithdrawUnbodedTxSuccess`. +If the operation is successful, the function will return a object of type `UnbondTx`. -```js +```json { - "isErr": false, "event": { - "member": "5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY", - "poolId": "1", - "balance": "100000000000000000000", - "points": "100000000000000000000" + "stash": "5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY", + "amount": "1000000000000000000" }, - "events": [...], - "txHash": "0xfaad26fc9bc45d02303772cbdddaf4866430fc72f1b52129aebda5fcbb50a964", - "txIndex": 1, - "blockHash": "0x1062735f5e11d1ffd1724d9d2892609dbb7b7065fadc3d0e7aa77618179016b7", - "blockNumber": 266 + "details": { + "txResult": {...}, + "events": [...], + "txHash": "0xbf264e0e95885fd64a35d5c64bd4e1cc17056a1e6b05fa9207d7c777395dffdf", + "txIndex": 1, + "blockHash": "0x9ef43aaca71ba7b91a53976de5170f80d8a1ed4fe3e95fae237f7ed91f953963", + "blockNumber": 9 + } } ``` -## Set State +## Validate Origin Level: Signed ### Interface ```js -function setState(poolId: number, state: PoolState, waitFor: WaitFor, account: KeyringPair, options?: Partial): Promise; +function validate(commission: number, blocked: boolean, waitFor: WaitFor, account: KeyringPair, options?: TransactionOptions): Promise>; ``` #### Parameters -| parameter | type | optional | description | -| --------- | ------------- | -------- | ----------------------------------------------- | -| poolId | number | false | pool id | -| state | PoolState | false | "Open" or "Blocked" or "Destroying" | -| 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 | +| parameter | type | optional | description | +| ---------- | ------------------ | -------- | ------------------------------------------------------------- | +| commission | number | false | how much validator charge nominators in 0 - 100 range | +| blocked | boolean | 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 | TransactionOptions | true | Can be used to set nonce, app id or other transaction options | ### Minimal Example ```js -import { SDK, WaitFor, Keyring, PoolState } from "avail-js-sdk" +import { SDK, WaitFor, Keyring } from "../../src/index" const main = async () => { const providerEndpoint = "ws://127.0.0.1:9944" @@ -2111,10 +2410,10 @@ const main = async () => { // Input const account = new Keyring({ type: "sr25519" }).addFromUri("//Alice") - const poolId = 2 - const state: PoolState = "Blocked" + const commission = 5 // 5% + const blocked = false - const result = await sdk.tx.nominationPools.setState(poolId, state, WaitFor.BlockInclusion, account) + const result = await sdk.tx.staking.validate(commission, blocked, WaitFor.BlockInclusion, account) if (result.isErr()) { console.log(result.error.reason) process.exit(1) @@ -2134,19 +2433,22 @@ If the operation fails, the function will return an error message indicating the #### On Success -If the operation is successful, the function will return a object of type `PoolSetStateTxSuccess`. +If the operation is successful, the function will return a object of type `ValidateTx`. -```js +```json { - "isErr": false, "event": { - "poolId": "1", - "newState": "Blocked" + "stash": "5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY", + "commission": "50000000", + "blocked": "false" }, - "events": [...], - "txHash": "0x921a187171a1d15a0779be75b9ecadc62eb1446f798bd0f4f1542700f32c724c", - "txIndex": 1, - "blockHash": "0xf2b85aae8a41eb4a27c72dfb2c4bce258213b829ef5f97f416a24d3989e7b3da", - "blockNumber": 184 + "details": { + "txResult": {...}, + "events": [...], + "txHash": "0x31f047da16a350e32b832cc73d3351c8d5e5991625fde6e8c36fc45ebb9d2735", + "txIndex": 1, + "blockHash": "0xa7735804f52602d4b73e1dd7f718cf0ab5cc00d111c927a9f8a2b3d02b66e09a", + "blockNumber": 14 + } } ``` diff --git a/avail-js/docs/extrinsics/balances_tranfer_all_no_wait.ts b/avail-js/docs/extrinsics/balances_tranfer_all_no_wait.ts index 5a3382477..a51fd5d54 100644 --- a/avail-js/docs/extrinsics/balances_tranfer_all_no_wait.ts +++ b/avail-js/docs/extrinsics/balances_tranfer_all_no_wait.ts @@ -11,7 +11,7 @@ const main = async () => { const txHash = await sdk.tx.balances.transferAllNoWait(dest, keepAlive, account) - console.log(txHash) + console.log(JSON.stringify(txHash, null, 2)) process.exit() } main() diff --git a/avail-js/docs/extrinsics/balances_tranfer_allow_death_no_wait.ts b/avail-js/docs/extrinsics/balances_tranfer_allow_death_no_wait.ts index fd176bc72..df9bcb4f5 100644 --- a/avail-js/docs/extrinsics/balances_tranfer_allow_death_no_wait.ts +++ b/avail-js/docs/extrinsics/balances_tranfer_allow_death_no_wait.ts @@ -11,7 +11,7 @@ const main = async () => { const txHash = await sdk.tx.balances.transferAllowDeathNoWait(dest, amount, account) - console.log(txHash) + console.log(JSON.stringify(txHash, null, 2)) process.exit() } main() diff --git a/avail-js/docs/extrinsics/balances_tranfer_keep_alive_no_wait.ts b/avail-js/docs/extrinsics/balances_tranfer_keep_alive_no_wait.ts index 8a03fe912..760b79bb6 100644 --- a/avail-js/docs/extrinsics/balances_tranfer_keep_alive_no_wait.ts +++ b/avail-js/docs/extrinsics/balances_tranfer_keep_alive_no_wait.ts @@ -11,7 +11,7 @@ const main = async () => { const txHash = await sdk.tx.balances.transferKeepAliveNoWait(dest, amount, account) - console.log(txHash) + console.log(JSON.stringify(txHash, null, 2)) process.exit() } main() diff --git a/avail-js/docs/extrinsics/da_create_application_key_no_wait.ts b/avail-js/docs/extrinsics/da_create_application_key_no_wait.ts index 7ebf33bd9..440830213 100644 --- a/avail-js/docs/extrinsics/da_create_application_key_no_wait.ts +++ b/avail-js/docs/extrinsics/da_create_application_key_no_wait.ts @@ -10,7 +10,7 @@ const main = async () => { const txHash = await sdk.tx.dataAvailability.createApplicationKeyNoWait(key, account) - console.log(txHash) + console.log(JSON.stringify(txHash, null, 2)) process.exit() } main() diff --git a/avail-js/docs/extrinsics/da_submit_data_no_wait.ts b/avail-js/docs/extrinsics/da_submit_data_no_wait.ts index be39fc956..5d87ccce9 100644 --- a/avail-js/docs/extrinsics/da_submit_data_no_wait.ts +++ b/avail-js/docs/extrinsics/da_submit_data_no_wait.ts @@ -11,7 +11,7 @@ const main = async () => { const options: TransactionOptions = { app_id: 1 } const txHash = await sdk.tx.dataAvailability.submitDataNoWait(data, account, options) - console.log(txHash) + console.log(JSON.stringify(txHash, null, 2)) process.exit() } main()