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

[BRO-39] Migrate away from injecting API (package) #476

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
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
1 change: 1 addition & 0 deletions .eslintignore
Original file line number Diff line number Diff line change
Expand Up @@ -9,3 +9,4 @@ package.json
!.storybook

packages/browser-wallet-api-helpers/lib
packages/browser-wallet-api/lib
1 change: 1 addition & 0 deletions examples/piggybank/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
"name": "piggybank",
"packageManager": "[email protected]",
"dependencies": {
"@concordium/browser-wallet-api": "workspace:^",
"@concordium/browser-wallet-api-helpers": "workspace:^",
"@concordium/web-sdk": "^7.3.2",
"react": "^18.1.0",
Expand Down
28 changes: 8 additions & 20 deletions examples/piggybank/src/Root.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
/* eslint-disable no-console */
import React, { useEffect, useState, useMemo, useCallback } from 'react';

import { detectConcordiumProvider } from '@concordium/browser-wallet-api-helpers';
import { walletApi } from '@concordium/browser-wallet-api';
import PiggyBankV0 from './Version0';
import PiggyBankV1 from './Version1';
import { state, State } from './utils';
Expand All @@ -19,27 +19,15 @@ export default function Root() {
setIsConnected(Boolean(accountAddress));
}, []);

const handleOnClick = useCallback(
() =>
detectConcordiumProvider()
.then((provider) => provider.connect())
.then(handleGetAccount),
[]
);
const handleOnClick = useCallback(() => walletApi.connect().then(handleGetAccount), []);

useEffect(() => {
detectConcordiumProvider()
.then((provider) => {
// Listen for relevant events from the wallet.
provider.on('accountChanged', setAccount);
provider.on('accountDisconnected', () =>
provider.getMostRecentlySelectedAccount().then(handleGetAccount)
);
provider.on('chainChanged', (chain) => console.log(chain));
// Check if you are already connected
provider.getMostRecentlySelectedAccount().then(handleGetAccount);
})
.catch(() => setIsConnected(false));
// Listen for relevant events from the wallet.
walletApi.on('accountChanged', setAccount);
walletApi.on('accountDisconnected', () => walletApi.getMostRecentlySelectedAccount().then(handleGetAccount));
walletApi.on('chainChanged', (chain) => console.log(chain));
// Check if you are already connected
walletApi.getMostRecentlySelectedAccount().then(handleGetAccount);
}, []);

const stateValue: State = useMemo(() => ({ isConnected, account }), [isConnected, account]);
Expand Down
31 changes: 14 additions & 17 deletions examples/piggybank/src/Version0.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import {
isInstanceInfoV0,
toBuffer,
} from '@concordium/web-sdk';
import { detectConcordiumProvider } from '@concordium/browser-wallet-api-helpers';
import { walletApi } from '@concordium/browser-wallet-api';
import { smash, deposit, state, CONTRACT_NAME, expectedInitName } from './utils';

import PiggyIcon from './assets/piggy-bank-solid.svg?react';
Expand All @@ -29,29 +29,26 @@ const isPiggybankSmashed = (piggyState: PiggyBankState): piggyState is PiggyBank
(piggyState as PiggyBankStateSmashed).Smashed !== undefined;

export default function PiggyBankV0() {
const grpc = new ConcordiumGRPCClient(walletApi.grpcTransport);

const { account, isConnected } = useContext(state);
const [piggybank, setPiggyBank] = useState<InstanceInfoV0>();
const input = useRef<HTMLInputElement>(null);

useEffect(() => {
// Get piggy bank data.
detectConcordiumProvider()
.then((provider) => {
const grpc = new ConcordiumGRPCClient(provider.grpcTransport);
return grpc.getInstanceInfo(ContractAddress.create(CONTRACT_INDEX, CONTRACT_SUB_INDEX));
})
.then((info) => {
if (expectedInitName.value !== info.name.value) {
// Check that we have the expected instance.
throw new Error(`Expected instance of PiggyBank: ${info?.name.value}`);
}
if (!isInstanceInfoV0(info)) {
// Check smart contract version. We expect V0.
throw new Error('Expected SC version 0');
}
grpc.getInstanceInfo(ContractAddress.create(CONTRACT_INDEX, CONTRACT_SUB_INDEX)).then((info) => {
if (expectedInitName.value !== info.name.value) {
// Check that we have the expected instance.
throw new Error(`Expected instance of PiggyBank: ${info?.name.value}`);
}
if (!isInstanceInfoV0(info)) {
// Check smart contract version. We expect V0.
throw new Error('Expected SC version 0');
}

setPiggyBank(info);
});
setPiggyBank(info);
});
}, []);

// The internal state of the piggy bank, which is either intact or smashed.
Expand Down
25 changes: 10 additions & 15 deletions examples/piggybank/src/Version1.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
/* eslint-disable no-console */
import React, { useEffect, useState, useContext, useRef } from 'react';
import { ConcordiumGRPCClient, ContractAddress, ReceiveName, ReturnValue, toBuffer } from '@concordium/web-sdk';
import { detectConcordiumProvider } from '@concordium/browser-wallet-api-helpers';
import { walletApi } from '@concordium/browser-wallet-api';
import { smash, deposit, state, CONTRACT_NAME, expectedInitName } from './utils';

import PiggyIcon from './assets/piggy-bank-solid.svg?react';
Expand All @@ -18,8 +18,7 @@ const CONTRACT_INDEX = 81n; // V1 instance
const CONTRACT_SUB_INDEX = 0n;

async function updateState(setSmashed: (x: boolean) => void, setAmount: (x: bigint) => void): Promise<void> {
const provider = await detectConcordiumProvider();
const grpc = new ConcordiumGRPCClient(provider.grpcTransport);
const grpc = new ConcordiumGRPCClient(walletApi.grpcTransport);
const res = await grpc.invokeContract({
method: ReceiveName.fromString(`${CONTRACT_NAME}.view`),
contract: ContractAddress.create(CONTRACT_INDEX, CONTRACT_SUB_INDEX),
Expand All @@ -42,19 +41,15 @@ export default function PiggyBank() {
useEffect(() => {
if (isConnected) {
// Get piggy bank owner.
detectConcordiumProvider()
.then((provider) => {
const grpc = new ConcordiumGRPCClient(provider.grpcTransport);
return grpc.getInstanceInfo(ContractAddress.create(CONTRACT_INDEX, CONTRACT_SUB_INDEX));
})
.then((info) => {
if (expectedInitName.value !== info.name.value) {
// Check that we have the expected instance.
throw new Error(`Expected instance of PiggyBank: ${info?.name.value}`);
}
const grpc = new ConcordiumGRPCClient(walletApi.grpcTransport);
grpc.getInstanceInfo(ContractAddress.create(CONTRACT_INDEX, CONTRACT_SUB_INDEX)).then((info) => {
if (expectedInitName.value !== info.name.value) {
// Check that we have the expected instance.
throw new Error(`Expected instance of PiggyBank: ${info?.name.value}`);
}

setOwner(info.owner.address);
});
setOwner(info.owner.address);
});
}
}, [isConnected]);

Expand Down
52 changes: 18 additions & 34 deletions examples/piggybank/src/utils.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
/* eslint-disable no-console */
import { createContext } from 'react';
import { detectConcordiumProvider } from '@concordium/browser-wallet-api-helpers';
import { walletApi } from '@concordium/browser-wallet-api';
import {
AccountTransactionType,
CcdAmount,
Expand All @@ -24,47 +24,31 @@ export const deposit = (account: string, index: bigint, subindex = 0n, amount =
return;
}

detectConcordiumProvider()
.then((provider) => {
provider
.sendTransaction(AccountAddress.fromBase58(account), AccountTransactionType.Update, {
amount: CcdAmount.fromMicroCcd(amount),
address: ContractAddress.create(index, subindex),
receiveName: ReceiveName.fromString(`${CONTRACT_NAME}.insert`),
maxContractExecutionEnergy: Energy.create(30000),
} as UpdateContractPayload)
.then((txHash) =>
console.log(`https://testnet.ccdscan.io/?dcount=1&dentity=transaction&dhash=${txHash}`)
)
.catch(alert);
})
.catch(() => {
throw new Error('Concordium Wallet API not accessible');
});
walletApi
.sendTransaction(AccountAddress.fromBase58(account), AccountTransactionType.Update, {
amount: CcdAmount.fromMicroCcd(amount),
address: ContractAddress.create(index, subindex),
receiveName: ReceiveName.fromString(`${CONTRACT_NAME}.insert`),
maxContractExecutionEnergy: Energy.create(30000),
} as UpdateContractPayload)
.then((txHash) => console.log(`https://testnet.ccdscan.io/?dcount=1&dentity=transaction&dhash=${txHash}`))
.catch(alert);
};

/**
* Action for smashing the piggy bank. This is only possible to do, if the account sending the transaction matches the owner of the piggy bank:
* https://github.com/Concordium/concordium-rust-smart-contracts/blob/c4d95504a51c15bdbfec503c9e8bf5e93a42e24d/examples/piggy-bank/part1/src/lib.rs#L64
*/
export const smash = (account: string, index: bigint, subindex = 0n) => {
detectConcordiumProvider()
.then((provider) => {
provider
.sendTransaction(AccountAddress.fromBase58(account), AccountTransactionType.Update, {
amount: CcdAmount.fromMicroCcd(0), // This feels weird? Why do I need an amount for a non-payable receive?
address: ContractAddress.create(index, subindex),
receiveName: ReceiveName.fromString(`${CONTRACT_NAME}.smash`),
maxContractExecutionEnergy: Energy.create(30000),
})
.then((txHash) =>
console.log(`https://testnet.ccdscan.io/?dcount=1&dentity=transaction&dhash=${txHash}`)
)
.catch(alert);
walletApi
.sendTransaction(AccountAddress.fromBase58(account), AccountTransactionType.Update, {
amount: CcdAmount.fromMicroCcd(0), // This feels weird? Why do I need an amount for a non-payable receive?
address: ContractAddress.create(index, subindex),
receiveName: ReceiveName.fromString(`${CONTRACT_NAME}.smash`),
maxContractExecutionEnergy: Energy.create(30000),
})
.catch(() => {
throw new Error('Concordium Wallet API not accessible');
});
.then((txHash) => console.log(`https://testnet.ccdscan.io/?dcount=1&dentity=transaction&dhash=${txHash}`))
.catch(alert);
};

/**
Expand Down
5 changes: 0 additions & 5 deletions examples/piggybank/vite.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,9 +13,4 @@ export default defineConfig({
wasm(),
topLevelAwait(), // For legacy browser compatibility
],
resolve: {
alias: {
'@concordium/rust-bindings': '@concordium/rust-bindings/bundler', // Resolve bundler-specific wasm entrypoints.
},
},
});
9 changes: 6 additions & 3 deletions examples/two-step-transfer/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
<head>
<title>My cool dapp</title>
<script src="/sdk.js"></script>
<script src="/helpers.js"></script>
<script src="/api.js"></script>
<script src="https://unpkg.com/cbor-web"></script>
<meta charset="utf-8" />
<script>
Expand All @@ -28,7 +28,7 @@
async function setupPage() {
const twoStepTransferSchema =
'AQAAABEAAAB0d28tc3RlcC10cmFuc2ZlcgEUAAIAAAALAAAAaW5pdF9wYXJhbXMUAAMAAAAPAAAAYWNjb3VudF9ob2xkZXJzEQALHAAAAHRyYW5zZmVyX2FncmVlbWVudF90aHJlc2hvbGQCFAAAAHRyYW5zZmVyX3JlcXVlc3RfdHRsDggAAAByZXF1ZXN0cxIBBRQABAAAAA8AAAB0cmFuc2Zlcl9hbW91bnQKDgAAAHRhcmdldF9hY2NvdW50CwwAAAB0aW1lc19vdXRfYXQNCgAAAHN1cHBvcnRlcnMRAgsBFAADAAAADwAAAGFjY291bnRfaG9sZGVycxEACxwAAAB0cmFuc2Zlcl9hZ3JlZW1lbnRfdGhyZXNob2xkAhQAAAB0cmFuc2Zlcl9yZXF1ZXN0X3R0bA4BAAAABwAAAHJlY2VpdmUVAgAAAA8AAABSZXF1ZXN0VHJhbnNmZXIBAwAAAAUKCw8AAABTdXBwb3J0VHJhbnNmZXIBAwAAAAUKCw==';
const provider = await concordiumHelpers.detectConcordiumProvider();
const provider = concordiumWalletApi.walletApi;

document.getElementById('connect').addEventListener('click', () => {
provider.connect().then((accountAddress) => {
Expand Down Expand Up @@ -258,7 +258,10 @@
.catch(alert);
});
}
setupPage();

window.onload = function () {
setupPage();
};
</script>
</head>

Expand Down
2 changes: 1 addition & 1 deletion examples/two-step-transfer/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
"live-server": "^1.2.2"
},
"scripts": {
"start": "live-server ../two-step-transfer/index.html --mount=/sdk.js:../../node_modules/@concordium/web-sdk/lib/min/concordium.web.min.js --mount=/helpers.js:../../packages/browser-wallet-api-helpers/lib/concordiumHelpers.min.js"
"start": "live-server ../two-step-transfer/index.html --mount=/sdk.js:../../node_modules/@concordium/web-sdk/lib/min/concordium.web.min.js --mount=/api.js:../../packages/browser-wallet-api/lib/concordiumWalletApi.min.js"
},
"dependencies": {
"@concordium/web-sdk": "^7.3.2"
Expand Down
1 change: 1 addition & 0 deletions examples/voting/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
"version": "1.1.3",
"packageManager": "[email protected]",
"dependencies": {
"@concordium/browser-wallet-api": "workspace:^",
"@concordium/browser-wallet-api-helpers": "^3.0.0",
"@concordium/web-sdk": "^7.3.2",
"bootstrap": "^5.2.1",
Expand Down
9 changes: 2 additions & 7 deletions examples/voting/src/Results.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import { Badge, Button, Col, Container, Row, Spinner } from 'react-bootstrap';
import ListGroup from 'react-bootstrap/ListGroup';
import { Link, useParams } from 'react-router-dom';
import moment from 'moment';
import { detectConcordiumProvider } from '@concordium/browser-wallet-api-helpers';
import { walletApi } from '@concordium/browser-wallet-api';
import { decodeView, decodeVotes } from './buffer';
import { getView, getVotes } from './Wallet';
import { REFRESH_INTERVAL } from './config';
Expand Down Expand Up @@ -45,8 +45,8 @@ function VoteLink(props) {
function Results() {
const params = useParams();
const { electionId } = params;
const client = walletApi;

const [client, setClient] = useState();
const [view, setView] = useState();
const [votes, setVotes] = useState();

Expand All @@ -57,11 +57,6 @@ function Results() {
return () => clearInterval(interval);
}, []);

// Attempt to initialize Browser Wallet Client.
useEffect(() => {
detectConcordiumProvider().then(setClient).catch(console.error);
}, []);

// Attempt to get general information about the election.
useEffect(() => {
if (client) {
Expand Down
4 changes: 2 additions & 2 deletions examples/voting/src/Wallet.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
/* eslint-disable import/no-unresolved */
/* eslint-disable no-plusplus */
import React from 'react';
import { detectConcordiumProvider } from '@concordium/browser-wallet-api-helpers';
import { walletApi } from '@concordium/browser-wallet-api';
import { Alert, Button } from 'react-bootstrap';
import {
AccountTransactionType,
Expand All @@ -19,7 +19,7 @@ import moment from 'moment';
import { RAW_SCHEMA_BASE64, TESTNET_GENESIS_BLOCK_HASH } from './config';

export async function init(setConnectedAccount) {
const client = await detectConcordiumProvider();
const client = walletApi;
// Listen for relevant events from the wallet.
client.on('accountChanged', (account) => {
console.debug('browserwallet event: accountChange', { account });
Expand Down
1 change: 0 additions & 1 deletion examples/voting/vite.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,6 @@ export default defineConfig({
},
resolve: {
alias: {
'@concordium/rust-bindings': '@concordium/rust-bindings/bundler', // Resolve bundler-specific wasm entrypoints.
stream: 'rollup-plugin-node-polyfills/polyfills/stream',
},
},
Expand Down
38 changes: 35 additions & 3 deletions packages/browser-wallet-api/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,27 @@
"private": true,
"version": "0.1.0",
"description": "API for interfacing with the concordium browser wallet",
"main": "src/index.ts",
"main": "lib/browser-wallet-api/src/index.js",
"browser": "lib/concordiumWalletApi.min.js",
"types": "lib/browser-wallet-api/src/index.d.ts",
"cdn": "lib/concordiumWalletApi.min.js",
"exports": {
".": {
"browser": "./lib/browser-wallet-api/src/index.js",
"import": "./lib/browser-wallet-api/src/index.js",
"types": "./lib/browser-wallet-api/src/index.d.ts",
"default": "./lib/browser-wallet-api/src/index.js"
},
"./src/util": {
"import": "./lib/browser-wallet-api/src/util.js"
},
"./src/constants": {
"import": "./lib/browser-wallet-api/src/constants.js"
}
},
"files": [
"/lib/**/*"
],
"author": "Concordium Software",
"license": "Apache-2.0",
"dependencies": {
Expand All @@ -17,12 +37,24 @@
"json-bigint": "^1.0.0"
},
"devDependencies": {
"@babel/core": "^7.24.7",
"@babel/plugin-syntax-typescript": "^7.24.7",
"@babel/plugin-transform-class-properties": "^7.24.7",
"@babel/plugin-transform-modules-commonjs": "^7.24.7",
"@babel/plugin-transform-runtime": "^7.24.7",
"@babel/plugin-transform-typescript": "^7.24.7",
"@babel/preset-env": "^7.24.7",
"@types/json-bigint": "^1.0.2",
"jest": "^29.7.0",
"ts-jest": "^29.1.1"
"node-polyfill-webpack-plugin": "^4.0.0",
"ts-jest": "^29.1.1",
"typescript": "^5.4.5",
"webpack": "^5.92.0",
"webpack-cli": "^5.1.4"
},
"scripts": {
"test": "jest",
"build": "tsc"
"build": "tsc && webpack",
"build:wallet-api": "yarn build"
}
}
Loading
Loading