Skip to content

Commit

Permalink
Merge pull request #39 from subspace/33-create-reusable-scripts-to-co…
Browse files Browse the repository at this point in the history
…ver-all-staking-functions

Create reusable example scripts to cover all staking functions
  • Loading branch information
marc-aurele-besner authored Jun 23, 2024
2 parents 4a41a94 + aec0383 commit 6cc890b
Show file tree
Hide file tree
Showing 16 changed files with 341 additions and 25 deletions.
2 changes: 2 additions & 0 deletions examples/node/.env.local
Original file line number Diff line number Diff line change
@@ -1,2 +1,4 @@
ALICE_SEED="//Alice"
BOB_SEED="//Bob"

LOCALHOST="true"
7 changes: 7 additions & 0 deletions examples/node/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,12 +12,19 @@ yarn

```bash
yarn balance
yarn operators
```

## Execute extrinsics

```bash
yarn transfer
yarn register-operator
yarn nominate-operator
yarn withdraw-stake
yarn deregister-operator
yarn unlock-funds
yarn unlock-nominator
```

## Utility
Expand Down
11 changes: 9 additions & 2 deletions examples/node/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -13,10 +13,17 @@
"url": "https://www.autonomys.net"
},
"scripts": {
"all": "yarn address && yarn balance && yarn transfer",
"all": "yarn address && yarn balance && yarn transfer && yarn operators && yarn register-operator && yarn nominate-operator && yarn withdraw-stake && yarn deregister-operator",
"address": "npx ts-node ./src/address.ts",
"balance": "npx ts-node ./src/balance.ts",
"transfer": "npx ts-node ./src/transfer.ts"
"transfer": "npx ts-node ./src/transfer.ts",
"operators": "npx ts-node ./src/operators.ts",
"register-operator": "npx ts-node ./src/register-operator.ts",
"nominate-operator": "npx ts-node ./src/nominate-operator.ts",
"withdraw-stake": "npx ts-node ./src/withdraw-stake.ts",
"deregister-operator": "npx ts-node ./src/deregister-operator.ts",
"unlock-funds": "npx ts-node ./src/unlock-funds.ts",
"unlock-nominator": "npx ts-node ./src/unlock-nominator.ts"
},
"dependencies": {
"@autonomys/auto-consensus": "workspace:*",
Expand Down
27 changes: 27 additions & 0 deletions examples/node/src/deregister-operator.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import { deregisterOperator } from '@autonomys/auto-consensus'
import { setup, signAndSend } from './utils'

const main = async () => {
const { api, alice } = await setup()

const operatorId = '1'

const tx = await deregisterOperator({
api,
operatorId,
})

console.log('\x1b[32m%s\x1b[0m', 'Transaction Prepared! (with hash:', tx.hash.toHex(), ')')
console.log('\x1b[33m%s\x1b[0m', 'Now broadcasting transaction!\n')

await signAndSend(alice[0], tx)

main()
.then(() => {
console.log('\x1b[34m%s\x1b[0m', 'Script executed successfully')
process.exit(0)
})
.catch((e) => {
console.error('\x1b[31m%s\x1b[0m', 'Error with script:', e)
process.exit(1)
})
54 changes: 54 additions & 0 deletions examples/node/src/nominate-operator.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
import { address, balance, nominateOperator } from '@autonomys/auto-consensus'
import { setup, signAndSend } from './utils'

const main = async () => {
const { api, alice } = await setup()

// Alice's Addresses
const aliceAddress = address(alice[0].address)

// Initial Balances
const initialAliceBalance = await balance(api, aliceAddress)
console.log(
'\x1b[36m%s\x1b[0m',
'Alice Initial Balance:',
initialAliceBalance.free.toString(),
'\x1b[36m',
'ATC',
'\x1b[0m',
)

// Transfer 2x10^18 ATC tokens from Alice to Bob
const amountToStake = BigInt(10 * 10 ** 18)
const tx = await nominateOperator({
api,
operatorId: '0',
amountToStake,
})

console.log('\x1b[32m%s\x1b[0m', 'Transaction Prepared! (with hash:', tx.hash.toHex(), ')')
console.log('\x1b[33m%s\x1b[0m', 'Now broadcasting transaction!\n')

await signAndSend(alice[0], tx)

// Final Balances
const finalAliceBalance = await balance(api, aliceAddress)
console.log(
'\n\x1b[36m%s\x1b[0m',
'Alice Final Balance:',
finalAliceBalance.free.toString(),
'\x1b[36m',
'ATC',
'\x1b[0m',
)
}

main()
.then(() => {
console.log('\x1b[34m%s\x1b[0m', 'Script executed successfully')
process.exit(0)
})
.catch((e) => {
console.error('\x1b[31m%s\x1b[0m', 'Error with script:', e)
process.exit(1)
})
19 changes: 19 additions & 0 deletions examples/node/src/operator.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import { operator } from '@autonomys/auto-consensus'
import { setup } from './utils/setup'

const main = async () => {
const { api } = await setup()

const operatorOne = await operator(api, 1)
console.log('\x1b[36m%s\x1b[0m', 'operatorOne:', operatorOne, '\x1b[0m')
}

main()
.then(() => {
console.log('\x1b[34m%s\x1b[0m', 'Script executed successfully')
process.exit(0)
})
.catch((e) => {
console.error('\x1b[31m%s\x1b[0m', 'Error with script:', e)
process.exit(1)
})
20 changes: 20 additions & 0 deletions examples/node/src/operators.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import { operators } from '@autonomys/auto-consensus'
import { setup } from './utils/setup'

const main = async () => {
const { api } = await setup()

// Query all operators
const allOperators = await operators(api)
console.log('\x1b[36m%s\x1b[0m', 'allOperators:', allOperators, '\x1b[0m')
}

main()
.then(() => {
console.log('\x1b[34m%s\x1b[0m', 'Script executed successfully')
process.exit(0)
})
.catch((e) => {
console.error('\x1b[31m%s\x1b[0m', 'Error with script:', e)
process.exit(1)
})
57 changes: 57 additions & 0 deletions examples/node/src/register-operator.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
import { address, balance, registerOperator } from '@autonomys/auto-consensus'
import { setup, signAndSend } from './utils'

const main = async () => {
const { api, alice, randomUser } = await setup()

// Alice's Addresses
const aliceAddress = address(alice[0].address)

// Initial Balances
const initialAliceBalance = await balance(api, aliceAddress)
console.log(
'\x1b[36m%s\x1b[0m',
'Alice Initial Balance:',
initialAliceBalance.free.toString(),
'\x1b[36m',
'ATC',
'\x1b[0m',
)
// Transfer 2x10^18 ATC tokens from Alice to Bob
const amountToStake = BigInt(100 * 10 ** 18)
const tx = await registerOperator({
api,
senderAddress: alice[0].address,
Operator: randomUser[0],
domainId: '0',
amountToStake,
minimumNominatorStake: BigInt(10 * 10 ** 18),
nominationTax: '5',
})

console.log('\x1b[32m%s\x1b[0m', 'Transaction Prepared! (with hash:', tx.hash.toHex(), ')')
console.log('\x1b[33m%s\x1b[0m', 'Now broadcasting transaction!\n')

await signAndSend(alice[0], tx)

// Final Balances
const finalAliceBalance = await balance(api, aliceAddress)
console.log(
'\n\x1b[36m%s\x1b[0m',
'Alice Final Balance:',
finalAliceBalance.free.toString(),
'\x1b[36m',
'ATC',
'\x1b[0m',
)
}

main()
.then(() => {
console.log('\x1b[34m%s\x1b[0m', 'Script executed successfully')
process.exit(0)
})
.catch((e) => {
console.error('\x1b[31m%s\x1b[0m', 'Error with script:', e)
process.exit(1)
})
24 changes: 2 additions & 22 deletions examples/node/src/transfer.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { address, balance, transfer } from '@autonomys/auto-consensus'
import { setup } from './utils/setup'
import { setup, signAndSend } from './utils'

const main = async () => {
const { api, alice, bob } = await setup()
Expand Down Expand Up @@ -39,27 +39,7 @@ const main = async () => {
console.log('\x1b[32m%s\x1b[0m', 'Transaction Prepared! (with hash:', tx.hash.toHex(), ')')
console.log('\x1b[33m%s\x1b[0m', 'Now broadcasting transaction!\n')

let txHashHex: string | undefined = undefined
let blockHash: string | undefined = undefined
await new Promise<void>((resolve, reject) => {
tx.signAndSend(alice[0], ({ events, status, txHash }) => {
if (status.isInBlock) {
txHashHex = txHash.toHex()
blockHash = status.asInBlock.toHex()
console.log('\x1b[32m%s\x1b[0m', 'Successful tx', txHashHex)
console.log('\x1b[32m%s\x1b[0m', 'In block', blockHash)
resolve()
} else if (
status.isRetracted ||
status.isFinalityTimeout ||
status.isDropped ||
status.isInvalid
) {
console.error('Transaction failed')
reject(new Error('Transaction failed'))
}
})
})
await signAndSend(alice[0], tx)

// Final Balances
const finalAliceBalance = await balance(api, aliceAddress)
Expand Down
28 changes: 28 additions & 0 deletions examples/node/src/unlock-funds.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import { unlockFunds } from '@autonomys/auto-consensus'
import { setup, signAndSend } from './utils'

const main = async () => {
const { api, alice } = await setup()

const operatorId = '1'

const tx = await unlockFunds({
api,
operatorId,
})

console.log('\x1b[32m%s\x1b[0m', 'Transaction Prepared! (with hash:', tx.hash.toHex(), ')')
console.log('\x1b[33m%s\x1b[0m', 'Now broadcasting transaction!\n')

await signAndSend(alice[0], tx)
}

main()
.then(() => {
console.log('\x1b[34m%s\x1b[0m', 'Script executed successfully')
process.exit(0)
})
.catch((e) => {
console.error('\x1b[31m%s\x1b[0m', 'Error with script:', e)
process.exit(1)
})
28 changes: 28 additions & 0 deletions examples/node/src/unlock-nominator.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import { unlockNominator } from '@autonomys/auto-consensus'
import { setup, signAndSend } from './utils'

const main = async () => {
const { api, alice } = await setup()

const operatorId = '1'

const tx = await unlockNominator({
api,
operatorId,
})

console.log('\x1b[32m%s\x1b[0m', 'Transaction Prepared! (with hash:', tx.hash.toHex(), ')')
console.log('\x1b[33m%s\x1b[0m', 'Now broadcasting transaction!\n')

await signAndSend(alice[0], tx)
}

main()
.then(() => {
console.log('\x1b[34m%s\x1b[0m', 'Script executed successfully')
process.exit(0)
})
.catch((e) => {
console.error('\x1b[31m%s\x1b[0m', 'Error with script:', e)
process.exit(1)
})
2 changes: 2 additions & 0 deletions examples/node/src/utils/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
export * from './setup'
export * from './signAndSend'
11 changes: 10 additions & 1 deletion examples/node/src/utils/setup.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { ActivateWalletInput, activateWallet, networks } from '@autonomys/auto-utils'
import { mnemonicGenerate } from '@polkadot/util-crypto'
import 'dotenv/config'

export const setup = async () => {
Expand All @@ -10,6 +11,8 @@ export const setup = async () => {
? { networkId: networks[0].id }
: { networkId: 'autonomys-localhost' }

console.log('\x1b[32m%s\x1b[0m', 'Network:', config.networkId, '\n')

const { api, accounts: alice } = await activateWallet({
...config,
uri: process.env.ALICE_SEED,
Expand All @@ -20,5 +23,11 @@ export const setup = async () => {
uri: process.env.BOB_SEED,
} as ActivateWalletInput)

return { api, alice, bob }
const randomMnemonic = mnemonicGenerate()
const { accounts: randomUser } = await activateWallet({
...config,
uri: randomMnemonic,
} as ActivateWalletInput)

return { api, alice, bob, randomUser }
}
45 changes: 45 additions & 0 deletions examples/node/src/utils/signAndSend.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
import type { AddressOrPair, SubmittableExtrinsic } from '@polkadot/api/types'
import type { ISubmittableResult } from '@polkadot/types/types'
import 'dotenv/config'

export const signAndSend = async (
sender: AddressOrPair,
tx: SubmittableExtrinsic<'promise', ISubmittableResult>,
) => {
let txHashHex: string | undefined = undefined
let blockHash: string | undefined = undefined
let success = false

await new Promise<void>((resolve, reject) => {
tx.signAndSend(sender, ({ events, status, txHash }) => {
if (status.isInBlock) {
txHashHex = txHash.toHex()
blockHash = status.asInBlock.toHex()
console.log('\x1b[32m%s\x1b[0m', 'Successful tx', txHashHex)
console.log('\x1b[32m%s\x1b[0m', 'In block', blockHash, '\n')

events.forEach(({ event: { data, method, section } }) => {
if (section === 'system' && method === 'ExtrinsicSuccess') success = true
console.log(
'Event Emitted:',
'\x1b[33m',
`${section}.${method}`,
'\x1b[0m',
data.toString(),
)
})
resolve()
} else if (
status.isRetracted ||
status.isFinalityTimeout ||
status.isDropped ||
status.isInvalid
) {
console.error('Transaction failed')
reject(new Error('Transaction failed'))
}
})
})

return { txHashHex, blockHash, success }
}
Loading

0 comments on commit 6cc890b

Please sign in to comment.