Skip to content

Commit

Permalink
improve balance and transfer function and test
Browse files Browse the repository at this point in the history
  • Loading branch information
marc-aurele-besner committed Jun 6, 2024
1 parent 616acb0 commit d746e6a
Show file tree
Hide file tree
Showing 2 changed files with 90 additions and 12 deletions.
69 changes: 59 additions & 10 deletions packages/auto-consensus/__test__/balances.test.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import type { NetworkInput } from '@autonomys/auto-utils'
import { activate, activateWallet, disconnect, networks } from '@autonomys/auto-utils'
import { address } from '../src/address'
import { totalIssuance, transfer } from '../src/balances'
import { balance, totalIssuance, transfer } from '../src/balances'

describe('Verify balances functions', () => {
const isLocalhost = process.env.LOCALHOST === 'true'
Expand All @@ -14,10 +14,10 @@ describe('Verify balances functions', () => {

const TEST_MNEMONIC = 'test test test test test test test test test test test junk'
const TEST_ADDRESS = '5Fj5aLd4crCYn7zM5hLZL8m6e9aNzWssiTgA3TrprLjxy6Mc'
const ALICE_URI = '//BOB'
const ALICE_ADDRESS = '5DAw2FpYk2y3JHrsia14KEx7tpezNymdFKkunicZ5ygPGXYF'
const BOB_URI = '//BOB'
const BOB_ADDRESS = '5DAw2FpYk2y3JHrsia14KEx7tpezNymdFKkunicZ5ygPGXYF'
const ALICE_URI = '//Alice'
const ALICE_ADDRESS = '5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY'
const BOB_URI = '//Bob'
const BOB_ADDRESS = '5FHneW46xGXgs5mUiveU4sbTyGBzmstUspZC92UhjJM694ty'

beforeAll(async () => {
await activate(TEST_NETWORK)
Expand All @@ -44,22 +44,67 @@ describe('Verify balances functions', () => {
...TEST_NETWORK,
mnemonic: TEST_MNEMONIC,
})
expect(accounts.length).toBeGreaterThan(0)
expect(accounts[0].address).toEqual(TEST_ADDRESS)

const balance = await api.query.balances.account(address(accounts[0].address))
expect(balance.free.toBigInt()).toEqual(BigInt(0))
const _balance = await balance(api, address(accounts[0].address))
expect(_balance.free).toEqual(BigInt(0))
})

if (isLocalhost) {
test('Check balance of Alice wallet is greater than 0', async () => {
const { api, accounts } = await activateWallet({
...TEST_NETWORK,
uri: ALICE_URI,
})
expect(accounts.length).toBeGreaterThan(0)
expect(accounts[0].address).toEqual(ALICE_ADDRESS)

const _balance = await balance(api, address(accounts[0].address))
expect(_balance.free).toBeGreaterThan(BigInt(0))
})
}
})

describe('Test transfer()', () => {
if (isLocalhost) {
test('Check transfer 1 ATC between Alice and Bob', async () => {
test('Check transfer 1 ATC between Alice and Bob and check the balance before and after', async () => {
const { api, accounts } = await activateWallet({
...TEST_NETWORK,
uri: ALICE_URI,
})
expect(accounts.length).toBeGreaterThan(0)
expect(accounts[0].address).toEqual(ALICE_ADDRESS)

const sender = accounts[0]
let txHash: string | undefined

const _balanceSenderStart = await balance(api, address(sender.address))
const _balanceReceiverStart = await balance(api, address(BOB_ADDRESS))
expect(_balanceSenderStart.free).toBeGreaterThan(BigInt(0))

const tx = await transfer(api, BOB_ADDRESS, 1)

const hash = await transfer(api, sender, BOB_ADDRESS, 1)
await new Promise<void>((resolve, reject) => {
tx.signAndSend(sender, ({ status }) => {
if (status.isInBlock) {
txHash = status.asInBlock.toHex()
console.log('Successful transfer of 1 with hash ' + txHash)
resolve()
} else if (status.isError) {
reject(new Error('Transaction failed'))
} else {
console.log('Status of transfer: ' + status.type)
}
})
})

expect(txHash).toBeDefined()

const _balanceSenderEnd = await balance(api, address(sender.address))
const _balanceReceiverEnd = await balance(api, address(BOB_ADDRESS))
expect(_balanceSenderEnd.free).toBeLessThan(_balanceSenderStart.free)
expect(_balanceReceiverEnd.free).toBeGreaterThan(_balanceReceiverStart.free)
})
}

Expand All @@ -68,9 +113,13 @@ describe('Verify balances functions', () => {
...TEST_NETWORK,
mnemonic: TEST_MNEMONIC,
})
expect(accounts.length).toBeGreaterThan(0)
expect(accounts[0].address).toEqual(TEST_ADDRESS)

const sender = accounts[0]
const tx = await transfer(api, ALICE_ADDRESS, 1)

expect(() => transfer(api, sender, ALICE_ADDRESS, 1)).toThrow(
expect(() => tx.signAndSend(sender)).toThrow(
'Unreachable code should not be executed (evaluating',
// To-Do: Confirm this is the expected error message
)
Expand Down
33 changes: 31 additions & 2 deletions packages/auto-consensus/src/balances.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,18 @@ import { activate } from '@autonomys/auto-utils'
import { ApiPromise } from '@polkadot/api'
import type { KeyringPair } from '@polkadot/keyring/types'

type RawBalanceData = {
free: any
reserved: any
frozen: any
flags: any
}
type BalanceData = {
free: any
reserved: any
frozen: any
}

export const totalIssuance = async (networkId?: string) => {
// Get the api instance for the network
const api = await activate({ networkId })
Expand All @@ -12,14 +24,31 @@ export const totalIssuance = async (networkId?: string) => {
return totalIssuance
}

export const balance = async (api: ApiPromise, address: string): Promise<BalanceData> => {
// Query the balance of the address and parse the data
try {
const rawBalance = await api.query.system.account(address)

const { data } = rawBalance as unknown as { data: RawBalanceData }

return {
free: BigInt(data.free.toString()),
reserved: BigInt(data.reserved.toString()),
frozen: BigInt(data.frozen.toString()),
}
} catch (error) {
console.log('error', error)
throw new Error('Error getting balance' + error)
}
}

export const transfer = async (
api: ApiPromise,
sender: KeyringPair,
receiver: string,
amount: BigInt | number | string,
) => {
// Transfer the tokens
const transfer = await api.tx.balances.transferKeepAlive(receiver, amount).signAndSend(sender)
const transfer = await api.tx.balances.transferKeepAlive(receiver, amount)

return transfer
}

0 comments on commit d746e6a

Please sign in to comment.