Skip to content

Commit

Permalink
Merge branch 'develop' into tuan-linh/initialize-hubble-stats
Browse files Browse the repository at this point in the history
  • Loading branch information
AtelyPham authored Jun 22, 2023
2 parents 3c61848 + be00264 commit ec51b7b
Show file tree
Hide file tree
Showing 38 changed files with 1,131 additions and 246 deletions.
3 changes: 0 additions & 3 deletions .github/workflows/check-build.yml
Original file line number Diff line number Diff line change
Expand Up @@ -46,8 +46,5 @@ jobs:
- name: Generate stats-dapp codegen
run: yarn gql:codegen

- name: Fetch the on-chain anchors data
run: yarn fetch:onChainConfig

- name: build
run: yarn nx run-many --all --target=build
3 changes: 0 additions & 3 deletions .github/workflows/release.yml
Original file line number Diff line number Diff line change
Expand Up @@ -82,9 +82,6 @@ jobs:
- name: Generate stats-dapp codegen
run: yarn gql:codegen

- name: Fetch the on-chain anchors data
run: yarn fetch:onChainConfig

- name: build
run: yarn nx run-many --all --target=build

Expand Down
1 change: 1 addition & 0 deletions apps/bridge-dapp/postcss.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ const { join } = require('path');

module.exports = {
plugins: {
'postcss-preset-env': {},
'postcss-import': {},
tailwindcss: {
config: join(__dirname, 'tailwind.config.js'),
Expand Down
26 changes: 16 additions & 10 deletions apps/bridge-dapp/scripts/localSubstrate.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,7 @@
* -v --verbose: Enable node logging
*/

import { ApiPromise, WsProvider } from '@polkadot/api';
import { LocalProtocolSubstrate } from '@webb-tools/test-utils';
import { ApiPromise } from '@polkadot/api';
import { BN } from 'bn.js';
import chalk from 'chalk';
import { Command } from 'commander';
Expand All @@ -27,8 +26,8 @@ import addAssetMetadata from './utils/addAssetMetadata';
import addAssetToPool from './utils/addAssetToPool';
import createPoolShare from './utils/createPoolShare';
import createVAnchor from './utils/createVAnchor';
import getLocalApi from './utils/getLocalApi';
import getKeyring from './utils/getKeyRing';
import getLocalApi from './utils/getLocalApi';
import transferAsset from './utils/transferAsset';

// Load env variables
Expand Down Expand Up @@ -66,28 +65,28 @@ async function main() {
// Start the nodes
console.log(chalk.blue('Starting local substrate protocol...'));

const aliceNode = await LocalProtocolSubstrate.start({
/* await LocalProtocolSubstrate.start({
name: 'substrate-alice',
authority: 'alice',
usageMode,
ports: 'auto',
enableLogging: options.verbose,
});
const _bobNode = await LocalProtocolSubstrate.start({
await LocalProtocolSubstrate.start({
name: 'substrate-bob',
authority: 'bob',
usageMode,
ports: 'auto',
enableLogging: options.verbose,
});
}); */

// Wait until we are ready and connected
console.log(chalk.blue('Waiting for API to be ready...'));

const aliceApi = await getLocalApi(ALICE_PORT);

console.log(chalk`=> {green.bold API are ready!}`);
console.log(chalk`=> {green.bold API is ready!}`);

await initPoolShare(aliceApi);
}
Expand Down Expand Up @@ -151,8 +150,15 @@ async function initPoolShare(api: ApiPromise) {
chalk` => {green Token transferred to test account with hash \`${hash}\`}`
);
}

console.log(chalk.green.bold('✅ Protocol Substrate ready to use!!!'));
}

main().catch(console.error);
main()
.then(() => {
console.log(chalk.green.bold('✅ Protocol Substrate ready to use!!!'));
process.exit(0);
})
.catch((error) => {
console.log(chalk.red.bold('❌ Protocol Substrate failed to start!!!'));
console.log(error);
process.exit(1);
});
1 change: 1 addition & 0 deletions apps/bridge-dapp/scripts/localTangle.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ import getLocalApi from './utils/getLocalApi';
import getKeyring from './utils/getKeyRing';
import transferAsset from './utils/transferAsset';

// TODO: Replace this lib with `execa`
// eslint-disable-next-line @typescript-eslint/no-var-requires
const shelljs = require('shelljs');

Expand Down
33 changes: 7 additions & 26 deletions apps/bridge-dapp/webpack.base.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,15 +11,13 @@ const CopyWebpackPlugin = require('copy-webpack-plugin');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const webpack = require('webpack');
const TerserPlugin = require('terser-webpack-plugin');
const { commandSync } = require('execa');
const { workspaceRoot } = require('nx/src/utils/workspace-root');

const findPackages = require('../../tools/scripts/findPackages');
const { ON_CHAIN_CONFIG_PATH } = require('../../tools/scripts/constants');
const packageJson = require(path.resolve(__dirname, 'package.json'));
const packageVersion = packageJson.version;

const onChainCfgPath = path.resolve(workspaceRoot, ON_CHAIN_CONFIG_PATH);

function mapChunks(name, regs, inc) {
return regs.reduce(
(result, test, index) => ({
Expand All @@ -36,19 +34,12 @@ function mapChunks(name, regs, inc) {
}

function createWebpack(env, mode = 'production') {
if (!fs.existsSync(onChainCfgPath)) {
throw new Error(
`Please run \`${chalk.cyan.bold.underline(
'yarn fetch:onChainConfig'
)}\` first. Missing on-chain config at ${onChainCfgPath}.`
);
} else {
console.log(
`Found on-chain config at ${onChainCfgPath}. Using it to generate the on-chain config.`
);
}
commandSync('yarn fetch:onChainConfig', {
cwd: workspaceRoot,
stdio: 'inherit',
});

console.log('Running webpack in: ', mode);
console.log(chalk.cyan('Running webpack in: ', mode));
const isDevelopment = mode === 'development';
const alias = findPackages().reduce((alias, { dir, name }) => {
alias[name] = path.resolve(__dirname, `../../libs/${dir}/src`);
Expand Down Expand Up @@ -107,24 +98,14 @@ function createWebpack(env, mode = 'production') {
sourceMap: isDevelopment,
},
},
{
// process tailwind stuff
// https://webpack.js.org/loaders/postcss-loader/
loader: 'postcss-loader',
options: {
sourceMap: isDevelopment,
postcssOptions: {
plugins: [require('tailwindcss')],
},
},
},
{
// load sass files into css files
loader: 'sass-loader',
options: {
sourceMap: isDevelopment,
},
},
'postcss-loader',
],
},
{
Expand Down
3 changes: 1 addition & 2 deletions apps/bridge-dapp/webpack.dev.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@ const path = require('path');
const { merge } = require('webpack-merge');

const baseConfig = require('./webpack.base.js');
const isDevelopment = process.env.NODE_ENV !== 'production';

module.exports = (env, config) => {
env.context = __dirname;
Expand All @@ -32,7 +31,7 @@ module.exports = (env, config) => {
inject: true,
template: './src/public/index.html',
}),
isDevelopment && new ReactRefreshWebpackPlugin(),
new ReactRefreshWebpackPlugin(),
],
watchOptions: {
// 5.66.0 work-around (was reduced to 20, then started failing)
Expand Down
7 changes: 0 additions & 7 deletions apps/webbsite/.env.example

This file was deleted.

4 changes: 1 addition & 3 deletions libs/abstract-api-provider/src/utils/utxoFromVAnchorNote.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,9 +24,7 @@ async function utxoFromVAnchorNote(note: JsNote, leafIndex = 0): Promise<Utxo> {
keypair,
};

return input.backend === 'Arkworks'
? Utxo.generateUtxo(input)
: CircomUtxo.generateUtxo(input);
return CircomUtxo.generateUtxo(input);
}

export default utxoFromVAnchorNote;
6 changes: 6 additions & 0 deletions libs/abstract-api-provider/src/webb-provider.interface.ts
Original file line number Diff line number Diff line change
Expand Up @@ -253,6 +253,12 @@ export interface WebbApiProvider<T> extends EventBus<WebbProviderEvents> {
provider?: providers.Provider | ApiPromise
) => Promise<number>;

// get vanchor levels
getVAnchorLevels: (
vAnchorAddressOrTreeId: string,
providerOrApi?: providers.Provider | ApiPromise
) => Promise<number>;

// generate utxo
generateUtxo: (input: UtxoGenInput) => Promise<Utxo>;
}
2 changes: 1 addition & 1 deletion libs/abstract-api-provider/tsconfig.lib.json
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,6 @@
"declaration": true,
"types": ["node"]
},
"include": ["**/*.ts"],
"include": ["**/*.ts", "../../types/**/*.d.ts"],
"exclude": ["jest.config.ts", "**/*.spec.ts", "**/*.test.ts"]
}
8 changes: 8 additions & 0 deletions libs/api-provider-environment/project.json
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,14 @@
"main": "libs/api-provider-environment/src/index.ts",
"tsConfig": "libs/api-provider-environment/tsconfig.lib.json",
"assets": ["libs/api-provider-environment/*.md"]
},
"dependsOn": ["fetch-on-chain-config", "^build"]
},
"fetch-on-chain-config": {
"executor": "nx:run-commands",
"options": {
"command": "yarn fetch:onChainConfig",
"color": true
}
},
"lint": {
Expand Down
3 changes: 0 additions & 3 deletions libs/api-provider-environment/src/types.ts

This file was deleted.

2 changes: 1 addition & 1 deletion libs/api-provider-environment/tsconfig.lib.json
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,6 @@
"declaration": true,
"types": ["node"]
},
"include": ["**/*.ts"],
"include": ["**/*.ts", "../../types/**/*.d.ts"],
"exclude": ["jest.config.ts", "**/*.spec.ts", "**/*.test.ts"]
}
5 changes: 5 additions & 0 deletions libs/dapp-config/src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,3 +42,8 @@ export interface AnchorMetadata {
*/
linkableAnchor: Record<string, string>;
}

export type ConfigType = Record<
number,
{ nativeCurrency: ICurrency; anchorMetadatas: AnchorMetadata[] }
>;
12 changes: 10 additions & 2 deletions libs/dapp-types/src/WebbError.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,10 +41,12 @@ export enum WebbErrorCodes {
ChainIdTypeUnformatted,
// Invalid amount to withdraw,
AmountToWithdrawExceedsTheDepositedAmount,
// Transaction is cancelled
/// Transaction is cancelled
TransactionCancelled,
// There is a transaction in progress
/// There is a transaction in progress
TransactionInProgress,
/// The tree not found
TreeNotFound,
// Insufficient disk space
InsufficientDiskSpace,
}
Expand Down Expand Up @@ -216,6 +218,12 @@ export class WebbError extends Error {
message: `No currency is available`,
};

case WebbErrorCodes.TreeNotFound:
return {
code,
message: `The tree not found`,
};

case WebbErrorCodes.InsufficientDiskSpace:
return {
code,
Expand Down
4 changes: 1 addition & 3 deletions libs/note-manager/src/note-manager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -376,9 +376,7 @@ export class NoteManager {
};

// Convert the amount to units of wei
const utxo = await (backend == 'Arkworks'
? Utxo.generateUtxo(input)
: CircomUtxo.generateUtxo(input));
const utxo = await CircomUtxo.generateUtxo(input);

const noteInput: NoteGenInput = {
...this.defaultNoteGenInput,
Expand Down
42 changes: 42 additions & 0 deletions libs/polkadot-api-provider/src/types.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
import { HexString } from '@polkadot/util/types';

export interface IVAnchorPublicInputs {
proof: HexString;
roots: HexString[];
inputNullifiers: HexString[];
outputCommitments: [HexString, HexString];
publicAmount: HexString;
extDataHash: HexString;
}

export interface Groth16Proof {
proof: {
pi_a: string[];
pi_b: string[][];
pi_c: string[];
curve: string;
prococol: 'groth16';
};
publicSignals: string[];
}

export interface VAnchorGroth16ProofInput {
roots: bigint[];
chainID: bigint;
inputNullifier: bigint[];
outputCommitment: bigint[];
publicAmount: bigint;
extDataHash: bigint;

inAmount: bigint[];
inPrivateKey: bigint[];
inBlinding: bigint[];
inPathIndices: bigint[];
inPathElements: bigint[][];

// data for 2 transaction outputs
outChainID: bigint[];
outAmount: bigint[];
outPubkey: bigint[];
outBlinding: bigint[];
}
11 changes: 11 additions & 0 deletions libs/polkadot-api-provider/src/utils/ensureHex.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import { HexString } from '@polkadot/util/types';

const ensureHex = (maybeHex: string): HexString => {
if (maybeHex.startsWith('0x')) {
return maybeHex as `0x${string}`;
}

return `0x${maybeHex}`;
};

export default ensureHex;
20 changes: 20 additions & 0 deletions libs/polkadot-api-provider/src/utils/getVAnchorExtDataHash.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import { IVariableAnchorExtData } from '@webb-tools/interfaces';
import { FIELD_SIZE } from '@webb-tools/sdk-core';
import { ethers } from 'ethers';
import ensureHex from './ensureHex';

const getVAnchorExtDataHash = (extData: IVariableAnchorExtData): bigint => {
const abi = new ethers.utils.AbiCoder();
const encodedData = abi.encode(
[
'(bytes recipient,int256 extAmount,bytes relayer,uint256 fee,uint256 refund,bytes token,bytes encryptedOutput1,bytes encryptedOutput2)',
],
[extData]
);

const hash = ethers.utils.keccak256(encodedData);

return BigInt(ensureHex(hash)) % FIELD_SIZE.toBigInt();
};

export default getVAnchorExtDataHash;
Loading

0 comments on commit ec51b7b

Please sign in to comment.