@portal-hq/web 0.0.1-beta-1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md ADDED
@@ -0,0 +1,297 @@
1
+ # `Portal`
2
+
3
+ The `@portal-hq/core` package includes a class constructor for the `Portal` class, a React Context Provider for the `PortalContext`, the `usePortal` hook for use within child components, and some helpful types and enums for working with Portal in your app. These pieces allow you to initialize `Portal` in your app, expose the instance to your component tree, and consume the instance in your child components.
4
+
5
+ ## The Portal Class
6
+
7
+ The `Portal` class that houses three main sub-classes
8
+
9
+ - `api` makes requests to the Portal api
10
+ - `mpc` facilitates the generation, backup, and recovery of MPC wallets
11
+ - `provider` the core Portal provider ([EIP-1139](https://eips.ethereum.org/EIPS/eip-1193) compliant)
12
+
13
+ ## Instantiation
14
+
15
+ When instantiating the `Portal` class, you must provide a `PortalOptions` object. This object is used to initialize all of the sub-classes (and their sub-classes).
16
+
17
+ ### Example instantiation
18
+
19
+ ```typescript
20
+ import { BackupMethods, Portal } from '@portal-hq/core'
21
+
22
+ const portal = new Portal({
23
+ apiKey: 'YOUR_PORTAL_CLIENT_API_KEY',
24
+ backup: {
25
+ gdrive: gDriveStorage, // See: @portal-hq/gdrive-storage
26
+ icloud: iCloudStorage, // See: @portal-hq/icloud-storage
27
+ },
28
+ chainId: 1,
29
+ gatewayConfig: 'https://mainnet.infura.io/v3/YOUR_INFURA_API_KEY',
30
+ isSimulator: DeviceInfo.isEmulator(),
31
+ keychain: keychain, // See: @portal-hq/keychain
32
+ })
33
+ ```
34
+
35
+ ### PortalOptions
36
+
37
+ The `PortalOptions` object is where you configure your instance of `Portal`. It contains a set of required properties and a set of optional properties.
38
+
39
+ #### Required properties
40
+
41
+ - `apiKey` **string** a valid Portal Client API Key created via the [Portal REST API](https://api.portalhq.io/api/clients)
42
+ - `backupConfig` **object**
43
+ - `gdrive` **Storage** (optional) expects an instance of `@portal-hq/gdrive-storage`
44
+ - `icloud` **Storage** (optional) expects an instance of `@portal-hq/icloud-storage`
45
+ - `chainId` **number** the ID of the current Ethereum chain you'd like to perform actions on
46
+ - You can update this property on your `Portal` instance later – if your app requires this – by setting `portal.chainId` property
47
+ - `gatewayConfig` **string** or **GatewayConfig** the base url (including your API key) you'd like us to use for Gateway requests (reading from and writing to chain) _**Note: this will be required in the future**_
48
+ - `GatewayConfig` – if you don't want to use the same url for all requests, you can instead provide a chain-level config for all Gateway RPC calls this can be passed in as an object with key/value pairs where the `key` is the `chainId` as a number and the value is the base url you'd like to use when performing actions on this `chainId`
49
+ - `isSimulator` **boolean** whether or not you're currently running the app in a simulator (this is required to ensure that keychain storage is configured appropriately for the current device)
50
+ - `keychain` **Keychain** expects an instance of either `@portal-hq/keychain` or `@portal-hq/mobile-key-values`
51
+
52
+ #### Optional properties
53
+
54
+ - `autoApprove` **boolean** (default: `false`) whether you'd like the provider to auto-approve transactions
55
+ - `mpcEnabled` **boolean** (default: `true`) whether or not to use MPC
56
+
57
+ ## `api`
58
+
59
+ The `api` property contains an instance of the `PortalApi` class, which has a number of helper methods to facilitate the retrieval of relevant application data from the Portal REST API.
60
+
61
+ ### Methods
62
+
63
+ #### `getEnabledDapps`
64
+
65
+ Fetches a list of allowed dApps based on your dApp settings in the Portal web app.
66
+
67
+ ##### Example usage
68
+
69
+ ```typescript
70
+ const portal = new Portal({
71
+ apiKey: 'YOUR_PORTAL_CLIENT_API_KEY',
72
+ backup: {
73
+ gdrive: gDriveStorage, // See: @portal-hq/gdrive-storage
74
+ icloud: iCloudStorage, // See: @portal-hq/icloud-storage
75
+ },
76
+ chainId: 1,
77
+ gatewayConfig: 'https://mainnet.infura.io/v3/YOUR_INFURA_API_KEY',
78
+ isSimulator: DeviceInfo.isEmulator(),,
79
+ keychain: keychain // See: @portal-hq/keychain
80
+ })
81
+
82
+ const dapps = await portal.api.getEnabledDapps()
83
+ ```
84
+
85
+ #### `getNetworks`
86
+
87
+ Fetches a list of supported networks based on your dApp settings in the Portal web app.
88
+
89
+ ##### Example usage
90
+
91
+ ```typescript
92
+ const portal = new Portal({
93
+ apiKey: 'YOUR_PORTAL_CLIENT_API_KEY',
94
+ backup: {
95
+ gdrive: gDriveStorage, // See: @portal-hq/gdrive-storage
96
+ icloud: iCloudStorage, // See: @portal-hq/icloud-storage
97
+ },
98
+ chainId: 1,
99
+ gatewayConfig: 'https://mainnet.infura.io/v3/YOUR_INFURA_API_KEY',
100
+ isSimulator: DeviceInfo.isEmulator(),,
101
+ keychain: keychain // See: @portal-hq/keychain
102
+ })
103
+
104
+ const networks = await portal.api.getNetworks()
105
+ ```
106
+
107
+ ## `mpc`
108
+
109
+ The `mpc` property contains an instance of the `PortalMpc` class, which has a number of helper methods to facilitate the management of Portal MPC wallets.
110
+
111
+ ### Methods
112
+
113
+ #### `generate`
114
+
115
+ Performs the MPC generate process to create an MPC wallet and its signing shares
116
+
117
+ ##### Example usage
118
+
119
+ ```typescript
120
+ const portal = new Portal({
121
+ apiKey: 'YOUR_PORTAL_CLIENT_API_KEY',
122
+ backup: {
123
+ gdrive: gDriveStorage, // See: @portal-hq/gdrive-storage
124
+ icloud: iCloudStorage, // See: @portal-hq/icloud-storage
125
+ },
126
+ chainId: 1,
127
+ gatewayConfig: 'https://mainnet.infura.io/v3/YOUR_INFURA_API_KEY',
128
+ isSimulator: DeviceInfo.isEmulator(),,
129
+ keychain: keychain // See: @portal-hq/keychain
130
+ })
131
+
132
+ const createWallet = async () => {
133
+ await portal.mpc.generate()
134
+ }
135
+ ```
136
+
137
+ #### `backup`
138
+
139
+ Performs the MPC backup process to create the backup shares for the generated MPC wallet.
140
+
141
+ ##### Example usage
142
+
143
+ ```typescript
144
+ const portal = new Portal({
145
+ apiKey: 'YOUR_PORTAL_CLIENT_API_KEY',
146
+ backup: {
147
+ gdrive: gDriveStorage, // See: @portal-hq/gdrive-storage
148
+ icloud: iCloudStorage, // See: @portal-hq/icloud-storage
149
+ },
150
+ chainId: 1,
151
+ gatewayConfig: 'https://mainnet.infura.io/v3/YOUR_INFURA_API_KEY',
152
+ isSimulator: DeviceInfo.isEmulator(),,
153
+ keychain: keychain, // See: @portal-hq/keychain
154
+ })
155
+
156
+ const backupWallet = async () => {
157
+ await portal.mpc.backup()
158
+ }
159
+ ```
160
+
161
+ #### `recover`
162
+
163
+ Performs the MPC recovery process to generate new signing shares for the MPC wallet.
164
+
165
+ ##### Example usage
166
+
167
+ ```typescript
168
+ const portal = new Portal({
169
+ apiKey: 'YOUR_PORTAL_CLIENT_API_KEY',
170
+ backup: {
171
+ gdrive: gDriveStorage, // See: @portal-hq/gdrive-storage
172
+ icloud: iCloudStorage, // See: @portal-hq/icloud-storage
173
+ },
174
+ chainId: 1,
175
+ gatewayConfig: 'https://mainnet.infura.io/v3/YOUR_INFURA_API_KEY',
176
+ isSimulator: DeviceInfo.isEmulator(),
177
+ keychain: keychain, // See: @portal-hq/keychain
178
+ })
179
+
180
+ const recoverWallet = async () => {
181
+ await portal.mpc.recover()
182
+ }
183
+ ```
184
+
185
+ ## `provider`
186
+
187
+ The `provider` property contains an [EIP-1139](https://eips.ethereum.org/EIPS/eip-1193) compliant provider.
188
+
189
+ ### Making requests through the provider
190
+
191
+ In order to perform basic web3 operations, such as `eth_accounts` and `eth_sendTransaction`, you can use the provider's `request` method.
192
+
193
+ This method conforms to [EIP-1139](https://eips.ethereum.org/EIPS/eip-1193).
194
+
195
+ #### Example usage
196
+
197
+ ```typescript
198
+ const transaction = {
199
+ data: '',
200
+ to: toAddress,
201
+ value: BigNumber.from('1').toHexString(),
202
+ gas: '0x6000',
203
+ from: portal.address, // The address of the current connected wallet
204
+ }
205
+
206
+ const txHash = await portal.provider.request({
207
+ method: 'eth_sendTransaction',
208
+ params: transaction,
209
+ })
210
+ ```
211
+
212
+ _For more information on how to use this provider natively within your React Native app, see the [Provider Docs](LINK_TO_PROVIDER_DOCS)._
213
+
214
+ ## The Portal context
215
+
216
+ `PortalContext` is used to persist an instance of `Portal` within your application. This allows you to initialize `Portal` once, and easily share this instance between all of the components within a given scope in your app.
217
+
218
+ The exported members allow for 2 ways to set the `PortalContext` and one way to get the `PortalContext`.
219
+
220
+ ### Setters
221
+
222
+ You only need to choose one of these when implementing the `PortalContext` in your app.
223
+
224
+ - `PortalContextProvider` a React Context Provider to provide your `Portal` instance to the components in your app
225
+
226
+ ### Getters
227
+
228
+ - `usePortal` a React hook to use the `Portal` instance in any component within the `PortalContextProvider` scope (any component being rendered as either a shallow or deep child of the `PortalContextProvider`)
229
+
230
+ _For more info on working with React Context, [check out the docs](https://reactjs.org/docs/context.html)._
231
+
232
+ ### `PortalContextProvider`
233
+
234
+ The `PortalContextProvider` allows you to share your instance of the Portal class with all components in your component tree. Providing a `value` prop with your Portal instance and wrapping your components in the `PortalContextProvider` enables this behavior. All children of the `PortalContextProvider` can access the Portal instance using the `usePortal` hook (see below).
235
+
236
+ _**Note**: The easiest way to ensure you're exposing Portal to all components in your component tree is to use it in your App component_
237
+
238
+ ```tsx
239
+ // MyRootComponent.tsx
240
+
241
+ import { useEffect, useState } from 'react'
242
+ import { Portal, PortalContextProvider } from '@portal-hq/react-native'
243
+
244
+ const MyRootComponent = () => {
245
+ const [portal, setPortal] = useState<Portal>(null)
246
+
247
+ useEffect(() => {
248
+ if (!portal) {
249
+ setPortal(
250
+ new Portal({
251
+ // TODO: Add all of the appropriate config options
252
+ }),
253
+ )
254
+ }
255
+ }, [portal])
256
+
257
+ return (
258
+ <PortalContextProvider value={portal}>
259
+ {/* Now all children rendered in this scope will have access to the `Portal` instance via the `usePortal` hook */}
260
+ </PortalContextProvider>
261
+ )
262
+ }
263
+ ```
264
+
265
+ ### `usePortal`
266
+
267
+ The `usePortal` hook allows any child in the component tree below a `PortalContextProvider` to access the Portal instance.
268
+
269
+ ```tsx
270
+ // MyChildComponent.tsx
271
+
272
+ import { usePortal } from '@portal-hq/react-native'
273
+
274
+ const MyChildComponent = () => {
275
+ const portal = usePortal()
276
+
277
+ // You can now do things with the `Portal` instance directly, such as:
278
+ // - `await portal.api.getEnabledDapps()`
279
+ // - `await portal.mpc.generate()`
280
+ //
281
+ // For more information on this, please see the `Portal` docs in `src/lib/portal`
282
+
283
+ ...
284
+ }
285
+
286
+ ```
287
+
288
+ ## Additional exports
289
+
290
+ In addition to the `Portal` class and context exports, the `@portal-hq/core` package exports some helpful types and enums for use when building your app.
291
+
292
+ The additional exports are as follows:
293
+
294
+ - `BackupMethods` – an enum of supported storage methods for backup MPC key shares
295
+ - `Address` - a type representing Portal Address records
296
+ - `Dapp` - a type representing Portal Dapp records (`portal.api.getEnabledDapps()` returns `Dapp[]`)
297
+ - `PortalOptions` - a type representing the object used to configure the `Portal` class on initialization
@@ -0,0 +1,201 @@
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ var __importDefault = (this && this.__importDefault) || function (mod) {
12
+ return (mod && mod.__esModule) ? mod : { "default": mod };
13
+ };
14
+ Object.defineProperty(exports, "__esModule", { value: true });
15
+ const mpc_1 = __importDefault(require("./mpc"));
16
+ const provider_1 = __importDefault(require("./provider"));
17
+ const storage_1 = __importDefault(require("./storage"));
18
+ class Portal {
19
+ constructor({
20
+ // Required
21
+ apiKey, gatewayConfig,
22
+ // Optional
23
+ apiHost = 'api.portalhq.io', autoApprove = false, backup = { default: new storage_1.default() }, chainId = 1, mpcHost = 'mpc.portalhq.io', mpcVersion = 'v4', webHost = 'web.portalhq.io', }) {
24
+ this.ready = false;
25
+ this.readyCallbacks = [];
26
+ this.apiHost = apiHost;
27
+ this.apiKey = apiKey;
28
+ this.autoApprove = autoApprove;
29
+ this.backup = backup;
30
+ this.chainId = chainId;
31
+ this.gatewayConfig = gatewayConfig;
32
+ this.mpcHost = mpcHost;
33
+ this.mpcVersion = mpcVersion;
34
+ this.rpcUrl = this.getRpcUrl();
35
+ this.webHost = webHost;
36
+ console.log(`Backup:`, this.backup);
37
+ // Portal Instances
38
+ this.mpc = new mpc_1.default({
39
+ apiHost: this.apiHost,
40
+ apiKey: this.apiKey,
41
+ autoApprove: this.autoApprove,
42
+ chainId: this.chainId,
43
+ mpcHost: this.mpcHost,
44
+ rpcUrl: this.rpcUrl,
45
+ webHost: this.webHost,
46
+ portal: this,
47
+ });
48
+ this.provider = new provider_1.default({
49
+ autoApprove: this.autoApprove,
50
+ mpcHost: this.mpcHost,
51
+ mpcVersion: this.mpcVersion,
52
+ portal: this,
53
+ });
54
+ }
55
+ /*****************************
56
+ * Initialization Methods
57
+ *****************************/
58
+ onReady(callback) {
59
+ if (this.ready) {
60
+ callback();
61
+ }
62
+ else {
63
+ this.readyCallbacks.push(callback);
64
+ }
65
+ }
66
+ triggerReady() {
67
+ if (this.ready && this.readyCallbacks.length > 0) {
68
+ this.readyCallbacks.forEach((callback) => {
69
+ callback();
70
+ });
71
+ this.readyCallbacks = [];
72
+ }
73
+ }
74
+ /*****************************
75
+ * Wallet Methods
76
+ *****************************/
77
+ createWallet() {
78
+ return __awaiter(this, void 0, void 0, function* () {
79
+ const address = yield this.mpc.generate({
80
+ host: this.mpcHost,
81
+ mpcVersion: this.mpcVersion,
82
+ });
83
+ this.address = address;
84
+ return address;
85
+ });
86
+ }
87
+ backupWallet() {
88
+ return __awaiter(this, void 0, void 0, function* () {
89
+ yield this.mpc.backup({
90
+ host: this.mpcHost,
91
+ mpcVersion: this.mpcVersion,
92
+ });
93
+ return '';
94
+ });
95
+ }
96
+ recoverWallet() {
97
+ return __awaiter(this, void 0, void 0, function* () {
98
+ yield this.mpc.recover({
99
+ host: this.mpcHost,
100
+ mpcVersion: this.mpcVersion,
101
+ });
102
+ return true;
103
+ });
104
+ }
105
+ /****************************
106
+ * Provider Methods
107
+ ****************************/
108
+ ethSendTransaction(transaction) {
109
+ return __awaiter(this, void 0, void 0, function* () {
110
+ return this.provider.request({
111
+ method: 'eth_sendTransaction',
112
+ params: transaction,
113
+ });
114
+ });
115
+ }
116
+ ethSign(message) {
117
+ return __awaiter(this, void 0, void 0, function* () {
118
+ return this.provider.request({
119
+ method: 'eth_sign',
120
+ params: [this.address, this.stringToHex(message)],
121
+ });
122
+ });
123
+ }
124
+ ethSignTransaction(transaction) {
125
+ return __awaiter(this, void 0, void 0, function* () {
126
+ return this.provider.request({
127
+ method: 'eth_signTransaction',
128
+ params: transaction,
129
+ });
130
+ });
131
+ }
132
+ ethSignTypedData(data) {
133
+ return __awaiter(this, void 0, void 0, function* () {
134
+ return this.provider.request({
135
+ method: 'eth_signTypedData',
136
+ params: [this.address, data],
137
+ });
138
+ });
139
+ }
140
+ ethSignTypedDataV3(data) {
141
+ return __awaiter(this, void 0, void 0, function* () {
142
+ return this.provider.request({
143
+ method: 'eth_signTypedData_v3',
144
+ params: [this.address, data],
145
+ });
146
+ });
147
+ }
148
+ ethSignTypedDataV4(data) {
149
+ return __awaiter(this, void 0, void 0, function* () {
150
+ return this.provider.request({
151
+ method: 'eth_signTypedData_v4',
152
+ params: [this.address, data],
153
+ });
154
+ });
155
+ }
156
+ personalSign(message) {
157
+ return __awaiter(this, void 0, void 0, function* () {
158
+ return this.provider.request({
159
+ method: 'personal_sign',
160
+ params: [this.stringToHex(message), this.address],
161
+ });
162
+ });
163
+ }
164
+ /****************************
165
+ * RPC Methods
166
+ ****************************/
167
+ getRpcUrl() {
168
+ if (typeof this.gatewayConfig === 'string') {
169
+ // If the gatewayConfig is just a static URL, return that
170
+ return this.gatewayConfig;
171
+ }
172
+ else if (typeof this.gatewayConfig === 'object' &&
173
+ !this.gatewayConfig.hasOwnProperty(this.chainId)) {
174
+ // If there's no explicit mapping for the current chainId, error out
175
+ throw new Error(`[PortalProvider] No RPC endpoint configured for chainId: ${this.chainId}`);
176
+ }
177
+ // Get the entry for the current chainId from the gatewayConfig
178
+ const config = this.gatewayConfig[this.chainId];
179
+ if (typeof config === 'string') {
180
+ return config;
181
+ }
182
+ // If we got this far, there's no way to support the chain with the current config
183
+ throw new Error(`[PortalProvider] Could not find a valid gatewayConfig entry for chainId: ${this.chainId}`);
184
+ }
185
+ /**************************
186
+ * RPC Encoding Methods
187
+ **************************/
188
+ stringToHex(str) {
189
+ if (str.startsWith('0x')) {
190
+ return str;
191
+ }
192
+ let hex = '0x';
193
+ for (let i = 0; i < str.length; i++) {
194
+ const charCode = str.charCodeAt(i);
195
+ const hexValue = charCode.toString(16);
196
+ hex += hexValue.padStart(2, '0'); // Ensure two-digit hex value
197
+ }
198
+ return hex;
199
+ }
200
+ }
201
+ exports.default = Portal;