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/multisig.ts b/avail-js/docs/advanced_examples/multisig.ts new file mode 100644 index 000000000..645607825 --- /dev/null +++ b/avail-js/docs/advanced_examples/multisig.ts @@ -0,0 +1,152 @@ +import { SDK, WaitFor, Keyring, BN, KeyringPair, Weight, TxResultDetails, 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 = 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 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, 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, threshold, call2signatures, timepoint, callHash, maxWeight) + + // 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.error.reason) + process.exit(1) + } + + return multisigAddress +} + +async function firstApproval( + sdk: SDK, + account: KeyringPair, + threshold: number, + otherSignatures: string[], + callHash: string, + maxWeight: Weight, +): Promise { + console.log("Alice is creating a Multisig Transaction...") + + const maybeTxResult = await sdk.tx.multisig.approveAsMulti( + threshold, + otherSignatures, + null, + callHash, + maxWeight, + WaitFor.BlockInclusion, + account, + ) + if (maybeTxResult.isErr()) { + console.log(maybeTxResult.error) + process.exit(1) + } + + return maybeTxResult.value.details +} + +async function nextApproval( + sdk: SDK, + account: KeyringPair, + threshold: number, + otherSignatures: string[], + timepoint: MultisigTimepoint, + callHash: string, + maxWeight: Weight, +): Promise { + console.log("Bob is approving the existing Multisig Transaction...") + + const maybeTxResult = await sdk.tx.multisig.approveAsMulti( + threshold, + otherSignatures, + timepoint, + callHash, + maxWeight, + WaitFor.BlockInclusion, + account, + ) + if (maybeTxResult.isErr()) { + console.log(maybeTxResult.error) + process.exit(1) + } + + return maybeTxResult.value.details +} + +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.tx.multisig.asMulti( + threshold, + otherSignatures, + timepoint, + callData, + maxWeight, + WaitFor.BlockInclusion, + account, + ) + if (maybeTxResult.isErr()) { + console.log(maybeTxResult.error) + process.exit(1) + } + + return maybeTxResult.value.details +} + +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/docs/extrinsics/README.md b/avail-js/docs/extrinsics/README.md index 4fd093d66..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) - if (result.isErr) { - console.log(result.reason) + 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, null, 2)) - + 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,15 +108,66 @@ 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 | - const result = await sdk.tx.dataAvailability.submitData(data, WaitFor.BlockInclusion, account) - if (result.isErr) { - console.log(result.reason) +### 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.balances.transferAllowDeath(dest, amount, WaitFor.BlockInclusion, account) + 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() @@ -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.reason) - process.exit(1) - } + const dest = "5HGjWAeFDfFCWPsjFQdVV2Msvz2XtMktvgocEZcCj68kUMaw" // Eve + const amount = SDK.oneAvail() - console.log(JSON.stringify(result, 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) - if (result.isErr) { - console.log(result.reason) + 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, null, 2)) - + 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" +``` -Origin Level: Root +# Data Availability + +Runtime Component: DataAvailability\ +Runtime Index: 29\ +Interface Module Name: dataAvailability + +## 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 result = await sdk.tx.dataAvailability.setSubmitDataFeeModifier(modifier, WaitFor.BlockInclusion, account) - if (result.isErr) { - console.log(result.reason) + const key = "MyAwesomeKey" + + 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, null, 2)) - + 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) - 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() @@ -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,12 @@ 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 result = await sdk.tx.balances.transferAllowDeath(dest, amount, WaitFor.BlockInclusion, account) - if (result.isErr) { - console.log(result.reason) - process.exit(1) - } + const data = "My Awesome Data" - console.log(JSON.stringify(result, null, 2)) + 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() @@ -478,66 +621,83 @@ 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 `SubmitDataTx`. -```js -{ - "isErr": false, - "event": { - "from": "5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY", - "to": "5HGjWAeFDfFCWPsjFQdVV2Msvz2XtMktvgocEZcCj68kUMaw", - "amount": "1000000000000000000" - }, - "events": [...], - "txHash": "0x63a73d2d1210ab9840341506788cca9592fd968609fecb5106cf0370c611061c", - "txIndex": 1, - "blockHash": "0xde2e95b63a4ca5927f9105931e4676b0634d12f524d4fff1048b403393419489", - "blockNumber": 2 -} +```json +"0x8643a0f94f1928eb542aaa44aacf943c7fe50ab4949c53a934debf006049bc7e" ``` -## Transfer All +# Multisig + +Runtime Component: Multisig\ +Runtime Index: 34\ +Interface Module Name: multisig + +## Approving As Multi Origin Level: Signed ### Interface ```js -function transferAll(dest: string, keepAlive: boolean, waitFor: WaitFor, account: KeyringPair, options?: Partial): Promise; +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 | -| --------- | ------------- | -------- | ------------------------------------------------ | -| 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. | +| 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 "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 dest = "5HGjWAeFDfFCWPsjFQdVV2Msvz2XtMktvgocEZcCj68kUMaw" // Eve - const keepAlive = true - - const result = await sdk.tx.balances.transferAll(dest, keepAlive, WaitFor.BlockInclusion, account) - if (result.isErr) { - console.log(result.reason) + // 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, null, 2)) - + console.log(JSON.stringify(result.value, null, 2)) process.exit() } main() @@ -551,72 +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 `TransferAllTxSuccess`. +If the operation is successful, the function will return a object of type `ApproveAsMultiTx`. -```js +```json { - "isErr": false, "event": { - "from": "5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY", - "to": "5HGjWAeFDfFCWPsjFQdVV2Msvz2XtMktvgocEZcCj68kUMaw", - "amount": "9999999873433871068464733" + "approving": "5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY", + "multisig": "5F3QVbS78a4aTYLiRAD8N3czjqVoNyV42L19CXyhqUMCh4Ch", + "callHash": "0x239258ef81456d5dbf5bf8a37709c7cf14c74ea7ed89961f47c7f3701de1e86b" }, - "events": [...], - "txHash": "0x343d3e8890bd479b4619cb7b0f2dfa91b7b91c0cedc0646247215f85baf1f63e", - "txIndex": 1, - "blockHash": "0xaec4adfad11f8aa902e1a985abb62737fc02445072b168238a956c3a0d8820f2", - "blockNumber": 2 + "details": { + "txResult": {...}, + "events": [...], + "txHash": "0x7beb1e4edb785c57533e0793f0d9051bbe6290e9551ee7e907d9c34ba9cad1a2", + "txIndex": 1, + "blockHash": "0xb23ef6eada32c5c19e75d3c0713c62ec88153613ceab70b28cac9ccd743e6b60", + "blockNumber": 103 + } } ``` -# Staking - -Runtime Component: Staking\ -Runtime Index: 10\ -Interface Module Name: staking - -## Bond +## As Multi Origin Level: Signed ### Interface ```js -function bond(value: BN, payee: StakingRewardDestination, 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 | -| --------- | ------------------------ | -------- | ------------------------------------------------------- | -| 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 | +| --------------- | ------------------------- | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | +| 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, BN } 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 value = new BN(100_000).mul(new BN(10).pow(new BN("18"))) // 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) + // 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, null, 2)) - + console.log(JSON.stringify(secondResult.value, null, 2)) process.exit() } main() @@ -630,23 +810,37 @@ 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 `AsMultiTx`. -```js +```json { - "isErr": false, "event": { - "stash": "5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY", - "amount": "100000" + "approving": "5FHneW46xGXgs5mUiveU4sbTyGBzmstUspZC92UhjJM694ty", + "timepoint": { + "height": 103, + "index": 1 + }, + "multisig": "5F3QVbS78a4aTYLiRAD8N3czjqVoNyV42L19CXyhqUMCh4Ch", + "callHash": "0x239258ef81456d5dbf5bf8a37709c7cf14c74ea7ed89961f47c7f3701de1e86b", + "result": "Ok" }, - "events": [...], - "txHash": "0x3e1cc48207b02ca5d680cf1beeb270ce7cbf0d18a6191844bc963d4081a0ca90", - "txIndex": 1, - "blockHash": "0xf854e74cb428d0baf22454cb15007731a84263e57c64d019a304c0ca1bd30276", - "blockNumber": 2 + "details": { + "txResult": {...}, + "events": [...], + "txHash": "0xada53aa3d7e7891404228c07251f51c86214143e57205be10b6f55b1dd63b933", + "txIndex": 1, + "blockHash": "0x84a33cb83078795f8be128835c5699f20a314119c8b6efa432cc626fa6ac8812", + "blockNumber": 150 + } } ``` +# Nomination Pools + +Runtime Component: Nomination Pools\ +Runtime Index: 36\ +Interface Module Name: nominationPools + ## Bond Extra Origin Level: Signed @@ -654,39 +848,39 @@ Origin Level: Signed ### Interface ```js -function bondExtra(maxAdditional: BN, waitFor: WaitFor, account: KeyringPair, options?: Partial): Promise; +function bondExtra(extra: BondExtra, 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 | +| --------- | ------------------ | -------- | ------------------------------------------------------------------------------------------------------ | +| 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" 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 amount = SDK.oneAvail().mul(new BN(10000)) // 10_000 Avail + const bondExtra = { FreeBalance: amount } as BondExtra - const result = await sdk.tx.staking.bondExtra(maxAdditional, WaitFor.BlockInclusion, account) - if (result.isErr) { - console.log(result.reason) + 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, null, 2)) - + console.log(JSON.stringify(result.value, null, 2)) process.exit() } main() @@ -700,20 +894,24 @@ 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 `BondExtraTx`. -```js +```json { - "isErr": false, "event": { - "stash": "5GNJqTPyNqANBkUVMN1LPPrxXnFouWXoe2wNSmmEoLctxiZY", - "amount": "1" + "member": "5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY", + "poolId": "1", + "bonded": "10000000000000000000000", + "joined": "false" }, - "events": [...], - "txHash": "0x940df5141925aeef2ab9aa767f6870689426de533f5f1d84b6d7be203e68ee77", - "txIndex": 1, - "blockHash": "0xc2a8375be07956586833f497a429ca2e29bafbb78ee5e051d5157df0ad5c8cb6", - "blockNumber": 7 + "details": { + "txResult": {...}, + "events": [...], + "txHash": "0xc09bdfbc1703763850a2f4255ccb0dd7d7e9f4b793d2f9f05782b9e3c63682d9", + "txIndex": 1, + "blockHash": "0xe06e35e61e2b59900e22d627dd8cd9cab39c87a304a40aba0fce87936e921843", + "blockNumber": 112 + } } ``` @@ -724,36 +922,38 @@ Origin Level: Signed ### Interface ```js -function chill(waitFor: WaitFor, account: KeyringPair, options?: Partial): Promise; +function chill(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) - if (result.isErr) { - console.log(result.reason) + 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, null, 2)) - + console.log(JSON.stringify(result.value, null, 2)) process.exit() } main() @@ -767,61 +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 `ChillTxSuccess`. +If the operation is successful, the function will return a object of type `ChillTx`. -```js +```json { - "isErr": false, - "event": { - "stash": "5GNJqTPyNqANBkUVMN1LPPrxXnFouWXoe2wNSmmEoLctxiZY" - }, - "events": [...], - "txHash": "0x4572681f19af32fdfb4759c914697697b0e82fde48a5dd7e28c2b3a263772b0d", - "txIndex": 1, - "blockHash": "0xad2e5376f53e6257e7bc0c842e5b6952f1d4af6f7499319b2d1ab59bdd742628", - "blockNumber": 13 + "details": { + "txResult": {...}, + "events": [...], + "txHash": "0x678fd95154114bb899598f8ef4413e3fdb5a90317a132d5a49f868ffb029cecf", + "txIndex": 1, + "blockHash": "0xa66f5eacd4c4294ba6679c868d90df11fccf5c85c773e8554856882ac64b4be7", + "blockNumber": 1106 + } } ``` -## Chill Other +## Claim Commission Origin Level: Signed ### Interface ```js -function chillOther(stash: string, waitFor: WaitFor, account: KeyringPair, options?: Partial): Promise; +function claimCommission(poolId: number, 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 | +| --------- | ------------------ | -------- | ------------------------------------------------------------- | +| 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 stash = "5GNJqTPyNqANBkUVMN1LPPrxXnFouWXoe2wNSmmEoLctxiZY" // Alice Stash + const account = new Keyring({ type: "sr25519" }).addFromUri("//Alice") + const poolId = 1 - const result = await sdk.tx.staking.chillOther(stash, WaitFor.BlockInclusion, account) - if (result.isErr) { - console.log(result.reason) + 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, null, 2)) - + console.log(JSON.stringify(result.value, null, 2)) process.exit() } main() @@ -835,35 +1034,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 `ClaimCommissionTx`. +```json +{ + "event": { + "poolId": "1", + "commission": "7652149502759813012" + }, + "details": { + "txResult": {...}, + "events": [...], + "txHash": "0x52292c2af7c2505c0bd39f5f1308bc10d92db7117f1b9fec208dc778e0c49654", + "txIndex": 1, + "blockHash": "0xdceaa5b12517f9634ad568e355061e8e13a8af25074e8966381c92fcea214285", + "blockNumber": 418 + } +} ``` -## Nominate +## Claim Payout Other Origin Level: Signed ### Interface ```js -function nominate(targets: string[], waitFor: WaitFor, account: KeyringPair, options?: Partial): Promise; +function claimPayoutOther(other: string, 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 | +| --------- | ------------------ | -------- | ------------------------------------------------------------- | +| 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" @@ -871,19 +1083,15 @@ const main = async () => { // Input const account = new Keyring({ type: "sr25519" }).addFromUri("//Alice") - const targets = [ - "5GNJqTPyNqANBkUVMN1LPPrxXnFouWXoe2wNSmmEoLctxiZY", // Alice Stash - "5FHneW46xGXgs5mUiveU4sbTyGBzmstUspZC92UhjJM694ty", // Bob - ] + const other = "5FHneW46xGXgs5mUiveU4sbTyGBzmstUspZC92UhjJM694ty" // Bob - const result = await sdk.tx.staking.nominate(targets, WaitFor.BlockInclusion, account) - if (result.isErr) { - console.log(result.reason) + 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, null, 2)) - + console.log(JSON.stringify(result.value, null, 2)) process.exit() } main() @@ -897,48 +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 `NominateTxSuccess`. +If the operation is successful, the function will return a object of type `ClaimPayoutOtherTx`. -```js +```json { - "isErr": false, - "txData": { - "targets": [ - "5GNJqTPyNqANBkUVMN1LPPrxXnFouWXoe2wNSmmEoLctxiZY", - "5FHneW46xGXgs5mUiveU4sbTyGBzmstUspZC92UhjJM694ty" - ] + "event": { + "member": "5FHneW46xGXgs5mUiveU4sbTyGBzmstUspZC92UhjJM694ty", + "poolId": "1", + "payout": "8198513381719500000" }, - "events": [...], - "txHash": "0x2f81a34f59d36eb7ada96ec1070358043026d7bd7cfb6fa5a532cc474190880b", - "txIndex": 1, - "blockHash": "0x49a57953aa2b2ba508f1c6991515309a0fe89723a79f3831f9a9263ba8c7baa4", - "blockNumber": 4 + "details": { + "txResult": {...}, + "events": [...], + "txHash": "0xe14015b25afc66c4954dda18631b3fd5efaeba80989070ed12712ca312dbec40", + "txIndex": 1, + "blockHash": "0x3abde836ab66ac38bc3ca260f081d370f1c15094f43048423e0995170569a51a", + "blockNumber": 594 + } } ``` -## Unbond +## Claim Payout Origin Level: Signed ### Interface ```js -function unbond(value: BN, waitFor: WaitFor, account: KeyringPair, options?: Partial): Promise; +function claimPayout(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 | +| --------- | ------------------ | -------- | ------------------------------------------------------------- | +| 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" @@ -946,15 +1154,14 @@ const main = async () => { // Input const account = new Keyring({ type: "sr25519" }).addFromUri("//Alice") - 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) + 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, null, 2)) + console.log(JSON.stringify(result.value, null, 2)) process.exit() } main() @@ -968,65 +1175,82 @@ 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 `ClaimPayoutTx`. -```js +```json { - "isErr": false, "event": { - "stash": "5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY", - "amount": "1000000000000000000" + "member": "5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY", + "poolId": "1", + "payout": "4008268787159890000" }, - "events": [...], - "txHash": "0xbf264e0e95885fd64a35d5c64bd4e1cc17056a1e6b05fa9207d7c777395dffdf", - "txIndex": 1, - "blockHash": "0x9ef43aaca71ba7b91a53976de5170f80d8a1ed4fe3e95fae237f7ed91f953963", - "blockNumber": 9 + "details": { + "txResult": {...}, + "events": [...], + "txHash": "0x15b50cb2a3885432811ba1417b7715e69e05b8d4dd8f7c9951f0b4f7a8ba5a61", + "txIndex": 1, + "blockHash": "0xdd24eca2111c6b7eea4a34c9bed02cfa6effde65c65c3dc66fb13c88e2fe6985", + "blockNumber": 426 + } } ``` -## Validate +## Create with Pool Id Origin Level: Signed ### Interface ```js -function validate(commission: number, blocked: boolean, 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 | -| ---------- | ------------- | -------- | ----------------------------------------------------- | -| 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`] | +| 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, 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 commission = 5 // 5% - const blocked = false + 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.validate(commission, blocked, WaitFor.BlockInclusion, account) - if (result.isErr) { - console.log(result.reason) + 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) } - console.log(JSON.stringify(result, null, 2)) - + console.log(JSON.stringify(result.value, null, 2)) process.exit() } main() @@ -1040,30 +1264,31 @@ 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 `CreateWithPoolIdTx`. -```js +```json { - "isErr": false, "event": { - "stash": "5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY", - "commission": "50000000", - "blocked": "false" + "depositor": "5FHneW46xGXgs5mUiveU4sbTyGBzmstUspZC92UhjJM694ty", + "poolId": "0" }, - "events": [...], - "txHash": "0x31f047da16a350e32b832cc73d3351c8d5e5991625fde6e8c36fc45ebb9d2735", - "txIndex": 1, - "blockHash": "0xa7735804f52602d4b73e1dd7f718cf0ab5cc00d111c927a9f8a2b3d02b66e09a", - "blockNumber": 14 + "event2": { + "member": "5FHneW46xGXgs5mUiveU4sbTyGBzmstUspZC92UhjJM694ty", + "poolId": "0", + "bonded": "10000", + "joined": "true" + }, + "details": { + "txResult": {...}, + "events": [...], + "txHash": "0x6b50caed7950e67934cabbf88a1f7dc2e7e995ac608402f91a4db19be0da5c41", + "txIndex": 1, + "blockHash": "0xc06df7dbb1e404f54499f942479ddcffc92665c021ea07c2798fc2f354f403d3", + "blockNumber": 6 + } } ``` -# Nomination Pools - -Runtime Component: Nomination Pools\ -Runtime Index: 36\ -Interface Module Name: nominationPools - ## Create Origin Level: Signed @@ -1071,25 +1296,25 @@ Origin Level: Signed ### Interface ```js -function create(amount: BN, root: string, nominator: string, bouncer: string, 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 | -| --------- | ------------- | -------- | -------------------------------------------------- | -| 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 | +| 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, BN } from "avail-js-sdk" +import { SDK, WaitFor, Keyring, BN } from "../../src/index" const main = async () => { const providerEndpoint = "ws://127.0.0.1:9944" @@ -1097,19 +1322,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() @@ -1125,83 +1350,148 @@ If the operation fails, the function will return an error message indicating the If the operation is successful, the function will return a object of type `PoolCreateTxSuccess`. +```json +{ + "event": { + "depositor": "5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY", + "poolId": "1" + }, + "event2": { + "member": "5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY", + "poolId": "1", + "bonded": "10000", + "joined": "true" + }, + "details": { + "txResult": {...}, + "events": [...], + "txHash": "0x9f019464c676682d9cbfb62814d019a85738e01b0ce92b18fa77878f80e16f66", + "txIndex": 1, + "blockHash": "0xdaa49f09b8c519bbd4c52ed05652d3de3f777afa3ac85db5c697cf705907e2d2", + "blockNumber": 5 + } +} +``` + +## Join + +Origin Level: Signed + +### Interface + +```js +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 | +| 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 "../../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 = 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.error.reason) + process.exit(1) + } + + console.log(JSON.stringify(result.value, 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 `JoinTx`. + +```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, - ) - if (result.isErr) { - console.log(result.reason) + const result = await sdk.tx.nominationPools.nominate(poolId, validators, WaitFor.BlockInclusion, account) + 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() @@ -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,16 +1550,15 @@ 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) - if (result.isErr) { - console.log(result.reason) + const result = await sdk.tx.nominationPools.setClaimPermission(permission, WaitFor.BlockInclusion, account) + 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() @@ -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,19 +1618,16 @@ 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) - if (result.isErr) { - console.log(result.reason) + const result = await sdk.tx.nominationPools.setCommission(poolId, newCommission, WaitFor.BlockInclusion, account) + 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() @@ -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,16 +1691,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 bondExtra = { FreeBalance: amount } as BondExtra + const poolId = 1 + const metadata = "My Metadata" - const result = await sdk.tx.nominationPools.bondExtra(bondExtra, WaitFor.BlockInclusion, account) - if (result.isErr) { - console.log(result.reason) + const result = await sdk.tx.nominationPools.setMetadata(poolId, metadata, WaitFor.BlockInclusion, account) + 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() @@ -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,16 +1760,16 @@ 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) - if (result.isErr) { - console.log(result.reason) + const result = await sdk.tx.nominationPools.setState(poolId, state, WaitFor.BlockInclusion, account) + 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() @@ -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,15 +1834,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() @@ -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,15 +1909,21 @@ 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) - if (result.isErr) { - console.log(result.reason) + const result = await sdk.tx.nominationPools.withdrawUnbonded( + memberAccount, + numSlashingSpans, + WaitFor.BlockInclusion, + account, + ) + 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() @@ -1646,58 +1937,72 @@ 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) - if (result.isErr) { - console.log(result.reason) + const result = await sdk.tx.staking.bondExtra(maxAdditional, WaitFor.BlockInclusion, account) + 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() @@ -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,15 +2066,16 @@ 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) - if (result.isErr) { - console.log(result.reason) + const result = await sdk.tx.staking.bond(value, payee, WaitFor.BlockInclusion, account) + 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() @@ -1776,60 +2089,63 @@ 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) - if (result.isErr) { - console.log(result.reason) + const result = await sdk.tx.staking.chillOther(stash, WaitFor.BlockInclusion, account) + 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() @@ -1843,63 +2159,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 `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) - if (result.isErr) { - console.log(result.reason) + const result = await sdk.tx.staking.chill(WaitFor.BlockInclusion, account) + 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() @@ -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,16 +2262,18 @@ 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) - if (result.isErr) { - console.log(result.reason) + const result = await sdk.tx.staking.nominate(targets, WaitFor.BlockInclusion, account) + 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() @@ -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,21 +2338,15 @@ 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, - ) - if (result.isErr) { - console.log(result.reason) + const result = await sdk.tx.staking.unbond(value, WaitFor.BlockInclusion, account) + 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() @@ -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,16 +2410,16 @@ 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) - if (result.isErr) { - console.log(result.reason) + const result = await sdk.tx.staking.validate(commission, blocked, WaitFor.BlockInclusion, account) + 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() @@ -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.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..a51fd5d54 --- /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(JSON.stringify(txHash, null, 2)) + 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..df9bcb4f5 --- /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(JSON.stringify(txHash, null, 2)) + 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..760b79bb6 --- /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(JSON.stringify(txHash, null, 2)) + 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..440830213 --- /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(JSON.stringify(txHash, null, 2)) + 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..5d87ccce9 --- /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(JSON.stringify(txHash, null, 2)) + process.exit() +} +main() 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/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/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/account.ts b/avail-js/src/sdk/account.ts new file mode 100644 index 000000000..2895e0603 --- /dev/null +++ b/avail-js/src/sdk/account.ts @@ -0,0 +1,114 @@ +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" +import { getNonceState, getNonceNode } from "./utils" + +export interface AccountBalance { + free: BN + reserved: BN + frozen: BN + flags: BN +} + +export class Account { + waitFor: WaitFor = WaitFor.BlockInclusion + nonce: number | null = null + appId: number | null = null + + constructor( + public sdk: SDK, + public keyring: KeyringPair, + ) {} + + setNonce(value: number | null) { + this.nonce = value + } + + 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) + } + + 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 { + return await getNonceState(this.sdk.api, this.keyring.address) + } + + async getNonceNode(): Promise { + return await getNonceNode(this.sdk.api, this.keyring.address) + } + + async getAppKeys(): Promise { + const appKeys: number[] = [] + const entries = await this.sdk.api.query.dataAvailability.appKeys.entries() + entries.forEach((entry: any) => { + if (entry[1].isSome) { + const { owner, id } = entry[1].unwrap() + if (owner.toString() == this.keyring.address) { + appKeys.push(parseInt(id.toString())) + } + } + }) + + return appKeys.sort((a, b) => a - b) + } + + oneAvail(): BN { + return SDK.oneAvail() + } + + private buildOptions(): any { + const 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 a06ac9425..28fc48bb6 100644 --- a/avail-js/src/sdk/index.ts +++ b/avail-js/src/sdk/index.ts @@ -1,13 +1,20 @@ 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" 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 { TxResultDetails, MultisigTimepoint } from "./utils" +export { Account } from "./account" + export { WaitFor, StakingRewardDestination, @@ -16,11 +23,13 @@ export { ClaimPermission, NewCommission, PoolState, + TransactionOptions, } from "./transactions" export class SDK { api: ApiPromise tx: Transactions + util: Utils static async New(endpoint: string): Promise { const api = await initialize(endpoint) @@ -30,5 +39,10 @@ export class SDK { private constructor(api: ApiPromise) { this.api = api 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/balances.ts b/avail-js/src/sdk/transactions/balances.ts index 2112b3db4..194fe3696 100644 --- a/avail-js/src/sdk/transactions/balances.ts +++ b/avail-js/src/sdk/transactions/balances.ts @@ -1,42 +1,33 @@ import { ApiPromise } from "@polkadot/api" import { ISubmittableResult } from "@polkadot/types/types/extrinsic" -import { H256, 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 } 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 { err, Result, ok } from "neverthrow" +import { WaitFor, standardCallback, TransactionFailed, TransactionOptions } 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 { @@ -51,8 +42,8 @@ export class Balances { keepAlive: boolean, waitFor: WaitFor, account: KeyringPair, - options?: Partial, - ): Promise { + options?: TransactionOptions, + ): Promise> { const optionWrapper = options || {} const maybeTxResult = await new Promise>((res, _) => { this.api.tx.balances @@ -66,29 +57,32 @@ 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 ok(new TransferAllTx(event, event2, details)) + } - return { isErr: false, event, event2, events, txHash, txIndex, blockHash, blockNumber } as TransferAllTxSuccess + 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( @@ -96,8 +90,8 @@ export class Balances { value: BN, waitFor: WaitFor, account: KeyringPair, - options?: Partial, - ): Promise { + options?: TransactionOptions, + ): Promise> { const optionWrapper = options || {} const maybeTxResult = await new Promise>((res, _) => { this.api.tx.balances @@ -111,38 +105,32 @@ 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 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( @@ -150,8 +138,8 @@ export class Balances { value: BN, waitFor: WaitFor, account: KeyringPair, - options?: Partial, - ): Promise { + options?: TransactionOptions, + ): Promise> { const optionWrapper = options || {} const maybeTxResult = await new Promise>((res, _) => { this.api.tx.balances @@ -165,28 +153,31 @@ 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 ok(new TransferKeepAliveTx(event, details)) + } - return { isErr: false, event, events, txHash, txIndex, blockHash, blockNumber } as TransferKeepAliveTxSuccess + 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) } } diff --git a/avail-js/src/sdk/transactions/common.ts b/avail-js/src/sdk/transactions/common.ts index 4383b968d..6fd6ccd7a 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,16 @@ 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, + ) {} +} + +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 bfa48cacc..1ca9fc6d6 100644 --- a/avail-js/src/sdk/transactions/da.ts +++ b/avail-js/src/sdk/transactions/da.ts @@ -1,14 +1,14 @@ import { ApiPromise } from "@polkadot/api" import { ISubmittableResult } from "@polkadot/types/types/extrinsic" -import { H256, 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 } 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, TransactionOptions } from "./common" +import { parseTransactionResult, TxResultDetails } from "../utils" +import { Bytes } from "@polkadot/types-codec" export type DispatchFeeModifier = { weightMaximumFee: BN | null @@ -16,51 +16,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 { @@ -71,11 +60,11 @@ export class DataAvailability { } async submitData( - data: string, + data: string | Bytes, waitFor: WaitFor, account: KeyringPair, - options?: Partial, - ): Promise { + options?: TransactionOptions, + ): Promise> { const optionWrapper = options || {} const maybeTxResult = await new Promise>((res, _) => { this.api.tx.dataAvailability @@ -89,50 +78,43 @@ 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 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, - ): Promise { + options?: TransactionOptions, + ): Promise> { const optionWrapper = options || {} const maybeTxResult = await new Promise>((res, _) => { this.api.tx.dataAvailability @@ -146,28 +128,26 @@ 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 ok(new CreateApplicationKeyTx(event, details)) + } - return { isErr: false, event, events, txHash, txIndex, blockHash, blockNumber } as CreateApplicationKeyTxSuccess + async createApplicationKeyNoWait(key: string, account: KeyringPair, options?: TransactionOptions): Promise { + const optionWrapper = options || {} + return this.api.tx.dataAvailability.createApplicationKey(key).signAndSend(account, optionWrapper) } async setApplicationKey( @@ -175,8 +155,8 @@ export class DataAvailability { newKey: string, waitFor: WaitFor, account: KeyringPair, - options?: Partial, - ): Promise { + options?: TransactionOptions, + ): Promise> { const optionWrapper = options || {} const maybeTxResult = await new Promise>((res, _) => { const call = this.api.tx.dataAvailability.setApplicationKey(oldKey, newKey) @@ -191,38 +171,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( @@ -230,8 +203,8 @@ export class DataAvailability { cols: number, waitFor: WaitFor, account: KeyringPair, - options?: Partial, - ): Promise { + options?: TransactionOptions, + ): Promise> { const optionWrapper = options || {} const maybeTxResult = await new Promise>((res, _) => { const call = this.api.tx.dataAvailability.submitBlockLengthProposal(rows, cols) @@ -246,54 +219,39 @@ 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( modifier: DispatchFeeModifier, waitFor: WaitFor, account: KeyringPair, - options?: Partial, - ): Promise { + options?: TransactionOptions, + ): Promise> { const optionWrapper = options || {} const maybeTxResult = await new Promise>((res, _) => { const call = this.api.tx.dataAvailability.setSubmitDataFeeModifier(modifier) @@ -308,38 +266,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/index.ts b/avail-js/src/sdk/transactions/index.ts index 67223e244..452c31d1e 100644 --- a/avail-js/src/sdk/transactions/index.ts +++ b/avail-js/src/sdk/transactions/index.ts @@ -3,8 +3,9 @@ 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 { WaitFor, TransactionOptions } from "./common" export { DispatchFeeModifier } from "./da" export { StakingRewardDestination } from "./staking" export { BondExtra, ClaimPermission, NewCommission, PoolState } from "./nomination_pools" @@ -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 new file mode 100644 index 000000000..79c5f4221 --- /dev/null +++ b/avail-js/src/sdk/transactions/multisig.ts @@ -0,0 +1,183 @@ +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 { WaitFor, standardCallback, TransactionFailed, TransactionOptions } 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?: TransactionOptions, + ): 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?: TransactionOptions, + ): 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/transactions/nomination_pools.ts b/avail-js/src/sdk/transactions/nomination_pools.ts index 5d6947e80..85fe296e6 100644 --- a/avail-js/src/sdk/transactions/nomination_pools.ts +++ b/avail-js/src/sdk/transactions/nomination_pools.ts @@ -1,14 +1,12 @@ 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, TransactionOptions } from "./common" +import { commissionNumberToPerbill, parseTransactionResult, TxResultDetails } from "../utils" export interface BondExtra { FreeBalance?: BN @@ -23,152 +21,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 { @@ -185,8 +130,8 @@ export class NominationPools { bouncer: string, waitFor: WaitFor, account: KeyringPair, - options?: Partial, - ): Promise { + options?: TransactionOptions, + ): Promise> { const optionWrapper = options || {} const maybeTxResult = await new Promise>((res, _) => { this.api.tx.nominationPools @@ -200,33 +145,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( @@ -237,8 +174,8 @@ export class NominationPools { poolId: number, waitFor: WaitFor, account: KeyringPair, - options?: Partial, - ): Promise { + options?: TransactionOptions, + ): Promise> { const optionWrapper = options || {} const maybeTxResult = await new Promise>((res, _) => { this.api.tx.nominationPools @@ -252,42 +189,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( @@ -295,8 +216,8 @@ export class NominationPools { poolId: number, waitFor: WaitFor, account: KeyringPair, - options?: Partial, - ): Promise { + options?: TransactionOptions, + ): Promise> { const optionWrapper = options || {} const maybeTxResult = await new Promise>((res, _) => { this.api.tx.nominationPools @@ -310,28 +231,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( @@ -339,8 +253,8 @@ export class NominationPools { validators: string[], waitFor: WaitFor, account: KeyringPair, - options?: Partial, - ): Promise { + options?: TransactionOptions, + ): Promise> { const optionWrapper = options || {} const maybeTxResult = await new Promise>((res, _) => { this.api.tx.nominationPools @@ -354,31 +268,24 @@ 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( extra: BondExtra, waitFor: WaitFor, account: KeyringPair, - options?: Partial, - ): Promise { + options?: TransactionOptions, + ): Promise> { const optionWrapper = options || {} const maybeTxResult = await new Promise>((res, _) => { this.api.tx.nominationPools @@ -392,28 +299,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( @@ -421,8 +321,8 @@ export class NominationPools { metadata: string, waitFor: WaitFor, account: KeyringPair, - options?: Partial, - ): Promise { + options?: TransactionOptions, + ): Promise> { const optionWrapper = options || {} const maybeTxResult = await new Promise>((res, _) => { this.api.tx.nominationPools @@ -436,23 +336,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( @@ -460,8 +353,8 @@ export class NominationPools { unbondingPoints: BN, waitFor: WaitFor, account: KeyringPair, - options?: Partial, - ): Promise { + options?: TransactionOptions, + ): Promise> { const optionWrapper = options || {} const maybeTxResult = await new Promise>((res, _) => { this.api.tx.nominationPools @@ -475,32 +368,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.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( poolId: number, waitFor: WaitFor, account: KeyringPair, - options?: Partial, - ): Promise { + options?: TransactionOptions, + ): Promise> { const optionWrapper = options || {} const maybeTxResult = await new Promise>((res, _) => { this.api.tx.nominationPools @@ -514,31 +401,24 @@ 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( poolId: number, waitFor: WaitFor, account: KeyringPair, - options?: Partial, - ): Promise { + options?: TransactionOptions, + ): Promise> { const optionWrapper = options || {} const maybeTxResult = await new Promise>((res, _) => { this.api.tx.nominationPools @@ -552,35 +432,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 { + options?: TransactionOptions, + ): Promise> { const optionWrapper = options || {} const maybeTxResult = await new Promise>((res, _) => { this.api.tx.nominationPools @@ -594,32 +467,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 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( other: string, waitFor: WaitFor, account: KeyringPair, - options?: Partial, - ): Promise { + options?: TransactionOptions, + ): Promise> { const optionWrapper = options || {} const maybeTxResult = await new Promise>((res, _) => { this.api.tx.nominationPools @@ -633,32 +499,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 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( permission: ClaimPermission, waitFor: WaitFor, account: KeyringPair, - options?: Partial, - ): Promise { + options?: TransactionOptions, + ): Promise> { const optionWrapper = options || {} const maybeTxResult = await new Promise>((res, _) => { this.api.tx.nominationPools @@ -672,23 +531,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( @@ -696,15 +548,15 @@ export class NominationPools { newCommission: NewCommission | null, waitFor: WaitFor, account: KeyringPair, - options?: Partial, - ): Promise { + options?: TransactionOptions, + ): 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 +572,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( @@ -749,8 +594,8 @@ export class NominationPools { numSlashingSpans: number, waitFor: WaitFor, account: KeyringPair, - options?: Partial, - ): Promise { + options?: TransactionOptions, + ): Promise> { const optionWrapper = options || {} const maybeTxResult = await new Promise>((res, _) => { this.api.tx.nominationPools @@ -764,28 +609,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( @@ -793,8 +631,8 @@ export class NominationPools { state: PoolState, waitFor: WaitFor, account: KeyringPair, - options?: Partial, - ): Promise { + options?: TransactionOptions, + ): Promise> { const optionWrapper = options || {} const maybeTxResult = await new Promise>((res, _) => { this.api.tx.nominationPools @@ -808,24 +646,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..2f9c1156f 100644 --- a/avail-js/src/sdk/transactions/staking.ts +++ b/avail-js/src/sdk/transactions/staking.ts @@ -1,81 +1,64 @@ 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, TransactionOptions } 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 { @@ -90,8 +73,8 @@ export class Staking { payee: StakingRewardDestination, waitFor: WaitFor, account: KeyringPair, - options?: Partial, - ): Promise { + options?: TransactionOptions, + ): Promise> { const optionWrapper = options || {} const maybeTxResult = await new Promise>((res, _) => { this.api.tx.staking @@ -105,36 +88,29 @@ 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( maxAdditional: BN, waitFor: WaitFor, account: KeyringPair, - options?: Partial, - ): Promise { + options?: TransactionOptions, + ): Promise> { const optionWrapper = options || {} const maybeTxResult = await new Promise>((res, _) => { this.api.tx.staking @@ -148,35 +124,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 { + options?: TransactionOptions, + ): Promise> { const optionWrapper = options || {} const maybeTxResult = await new Promise>((res, _) => { this.api.tx.staking @@ -190,36 +159,29 @@ 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( stash: string, waitFor: WaitFor, account: KeyringPair, - options?: Partial, - ): Promise { + options?: TransactionOptions, + ): Promise> { const optionWrapper = options || {} const maybeTxResult = await new Promise>((res, _) => { this.api.tx.staking @@ -233,36 +195,29 @@ 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( targets: string[], waitFor: WaitFor, account: KeyringPair, - options?: Partial, - ): Promise { + options?: TransactionOptions, + ): Promise> { const optionWrapper = options || {} const maybeTxResult = await new Promise>((res, _) => { this.api.tx.staking @@ -276,44 +231,29 @@ 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( value: BN, waitFor: WaitFor, account: KeyringPair, - options?: Partial, - ): Promise { + options?: TransactionOptions, + ): Promise> { const optionWrapper = options || {} const maybeTxResult = await new Promise>((res, _) => { this.api.tx.staking @@ -327,28 +267,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( @@ -356,11 +289,11 @@ export class Staking { blocked: boolean, waitFor: WaitFor, account: KeyringPair, - options?: Partial, - ): Promise { + options?: TransactionOptions, + ): 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 +310,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.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..10a2834ca --- /dev/null +++ b/avail-js/src/sdk/utils/index.ts @@ -0,0 +1,140 @@ +import { ApiPromise } from "@polkadot/api" +import { err, ok, Result } from "neverthrow" +import { ISubmittableResult } from "@polkadot/types/types/extrinsic" +import { EventRecord, H256 } from "@polkadot/types/interfaces" +import { decodeError } from "../../helpers" +import { getBlockHashAndTxHash, WaitFor } from "../transactions/common" +import { createKeyMulti, encodeAddress, sortAddresses } from "@polkadot/util-crypto" + +export class TxResultDetails { + constructor( + public txResult: ISubmittableResult, + public events: EventRecord[], + public txHash: H256, + public txIndex: number, + public blockHash: H256, + public blockNumber: number, + ) {} +} + +export class FailedTxResult { + constructor( + public reason: string, + public details: TxResultDetails | null, + ) {} +} + +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) + } + + /// Sorts multisig address so that ce be used for other multisig functions + 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( + api: ApiPromise, + txResult: ISubmittableResult, + waitFor: WaitFor, +): Promise> { + if (txResult.isError) { + 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({ reason: decodeError(api, failed.event.data[0]), details }) + } + + return ok(details) +} + +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) +} + +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()) +}