Skip to content

Commit

Permalink
Merge pull request #53 from scio-labs/feat/52-typechain-integration
Browse files Browse the repository at this point in the history
Feat/52 typechain integration
  • Loading branch information
wottpal authored Jan 24, 2024
2 parents ee4c99b + 194120d commit 756d685
Show file tree
Hide file tree
Showing 30 changed files with 1,285 additions and 867 deletions.
6 changes: 6 additions & 0 deletions .changeset/warm-grapes-rhyme.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
---
"@inkathon/contracts": minor
"@inkathon/frontend": minor
---

Add type-safe contract integrations via `useRegisteredTypedContract` and `typechain-polkadot`.
12 changes: 11 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -165,6 +165,7 @@ For general scripts, the same environment variable initialization & configuratio
- Contract Interactions: `polkadot-js`, [`useInkathon`](https://github.com/scio-labs/use-inkathon) React Hooks & Utility Library (alternatively: [`useInk`](https://use.ink/frontend/getting-started))
- Styling: `shadcn/ui`, `tailwindcss`
- Linting & Formatting: `eslint`, `prettier`, `simple-git-hooks`, `lint-staged`
- Type-safe contract generation via [`typechain-polkadot`](https://github.com/Brushfam/typechain-polkadot)

<small>Styling, linting, and formatting libraries can be fully dropped or replaced with alternatives.</small>

Expand Down Expand Up @@ -314,14 +315,23 @@ Currently it offers styling via the following options out of the box:
</details>

<details>
<summary><strong>How do type-safe contract interactions work?</strong></summary>

With [`typechain-polkadot`](https://github.com/Brushfam/typechain-polkadot), types for each contract (TypeScript files) are created upon build (via the `build` script or `build-all.sh` command). You can suppress this behavior by passing `--skip-types`.

They are stored under `contracts/typed-contracts/` and imported directly from the frontend. Then, via the new `useRegisteredTypedContract` hook from [`useInkathon`](https://github.com/scio-labs/use-inkathon) instances with pre-defined api, network-dependant contract address, and injected signer are being created. See `greeter-contract-interactions.tsx` for an example.

</details>

<details>
<summary><strong>Resources to learn more about Substrate, ink!, and polkadot.js</strong></summary>

- [ink! Documentation](https://use.ink/)
- [polkadot.js Documentation](https://polkadot.js.org/docs/)
- [Polkadot Wiki ink! Tools](https://wiki.polkadot.network/docs/build-open-source)
- [Aleph Zero Documentation](https://docs.alephzero.org/aleph-zero/build/)
- [ink!athon Workshop Recording](https://youtube.com/watch?v=SoNLZfsd0mQ)
- [ink!athon Workshop Recording](https://youtube.com/watch?v=DA1pLk5--GE)
- [ink!athon Telegram Group](https://t.me/inkathon)

</details>
3 changes: 2 additions & 1 deletion contracts/.eslintignore
Original file line number Diff line number Diff line change
Expand Up @@ -3,4 +3,5 @@ deployments
target
src
dist
.node-data
.node-data
typed-contracts
3 changes: 2 additions & 1 deletion contracts/.prettierignore
Original file line number Diff line number Diff line change
Expand Up @@ -3,4 +3,5 @@ deployments
target
src
dist
.node-data
.node-data
typed-contracts
7 changes: 7 additions & 0 deletions contracts/build-all.sh
Original file line number Diff line number Diff line change
Expand Up @@ -22,4 +22,11 @@ do
$CP_CMD ./target/ink/$i/$i.contract $DIR/$i/
$CP_CMD ./target/ink/$i/$i.wasm $DIR/$i/
$CP_CMD ./target/ink/$i/$i.json $DIR/$i/

if [[ "$@" != *"--skip-types"* ]]; then
echo "Generate types via typechain into './typed-contracts'…"
# Because of an open issue, this used the npx-installed version of `@727-ventures/typechain-polkadot`
# See: https://github.com/Brushfam/typechain-polkadot/issues/115
npx @727-ventures/typechain-polkadot --in $DIR/$i/ --out typed-contracts --yes
fi
done
2 changes: 1 addition & 1 deletion contracts/deployments/greeter/greeter.contract

Large diffs are not rendered by default.

4 changes: 2 additions & 2 deletions contracts/deployments/greeter/greeter.json
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
{
"source": {
"hash": "0x594f6192f714665ea04eddc473def48dd71497034b89ea617ff97a44a1aa84e2",
"hash": "0x1eb1e54e98c611573ce9b600b676e139c8766786395147f48b67f5331938bbb2",
"language": "ink! 4.3.0",
"compiler": "rustc 1.72.1",
"compiler": "rustc 1.74.0",
"build_info": {
"build_mode": "Release",
"cargo_contract_version": "3.2.0",
Expand Down
Binary file modified contracts/deployments/greeter/greeter.wasm
Binary file not shown.
3 changes: 3 additions & 0 deletions contracts/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -19,18 +19,21 @@
"lint:format": "prettier . --write"
},
"devDependencies": {
"@727-ventures/typechain-types": "^1.1.2",
"@polkadot/api": "^10.11.2",
"@polkadot/api-contract": "^10.11.2",
"@polkadot/keyring": "^12.6.2",
"@polkadot/types": "^10.11.2",
"@polkadot/util": "^12.6.2",
"@polkadot/util-crypto": "^12.6.2",
"@scio-labs/use-inkathon": "^0.6.3",
"@types/bn.js": "~5.1.5",
"@types/eslint": "^8.56.2",
"@types/eslint-config-prettier": "^6.11.3",
"@types/node": "^20.11.0",
"@typescript-eslint/eslint-plugin": "^6.18.1",
"@typescript-eslint/parser": "^6.18.1",
"bn.js": "^5.2.1",
"dotenv": "^16.3.1",
"eslint": "^8.56.0",
"eslint-config-prettier": "^9.1.0",
Expand Down
4 changes: 2 additions & 2 deletions contracts/scripts/utils/initPolkadotJs.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ export type InitParams = {
toBNWithDecimals: (_: number | string) => BN
}
export const initPolkadotJs = async (): Promise<InitParams> => {
const accountUti = process.env.ACCOUNT_URI || '//Alice'
const accountUri = process.env.ACCOUNT_URI || '//Alice'
const chain = getSubstrateChain(chainId)
if (!chain) throw new Error(`Chain '${chainId}' not found`)

Expand All @@ -42,7 +42,7 @@ export const initPolkadotJs = async (): Promise<InitParams> => {

// Initialize account & set signer
const keyring = new Keyring({ type: 'sr25519' })
const account = keyring.addFromUri(accountUti)
const account = keyring.addFromUri(accountUri)
const balance = await getBalance(api, account.address)
console.log(`Initialized Account: ${account.address} (${balance.balanceFormatted})\n`)

Expand Down
13 changes: 9 additions & 4 deletions contracts/tsconfig.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"ts-node": {
"esm": true,
"experimentalSpecifierResolution": "node"
"experimentalSpecifierResolution": "node",
},
"compilerOptions": {
"module": "esnext",
Expand All @@ -16,9 +16,14 @@
"composite": true,
"baseUrl": ".",
"paths": {
"@/*": ["./scripts/*"]
}
"@/*": ["./scripts/*"],
},
},
"exclude": ["node_modules", "dist", "target", "./*/target"],
"include": ["./deployments/**/*.json", "./deployments/**/*.ts", "./scripts/**/*.ts"]
"include": [
"./deployments/**/*.json",
"./deployments/**/*.ts",
"./scripts/**/*.ts",
"./typed-contracts/**/*.ts",
],
}
45 changes: 45 additions & 0 deletions contracts/typed-contracts/build-extrinsic/greeter.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
/* This file is auto-generated */

import type { ContractPromise } from '@polkadot/api-contract';
import type { GasLimit, GasLimitAndRequiredValue } from '@727-ventures/typechain-types';
import { buildSubmittableExtrinsic } from '@727-ventures/typechain-types';
import type * as ArgumentTypes from '../types-arguments/greeter';
import type BN from 'bn.js';
import type { ApiPromise } from '@polkadot/api';



export default class Methods {
readonly __nativeContract : ContractPromise;
readonly __apiPromise: ApiPromise;

constructor(
nativeContract : ContractPromise,
apiPromise: ApiPromise,
) {
this.__nativeContract = nativeContract;
this.__apiPromise = apiPromise;
}
/**
* greet
*
*/
"greet" (
__options: GasLimit,
){
return buildSubmittableExtrinsic( this.__apiPromise, this.__nativeContract, "greet", [], __options);
}

/**
* setMessage
*
* @param { string } newValue,
*/
"setMessage" (
newValue: string,
__options: GasLimit,
){
return buildSubmittableExtrinsic( this.__apiPromise, this.__nativeContract, "setMessage", [newValue], __options);
}

}
80 changes: 80 additions & 0 deletions contracts/typed-contracts/constructors/greeter.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
import type { ConstructorOptions } from '@727-ventures/typechain-types'
import {
_genValidGasLimitAndValue,
_signAndSend,
SignAndSendSuccessResponse,
} from '@727-ventures/typechain-types'
import type { ApiPromise } from '@polkadot/api'
import { CodePromise } from '@polkadot/api-contract'
import type { KeyringPair } from '@polkadot/keyring/types'
import type { WeightV2 } from '@polkadot/types/interfaces'
import { ContractFile } from '../contract-info/greeter'

export default class Constructors {
readonly nativeAPI: ApiPromise
readonly signer: KeyringPair

constructor(nativeAPI: ApiPromise, signer: KeyringPair) {
this.nativeAPI = nativeAPI
this.signer = signer
}

/**
* new
*
* @param { string } initValue,
*/
async new(initValue: string, __options?: ConstructorOptions) {
const __contract = JSON.parse(ContractFile)
const code = new CodePromise(this.nativeAPI, __contract, __contract.source.wasm)
const gasLimit = (await _genValidGasLimitAndValue(this.nativeAPI, __options))
.gasLimit as WeightV2

const storageDepositLimit = __options?.storageDepositLimit
const tx = code.tx['new']!(
{ gasLimit, storageDepositLimit, value: __options?.value },
initValue,
)
let response

try {
console.log('sd')
response = await _signAndSend(this.nativeAPI.registry, tx, this.signer, (event: any) => event)
} catch (error) {
console.log(error)
}

return {
result: response as SignAndSendSuccessResponse,
// @ts-ignore
address: (response as SignAndSendSuccessResponse)!.result!.contract.address.toString(),
}
}
/**
* default
*
*/
async default(__options?: ConstructorOptions) {
const __contract = JSON.parse(ContractFile)
const code = new CodePromise(this.nativeAPI, __contract, __contract.source.wasm)
const gasLimit = (await _genValidGasLimitAndValue(this.nativeAPI, __options))
.gasLimit as WeightV2

const storageDepositLimit = __options?.storageDepositLimit
const tx = code.tx['default']!({ gasLimit, storageDepositLimit, value: __options?.value })
let response

try {
console.log('this.signer', this.signer)
response = await _signAndSend(this.nativeAPI.registry, tx, this.signer, (event: any) => event)
} catch (error) {
console.log(error)
}

return {
result: response as SignAndSendSuccessResponse,
// @ts-ignore
address: (response as SignAndSendSuccessResponse)!.result!.contract.address.toString(),
}
}
}
Loading

1 comment on commit 756d685

@vercel
Copy link

@vercel vercel bot commented on 756d685 Jan 24, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please sign in to comment.