@concordium/browser-wallet-api-helpers 0.1.0

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,116 @@
1
+ # browser-wallet-api-helpers
2
+
3
+ This package includes the types for the API to be used in web applications for communicating with the Concordium browser wallet. The API is injected into `window.concordium` when it is ready.
4
+
5
+ The actual implementation of the wallet API can be found in the [in the Concordium browser wallet repository.](https://github.com/Concordium/concordium-browser-wallet/tree/main/packages/browser-wallet-api)
6
+
7
+ ## Development
8
+
9
+ ### Installing
10
+
11
+ See [installing](../../README.md#installing) in repository root.
12
+
13
+ ### Building
14
+
15
+ - Run `yarn build` in the package root, which will output into the folder "lib".
16
+
17
+ ## Using the API
18
+
19
+ The API is automatically injected into web applications if the Concordium browser wallet extension is installed in the browser. To get access to the API a helper function is provided by this package which can be used as follows:
20
+
21
+ ```typescript
22
+ import { detectConcordiumProvider } from '@concordium/browser-wallet-api-helpers';
23
+
24
+ detectConcordiumProvider()
25
+ .then((provider) => {
26
+ // The API is ready for use.
27
+ provider
28
+ .connect()
29
+ .then((accountAddress) => {
30
+ // The wallet is connected to the dApp.
31
+ })
32
+ .catch(() => console.log('Connection to the Concordium browser wallet was rejected.'));
33
+ })
34
+ .catch(() => console.log('Connection to the Concordium browser wallet timed out.'));
35
+ ```
36
+
37
+ ### Custom method for accessing the API
38
+
39
+ If you do not wish to use the provided utility function, then it is also possible to access the API directly on `window.concordium`. If you do this, then it is your responsibility to make the necessary checks to determine if the API is ready to use. To get proper typing for this you need to update your global definitions for `Window`.
40
+
41
+ ```typescript
42
+ import { WalletApi } from '@concordium/browser-wallet-api-helpers';
43
+ declare global {
44
+ interface Window {
45
+ concordium: WalletApi | undefined;
46
+ }
47
+ }
48
+ ```
49
+
50
+ ## API instance methods
51
+
52
+ ### connect
53
+
54
+ To request a connection to the wallet from the user, the `connect` method has to be invoked. The method returns a `Promise` resolving with information related to the currently selected account in the wallet, or rejecting if the request is rejected in the wallet. If this is not called, it will be called as part of any other request (f.x. `sendTransaction` or `signMessage`) made by the API.
55
+
56
+ ```typescript
57
+ const provider = await detectConcordiumProvider();
58
+ const accountAddress = await provider.connect();
59
+ ```
60
+
61
+ ### sendTransaction
62
+
63
+ To send a transaction, two arguments need to be provided: A transaction type and a corresponding payload. Invoking `sendTransaction` returns a `Promise`, which resolves with the transaction hash for the submitted transaction.
64
+
65
+ The following exemplifies how to create a simple transfer of funds from one account (selected account in the wallet) to another. Please note that [@concordium/web-sdk](https://github.com/Concordium/concordium-node-sdk-js/tree/main/packages/web) is used to provide the correct formats and types for the transaction payload.
66
+
67
+ ```typescript
68
+ const provider = await detectConcordiumProvider();
69
+ const txHash = await provider.sendTransaction(concordiumSDK.AccountTransactionType.SimpleTransfer, {
70
+ amount: new concordiumSDK.GtuAmount(1n),
71
+ toAddress: new concordiumSDK.AccountAddress('39bKAuC7sXCZQfo7DmVQTMbiUuBMQJ5bCfsS7sva1HvDnUXp13'),
72
+ });
73
+ ```
74
+
75
+ In the case of a smart contract init/update, parameters for the specific function and a corresponding schema for serializing the parameters can be defined.
76
+
77
+ ```typescript
78
+ const provider = await detectConcordiumProvider();
79
+ const txHash = await provider.sendTransaction(
80
+ concordiumSDK.AccountTransactionType.UpdateSmartContractInstance,
81
+ {
82
+ amount: new concordiumSDK.GtuAmount(1n),
83
+ contractAddress: {
84
+ index: 11n,
85
+ subindex: 0n,
86
+ },
87
+ receiveName: 'two-step-transfer.receive',
88
+ maxContractExecutionEnergy: 30000n,
89
+ },
90
+ {
91
+ RequestTransfer: ['1000', '1', '3Y1RLgi5pW3x96xZ7CiDiKsTL9huU92qn6mfxpebwmtkeku8ry'],
92
+ },
93
+ 'AQAAABEAAAB0d28tc3RlcC10cmFuc2ZlcgEUAAIAAAALAAAAaW5pdF9wYXJhbXMUAAMAAAAPAAAAYWNjb3VudF9ob2xkZXJzEQALHAAAAHRyYW5zZmVyX2FncmVlbWVudF90aHJlc2hvbGQCFAAAAHRyYW5zZmVyX3JlcXVlc3RfdHRsDggAAAByZXF1ZXN0cxIBBRQABAAAAA8AAAB0cmFuc2Zlcl9hbW91bnQKDgAAAHRhcmdldF9hY2NvdW50CwwAAAB0aW1lc19vdXRfYXQNCgAAAHN1cHBvcnRlcnMRAgsBFAADAAAADwAAAGFjY291bnRfaG9sZGVycxEACxwAAAB0cmFuc2Zlcl9hZ3JlZW1lbnRfdGhyZXNob2xkAhQAAAB0cmFuc2Zlcl9yZXF1ZXN0X3R0bA4BAAAABwAAAHJlY2VpdmUVAgAAAA8AAABSZXF1ZXN0VHJhbnNmZXIBAwAAAAUKCw8AAABTdXBwb3J0VHJhbnNmZXIBAwAAAAUKCw=='
94
+ );
95
+ ```
96
+
97
+ ### signMessage
98
+
99
+ It is possible to sign arbitrary messages using the keys for an account stored in the wallet, by invoking the `signMessage` method. This method returns a `Promise` resolving with a signature of the message.
100
+
101
+ The following exemplifies requesting a signature of a message:
102
+
103
+ ```typescript
104
+ const provider = await detectConcordiumProvider();
105
+ const signature = await provider.signMessage('This is a message to be signed');
106
+ ```
107
+
108
+ ### addChangeAccountListener
109
+
110
+ To react when the selected account in the wallet changes, a handler function can be assigned through `addChangeAccountListener`. This does **not** return the currently selected account when the handler is initially assigned. This can be obtained by invoking the `connect` method.
111
+
112
+ ```typescript
113
+ const provider = await detectConcordiumProvider();
114
+ let selectedAccountAddress: string | undefined = undefined;
115
+ provider.addChangeAccountListener((address) => (selectedAccountAddress = address));
116
+ ```
@@ -0,0 +1,2 @@
1
+ !function(e,o){"object"==typeof exports&&"object"==typeof module?module.exports=o():"function"==typeof define&&define.amd?define([],o):"object"==typeof exports?exports.concordiumHelpers=o():e.concordiumHelpers=o()}(self,(()=>(()=>{"use strict";var e={611:(e,o)=>{Object.defineProperty(o,"__esModule",{value:!0}),o.detectConcordiumProvider=async function(e=5e3){return new Promise(((o,r)=>{if(window.concordium)o(window.concordium);else{const t=setTimeout((()=>{window.concordium?o(window.concordium):r()}),e);window.addEventListener("concordium#initialized",(()=>{window.concordium&&(clearTimeout(t),o(window.concordium))}),{once:!0})}}))}},685:(e,o,r)=>{Object.defineProperty(o,"__esModule",{value:!0});var t={detectConcordiumProvider:!0};Object.defineProperty(o,"detectConcordiumProvider",{enumerable:!0,get:function(){return i.detectConcordiumProvider}});var n=r(740);Object.keys(n).forEach((function(e){"default"!==e&&"__esModule"!==e&&(Object.prototype.hasOwnProperty.call(t,e)||e in o&&o[e]===n[e]||Object.defineProperty(o,e,{enumerable:!0,get:function(){return n[e]}}))}));var i=r(611)},740:(e,o)=>{Object.defineProperty(o,"__esModule",{value:!0})}},o={};return function r(t){var n=o[t];if(void 0!==n)return n.exports;var i=o[t]={exports:{}};return e[t](i,i.exports,r),i.exports}(685)})()));
2
+ //# sourceMappingURL=concordiumHelpers.min.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"concordiumHelpers.min.js","mappings":"CAAA,SAA2CA,EAAMC,GAC1B,iBAAZC,SAA0C,iBAAXC,OACxCA,OAAOD,QAAUD,IACQ,mBAAXG,QAAyBA,OAAOC,IAC9CD,OAAO,GAAIH,GACe,iBAAZC,QACdA,QAA2B,kBAAID,IAE/BD,EAAwB,kBAAIC,IAR9B,CASGK,MAAM,I,kHCHFC,eAAwCC,EAAU,KACrD,OAAO,IAAIC,SAAQ,CAACC,EAASC,KACzB,GAAIC,OAAOC,WACPH,EAAQE,OAAOC,gBAEd,CACD,MAAMC,EAAIC,YAAW,KACbH,OAAOC,WACPH,EAAQE,OAAOC,YAGfF,MAELH,GACHI,OAAOI,iBAAiB,0BAA0B,KAC1CJ,OAAOC,aACPI,aAAaH,GACbJ,EAAQE,OAAOC,eAEpB,CAAEK,MAAM,U,yNCzBvB,8NACA,c,+DCAIC,EAA2B,G,OAG/B,SAASC,EAAoBC,GAE5B,IAAIC,EAAeH,EAAyBE,GAC5C,QAAqBE,IAAjBD,EACH,OAAOA,EAAapB,QAGrB,IAAIC,EAASgB,EAAyBE,GAAY,CAGjDnB,QAAS,IAOV,OAHAsB,EAAoBH,GAAUlB,EAAQA,EAAOD,QAASkB,GAG/CjB,EAAOD,QClBWkB,CAAoB,M","sources":["webpack:///webpack/universalModuleDefinition","webpack:///./lib/detector.js","webpack:///./lib/index.js","webpack:///webpack/bootstrap","webpack:///webpack/startup"],"sourcesContent":["(function webpackUniversalModuleDefinition(root, factory) {\n\tif(typeof exports === 'object' && typeof module === 'object')\n\t\tmodule.exports = factory();\n\telse if(typeof define === 'function' && define.amd)\n\t\tdefine([], factory);\n\telse if(typeof exports === 'object')\n\t\texports[\"concordiumHelpers\"] = factory();\n\telse\n\t\troot[\"concordiumHelpers\"] = factory();\n})(self, () => {\nreturn ","/**\n * Detect the Concordium browser wallet API by waiting for it to have been successfully injected\n * into the window so that it is ready for use.\n * @param timeout determines how long to wait before rejecting if the Concordium provider is not available, in milliseconds.\n * @returns a promise containing the Concordium Wallet provider API.\n */\nexport async function detectConcordiumProvider(timeout = 5000) {\n return new Promise((resolve, reject) => {\n if (window.concordium) {\n resolve(window.concordium);\n }\n else {\n const t = setTimeout(() => {\n if (window.concordium) {\n resolve(window.concordium);\n }\n else {\n reject();\n }\n }, timeout);\n window.addEventListener('concordium#initialized', () => {\n if (window.concordium) {\n clearTimeout(t);\n resolve(window.concordium);\n }\n }, { once: true });\n }\n });\n}\n","export * from './wallet-api-types';\nexport { detectConcordiumProvider } from './detector';\n","// The module cache\nvar __webpack_module_cache__ = {};\n\n// The require function\nfunction __webpack_require__(moduleId) {\n\t// Check if module is in cache\n\tvar cachedModule = __webpack_module_cache__[moduleId];\n\tif (cachedModule !== undefined) {\n\t\treturn cachedModule.exports;\n\t}\n\t// Create a new module (and put it into the cache)\n\tvar module = __webpack_module_cache__[moduleId] = {\n\t\t// no module.id needed\n\t\t// no module.loaded needed\n\t\texports: {}\n\t};\n\n\t// Execute the module function\n\t__webpack_modules__[moduleId](module, module.exports, __webpack_require__);\n\n\t// Return the exports of the module\n\treturn module.exports;\n}\n\n","// startup\n// Load entry module and return exports\n// This entry module is referenced by other modules so it can't be inlined\nvar __webpack_exports__ = __webpack_require__(685);\n"],"names":["root","factory","exports","module","define","amd","self","async","timeout","Promise","resolve","reject","window","concordium","t","setTimeout","addEventListener","clearTimeout","once","__webpack_module_cache__","__webpack_require__","moduleId","cachedModule","undefined","__webpack_modules__"],"sourceRoot":""}
@@ -0,0 +1,8 @@
1
+ import { WalletApi } from './wallet-api-types';
2
+ /**
3
+ * Detect the Concordium browser wallet API by waiting for it to have been successfully injected
4
+ * into the window so that it is ready for use.
5
+ * @param timeout determines how long to wait before rejecting if the Concordium provider is not available, in milliseconds.
6
+ * @returns a promise containing the Concordium Wallet provider API.
7
+ */
8
+ export declare function detectConcordiumProvider(timeout?: number): Promise<WalletApi>;
@@ -0,0 +1,29 @@
1
+ /**
2
+ * Detect the Concordium browser wallet API by waiting for it to have been successfully injected
3
+ * into the window so that it is ready for use.
4
+ * @param timeout determines how long to wait before rejecting if the Concordium provider is not available, in milliseconds.
5
+ * @returns a promise containing the Concordium Wallet provider API.
6
+ */
7
+ export async function detectConcordiumProvider(timeout = 5000) {
8
+ return new Promise((resolve, reject) => {
9
+ if (window.concordium) {
10
+ resolve(window.concordium);
11
+ }
12
+ else {
13
+ const t = setTimeout(() => {
14
+ if (window.concordium) {
15
+ resolve(window.concordium);
16
+ }
17
+ else {
18
+ reject();
19
+ }
20
+ }, timeout);
21
+ window.addEventListener('concordium#initialized', () => {
22
+ if (window.concordium) {
23
+ clearTimeout(t);
24
+ resolve(window.concordium);
25
+ }
26
+ }, { once: true });
27
+ }
28
+ });
29
+ }
@@ -0,0 +1,6 @@
1
+ import { WalletApi } from './wallet-api-types';
2
+ declare global {
3
+ interface Window {
4
+ concordium: WalletApi | undefined;
5
+ }
6
+ }
@@ -0,0 +1 @@
1
+ export {};
package/lib/index.d.ts ADDED
@@ -0,0 +1,2 @@
1
+ export * from './wallet-api-types';
2
+ export { detectConcordiumProvider } from './detector';
package/lib/index.js ADDED
@@ -0,0 +1,2 @@
1
+ export * from './wallet-api-types';
2
+ export { detectConcordiumProvider } from './detector';
@@ -0,0 +1,36 @@
1
+ import type { AccountTransactionPayload, AccountTransactionSignature, AccountTransactionType } from '@concordium/web-sdk';
2
+ export declare type WalletEventHandler<T = any> = (payload: T) => void;
3
+ export interface WalletApi {
4
+ /**
5
+ * React to changes to the selected account in the Concordium Wallet. Note that to get the initially selected account on load, the "connect" method should be used.
6
+ * @param handler a handler function called with the account address of the selected account.
7
+ */
8
+ addChangeAccountListener(handler: WalletEventHandler<string>): void;
9
+ /**
10
+ * Sends a transaction to the Concordium Wallet and awaits the users action. Note that a header is not sent, and will be constructed by the wallet itself.
11
+ * Note that if the user rejects signing the transaction, this will throw an error.
12
+ * @param type the type of transaction that is to be signed and sent.
13
+ * @param payload the payload of the transaction to be signed and sent.
14
+ * @param parameters parameters for the initContract and updateContract transactions in JSON-like format.
15
+ * @param schema schema used for the initContract and updateContract transactions to serialize the parameters. Should be base64 encoded.
16
+ */
17
+ sendTransaction(type: AccountTransactionType.UpdateSmartContractInstance | AccountTransactionType.InitializeSmartContractInstance, payload: AccountTransactionPayload, parameters: Record<string, unknown>, schema: string): Promise<string>;
18
+ /**
19
+ * Sends a transaction to the Concordium Wallet and awaits the users action. Note that a header is not sent, and will be constructed by the wallet itself.
20
+ * Note that if the user rejects signing the transaction, this will throw an error.
21
+ * @param type the type of transaction that is to be signed and sent.
22
+ * @param payload the payload of the transaction to be signed and sent.
23
+ */
24
+ sendTransaction(type: AccountTransactionType, payload: AccountTransactionPayload): Promise<string>;
25
+ /**
26
+ * Sends a message to the Concordium Wallet and awaits the users action. If the user signs the message, this will resolve to the signature.
27
+ * Note that if the user rejects signing the message, this will throw an error.
28
+ * @param message message to be signed. Note that the wallet will prepend some bytes to ensure the message cannot be a transaction
29
+ */
30
+ signMessage(message: string): Promise<AccountTransactionSignature>;
31
+ /**
32
+ * Requests a connection to the Concordium wallet, prompting the user to either accept or reject the request.
33
+ * If a connection has already been accepted for the url once the returned promise will resolve without prompting the user.
34
+ */
35
+ connect(): Promise<string | undefined>;
36
+ }
@@ -0,0 +1 @@
1
+ export {};
package/package.json ADDED
@@ -0,0 +1,36 @@
1
+ {
2
+ "name": "@concordium/browser-wallet-api-helpers",
3
+ "version": "0.1.0",
4
+ "license": "Apache-2.0",
5
+ "packageManager": "yarn@3.2.0",
6
+ "main": "lib/index.js",
7
+ "browser": "lib/concordiumHelpers.min.js",
8
+ "types": "lib/index.d.ts",
9
+ "files": [
10
+ "/lib/**/*"
11
+ ],
12
+ "repository": {
13
+ "type": "git",
14
+ "url": "https://github.com/Concordium/concordium-browser-wallet"
15
+ },
16
+ "author": {
17
+ "name": "Concordium Software",
18
+ "email": "support@concordium.software",
19
+ "url": "https://concordium.com"
20
+ },
21
+ "dependencies": {
22
+ "@concordium/web-sdk": "^0.1.2"
23
+ },
24
+ "devDependencies": {
25
+ "@babel/core": "^7.17.10",
26
+ "@babel/plugin-transform-modules-commonjs": "^7.12.1",
27
+ "@babel/plugin-transform-runtime": "^7.12.1",
28
+ "@babel/preset-env": "^7.12.1",
29
+ "typescript": "^4.3.5",
30
+ "webpack": "^5.72.0",
31
+ "webpack-cli": "^4.9.2"
32
+ },
33
+ "scripts": {
34
+ "build": "tsc && webpack"
35
+ }
36
+ }