Skip to content

Commit

Permalink
Added more avail-js doc examples
Browse files Browse the repository at this point in the history
  • Loading branch information
markopoloparadox committed Nov 28, 2024
1 parent 7926ab7 commit 07592ad
Show file tree
Hide file tree
Showing 29 changed files with 271 additions and 178 deletions.
10 changes: 5 additions & 5 deletions avail-js/docs/book/src/examples/batch.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,10 +22,10 @@ export async function run() {
// and the error of the failed call. If all were successful, then the `BatchCompleted`
// event is deposited.
const batchTx = new Transaction(api, api.tx.utility.batch(calls))
const batchRes = (await batchTx.execute_wait_for_inclusion(account))._unsafeUnwrap()
const batchRes = (await batchTx.executeWaitForInclusion(account))._unsafeUnwrap()
console.log("-- Batch Call --")

const batchInterrupted = batchRes.findAllEvents(Events.Utility.BatchInterrupted)
const batchInterrupted = batchRes.findEvent(Events.Utility.BatchInterrupted)
if (batchInterrupted.length > 0) {
console.log("At least one call has failed")
}
Expand All @@ -39,16 +39,16 @@ export async function run() {
// Send a batch of dispatch calls and atomically execute them.
// The whole transaction will rollback and fail if any of the calls failed.
const batchAllTx = new Transaction(api, api.tx.utility.batchAll(calls))
const _ = (await batchAllTx.execute_wait_for_inclusion(account))._unsafeUnwrapErr()
const _ = (await batchAllTx.executeWaitForInclusion(account))._unsafeUnwrapErr()

// Force Batch
// Send a batch of dispatch calls.
// Unlike `batch`, it allows errors and won't interrupt.
const forceBatchTx = new Transaction(api, api.tx.utility.forceBatch(calls))
const forceBatchRes = (await forceBatchTx.execute_wait_for_inclusion(account))._unsafeUnwrap()
const forceBatchRes = (await forceBatchTx.executeWaitForInclusion(account))._unsafeUnwrap()
console.log("-- Force Batch Call --")

const itemFailed = forceBatchRes.findAllEvents(Events.Utility.ItemFailed)
const itemFailed = forceBatchRes.findEvent(Events.Utility.ItemFailed)
if (itemFailed.length > 0) {
console.log("At least one call has failed")
}
Expand Down
7 changes: 4 additions & 3 deletions avail-js/docs/book/src/examples/data_submission.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,10 @@
```

```ts
Block Hash: 0xec8d782508a3a143c5726a90db19958aa29e04742ee8af3ad0c14d0427cfd3d0, Block Number: 3, Tx Hash: 0x57047257d438e4b626431367e660e46bef678367eb5ec1c14b8ae8dd62a65c20, Tx Index: 1
Tx Hash: 0x57047257d438e4b626431367e660e46bef678367eb5ec1c14b8ae8dd62a65c20, Tx Index: 1, Data: 4d792044617461, Tx Signer: 5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY, App Id: 10
Block Hash: 0xab3a0e05dc6392cc0545bb7bbd3ab0413a647c484616d1536f75ea1ae8c8e2b5, Block Number: 3, Tx Hash: 0x5afb8278dae8c18d286dc6b1c67b8ae214978f1dc93f66f760c2cffae63b0e16, Tx Index: 1
Call data: 0x4d792044617461
Tx Hash: 0x5afb8278dae8c18d286dc6b1c67b8ae214978f1dc93f66f760c2cffae63b0e16, Tx Index: 1, Data: 4d792044617461, Tx Signer: 5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY, App Id: 10
Ascii data: My Data
Tx Hash: 0x57047257d438e4b626431367e660e46bef678367eb5ec1c14b8ae8dd62a65c20, Tx Index: 1, Data: 4d792044617461, Tx Signer: 5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY, App Id: 10
Tx Hash: 0x5afb8278dae8c18d286dc6b1c67b8ae214978f1dc93f66f760c2cffae63b0e16, Tx Index: 1, Data: 4d792044617461, Tx Signer: 5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY, App Id: 10
Ascii data: My Data
```
13 changes: 6 additions & 7 deletions avail-js/docs/book/src/examples/data_submission.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import { CallData } from "../../../../src/sdk/transactions"
import { SDK, Events, Block, DataSubmission } from "./../../../../src/index"
import { SDK, Events, Block, DataSubmission, CallData } from "./../../../../src/index"

export async function run() {
const sdk = await SDK.New(SDK.localEndpoint())
Expand All @@ -10,7 +9,7 @@ export async function run() {
// Application Key Creation
const key = "My JS Key"
const tx = sdk.tx.dataAvailability.createApplicationKey(key)
const keyRes = (await tx.execute_wait_for_inclusion(account))._unsafeUnwrap()
const keyRes = (await tx.executeWaitForInclusion(account))._unsafeUnwrap()

const keyEvent = keyRes.findFirstEvent(Events.DataAvailability.ApplicationKeyCreated)
if (keyEvent == null) throw Error("Failed to find Key Event")
Expand All @@ -19,21 +18,21 @@ export async function run() {
// Data Submission
const data = "My Data"
const tx2 = sdk.tx.dataAvailability.submitData(data)
const submitRes = (await tx2.execute_wait_for_inclusion(account, { app_id: appId }))._unsafeUnwrap()
const submitRes = (await tx2.executeWaitForInclusion(account, { app_id: appId }))._unsafeUnwrap()

console.log(
`Block Hash: ${submitRes.blockHash}, Block Number: ${submitRes.blockNumber}, Tx Hash: ${submitRes.txHash}, Tx Index: ${submitRes.txIndex}`,
)

const callData = await submitRes.getData(api, CallData.DataAvailability.SubmitData)
if (callData != null) {
console.log(`Call data: ${callData.data}`)
console.log(`Call data: 0x${callData.data}`)
}

// TODO Call Data

// Getting Data Submission from Block #1
const block = await Block.New(api, submitRes.blockHash)

// dataSubmissionsBySigner, dataSubmissionsByIndex, dataSubmissionsByHash, dataSubmissionsByAppId
const dataSubmissions = block.dataSubmissionsAll()
for (const ds of dataSubmissions) {
console.log(
Expand Down
16 changes: 16 additions & 0 deletions avail-js/docs/book/src/examples/events.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
# Events

```rs
{{#include ./events.ts}}
```

```ts
Pallet name: balances, Event name: Withdraw
Pallet name: balances, Event name: Transfer
Pallet name: balances, Event name: Deposit
Pallet name: balances, Event name: Deposit
Pallet name: balances, Event name: Deposit
Pallet name: transactionPayment, Event name: TransactionFeePaid
Pallet name: system, Event name: ExtrinsicSuccess
Transfer from: 5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY, to: 5FHneW46xGXgs5mUiveU4sbTyGBzmstUspZC92UhjJM694ty, amount: 1000000000000000000
```
22 changes: 22 additions & 0 deletions avail-js/docs/book/src/examples/events.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import { SDK, Events } from "./../../../../src/index"

export async function run() {
const sdk = await SDK.New(SDK.localEndpoint())

const account = SDK.alice()

const dest = "5FHneW46xGXgs5mUiveU4sbTyGBzmstUspZC92UhjJM694ty"
const value = SDK.oneAvail()
const tx = sdk.tx.balances.transferKeepAlive(dest, value)
const res = (await tx.executeWaitForInclusion(account))._unsafeUnwrap()

for (const eventRecord of res.events) {
console.log(`Pallet name: ${eventRecord.event.section}, Event name: ${eventRecord.event.method}`)
}

// findFirstEvent, findLastEvent, findEvent
const event = res.findFirstEvent(Events.Balances.Transfer)
if (event == null) throw Error("qed")

console.log(`Transfer from: ${event.from}, to: ${event.to}, amount: ${event.amount}`)
}
5 changes: 4 additions & 1 deletion avail-js/docs/book/src/examples/index.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
import * as Batch from "./batch"
import * as DA from "./data_submission"
import * as Events from "./events"
import * as Transactions from "./transactions"
import * as Validator from "./validator"

export async function run() {
await DA.run()
await Validator.run()
}
78 changes: 23 additions & 55 deletions avail-js/docs/book/src/examples/multisig.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { SDK, WaitFor, BN, KeyringPair, Weight, TxResultDetails, MultisigTimepoint } from "./../../../../src/index"
import { SDK, BN, KeyringPair, Weight, TxResultDetails, MultisigTimepoint, utils } from "./../../../../src/index"

const main = async () => {
const sdk = await SDK.New(SDK.localEndpoint())
Expand All @@ -8,7 +8,7 @@ const main = async () => {

// Create Multisig Account
const threshold = 3
const multisigAddress = sdk.util.generateMultisig([alice.address, bob.address, charlie.address], threshold)
const multisigAddress = utils.generateMultisig([alice.address, bob.address, charlie.address], threshold)
await fundMultisigAccount(sdk, alice, multisigAddress)

// Define what action will be taken by the multisig account
Expand Down Expand Up @@ -36,16 +36,16 @@ const main = async () => {
*/

// Create New Multisig
const call1signatures = sdk.util.sortMultisigAddresses([bob.address, charlie.address])
const call1signatures = utils.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 call2signatures = utils.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 call3signatures = utils.sortMultisigAddresses([alice.address, bob.address])
const _thirdResult = await lastApproval(sdk, charlie, threshold, call3signatures, timepoint, callData, maxWeight)

process.exit()
Expand All @@ -54,11 +54,9 @@ const main = async () => {
async function fundMultisigAccount(sdk: SDK, alice: KeyringPair, multisigAddress: string): Promise<string> {
console.log("Funding multisig account...")
const amount = SDK.oneAvail().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)
}
const tx = sdk.tx.balances.transferKeepAlive(multisigAddress, amount)
const result = await tx.executeWaitForInclusion(alice)
if (result.isErr()) throw Error(result.error.reason)

return multisigAddress
}
Expand All @@ -73,21 +71,11 @@ async function firstApproval(
): Promise<TxResultDetails> {
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
const tx = sdk.tx.multisig.approveAsMulti(threshold, otherSignatures, null, callHash, maxWeight)
const result = await tx.executeWaitForInclusion(account)
if (result.isErr()) throw Error(result.error.reason)

return result.value
}

async function nextApproval(
Expand All @@ -101,21 +89,11 @@ async function nextApproval(
): Promise<TxResultDetails> {
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
const tx = sdk.tx.multisig.approveAsMulti(threshold, otherSignatures, timepoint, callHash, maxWeight)
const result = await tx.executeWaitForInclusion(account)
if (result.isErr()) throw Error(result.error.reason)

return result.value
}

async function lastApproval(
Expand All @@ -129,21 +107,11 @@ async function lastApproval(
): Promise<TxResultDetails> {
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
const tx = sdk.tx.multisig.asMulti(threshold, otherSignatures, timepoint, callData, maxWeight)
const result = await tx.executeWaitForInclusion(account)
if (result.isErr()) throw Error(result.error.reason)

return result.value
}

main()
5 changes: 0 additions & 5 deletions avail-js/docs/book/src/examples/transaction_options.md

This file was deleted.

25 changes: 0 additions & 25 deletions avail-js/docs/book/src/examples/transaction_options.ts

This file was deleted.

21 changes: 21 additions & 0 deletions avail-js/docs/book/src/examples/transactions.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
# Transactions

```rs
{{#include ./transactions.ts}}
```

```ts
Tx Pallet name: timestamp, Tx Name: set, Tx Hash: 0xe5e3356b11db7a8528f58c302d678bcc77535cfd3af6e6996caeaffad2dd81cd
Event Pallet name: system, Event Name: ExtrinsicSuccess
Tx Pallet name: balances, Tx Name: transferKeepAlive, Tx Hash: 0x0338202e3f858c292930630151ee6360b52ce393726b1d5fed50f9c597934d76
Event Pallet name: balances, Event Name: Withdraw
Event Pallet name: balances, Event Name: Transfer
Event Pallet name: balances, Event Name: Deposit
Event Pallet name: balances, Event Name: Deposit
Event Pallet name: balances, Event Name: Deposit
Event Pallet name: transactionPayment, Event Name: TransactionFeePaid
Event Pallet name: system, Event Name: ExtrinsicSuccess
Transfer dest: 5FHneW46xGXgs5mUiveU4sbTyGBzmstUspZC92UhjJM694ty, value: 1000000000000000000
Tx Pallet name: vector, Tx Name: failedSendMessageTxs, Tx Hash: 0x92cdb77314063a01930b093516d19a453399710cc8ae635ff5ab6cf76b26f218
Event Pallet name: system, Event Name: ExtrinsicSuccess
```
29 changes: 29 additions & 0 deletions avail-js/docs/book/src/examples/transactions.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
import { SDK, Block, Events, CallData } from "./../../../../src/index"

export async function run() {
const sdk = await SDK.New(SDK.localEndpoint())
const api = sdk.api

const account = SDK.alice()

const dest = "5FHneW46xGXgs5mUiveU4sbTyGBzmstUspZC92UhjJM694ty"
const value = SDK.oneAvail()
const tx = sdk.tx.balances.transferKeepAlive(dest, value)
const res = (await tx.executeWaitForInclusion(account))._unsafeUnwrap()

const block = await Block.New(api, res.blockHash)

// transactionAll, transactionBySigner, transactionByIndex, transactionByHash, transactionByAppId
for (const [index, tx] of block.transactionAll().entries()) {
console.log(`Tx Pallet name: ${tx.method.section}, Tx Name: ${tx.method.method}, Tx Hash: ${tx.hash.toHex()}`)

const eventRecords = await Events.fetchEvents(api, res.blockHash, index)
for (const eventRecord of eventRecords) {
console.log(`\tEvent Pallet name: ${eventRecord.event.section}, Event Name: ${eventRecord.event.method}`)
}
const balance_tx = CallData.Balances.TransferKeepAlive.decode(tx)
if (balance_tx != null) {
console.log(`Transfer dest: ${balance_tx.dest}, value: ${balance_tx.value}`)
}
}
}
5 changes: 5 additions & 0 deletions avail-js/docs/book/src/examples/validator.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
# Validator

```rs
{{#include ./validator.ts}}
```
27 changes: 27 additions & 0 deletions avail-js/docs/book/src/examples/validator.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import { SDK, BN, utils } from "./../../../../src/index"

export async function run() {
const sdk = await SDK.New(SDK.localEndpoint())
const api = sdk.api

const account = SDK.alice()

// Bond minValidatorBond or 1 AVAIL token
const minValidatorBond: BN = ((await api.query.staking.minValidatorBond()) as any) || SDK.oneAvail()

// Bond
const bondTx = sdk.tx.staking.bond(minValidatorBond, "Staked")
const _r1 = (await bondTx.executeWaitForInclusion(account))._unsafeUnwrap()

// Generate Session Keys
const keysBytes = await api.rpc.author.rotateKeys()
const keys = utils.deconstruct_session_keys(keysBytes.toString())

// Set Keys
const setKeysTx = sdk.tx.session.setKeys(keys)
const _r2 = (await setKeysTx.executeWaitForInclusion(account))._unsafeUnwrap()

// Validate
const validateTx = sdk.tx.staking.validate(50, false)
const _r3 = (await validateTx.executeWaitForInclusion(account))._unsafeUnwrap()
}
Loading

0 comments on commit 07592ad

Please sign in to comment.