Skip to content
This repository has been archived by the owner on Nov 28, 2023. It is now read-only.

Commit

Permalink
Merge pull request #23 from Phala-Network/bugfix/add-polyfill
Browse files Browse the repository at this point in the history
jssdk compatible for both node and browser
  • Loading branch information
Leechael authored Jan 18, 2023
2 parents 7f91397 + 7c46605 commit af8b539
Show file tree
Hide file tree
Showing 46 changed files with 21,738 additions and 17,359 deletions.
8 changes: 4 additions & 4 deletions .github/workflows/build.yml
Original file line number Diff line number Diff line change
Expand Up @@ -13,16 +13,16 @@ jobs:
- uses: actions/checkout@v2
- uses: actions/setup-node@v2
with:
node-version: '16'
registry-url: 'https://registry.npmjs.org'
cache: 'yarn'
node-version: "16"
registry-url: "https://registry.npmjs.org"
cache: "yarn"
- run: yarn
- run: yarn test
- run: yarn lint
- run: yarn build
- uses: actions/upload-artifact@v2
with:
name: 'phala-js-sdk'
name: "phala-js-sdk"
path: |
packages/sdk/dist/
packages/sdk/package.json
Expand Down
8 changes: 4 additions & 4 deletions .github/workflows/publish.yml
Original file line number Diff line number Diff line change
Expand Up @@ -9,11 +9,11 @@ jobs:
- uses: actions/checkout@v2
- uses: actions/setup-node@v2
with:
node-version: '16'
registry-url: 'https://registry.npmjs.org'
cache: 'yarn'
node-version: "16"
registry-url: "https://registry.npmjs.org"
cache: "yarn"
- run: yarn
- run: yarn workspace @phala/sdk build
- run: yarn workspace @phala/sdk publish
- run: yarn workspace @phala/sdk auto-publish
env:
NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -9,3 +9,4 @@ dist
tsconfig.tsbuildinfo
.npmrc
.eslintcache
browser
5 changes: 2 additions & 3 deletions .prettierrc
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
{
"semi": false,
"singleQuote": true,
"bracketSpacing": false
"proseWrap": "never",
"quoteProps": "consistent"
}
2 changes: 1 addition & 1 deletion .vscode/settings.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
"source.fixAll.eslint": true,
"source.sortImports": true
},
"eslint.workingDirectories": [{"pattern": "./packages/*/"}],
"eslint.workingDirectories": [{ "pattern": "./packages/*/" }],
"cSpell.ignoreWords": [
"polkadot",
"jotai",
Expand Down
4 changes: 2 additions & 2 deletions jest.config.cjs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
/** @type {import('ts-jest/dist/types').InitialOptionsTsJest} */
module.exports = {
preset: 'ts-jest',
}
preset: "ts-jest",
};
5 changes: 4 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -22,5 +22,8 @@
"ts-node": "^10.9.1",
"typescript": "^4.8.4"
},
"packageManager": "[email protected]"
"packageManager": "[email protected]",
"dependencies": {
"@polkadot/util": "^10.2.3"
}
}
3 changes: 2 additions & 1 deletion packages/example/.eslintrc
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
],
"parser": "@typescript-eslint/parser",
"rules": {
"no-console": "error"
"no-console": "error",
"@typescript-eslint/no-explicit-any": 0
}
}
10 changes: 5 additions & 5 deletions packages/example/atoms/account.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
import {atomWithStorage} from 'jotai/utils'
import type {InjectedAccountWithMeta} from '@polkadot/extension-inject/types'
import { atomWithStorage } from "jotai/utils";
import type { InjectedAccountWithMeta } from "@polkadot/extension-inject/types";

const accountAtom = atomWithStorage<InjectedAccountWithMeta | null>(
'atom:account',
"atom:account",
null
)
);

export default accountAtom
export default accountAtom;
82 changes: 41 additions & 41 deletions packages/example/components/AccountSelect.tsx
Original file line number Diff line number Diff line change
@@ -1,56 +1,56 @@
import {useState, useEffect} from 'react'
import type {InjectedAccountWithMeta} from '@polkadot/extension-inject/types'
import {useAtom} from 'jotai'
import {Select} from 'baseui/select'
import {LabelSmall, MonoParagraphXSmall} from 'baseui/typography'
import {Block} from 'baseui/block'
import {FormControl} from 'baseui/form-control'
import accountAtom from '../atoms/account'
import {enablePolkadotExtension} from '../lib/polkadotExtension'
import { useState, useEffect } from "react";
import type { InjectedAccountWithMeta } from "@polkadot/extension-inject/types";
import { useAtom } from "jotai";
import { Select } from "baseui/select";
import { LabelSmall, MonoParagraphXSmall } from "baseui/typography";
import { Block } from "baseui/block";
import { FormControl } from "baseui/form-control";
import accountAtom from "../atoms/account";
import { enablePolkadotExtension } from "../lib/polkadotExtension";

const trimAddress = (address: string) =>
`${address.slice(0, 6)}${address.slice(-6)}`
`${address.slice(0, 6)}${address.slice(-6)}`;

const AccountSelect = (): JSX.Element => {
const [error, setError] = useState(false)
const [account, setAccount] = useAtom(accountAtom)
const [options, setOptions] = useState<InjectedAccountWithMeta[]>([])
const [error, setError] = useState(false);
const [account, setAccount] = useAtom(accountAtom);
const [options, setOptions] = useState<InjectedAccountWithMeta[]>([]);

useEffect(() => {
let unsubscribe: () => void
let unsubscribe: () => void;

const subscribeAccounts = async () => {
await enablePolkadotExtension()
await enablePolkadotExtension();
const handleAccounts = (accounts: InjectedAccountWithMeta[]): void => {
setOptions(accounts)
}
const {web3Accounts, web3AccountsSubscribe} = await import(
'@polkadot/extension-dapp'
)
const accounts = await web3Accounts()
handleAccounts(accounts)
unsubscribe = await web3AccountsSubscribe(handleAccounts)
}
setOptions(accounts);
};
const { web3Accounts, web3AccountsSubscribe } = await import(
"@polkadot/extension-dapp"
);
const accounts = await web3Accounts();
handleAccounts(accounts);
unsubscribe = await web3AccountsSubscribe(handleAccounts);
};

try {
subscribeAccounts()
subscribeAccounts();
} catch (err) {
setError(true)
throw err
setError(true);
throw err;
}

return () => unsubscribe?.()
}, [])
return () => unsubscribe?.();
}, []);

useEffect(() => {
if (
account &&
options.length &&
!options.find(({address}) => address === account.address)
!options.find(({ address }) => address === account.address)
) {
setAccount(null)
setAccount(null);
}
}, [options, account, setAccount])
}, [options, account, setAccount]);

return (
<Block padding="0 20px" flex="0">
Expand All @@ -63,23 +63,23 @@ const AccountSelect = (): JSX.Element => {
},
},
}}
{...(error && {error: 'Polkadot{.js} extension error'})}
{...(error && { error: "Polkadot{.js} extension error" })}
>
<Select
size="compact"
placeholder="Select Account"
options={options}
getOptionLabel={({option}) =>
getOptionLabel={({ option }) =>
option && (
<>
<LabelSmall>{option.meta.name || 'Unknown'}</LabelSmall>
<LabelSmall>{option.meta.name || "Unknown"}</LabelSmall>
<MonoParagraphXSmall as="div">
{trimAddress(option.address)}
</MonoParagraphXSmall>
</>
)
}
getValueLabel={({option}) => (
getValueLabel={({ option }) => (
<>
<LabelSmall>{option.meta.name}</LabelSmall>
<MonoParagraphXSmall as="div">
Expand All @@ -90,14 +90,14 @@ const AccountSelect = (): JSX.Element => {
searchable={false}
valueKey="address"
value={account ? [account] : []}
onChange={({value}) =>
onChange={({ value }) =>
setAccount((value[0] as InjectedAccountWithMeta) || null)
}
overrides={{Root: {style: {width: '200px'}}}}
overrides={{ Root: { style: { width: "200px" } } }}
></Select>
</FormControl>
</Block>
)
}
);
};

export default AccountSelect
export default AccountSelect;
96 changes: 48 additions & 48 deletions packages/example/components/ContractLoader.tsx
Original file line number Diff line number Diff line change
@@ -1,59 +1,59 @@
import {create} from '@phala/sdk'
import type {ApiPromise} from '@polkadot/api'
import {ContractPromise} from '@polkadot/api-contract'
import {Button} from 'baseui/button'
import {FormControl} from 'baseui/form-control'
import {Input} from 'baseui/input'
import {Textarea} from 'baseui/textarea'
import {toaster} from 'baseui/toast'
import {useAtom} from 'jotai'
import {focusAtom} from 'jotai/optics'
import {atomWithStorage} from 'jotai/utils'
import {useRef, VFC} from 'react'
import useIsClient from '../hooks/useIsClient'
import {createApi} from '../lib/polkadotApi'
import { create } from "@phala/sdk";
import type { ApiPromise } from "@polkadot/api";
import { ContractPromise } from "@polkadot/api-contract";
import { Button } from "baseui/button";
import { FormControl } from "baseui/form-control";
import { Input } from "baseui/input";
import { Textarea } from "baseui/textarea";
import { toaster } from "baseui/toast";
import { useAtom } from "jotai";
import { focusAtom } from "jotai/optics";
import { atomWithStorage } from "jotai/utils";
import { useRef, VFC } from "react";
import useIsClient from "../hooks/useIsClient";
import { createApi } from "../lib/polkadotApi";

const endpointAtom = atomWithStorage<string>(
'atom:endpoint',
'ws://localhost:9944'
)
"atom:endpoint",
"ws://localhost:9944"
);
const pruntimeURLAtom = atomWithStorage<string>(
'atom:pruntime_url',
'http://localhost:8000'
)
"atom:pruntime_url",
"http://localhost:8000"
);
const contractsAtom = atomWithStorage<
Record<string, {contractId: string; metadata: string}>
>('atom:contracts', {})
Record<string, { contractId: string; metadata: string }>
>("atom:contracts", {});

const ContractLoader: VFC<{
name: string
onLoad: (res: {api: ApiPromise; contract: ContractPromise}) => void
}> = ({name, onLoad}) => {
name: string;
onLoad: (res: { api: ApiPromise; contract: ContractPromise }) => void;
}> = ({ name, onLoad }) => {
const contractInfoAtom = useRef(
focusAtom(contractsAtom, (optic) => optic.prop(name))
)
const [contractInfo, setContractInfo] = useAtom(contractInfoAtom.current)
const [endpoint, setEndpoint] = useAtom(endpointAtom)
const [pruntimeURL, setPruntimeURL] = useAtom(pruntimeURLAtom)
const {contractId = '', metadata = ''} = contractInfo || {}
const isClient = useIsClient()
if (!isClient) return null
);
const [contractInfo, setContractInfo] = useAtom(contractInfoAtom.current);
const [endpoint, setEndpoint] = useAtom(endpointAtom);
const [pruntimeURL, setPruntimeURL] = useAtom(pruntimeURLAtom);
const { contractId = "", metadata = "" } = contractInfo || {};
const isClient = useIsClient();
if (!isClient) return null;

const loadContract = async () => {
try {
const api = await createApi(endpoint)
const api = await createApi(endpoint);
const contract = new ContractPromise(
(await create({api, baseURL: pruntimeURL, contractId})).api,
(await create({ api, baseURL: pruntimeURL, contractId })).api,
JSON.parse(metadata),
contractId
)
onLoad({api, contract})
toaster.positive('Contract loaded successfully', {})
);
onLoad({ api, contract });
toaster.positive("Contract loaded successfully", {});
} catch (err) {
toaster.negative((err as Error).message, {})
throw err
toaster.negative((err as Error).message, {});
throw err;
}
}
};

return (
<>
Expand All @@ -63,7 +63,7 @@ const ContractLoader: VFC<{
overrides={{
Input: {
style: {
fontFamily: 'monospace',
fontFamily: "monospace",
},
},
}}
Expand All @@ -77,7 +77,7 @@ const ContractLoader: VFC<{
overrides={{
Input: {
style: {
fontFamily: 'monospace',
fontFamily: "monospace",
},
},
}}
Expand All @@ -90,7 +90,7 @@ const ContractLoader: VFC<{
overrides={{
Input: {
style: {
fontFamily: 'monospace',
fontFamily: "monospace",
},
},
}}
Expand All @@ -108,8 +108,8 @@ const ContractLoader: VFC<{
overrides={{
Input: {
style: {
fontFamily: 'monospace',
height: '600px',
fontFamily: "monospace",
height: "600px",
},
},
}}
Expand All @@ -127,7 +127,7 @@ const ContractLoader: VFC<{
Load Contract
</Button>
</>
)
}
);
};

export default ContractLoader
export default ContractLoader;
Loading

0 comments on commit af8b539

Please sign in to comment.