Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: Cere Wallet signer not triggering 3rd party extensions consent #259

Merged
merged 3 commits into from
Jul 29, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 8 additions & 8 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion packages/blockchain/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@
"author": "Cere Network <contact@cere.io (https://www.cere.io/)",
"license": "Apache-2.0",
"dependencies": {
"@cere/embed-wallet-inject": "^0.18.2",
"@cere/embed-wallet-inject": "^0.20.1",
"@polkadot/api": "^10.11.2",
"@polkadot/api-base": "^10.11.2",
"@polkadot/api-contract": "^10.11.2",
Expand Down
48 changes: 25 additions & 23 deletions packages/blockchain/src/Blockchain.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { ApiPromise, WsProvider } from '@polkadot/api';
import { AddressOrPair, SignerOptions } from '@polkadot/api/types';
import { AddressOrPair, SignerOptions, ApiOptions } from '@polkadot/api/types';
import { Index, AccountInfo } from '@polkadot/types/interfaces';
import { SubmittableExtrinsic } from '@polkadot/api-base/types';
import { formatBalance } from '@polkadot/util';
Expand All @@ -22,6 +22,7 @@ export type BlockchainConnectOptions =
}
| {
wsEndpoint: string;
apiOptions?: Omit<ApiOptions, 'provider'>;
};

/**
Expand All @@ -39,56 +40,57 @@ export type BlockchainConnectOptions =
* ```
*/
export class Blockchain {
private readonly apiPromise: ApiPromise;
readonly api: ApiPromise;

/**
* The DDC Nodes pallet.
*
* @category Pallets
*/
public readonly ddcNodes: DDCNodesPallet;
readonly ddcNodes: DDCNodesPallet;

/**
* The DDC Clusters pallet.
*
* @category Pallets
*/
public readonly ddcClusters: DDCClustersPallet;
readonly ddcClusters: DDCClustersPallet;

/**
* The DDC Staking pallet.
*
* @category Pallets
*/
public readonly ddcStaking: DDCStakingPallet;
readonly ddcStaking: DDCStakingPallet;

/**
* The DDC Customers pallet.
*
* @category Pallets
*/
public readonly ddcCustomers: DDCCustomersPallet;
readonly ddcCustomers: DDCCustomersPallet;

/**
* The DDC Cluster government pallet.
*
* @category Pallets
*/
public readonly ddcClustersGov: DDCClustersGovPallet;
readonly ddcClustersGov: DDCClustersGovPallet;

constructor(options: BlockchainConnectOptions) {
this.apiPromise =
this.api =
'apiPromise' in options
? options.apiPromise
: new ApiPromise({
provider: new WsProvider(options.wsEndpoint),
...options.apiOptions,
});

this.ddcNodes = new DDCNodesPallet(this.apiPromise);
this.ddcClusters = new DDCClustersPallet(this.apiPromise);
this.ddcStaking = new DDCStakingPallet(this.apiPromise);
this.ddcCustomers = new DDCCustomersPallet(this.apiPromise);
this.ddcClustersGov = new DDCClustersGovPallet(this.apiPromise);
this.ddcNodes = new DDCNodesPallet(this.api);
this.ddcClusters = new DDCClustersPallet(this.api);
this.ddcStaking = new DDCStakingPallet(this.api);
this.ddcCustomers = new DDCCustomersPallet(this.api);
this.ddcClustersGov = new DDCClustersGovPallet(this.api);
}

/**
Expand Down Expand Up @@ -121,7 +123,7 @@ export class Blockchain {
* ```
*/
async isReady() {
await this.apiPromise.isReady;
await this.api.isReady;

return true;
}
Expand All @@ -130,7 +132,7 @@ export class Blockchain {
* The decimals of the chain's native token.
*/
get chainDecimals() {
const [decimals] = this.apiPromise.registry.chainDecimals;
const [decimals] = this.api.registry.chainDecimals;

return decimals;
}
Expand All @@ -149,7 +151,7 @@ export class Blockchain {
* ```
*/
async getNextNonce(address: string | AccountId) {
const nonce = await this.apiPromise.rpc.system.accountNextIndex<Index>(address);
const nonce = await this.api.rpc.system.accountNextIndex<Index>(address);

return nonce.toNumber();
}
Expand Down Expand Up @@ -204,7 +206,7 @@ export class Blockchain {
let errorMessage: string;

if (result.dispatchError.isModule) {
const decoded = this.apiPromise.registry.findMetaError(result.dispatchError.asModule);
const decoded = this.api.registry.findMetaError(result.dispatchError.asModule);
errorMessage = `${decoded.section}.${decoded.name}: ${decoded.docs.join(' ')}`;
} else {
errorMessage = result.dispatchError.toString();
Expand Down Expand Up @@ -238,7 +240,7 @@ export class Blockchain {
* ```
*/
batchSend(sendables: Sendable[], options: SendOptions) {
return this.send(this.apiPromise.tx.utility.batch(sendables), options);
return this.send(this.api.tx.utility.batch(sendables), options);
}

/**
Expand All @@ -263,11 +265,11 @@ export class Blockchain {
* ```
*/
batchAllSend(sendables: Sendable[], options: SendOptions) {
return this.send(this.apiPromise.tx.utility.batchAll(sendables), options);
return this.send(this.api.tx.utility.batchAll(sendables), options);
}

sudo(sendable: Sendable) {
return this.apiPromise.tx.sudo.sudo(sendable) as Sendable;
return this.api.tx.sudo.sudo(sendable) as Sendable;
}

/**
Expand All @@ -281,7 +283,7 @@ export class Blockchain {
* ```
*/
disconnect() {
return this.apiPromise.disconnect();
return this.api.disconnect();
}

formatBalance(balance: string | number | bigint, withUnit: boolean | string = 'CERE') {
Expand All @@ -302,7 +304,7 @@ export class Blockchain {
* ```
*/
async getAccountFreeBalance(accountId: AccountId) {
const { data } = await this.apiPromise.query.system.account<AccountInfo>(accountId);
const { data } = await this.api.query.system.account<AccountInfo>(accountId);
return data.free.toBigInt();
}

Expand All @@ -320,7 +322,7 @@ export class Blockchain {
* ```
*/
async getCurrentBlockNumber() {
const { number } = await this.apiPromise.rpc.chain.getHeader();
const { number } = await this.api.rpc.chain.getHeader();
return number.toNumber();
}
}
Expand Down
60 changes: 42 additions & 18 deletions packages/blockchain/src/Signer/CereWalletSigner.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,14 @@
import type { EmbedWallet, PermissionRequest } from '@cere/embed-wallet';
import { inject } from '@cere/embed-wallet-inject';
import type { InjectedAccount, InjectedExtension } from '@polkadot/extension-inject/types';
import { enable } from '@cere/embed-wallet-inject';
import type { EmbedWallet, WalletConnectOptions } from '@cere/embed-wallet';

import { Web3Signer } from './Web3Signer';
import { Web3Signer, Web3SignerOptions } from './Web3Signer';
import { cryptoWaitReady } from '../utils';

const CERE_WALLET_EXTENSION = 'Cere Wallet';

export type CereWalletSignerOptions = {
permissions?: PermissionRequest;
export type CereWalletSignerOptions = Pick<Web3SignerOptions, 'autoConnect'> & {
connectOptions?: WalletConnectOptions;
};

/**
Expand All @@ -29,27 +31,49 @@ export type CereWalletSignerOptions = {
* ```
*/
export class CereWalletSigner extends Web3Signer {
protected wallet: EmbedWallet;
private extensionPromise: Promise<InjectedExtension>;

constructor(
wallet: EmbedWallet,
private wallet: EmbedWallet,
private options: CereWalletSignerOptions = {},
) {
super({ extensions: [CERE_WALLET_EXTENSION] });
super(options);

this.wallet = wallet;
}
this.extensionPromise = enable(this.wallet, { autoConnect: false }).then((injected) => {
injected.accounts.get().then(this.setAccount);
injected.accounts.subscribe(this.setAccount);

async connect() {
await inject(this.wallet, {
name: CERE_WALLET_EXTENSION,
autoConnect: true,
permissions: this.options.permissions || {
ed25519_signRaw: {}, // Request permission to sign messages in the login process
},
return { ...injected, name: CERE_WALLET_EXTENSION, version: '0.20.0' };
});
}

private setAccount = ([account]: InjectedAccount[]) => {
this.injectedAccount = account;
};

protected async getInjector() {
return this.extensionPromise;
}

/**
* @inheritdoc
*/
async isReady() {
await cryptoWaitReady();

if (this.injectedAccount) {
return true;
}

if (this.autoConnect) {
await this.connect(this.options.connectOptions);
}

return true;
}

await super.connect();
async connect(options?: WalletConnectOptions) {
await this.wallet.connect(options);

return this;
}
Expand Down
53 changes: 32 additions & 21 deletions packages/ddc-client/src/DdcClient.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,13 +38,30 @@ type DepositBalanceOptions = {
* It provides methods to manage buckets, grant access, and store and read files and DAG nodes.
*/
export class DdcClient {
protected constructor(
private readonly ddcNode: NodeInterface,
private readonly blockchain: Blockchain,
private readonly fileStorage: FileStorage,
private readonly signer: Signer,
private readonly logger: Logger,
) {
private readonly ddcNode: NodeInterface;
private readonly blockchain: Blockchain;
private readonly fileStorage: FileStorage;
private readonly signer: Signer;
private readonly logger: Logger;

constructor(uriOrSigner: Signer | string, config: DdcClientConfig = DEFAULT_PRESET) {
const logger = createLogger('DdcClient', config);
const blockchain =
typeof config.blockchain === 'string' ? new Blockchain({ wsEndpoint: config.blockchain }) : config.blockchain;

const signer = typeof uriOrSigner === 'string' ? new UriSigner(uriOrSigner) : uriOrSigner;
const router = config.nodes
? new Router({ signer, nodes: config.nodes, logger })
: new Router({ signer, blockchain, logger });

this.blockchain = blockchain;
this.signer = signer;
this.logger = logger;
this.ddcNode = new BalancedNode({ ...config, router, logger });
this.fileStorage = new FileStorage(router, { ...config, logger });

logger.debug(config, 'DdcClient created');

bindErrorLogger(this, this.logger, [
'getBalance',
'depositBalance',
Expand Down Expand Up @@ -80,27 +97,21 @@ export class DdcClient {
* ```
*/
static async create(uriOrSigner: Signer | string, config: DdcClientConfig = DEFAULT_PRESET) {
const logger = createLogger('DdcClient', config);
const signer = typeof uriOrSigner === 'string' ? new UriSigner(uriOrSigner) : uriOrSigner;
const blockchain =
typeof config.blockchain === 'string'
? await Blockchain.connect({ wsEndpoint: config.blockchain })
: config.blockchain;
const client = new DdcClient(uriOrSigner, config);

const router = config.nodes
? new Router({ signer, nodes: config.nodes, logger })
: new Router({ signer, blockchain, logger });
return client.connect();
}

const ddcNode = new BalancedNode({ ...config, router, logger });
const fileStorage = new FileStorage(router, { ...config, logger });
async connect() {
await this.blockchain.isReady();

logger.debug(config, 'DdcClient created');

return new DdcClient(ddcNode, blockchain, fileStorage, signer, logger);
return this;
}

async disconnect() {
await this.blockchain.disconnect();

return this;
}

/**
Expand Down
2 changes: 1 addition & 1 deletion playground/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@
"dependencies": {
"@cere-ddc-sdk/blockchain": "2.10.0",
"@cere-ddc-sdk/ddc-client": "2.12.0",
"@cere/embed-wallet": "^0.17.0",
"@cere/embed-wallet": "^0.20.1",
"@emotion/react": "^11.11.4",
"@emotion/styled": "^11.11.5",
"@mui/icons-material": "^5.15.16",
Expand Down
Loading