Skip to content

Commit

Permalink
Merge pull request #20 from subspace/4-connect-a-wallet-to-the-api-an…
Browse files Browse the repository at this point in the history
…d-add-a-transfer-function

Connect a wallet to the api and add balance and transfer function
  • Loading branch information
marc-aurele-besner authored Jun 12, 2024
2 parents e525d7a + eb3274d commit 9ebf2bd
Show file tree
Hide file tree
Showing 29 changed files with 1,365 additions and 33 deletions.
10 changes: 5 additions & 5 deletions .github/workflows/build.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -9,26 +9,26 @@ jobs:
steps:
- name: Checkout 🛎️
uses: actions/checkout@v3

- name: Set up Node.js
uses: actions/setup-node@v2
with:
node-version: '18'

- name: Enable Corepack
run: corepack enable

- name: Set Yarn version to Berry
run: corepack prepare [email protected] --activate

- name: Install dependencies
run: yarn install

- name: Build auto-utils package 🔧
run: yarn workspace @autonomys/auto-utils build

- name: Build all packages 🔧
run: yarn build

- name: Run tests 🧪
run: yarn test
2 changes: 1 addition & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ node_modules/
packages/*/node_modules/

# Yarn cache
.yarn/*
.yarn/cache/*
.yarnrc.yml

# TypeScript build outputs
Expand Down
Binary file added .yarn/install-state.gz
Binary file not shown.
894 changes: 894 additions & 0 deletions .yarn/releases/yarn-4.2.2.cjs

Large diffs are not rendered by default.

2 changes: 2 additions & 0 deletions .yarnrc.yml
Original file line number Diff line number Diff line change
@@ -1 +1,3 @@
nodeLinker: node-modules

yarnPath: .yarn/releases/yarn-4.2.2.cjs
8 changes: 4 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ The repository is organized as follows:
## Requirements

- Node.js
- Yarn 2 (Berry) or later
- Yarn 4

## Setup

Expand All @@ -39,13 +39,13 @@ The repository is organized as follows:

To build all packages:

`yarn build`
`yarn run build`

### Test

To run tests for all packages:

`yarn test`
`yarn run test`

### Localhost testing

Expand Down Expand Up @@ -86,7 +86,7 @@ To test the packages against a local node, you can use the script at `scripts/ru

## Workspaces

This project uses Yarn workspaces. Packages are located in the `packages` directory. Each package can have its own dependencies and build scripts.
This project uses workspaces. Packages are located in the `packages` directory. Each package can have its own dependencies and build scripts.

## License

Expand Down
20 changes: 18 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -8,12 +8,28 @@
],
"scripts": {
"build": "yarn workspaces foreach --all run build",
"clean": "yarn workspaces foreach --all run clean",
"format": "yarn workspaces foreach --all run format",
"test": "yarn workspaces foreach --all run test"
},
"packageManager": "[email protected]",
"engines": {
"node": ">=18.0.0"
},
"repository": {
"type": "git",
"url": "https://github.com/subspace/auto-sdk"
},
"author": {
"name": "Autonomys",
"url": "https://www.autonomys.net"
},
"devDependencies": {
"@types/jest": "^29.5.12",
"eslint": "^8.57.0",
"jest": "^29.7.0",
"prettier": "^3.2.5",
"ts-jest": "^29.1.4",
"typescript": "^5.4.5"
},
"packageManager": "[email protected]"
}
}
73 changes: 63 additions & 10 deletions packages/auto-consensus/__test__/balances.test.ts
Original file line number Diff line number Diff line change
@@ -1,21 +1,74 @@
import { activate, disconnect } from '@autonomys/auto-utils'
import { totalIssuance } from '../src/balances'
import type { NetworkInput } from '@autonomys/auto-utils'
import {
ActivateWalletInput,
activate,
activateWallet,
disconnect,
networks,
} from '@autonomys/auto-utils'
import { address } from '../src/address'
import { balance, totalIssuance } from '../src/balances'

describe('Verify balances functions', () => {
const isLocalhost = process.env.LOCALHOST === 'true'

// Define the test network and its details
const TEST_NETWORK: NetworkInput = !isLocalhost
? { networkId: networks[0].id }
: { networkId: 'autonomys-localhost' }
const TEST_INVALID_NETWORK = { networkId: 'invalid-network' }

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

beforeAll(async () => {
await activate()
await activate(TEST_NETWORK)
})

afterAll(async () => {
await disconnect()
})

test('Check totalIssuance return a number greater than zero', async () => {
// totalIssuance is an async function that returns a hex number as a string
const rawIssuance = await totalIssuance()
// Convert the hex number to a BigInt
const issuance = BigInt(rawIssuance.toString())
// Check if the issuance is greater than zero
expect(issuance).toBeGreaterThan(BigInt(0))
describe('Test totalIssuance()', () => {
test('Check totalIssuance return a number greater than zero', async () => {
// totalIssuance is an async function that returns a hex number as a string
const rawIssuance = await totalIssuance()
// Convert the hex number to a BigInt
const issuance = BigInt(rawIssuance.toString())
// Check if the issuance is greater than zero
expect(issuance).toBeGreaterThan(BigInt(0))
})
})

describe('Test balance()', () => {
test('Check balance of Test wallet is 0', async () => {
const { api, accounts } = await activateWallet({
...TEST_NETWORK,
mnemonic: TEST_MNEMONIC,
} as ActivateWalletInput)
expect(accounts.length).toBeGreaterThan(0)
expect(accounts[0].address).toEqual(TEST_ADDRESS)

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,
} as ActivateWalletInput)
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))
})
}
})
})
6 changes: 3 additions & 3 deletions packages/auto-consensus/__test__/info.test.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { activate, disconnect } from '@autonomys/auto-utils'
import { currentTimestamp } from '../src/info'
import { networkTimestamp } from '../src/info'

describe('Verify info functions', () => {
beforeAll(async () => {
Expand All @@ -10,9 +10,9 @@ describe('Verify info functions', () => {
await disconnect()
})

test('Check timestamp return a number greater than zero', async () => {
test('Check network timestamp return a number greater than zero', async () => {
// totalIssuance is an async function that returns a hex number as a string
const rawTimestamp = await currentTimestamp()
const rawTimestamp = await networkTimestamp()
// Convert the hex number to a BigInt
const timestamp = BigInt(rawTimestamp.toString())
// Check if the issuance is greater than zero
Expand Down
88 changes: 88 additions & 0 deletions packages/auto-consensus/__test__/transfer.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
import type { NetworkInput } from '@autonomys/auto-utils'
import {
ActivateWalletInput,
activate,
activateWallet,
disconnect,
networks,
} from '@autonomys/auto-utils'
import { address } from '../src/address'
import { balance } from '../src/balances'
import { transfer } from '../src/transfer'

describe('Verify transfer functions', () => {
const isLocalhost = process.env.LOCALHOST === 'true'

// Define the test network and its details
const TEST_NETWORK: NetworkInput = !isLocalhost
? { networkId: networks[0].id }
: { networkId: 'autonomys-localhost' }
const TEST_INVALID_NETWORK = { networkId: 'invalid-network' }

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

beforeAll(async () => {
await activate(TEST_NETWORK)
})

afterAll(async () => {
await disconnect()
})

if (isLocalhost) {
describe('Test transfer()', () => {
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,
} as ActivateWalletInput)
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)

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.isRetracted ||
status.isFinalityTimeout ||
status.isDropped ||
status.isInvalid
) {
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)
})
})
} else {
test('Transfer test only run on localhost', async () => {
expect(true).toBeTruthy()
})
}
})
12 changes: 12 additions & 0 deletions packages/auto-consensus/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,18 +4,30 @@
"main": "dist/index.js",
"scripts": {
"build": "tsc",
"clean": "rm -rf dist",
"format": "prettier --write \"src/**/*.ts\"",
"test": "jest"
},
"files": [
"dist",
"README.md"
],
"repository": {
"type": "git",
"url": "https://github.com/subspace/auto-sdk"
},
"author": {
"name": "Autonomys",
"url": "https://www.autonomys.net"
},
"dependencies": {
"@autonomys/auto-utils": "workspace:*"
},
"devDependencies": {
"@types/jest": "^29.5.12",
"eslint": "^8.57.0",
"jest": "^29.7.0",
"prettier": "^3.2.5",
"ts-jest": "^29.1.4",
"typescript": "^5.4.5"
}
Expand Down
3 changes: 3 additions & 0 deletions packages/auto-consensus/src/address.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
import { encodeAddress } from '@polkadot/keyring'

export const address = (address: string | Uint8Array): string => encodeAddress(address, 2254)
32 changes: 32 additions & 0 deletions packages/auto-consensus/src/balances.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,18 @@
import { activate } from '@autonomys/auto-utils'
import { ApiPromise } from '@polkadot/api'
import type { BN } from '@polkadot/util'

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

export const totalIssuance = async (networkId?: string) => {
// Get the api instance for the network
Expand All @@ -9,3 +23,21 @@ 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)
}
}
2 changes: 2 additions & 0 deletions packages/auto-consensus/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,2 +1,4 @@
export * from './address'
export * from './balances'
export * from './info'
export * from './transfer'
2 changes: 1 addition & 1 deletion packages/auto-consensus/src/info.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { activate } from '@autonomys/auto-utils'

export const currentTimestamp = async (networkId?: string) => {
export const networkTimestamp = async (networkId?: string) => {
// Get the api instance for the network
const api = await activate({ networkId })

Expand Down
Loading

0 comments on commit 9ebf2bd

Please sign in to comment.