Gathering detailed insights and metrics for @portkey/detect-provider
Gathering detailed insights and metrics for @portkey/detect-provider
npm install @portkey/detect-provider
Typescript
Module System
Node Version
NPM Version
73.4
Supply Chain
99
Quality
98.3
Maintenance
100
Vulnerability
98.9
License
TypeScript (88.33%)
JavaScript (9.73%)
HTML (1.43%)
CSS (0.4%)
Shell (0.1%)
Less (0.02%)
Total Downloads
59,403
Last Day
261
Last Week
1,378
Last Month
4,730
Last Year
51,425
11 Commits
1 Forks
19 Branches
8 Contributors
Latest Version
2.4.0-alpha.5
Package Id
@portkey/detect-provider@2.4.0-alpha.5
Unpacked Size
36.38 kB
Size
8.70 kB
File Count
16
NPM Version
lerna/6.6.2/node@v22.3.0+arm64 (darwin)
Node Version
22.3.0
Publised On
08 Jan 2025
Cumulative downloads
Total Downloads
Last day
161%
261
Compared to previous day
Last week
18.9%
1,378
Compared to previous week
Last month
-27.2%
4,730
Compared to previous month
Last year
544.6%
51,425
Compared to previous year
1
1# for npm user 2npm install @portkey/detect-provider 3 4#for yarn user 5yarn add @portkey/detect-provider
1import detectProvider, {isPortkeyProvider} from '@portkey/detect-provider'; 2// ES6 Async/Await syntax 3const provider:IPortkeyProvider = await detectProvider(); 4// ES6 Promise syntax 5detectProvider().then((provider:IPortkeyProvider) => { 6 // do something with provider 7 provider.request({method: ... }) 8}).catch((error:Error) => { 9 // Handle error 10});
1function detectProvider<T extends IPortkeyProvider = IPortkeyProvider> 2(options?: DetectProviderOptions): Promise<T | null>;
1interface DetectProviderOptions { 2 timeout?: number; // default is 3000 ms 3}
Promise<IPortkeyProvider | null>
See Provider section for more information.
1function isPortkeyProvider<T extends IPortkeyProvider = IPortkeyProvider> 2(provider: unknown): provider is T
1provider: unknown
1provider is T // effect like boolean
See the above example for usage.
1interface Provider { 2 isPortkey: boolean; 3 isConnected(): boolean; 4 on(event: DappEvents, callback: (...data: any) => void): this; 5 once(event: DappEvents, callback: (...data: any) => void): this; 6 removeListener(event: DappEvents, callback: (...data: any) => void): this; 7 request<T extends MethodResponse = any>(params: RequestOption): Promise<T>; 8 getChain(chainId: ChainId): Promise<IChain>; 9}
Determines whether the current environment is Portkey, if everything works well, it is true
.
Use it to detect if current Portkey APP's wallet is connected.
1if(!provider.isConnected()){ 2 // Portkey APP's wallet is not connected 3 alert("it seems that we have lost the APP's wallet connection"); 4 throw new Error('wallet disconnected...'); 5}
on(event,callback) is used to listen to the events triggered by Portkey APP. once(event,callback) works in a similar way, but it will only be triggered once.
1provider.on('connected',()=>{ 2 // Portkey APP's wallet is connected 3 ... 4}); 5provider.once('accountsChanged',(accounts)=>{ 6 // Portkey APP's wallet's accounts have changed 7 ... 8});
Use this method to remove the listener you added before.
If you wish your listener to be removed after it is triggered, use once(event,callback)
will be more efficient.
Since you need to process the function object as the parameter, you need to keep a reference to the function object.
1const listener = ()=> { 2 // Portkey APP's wallet is connected 3 ... 4}; 5provider.on('connected',listener); 6provider.removeListener('connected',listener);
See Request Method & Generic Type for more details.
1provider.request({ method: "42" }).then((result: any) => { 2// Do something with the result 3}); 4// When using typescript, you can see type definition if you call particular method name 5provider.request({ method: "chainIds" }).then((result: ChainId[]) => { 6 // result is ChainIds = ChainId[] 7 console.log('chainIds:',result); 8});
This method provides a way to get the chain
( type of IChain
) object, which handles the on-chain operations.
1provider.getChain('AELF').then((chain:IChain) => { 2 // Do something with the chain object 3 console.log('chainId:',chain.chainId); 4});
See IChain section for more details.
DappEvents
will be triggered when the corresponding event occurs.
1type DappEvents = 'connected' | 'message' | 'disconnected' | 'accountsChanged' | 'networkChanged' | 'chainChanged' | 'error';
Use provider.on(event,callback) to listen to those events.
You can see the detailed type definition in @portkey/provider-types project .
1interface IChain { 2 rpcUrl: string; 3 type: ChainType; 4 chainId: ChainId; 5 getContract(contractAddress: string): IContract; 6} 7 8interface IAElfChain extends IAElfRPCMethods, IChain { 9 /** @deprecated use getContract */ 10 contractAt<T = any>(address: string, wallet: AElfWallet): Promise<ChainMethodResult<T>>; 11}
rpcUrl
is the url of the chain's rpc server.
You can use it to send rpc requests to the chain directly.
type
describes the type of the chain, for now it is either 'aelf'
or 'ethereum'
.
You can use it to determine which chain the APP are using.
if type
is 'aelf'
, chainId
shows which chain type the APP is on.
For example, 'AELF'
means mainchain, 'tDVV'
means sidechain.
getContract
creates a way to get the contract
( type of IContract
) object, which handles the contract operations.
1try{ 2 const chain = await provider.getChain('AELF'); 3 const contract = chain.getContract('your-contract-address'); 4 // Do something with the contract object 5 const result = await contract.callViewMethod('how-much-token-do-i-have', 'aelf0x12345678'); 6 console.log('result:', result); 7}catch(e){ 8 console.error('getContract error:', e); 9}
You can see detailed type definition in source code .
1interface IProviderError extends Error { 2 code: number; 3 data?: unknown; 4} 5 6// Those codes may change in the future, see the source file for the latest version. 7export enum ResponseCode { 8 SUCCESS = 0, 9 10 USER_DENIED = 4001, 11 ERROR_IN_PARAMS = 4002, 12 UNKNOWN_METHOD = 4003, 13 UNIMPLEMENTED = 4004, 14 15 UNAUTHENTICATED = 4005, 16 TIMEOUT = 4006, 17 CONTRACT_ERROR = 4007, 18 INTERNAL_ERROR = 5001, 19}
IProviderError
is the error object that will be thrown when an error occurs.
See Error Code Enumeration for more details.
1 request(params: { method: 'accounts' }): Promise<Accounts>; 2 request(params: { method: 'chainId' }): Promise<ChainIds>; 3 request(params: { method: 'chainIds' }): Promise<ChainIds>; 4 request(params: { method: 'chainsInfo' }): Promise<ChainsInfo>; 5 request(params: { method: 'requestAccounts'}): Promise<Accounts>; 6 request(params: { method: 'wallet_getWalletState' }): Promise<WalletState>; 7 request(params: { method: 'wallet_getWalletName' }): Promise<WalletName>; 8 request(params: { method: 'network' }): Promise<NetworkType>; 9 request(params: { 10 method: 'sendTransaction'; 11 payload: SendTransactionParams; 12 }): Promise<Transaction>; 13 request(params: { 14 method: 'wallet_getSignature', 15 payload: GetSignatureParams, 16 }): Promise<Signature>; 17 request<T extends MethodResponse = any>(params: RequestOption): Promise<T>;
You can find the complete type definition like Accounts
in source code .
We recommend you to use the Async/Await syntax to call those methods.
It helps you find out errors more effectively.
1try { 2 const result = provider.request({method:'sth'}); 3 ... 4} catch (e) { 5 // when the promise is rejected, an error will be thrown 6 ... 7} 8 9// you can still use the promise syntax 10provider.request({method:'sth'}).then((result)=>{ 11 ... 12}).catch((e)=>{ 13 ... 14}); 15
Returns the current chainId of the Portkey APP's wallet.
Need to know that 'chainId'
gets the current chainId, while 'chainIds'
gets all the supported chainIds.
1const chainId = await provider.request({ method: 'chainId' }); 2// Although the chainId object is an array, it only contains one chainId. 3console.log('current chainId:',chainId[0]); 4 5const chainIds = await provider.request({ method: 'chainIds' }); 6console.log('all the supported chainIds:',chainIds);
Gets all the supported chains' information.
1const chainsInfo = await provider.request({ method: 'chainsInfo' }); 2console.log('all the on-chain info:', chainsInfo);
Returns the current network type of the Portkey APP's wallet.
For now it's either 'MAINNET'
or 'TESTNET'
.
1const networkType = await provider.request({ method: 'network' }); 2console.log('current network type is :',networkType);
Request the Portkey APP's wallet to connect to your dapp, this method is the bridge to get the permission required by the following methods below.
If the user has not connected to your dapp, the Portkey APP's wallet will pop up a window to ask the user to connect to your dapp.
If the user has connected to your dapp and hasn't remove the permission, this method returns info without a second confirmation.
1try { 2 const accounts = await provider.request({ method: 'requestAccounts' }); 3 console.log(accounts); 4}catch (e) { 5 // An error will be thrown if the user denies the permission request. 6 console.log('user denied the permission request'); 7}
Returns the current account addresses of the Portkey APP's wallet.
NOTICE: You should use request({ method: 'requestAccounts' })
first for the permission to access.
1const accounts = await provider.request({ method: 'accounts' }); 2console.log(accounts);
Returns the current wallet state of the Portkey APP's wallet.
NOTICE: You should use request({ method: 'requestAccounts' })
first for the permission to access.
1const walletState = await provider.request({ method: 'wallet_getWalletState' }); 2console.log('walletState:', walletState);
Returns the current wallet name of the Portkey APP's wallet.
NOTICE: You should use request({ method: 'requestAccounts' })
first for the permission to access.
1 const walletName = await provider.request({ method: 'wallet_getWalletName' }); 2 console.log('walletName:', walletName);
Send a transaction to the Portkey APP's wallet.
NOTICE: You should use request({ method: 'requestAccounts' })
first for the permission to access.
1try { 2 const txId = await provider.request({ 3 method: 'sendTransaction', 4 payload: { 5 to: '0x...', 6 ... 7 }, 8 }); 9 if(!txId) throw new Error('transaction failed!'); 10 console.log('transaction success! transaction id:', txId); 11 } catch (e) { 12 // An error will be thrown if the user denies the permission request, or other issues. 13 ... 14 }
Get a signature from the Portkey APP's wallet.
NOTICE: You should use request({ method: 'requestAccounts' })
first for the permission to access.
1try { 2 const signature = await provider.request({ 3 method: 'wallet_getSignature', 4 payload: { 5 data: '0x...', 6 }, 7 }); 8 if (!signature) throw new Error('sign failed!'); 9 console.log('sign success! signature:', signature); 10} catch (e) { 11// An error will be thrown if the user denies the permission request, or other issues. 12... 13}
Get the ManagementAccount Address of the current wallet user
NOTICE: You should use request({ method: 'requestAccounts' })
first for the permission to access.
1try { 2 const managerAddress = await provider.request({ 3 method: 'wallet_getCurrentManagerAddress', 4 }); 5} catch (e) { 6// An error will be thrown if the user denies the permission request, or other issues. 7... 8}
Get the current wallet user managementAccount synchronization status
NOTICE: You should use request({ method: 'requestAccounts' })
first for the permission to access.
1try { 2 const status = await provider.request({ 3 method: 'wallet_getManagerSyncStatus', 4 payload: { 5 chainId: chainId, // AELF, tDVV, tDVW 6 }, 7 }); 8 if(status){ 9 // manager synchronization completed 10 } else { 11 // manager synchronizing 12 } 13} catch (e) { 14// An error will be thrown if the user denies the permission request, or other issues. 15... 16}
It means nothing wrong happened, and the result is exactly what you want.
It means the user denied the permission request, when you call methods like request({ method: 'requestAccounts' })
that needs the user's permission.
The Wallet will show a dialog that asks the user to make a decision, if the user clicks the "cancel" button, this error will be thrown.
It is recommended to catch this error when you call those methods(for now):
It means the parameters you passed in are invalid, you should check them again.
If you think your params may cause this trouble, you should catch this error and handle it.
If you are using a method that doesn't need any params, you can ignore this error.
It means the method you called is not supported by the wallet, check it again.
You are using a method that is not implemented yet, or removed in current version because it is deprecated. Check the Wallet's version before calling those methods.
It means the user has not connected to your dapp, you should call request({ method: 'requestAccounts' })
first to get the permission.
The wallet can not provide your expected result in time, you should try again later.
There's some issues happened when the wallet is calling the contract, you should check your params and try again.
The wallet is facing some internal issues which results in the failure of your request, you should try again later or refresh your page.
No vulnerabilities found.
No security vulnerabilities found.