Skip to content

Commit

Permalink
Browse files Browse the repository at this point in the history
…into smr-2859-auto-gasMultiplier
  • Loading branch information
Benjimmutable committed Jun 3, 2024
2 parents 5601f17 + 9579ae4 commit 8275113
Show file tree
Hide file tree
Showing 330 changed files with 92,278 additions and 2,843 deletions.
4 changes: 3 additions & 1 deletion .eslintignore
Original file line number Diff line number Diff line change
Expand Up @@ -14,5 +14,7 @@ jest.*.js
# sample apps
**sample-app**/
**playground**/
samples/apps/passport/
samples/**/*

# put module specific ignore paths here
# put module specific ignore paths here
1 change: 1 addition & 0 deletions .eslintrc
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
"rollup.config.*",
"node_modules/",
"dist/",
"samples/",
"**sample-app**/",
"**playground**/"
],
Expand Down
38 changes: 38 additions & 0 deletions .github/workflows/detect-node-version-change.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
name: Detect Node Engine Version Change

on:
pull_request:
branches:
- main
merge_group:
branches:
- main

jobs:
detect:
name: Detect Node engine version change
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v3

- name: Get Node engine version from package.json
id: get_package_json_node_engine_version
run: |
node_engine_major_version=$(jq -r '.engines.node' ./sdk/package.json | sed 's/^>=//' | cut -d. -f1)
echo "::set-output name=node_engine_major_version::$node_engine_major_version"
- name: Get Node.js version from .nvmrc
id: get_nvmrc_node_version
run: echo "::set-output name=nvmrc_node_version::$(head -n 1 .nvmrc | cut -d. -f1)"

- name: Check Node.js engine version change
run: |
package_version_major=$(echo "${{ steps.get_package_json_node_engine_version.outputs.node_engine_major_version }}")
nvmrc_version_major=$(echo "${{ steps.get_nvmrc_node_version.outputs.nvmrc_node_version }}")
if [ "$package_version_major" != "$nvmrc_version_major" ]; then
echo "Node.js engine version has changed"
exit 1
else
echo "Node.js engine version has not changed"
fi
2 changes: 1 addition & 1 deletion .github/workflows/secret-scan.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ jobs:
- uses: actions/checkout@v3
with:
fetch-depth: 0
- uses: gitleaks/gitleaks-action@v2
- uses: gitleaks/gitleaks-action@v2.3.4
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
GITLEAKS_LICENSE: ${{ secrets.GITLEAKS_LICENSE }}
2 changes: 1 addition & 1 deletion .nvmrc
Original file line number Diff line number Diff line change
@@ -1 +1 @@
lts/*
20
2 changes: 2 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
"eslint": "^8.40.0",
"eslint-config-airbnb": "^19.0.4",
"eslint-config-airbnb-typescript": "^17.0.0",
"eslint-plugin-react-refresh": "latest",
"http-server": "^14.1.1",
"husky": "^8.0.3",
"lint-staged": "^13.2.0",
Expand Down Expand Up @@ -43,6 +44,7 @@
"scripts": {
"build": "NODE_OPTIONS=--max-old-space-size=14366 wsrun -y 4 -p @imtbl/sdk -p @imtbl/checkout-widgets -e -r --serial build && yarn syncpack:format && yarn wsrun -p @imtbl/sdk -a -m copyBrowserBundles",
"build:onlysdk": "NODE_OPTIONS=--max-old-space-size=14366 wsrun -y 4 -p @imtbl/sdk --stages build && yarn syncpack:format",
"dev": "wsrun --parallel --exclude-missing dev",
"docs:build": "typedoc",
"docs:serve": "http-server ./docs --cors -p 8080 -c-1",
"lint": "wsrun --exclude-missing -e lint --no-error-on-unmatched-pattern",
Expand Down
1 change: 1 addition & 0 deletions packages/blockchain-data/sdk/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@
"repository": "immutable/ts-immutable-sdk.git",
"scripts": {
"build": "NODE_ENV=production rollup --config rollup.config.js",
"dev": "rollup --config rollup.config.js -w",
"generate-types": "typechain --target=ethers-v5 --out-dir=src/typechain/types 'abi/*.json'",
"lint": "eslint ./src --ext .ts,.jsx,.tsx --max-warnings=0",
"test": "jest",
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import { useEffect } from "react";
import { passport } from "../passport";

export function PassportLoginCallback() {
useEffect(() => {
passport?.loginCallback();
}, [passport])
return(<></>);
}
7 changes: 7 additions & 0 deletions packages/checkout/sdk-sample-app/src/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,9 @@ import ConnectWidget from './pages/ConnectWidget';
import { onLightBase } from '@biom3/design-tokens';
import { BiomeCombinedProviders, Box } from '@biom3/react';
import SmartCheckout from './pages/SmartCheckout';
import {
PassportLoginCallback
} from "./components/PassportLoginCallback";

const router = createBrowserRouter([
{
Expand All @@ -22,6 +25,10 @@ const router = createBrowserRouter([
path: '/smart-checkout',
element: <SmartCheckout />,
},
{
path: '/login/callback',
element: <PassportLoginCallback />
},
]);

const root = ReactDOM.createRoot(
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import { useEffect } from 'react';
import { passport } from '../passport';

export function PassportLoginCallback() {
useEffect(() => {
passport?.loginCallback();
}, [passport])
return(<></>);
}
1 change: 1 addition & 0 deletions packages/checkout/sdk/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,7 @@
"scripts": {
"build": "rollup --config rollup.config.js",
"build:dev": "CHECKOUT_DEV_MODE=true yarn build",
"dev": "CHECKOUT_DEV_MODE=true rollup --config rollup.config.js -w",
"docs": "typedoc --plugin typedoc-plugin-markdown --skipErrorChecking --disableSources --out docs src/index.ts",
"lint": "eslint ./src --ext .ts,.jsx,.tsx --max-warnings=0",
"lint:fix": "eslint ./src --ext .ts,.jsx,.tsx --max-warnings=0 --fix",
Expand Down
1 change: 1 addition & 0 deletions packages/checkout/sdk/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ export { IMMUTABLE_API_BASE_URL } from './env';
export {
getPassportProviderDetail,
getMetaMaskProviderDetail,
validateProvider,
} from './provider';

export {
Expand Down
70 changes: 66 additions & 4 deletions packages/checkout/sdk/src/provider/getUnderlyingProvider.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,23 @@ import { WalletAction } from '../types/wallet';
import { CheckoutErrorType } from '../errors';

describe('getUnderlyingChainId', () => {
it('should return the underlying chain id', async () => {
it('should return underlying chain id from property', async () => {
const provider = {
provider: {
request: jest.fn().mockResolvedValue('0xAA36A7'),
chainId: ChainId.SEPOLIA,
request: jest.fn(),
},
} as unknown as Web3Provider;

const chainId = await getUnderlyingChainId(provider);
expect(chainId).toEqual(ChainId.SEPOLIA);
expect(provider.provider.request).not.toBeCalled();
});

it('should return the underlying chain id from rpc call', async () => {
const provider = {
provider: {
request: jest.fn().mockResolvedValue('0xaa36a7'),
},
} as unknown as Web3Provider;

Expand All @@ -20,11 +33,35 @@ describe('getUnderlyingChainId', () => {
});
});

it('should properly parse chain id', async () => {
const intChainId = 13473;
const strChainId = intChainId.toString();
const hexChainId = `0x${intChainId.toString(16)}`;
const getMockProvider = (chainId: unknown) => ({ provider: { chainId } } as unknown as Web3Provider);

// Number
expect(await getUnderlyingChainId(getMockProvider(intChainId))).toEqual(
intChainId,
);

// String to Number
expect(await getUnderlyingChainId(getMockProvider(strChainId))).toEqual(
intChainId,
);

// Hex to Number
expect(await getUnderlyingChainId(getMockProvider(hexChainId))).toEqual(
intChainId,
);
});

it('should throw an error if provider missing from web3provider', async () => {
try {
await getUnderlyingChainId({} as Web3Provider);
} catch (err: any) {
expect(err.message).toEqual('Parsed provider is not a valid Web3Provider');
expect(err.message).toEqual(
'Parsed provider is not a valid Web3Provider',
);
expect(err.type).toEqual(CheckoutErrorType.WEB3_PROVIDER_ERROR);
}
});
Expand All @@ -33,8 +70,33 @@ describe('getUnderlyingChainId', () => {
try {
await getUnderlyingChainId({ provider: {} } as Web3Provider);
} catch (err: any) {
expect(err.message).toEqual('Parsed provider is not a valid Web3Provider');
expect(err.message).toEqual(
'Parsed provider is not a valid Web3Provider',
);
expect(err.type).toEqual(CheckoutErrorType.WEB3_PROVIDER_ERROR);
}
});

it('should throw an error if invalid chain id value from property', async () => {
const provider = {
provider: {
chainId: 'invalid',
request: jest.fn(),
},
} as unknown as Web3Provider;

expect(provider.provider.request).not.toHaveBeenCalled();
expect(getUnderlyingChainId(provider)).rejects.toThrow('Invalid chainId');
});

it('should throw an error if invalid chain id value returned from rpc call ', async () => {
const provider = {
provider: {
request: jest.fn().mockResolvedValue('invalid'),
},
} as unknown as Web3Provider;

expect(getUnderlyingChainId(provider)).rejects.toThrow('Invalid chainId');
expect(provider.provider.request).toHaveBeenCalled();
});
});
43 changes: 39 additions & 4 deletions packages/checkout/sdk/src/provider/getUnderlyingProvider.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,18 +4,53 @@ import { Web3Provider } from '@ethersproject/providers';
import { CheckoutError, CheckoutErrorType } from '../errors';
import { WalletAction } from '../types';

// this gives us access to the properties of the underlying provider object
export async function getUnderlyingChainId(web3Provider: Web3Provider) {
const parseChainId = (chainId: unknown): number => {
if (typeof chainId === 'number') {
return chainId;
}

if (typeof chainId === 'string' && !Number.isNaN(Number(chainId))) {
return chainId.startsWith('0x') ? parseInt(chainId, 16) : Number(chainId);
}

throw new CheckoutError(
'Invalid chainId',
CheckoutErrorType.WEB3_PROVIDER_ERROR,
);
};

/**
* Get chain id from RPC method
* @param web3Provider
* @returns chainId number
*/
async function requestChainId(web3Provider: Web3Provider): Promise<number> {
if (!web3Provider.provider?.request) {
throw new CheckoutError(
'Parsed provider is not a valid Web3Provider',
CheckoutErrorType.WEB3_PROVIDER_ERROR,
);
}

const chainId = await web3Provider.provider.request({
const chainId: string = await web3Provider.provider.request({
method: WalletAction.GET_CHAINID,
params: [],
});
return parseInt(chainId, 16);

return parseChainId(chainId);
}

/**
* Get the underlying chain id from the provider
* @param web3Provider
* @returns chainId number
*/
export async function getUnderlyingChainId(web3Provider: Web3Provider): Promise<number> {
const chainId = (web3Provider.provider as any)?.chainId;

if (chainId) {
return parseChainId(chainId);
}

return requestChainId(web3Provider);
}
7 changes: 6 additions & 1 deletion packages/checkout/sdk/src/smartCheckout/buy/buy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import {
OrderStatusName,
} from '@imtbl/orderbook';
import { GetTokenResult } from '@imtbl/generated-clients/dist/multi-rollup';
import { track } from '@imtbl/metrics';
import * as instance from '../../instance';
import { CheckoutConfiguration, getL1ChainId, getL2ChainId } from '../../config';
import { CheckoutError, CheckoutErrorType } from '../../errors';
Expand Down Expand Up @@ -92,6 +93,8 @@ export const buy = async (
waitFulfillmentSettlements: true,
},
): Promise<BuyResult> => {
track('checkout_sdk', 'buy_initiated');

if (orders.length === 0) {
throw new CheckoutError(
'No orders were provided to the orders array. Please provide at least one order.',
Expand Down Expand Up @@ -166,7 +169,9 @@ export const buy = async (

let fees: FeeValue[] = [];
if (takerFees && takerFees.length > 0) {
fees = calculateFees(takerFees, buyToken.amount, decimals);
// eslint-disable-next-line max-len
const tokenQuantity = order.result.sell[0].type === ItemType.ERC721 ? BigNumber.from(1) : BigNumber.from(order.result.sell[0].amount);
fees = calculateFees(takerFees, buyToken.amount, decimals, tokenQuantity);
}

let unsignedApprovalTransactions: TransactionRequest[] = [];
Expand Down
18 changes: 17 additions & 1 deletion packages/checkout/sdk/src/smartCheckout/fees/fees.test.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { utils } from 'ethers';
import { BigNumber, utils } from 'ethers';
import { calculateFees } from './fees';
import { BuyToken, ItemType } from '../../types';
import { CheckoutErrorType } from '../../errors';
Expand Down Expand Up @@ -94,6 +94,22 @@ describe('orderbook fees', () => {
}]);
});

it('TD-1453 sell token quantity > 1 and non divisible fee amount', async () => {
const decimals = 18;
const amount = utils.parseUnits('40.32258064516129033', 18).toString();
const makerFees = [{
amount: { percentageDecimal: 0.01 },
recipient: '0x222',
}];

const result = calculateFees(makerFees, amount, decimals, BigNumber.from(10));

expect(result).toEqual([{
amount: '403225806451612900',
recipientAddress: '0x222',
}]);
});

it('should calculate the fees with multiple percentageDecimals', async () => {
const decimals = 18;
const amount = utils.parseUnits('10', 18).toString();
Expand Down
Loading

0 comments on commit 8275113

Please sign in to comment.