Skip to content
This repository has been archived by the owner on Feb 23, 2024. It is now read-only.

Commit

Permalink
feat: update to work with bigints from new fuels-ts (#96)
Browse files Browse the repository at this point in the history
  • Loading branch information
luizstacio authored May 17, 2022
1 parent 0fd3661 commit efe9857
Show file tree
Hide file tree
Showing 15 changed files with 2,550 additions and 2,337 deletions.
10 changes: 5 additions & 5 deletions client/deploy-contracts/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,15 +15,15 @@ import {
import path from 'path';
import fs from 'fs';
// @ts-ignore
import { SwayswapContractAbi__factory, TokenContractAbi__factory } from '../src/types/contracts';
import { ExchangeContractAbi__factory, TokenContractAbi__factory } from '../src/types/contracts';

const tokenPath = path.join(
__dirname,
'../../contracts/token_contract/out/debug/token_contract.bin'
);
const contractPath = path.join(
__dirname,
'../../contracts/swayswap_contract/out/debug/swayswap_contract.bin'
'../../contracts/exchange_contract/out/debug/exchange_contract.bin'
);
const providerUrl = process.env.REACT_APP_FUEL_PROVIDER_URL || 'https://node.swayswap.io/graphql';

Expand All @@ -38,10 +38,10 @@ export const seedWallet = async (wallet: Wallet) => {
transactionRequest.addCoin({
id: '0x000000000000000000000000000000000000000000000000000000000000000000',
assetId: NativeAssetId,
amount: parseUnits('.5', 9),
amount: parseUnits('.5', 9).toBigInt(),
owner: '0xf1e92c42b90934aa6372e30bc568a326f6e66a1a0288595e6e3fbd392a4f3e6e',
});
transactionRequest.addCoinOutput(wallet.address, parseUnits('.5', 9), NativeAssetId);
transactionRequest.addCoinOutput(wallet.address, parseUnits('.5', 9).toBigInt(), NativeAssetId);
const submit = await wallet.sendTransaction(transactionRequest);

return submit.wait();
Expand Down Expand Up @@ -71,7 +71,7 @@ export async function deployContract(contextLog: string, binaryPath: string, abi
const contract = await deployContract(
'SwaySwap',
contractPath,
SwayswapContractAbi__factory.abi
ExchangeContractAbi__factory.abi
);
const token = await deployContract('Token', tokenPath, TokenContractAbi__factory.abi);

Expand Down
4 changes: 2 additions & 2 deletions client/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@
"classnames": "^2.3.1",
"clipboard": "^2.0.11",
"ethers": "^5.5.4",
"fuels": "^0.0.0-master-e10c317d",
"fuels": "^0.0.0-master-d5e02003",
"react": "^18.1.0",
"react-dom": "^18.1.0",
"react-error-boundary": "^3.1.4",
Expand Down Expand Up @@ -70,6 +70,6 @@
"prettier-plugin-tailwindcss": "^0.1.8",
"tailwindcss": "^3.0.23",
"typechain": "^8.0.0",
"typechain-target-fuels": "^0.0.0-master-e10c317d"
"typechain-target-fuels": "^0.0.0-master-d5e02003"
}
}
6 changes: 3 additions & 3 deletions client/scripts/build-contracts.sh
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
#!/bin/sh

CLIENT_DIR=$(realpath ../)
SWAYSWAP_CONTRACT=$CLIENT_DIR/contracts/swayswap_contract
EXCHANGE_CONTRACT=$CLIENT_DIR/contracts/exchange_contract
TOKEN_CONTRACT=$CLIENT_DIR/contracts/token_contract

echo $SWAYSWAP_CONTRACT
echo $EXCHANGE_CONTRACT
echo $TOKEN_CONTRACT

echo "Build SwaySwap contract"
forc build -p $SWAYSWAP_CONTRACT
forc build -p $EXCHANGE_CONTRACT
echo "Build Token contract"
forc build -p $TOKEN_CONTRACT
echo "Build Types for contract"
Expand Down
15 changes: 8 additions & 7 deletions client/src/components/CoinInput.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
import { Menu, Transition } from "@headlessui/react";
import classNames from "classnames";
import { formatUnits, parseUnits } from "ethers/lib/utils";
import { BigNumber } from "fuels";
import { useCallback } from "react";
import { useEffect } from "react";
import { Fragment, useState } from "react";
Expand Down Expand Up @@ -149,10 +148,10 @@ export function CoinInput({
onInput,
}: {
disabled?: boolean;
amount?: BigNumber | null;
amount?: bigint | null;
coin?: Coin | null;
coins?: Coin[];
onChangeAmount?: (value: BigNumber | null) => void;
onChangeAmount?: (value: bigint | null) => void;
onChangeCoin?: (value: Coin) => void;
onInput?: (...args: any) => void;
}) {
Expand All @@ -162,11 +161,13 @@ export function CoinInput({
<NumberFormat
placeholder="0"
decimalScale={DECIMAL_UNITS}
value={amount && formatUnits(amount, DECIMAL_UNITS)}
value={amount ? formatUnits(amount, DECIMAL_UNITS) : ''}
displayType={disabled ? "text" : "input"}
onValueChange={(e) =>
onChangeAmount?.(e.value !== "" ? parseUnits(e.value, DECIMAL_UNITS) : null)
}
onValueChange={(e) => {
onChangeAmount?.(
e.value !== "" ? parseUnits(e.value, DECIMAL_UNITS).toBigInt() : null
)
}}
className={style.transferPropInput}
thousandSeparator={false}
onInput={onInput}
Expand Down
8 changes: 4 additions & 4 deletions client/src/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,8 @@ export const FUEL_FAUCET_URL =
export const CONTRACT_ID = process.env.REACT_APP_CONTRACT_ID!;
export const TOKEN_ID = process.env.REACT_APP_TOKEN_ID!;
export const DECIMAL_UNITS = 3;
export const FAUCET_AMOUNT = parseUnits('0.5', DECIMAL_UNITS);
export const MINT_AMOUNT = parseUnits('2000', DECIMAL_UNITS);
export const ONE_ASSET = parseUnits('1', DECIMAL_UNITS).toNumber();
export const FAUCET_AMOUNT = parseUnits('0.5', DECIMAL_UNITS).toBigInt();
export const MINT_AMOUNT = parseUnits('2000', DECIMAL_UNITS).toBigInt();
export const ONE_ASSET = parseUnits('1', DECIMAL_UNITS).toBigInt();
export const RECAPTCHA_SITE_KEY = process.env.REACT_APP_RECAPTCHA_SITE_KEY!;
export const ENABLE_FAUCET_API = Boolean(process.env.REACT_APP_ENABLE_FAUCET_API)!;
export const ENABLE_FAUCET_API = process.env.REACT_APP_ENABLE_FAUCET_API === "true";
16 changes: 9 additions & 7 deletions client/src/context/AppContext.tsx
Original file line number Diff line number Diff line change
@@ -1,20 +1,20 @@
import React, { PropsWithChildren, useContext, useMemo } from "react";
import { Wallet, ScriptTransactionRequest, TransactionResult } from "fuels";
import { Wallet, ScriptTransactionRequest, TransactionResult, CoinStatus, toBigInt } from "fuels";
import { CoinETH } from "src/lib/constants";
import { randomBytes } from "ethers/lib/utils";
import { CONTRACT_ID, FAUCET_AMOUNT, FUEL_PROVIDER_URL } from "src/config";
import { atom, useRecoilState } from "recoil";
import { persistEffect } from "src/lib/recoilEffects";
import {
SwayswapContractAbi,
SwayswapContractAbi__factory,
ExchangeContractAbi,
ExchangeContractAbi__factory,
} from "src/types/contracts";

interface AppContextValue {
wallet: Wallet | null;
contract: SwayswapContractAbi | null;
contract: ExchangeContractAbi | null;
createWallet: () => void;
faucet: () => Promise<TransactionResult>;
faucet: () => Promise<TransactionResult<'success'>>;
}

const walletPrivateKeyState = atom<string | null>({
Expand Down Expand Up @@ -47,7 +47,7 @@ export const AppContextProvider = ({ children }: PropsWithChildren<{}>) => {

const contract = useMemo(() => {
if (!wallet) return null;
return SwayswapContractAbi__factory.connect(CONTRACT_ID, wallet);
return ExchangeContractAbi__factory.connect(CONTRACT_ID, wallet);
}, [wallet]);

return (
Expand All @@ -69,13 +69,15 @@ export const AppContextProvider = ({ children }: PropsWithChildren<{}>) => {
script: "0x24400000",
scriptData: randomBytes(32),
});
// @ts-ignore
transactionRequest.addCoin({
id: "0x000000000000000000000000000000000000000000000000000000000000000000",
assetId: CoinETH,
amount: FAUCET_AMOUNT,
owner:
"0xf1e92c42b90934aa6372e30bc568a326f6e66a1a0288595e6e3fbd392a4f3e6e",
status: CoinStatus.Unspent,
maturity: toBigInt(0),
blockCreated: toBigInt(0)
});
transactionRequest.addCoinOutput(
wallet!.address,
Expand Down
19 changes: 6 additions & 13 deletions client/src/pages/PoolPage.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import classNames from "classnames";
import { BigNumber } from "fuels";
import { useState } from "react";
import { RiCheckFill } from "react-icons/ri";
import { useContract } from "src/context/AppContext";
Expand Down Expand Up @@ -63,8 +62,8 @@ export default function PoolPage() {
assets[0],
assets[1],
]);
const [fromAmount, setFromAmount] = useState(null as BigNumber | null);
const [toAmount, setToAmount] = useState(null as BigNumber | null);
const [fromAmount, setFromAmount] = useState(null as bigint | null);
const [toAmount, setToAmount] = useState(null as bigint | null);
const [stage, setStage] = useState(0);
const { data: poolInfo } = useQuery("PoolPage-poolInfo", () =>
contract.callStatic.get_info()
Expand Down Expand Up @@ -164,21 +163,15 @@ export default function PoolPage() {
<br />
DAI:{" "}
{formatUnits(poolInfo.token_reserve, DECIMAL_UNITS).toString()}
{BigNumber.from(poolInfo.eth_reserve).gt(0) &&
BigNumber.from(poolInfo.token_reserve).gt(0) ? (
{poolInfo.eth_reserve > 0 &&
poolInfo.token_reserve > 0 ? (
<>
<br />
ETH/DAI:{" "}
{BigNumber.from(ONE_ASSET)
.mul(poolInfo.eth_reserve)
.div(poolInfo.token_reserve)
.toNumber() / ONE_ASSET}
{((ONE_ASSET * poolInfo.eth_reserve)/poolInfo.token_reserve)/ONE_ASSET}
<br />
DAI/ETH:{" "}
{BigNumber.from(ONE_ASSET)
.mul(poolInfo.token_reserve)
.div(poolInfo.eth_reserve)
.toNumber() / ONE_ASSET}
{((ONE_ASSET * poolInfo.token_reserve)/poolInfo.eth_reserve)/ONE_ASSET}
</>
) : null}
</div>
Expand Down
7 changes: 3 additions & 4 deletions client/src/pages/RemoveLiquidityPage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ import { useContract, useWallet } from "src/context/AppContext";
import coins from "src/lib/CoinsMetadata";
import { CoinInput } from "src/components/CoinInput";
import { useNavigate } from "react-router-dom";
import { BigNumber } from "fuels";
import { Pages } from "src/types/pages";
import { CONTRACT_ID, DECIMAL_UNITS } from "src/config";
import { useMutation, useQuery } from "react-query";
Expand All @@ -20,7 +19,7 @@ const style = {

export default function RemoveLiquidityPage() {
const liquidityToken = coins.find((c) => c.assetId === CONTRACT_ID);
const [amount, setAmount] = useState(null as BigNumber | null);
const [amount, setAmount] = useState(null as bigint | null);
const wallet = useWallet()!;
const contract = useContract()!;
const navigate = useNavigate();
Expand All @@ -39,7 +38,7 @@ export default function RemoveLiquidityPage() {
if (!amount) {
throw new Error('"amount" is required');
}
if (amount?.gt(balance!)) {
if (amount > (balance || 0)) {
alert("Amount is bigger them the current balance!");
}

Expand Down Expand Up @@ -86,7 +85,7 @@ export default function RemoveLiquidityPage() {
disabled={
!amount ||
!balance ||
amount.gt(balance) ||
amount > balance ||
removeLiquidityMutation.isLoading
}
>
Expand Down
22 changes: 9 additions & 13 deletions client/src/pages/SwapPage.tsx
Original file line number Diff line number Diff line change
@@ -1,11 +1,9 @@
import { useState } from "react";
import { RiSettings3Fill } from "react-icons/ri";
import assets from "src/lib/CoinsMetadata";
import { Coin, CoinInput } from "src/components/CoinInput";
import { InvertButton } from "src/components/InvertButton";
import { useContract } from "src/context/AppContext";
import { SwayswapContractAbi } from "src/types/contracts";
import { BigNumber } from "fuels";
import { ExchangeContractAbi } from "src/types/contracts";
import { useNavigate } from "react-router-dom";
import { Pages } from "src/types/pages";
import { useMutation, useQuery } from "react-query";
Expand All @@ -21,9 +19,9 @@ const style = {
};

const getSwapWithMaximumRequiredAmount = async (
contract: SwayswapContractAbi,
contract: ExchangeContractAbi,
assetId: string,
amount: BigNumber
amount: bigint
) => {
const requiredAmount = await contract.callStatic.get_swap_with_maximum(
amount,
Expand All @@ -35,9 +33,9 @@ const getSwapWithMaximumRequiredAmount = async (
};

const getSwapWithMinimumMinAmount = async (
contract: SwayswapContractAbi,
contract: ExchangeContractAbi,
assetId: string,
amount: BigNumber
amount: bigint
) => {
const minAmount = await contract.callStatic.get_swap_with_minimum(amount, {
forward: [0, assetId],
Expand All @@ -53,13 +51,13 @@ export default function SwapPage() {
]);
const getOtherCoins = (coins: Coin[]) =>
assets.filter(({ assetId }) => !coins.find((c) => c.assetId === assetId));
const [fromAmount, setFromAmount] = useState(null as BigNumber | null);
const [toAmount, setToAmount] = useState(null as BigNumber | null);
const [fromAmount, setFromAmount] = useState<bigint | null>(null);
const [toAmount, setToAmount] = useState<bigint | null>(null);
const [activeInput, setActiveInput] = useState(null as "from" | "to" | null);
const navigate = useNavigate();

const { data: inactiveAmount } = useQuery(
["SwapPage-inactiveAmount", activeInput, toAmount, fromAmount],
["SwapPage-inactiveAmount", activeInput, toAmount?.toString(), fromAmount?.toString()],
async () => {
if (activeInput === "to") {
if (!toAmount) return null;
Expand Down Expand Up @@ -130,9 +128,7 @@ export default function SwapPage() {
<div className={style.content}>
<div className={style.formHeader}>
<h1>Swap</h1>
<div>
{/* <RiSettings3Fill /> */}
</div>
<div>{/* <RiSettings3Fill /> */}</div>
</div>

<div className="mt-6">
Expand Down
13 changes: 6 additions & 7 deletions client/src/pages/WalletPage.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
import { FaFaucet, FaRegCopy } from "react-icons/fa";
import { useWallet, useAppContext } from "src/context/AppContext";
import { CoinQuantity } from "fuels";
import { BigNumber } from "ethers";
import { CoinQuantity, toBigInt } from "fuels";
import { Coin, CoinInput } from "src/components/CoinInput";
import CoinsMetadata from "src/lib/CoinsMetadata";
import { Spinner } from "src/components/Spinner";
Expand All @@ -23,10 +22,10 @@ const style = {
copyButton: `w-8 h-8 flex justify-center items-center p-1`,
accountContainer: `flex justify-center w-full text-sm my-8`,
accountContent: `flex items-center border-radius rounded-xl border border-[#3f444e] text-sm p-2 hover:opacity-70 active:opacity-50 cursor-pointer`,
address: `text-[#e3e9f3] pl-2 pr-2`
address: `text-[#e3e9f3] pl-2 pr-2`,
};

type Asset = Coin & { amount: BigNumber };
type Asset = Coin & { amount: bigint };
const mergeCoinsWithMetadata = (coins: CoinQuantity[]): Array<Asset> => {
return coins.map((coin) => {
const coinMetadata = CoinsMetadata.find((c) => c.assetId === coin.assetId);
Expand All @@ -38,7 +37,7 @@ const mergeCoinsWithMetadata = (coins: CoinQuantity[]): Array<Asset> => {
name: coinMetadata?.name || "404",
img: coinMetadata?.img || "/icons/other.svg",
assetId: coin.assetId,
amount: coin.amount || 0,
amount: toBigInt(coin.amount || 0),
};
});
};
Expand All @@ -54,7 +53,7 @@ export default function WalletPage() {

const handleCopy = () => {
clipboard.copy(wallet!.address);
}
};

const faucetMutation = useMutation(
async () => {
Expand Down Expand Up @@ -105,7 +104,7 @@ export default function WalletPage() {
</button>
</div>
</div>
<div className={classNames(style.divider, 'mb-6')} />
<div className={classNames(style.divider, "mb-6")} />
<div className="px-6">
<div className={style.sectionTitle}>Assets</div>
{balances ? (
Expand Down
Loading

0 comments on commit efe9857

Please sign in to comment.