Skip to content

Commit

Permalink
merge master
Browse files Browse the repository at this point in the history
  • Loading branch information
Space-Bean committed Dec 10, 2023
2 parents 53ddfbc + 45b825f commit d9045ea
Show file tree
Hide file tree
Showing 135 changed files with 2,751 additions and 926 deletions.
9 changes: 2 additions & 7 deletions .github/workflows/ci.sdk-core.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -24,13 +24,8 @@ jobs:
- name: Install Dependencies
if: steps.node-modules-cache.outputs.cache-hit != 'true'
run: yarn install --immutable
- name: Install rust
uses: actions-rs/toolchain@v1
with:
toolchain: stable
target: wasm32-unknown-unknown
profile: minimal
override: true
- name: Install Rust (Stable)
run: curl https://sh.rustup.rs -sSf | sh -s -- -y
- name: Install Anvil
uses: foundry-rs/foundry-toolchain@v1
with:
Expand Down
9 changes: 2 additions & 7 deletions .github/workflows/ci.sdk-wells.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -26,13 +26,8 @@ jobs:
run: yarn install --immutable
- name: Generate Typedefs
run: yarn sdk:generate
- name: Install rust
uses: actions-rs/toolchain@v1
with:
toolchain: stable
target: wasm32-unknown-unknown
profile: minimal
override: true
- name: Install Rust (Stable)
run: curl https://sh.rustup.rs -sSf | sh -s -- -y
- name: Install Anvil
uses: foundry-rs/foundry-toolchain@v1
with:
Expand Down
13 changes: 3 additions & 10 deletions .github/workflows/ci.sdk.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -24,22 +24,15 @@ jobs:
- name: Install Dependencies
if: steps.node-modules-cache.outputs.cache-hit != 'true'
run: yarn install --immutable
- name: Install rust
uses: actions-rs/toolchain@v1
with:
toolchain: stable
target: wasm32-unknown-unknown
profile: minimal
override: true
- name: Install Rust (Stable)
run: curl https://sh.rustup.rs -sSf | sh -s -- -y
- name: Install Anvil
uses: foundry-rs/foundry-toolchain@v1
with:
version: nightly
# TODO: Cache Anvil RPC calls between runs to speed up tests
- name: Launch Anvil
run: anvil --fork-url $ANVIL_FORK_URL --chain-id 1337 &
env:
ANVIL_FORK_URL: ${{ secrets.ANVIL_FORK_URL }}
run: yarn anvil4tests &
- name: Build All
run: yarn build
- run: yarn sdk:test
Expand Down
4 changes: 3 additions & 1 deletion .github/workflows/ci.ui.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ jobs:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- name: UI Tests
- name: Setup Node
uses: actions/setup-node@v3
with:
node-version: "16"
Expand All @@ -30,3 +30,5 @@ jobs:
run: yarn ui:generate
- name: Unit Tests
run: yarn ui:test
env:
VITE_ALCHEMY_API_KEY: ${{ secrets.VITE_ALCHEMY_API_KEY }}
1 change: 1 addition & 0 deletions .node-version
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
v18.18
3 changes: 3 additions & 0 deletions jest.config.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,15 @@
import type { JestConfigWithTsJest } from "ts-jest";

const jestConfig: JestConfigWithTsJest = {
testSequencer: "<rootDir>/testSequencer.js",
runner: "jest-serial-runner",
projects: [
{
// @ts-ignore
preset: "ts-jest",
displayName: "sdk-wells",
rootDir: "projects/sdk-wells",

testMatch: ["<rootDir>/src/**/?(*.)+(spec|test).[jt]s?(x)", "<rootDir>/test/**/?(*.)+(spec|test).[jt]s?(x)"],
moduleNameMapper: {
"@beanstalk/sdk-wells/(.*)$": "<rootDir>/src/$1",
Expand Down
5 changes: 4 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
"@types/prettier": "^2",
"husky": "8.0.1",
"jest": "29.2.2",
"jest-serial-runner": "1.2.1",
"lint-staged": "13.1.0",
"prettier": "2.7.1",
"ts-jest": "29.0.3",
Expand Down Expand Up @@ -43,6 +44,8 @@
"ui:build": "yarn workspace ui build",
"ui:test": "yarn workspace ui test",
"test:browser": "yarn workspace tests test:browser",
"ex": "yarn workspace @beanstalk/examples x"
"ex": "yarn workspace @beanstalk/examples x",
"anvil": "anvil --fork-url https://eth-mainnet.g.alchemy.com/v2/5ubn94zT7v7DnB5bNW1VOnoIbX5-AG2N --chain-id 1337",
"anvil4tests": "anvil --fork-url https://eth-mainnet.g.alchemy.com/v2/Kk7ktCQL5wz4v4AG8bR2Gun8TAASQ-qi --chain-id 1337 --fork-block-number 18629000"
}
}
14 changes: 14 additions & 0 deletions projects/cli/src/cli.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@ import { sunrise } from "./commands/sunrise.js";
import { setPrice } from "./commands/setprice.js";
import { help } from "./commands/help.js";
import { mineBlocks } from "./commands/mine.js";
import { setDeltaB } from "./commands/setDeltaB.js";
import { getDeltaB } from "./commands/getDeltaB.js";

main().catch((e) => {
console.log("FAILED:");
Expand All @@ -28,6 +30,7 @@ async function main() {
const args = commandLineArgs(commands, { partial: true });

const { sdk, chain, stop } = await setupSDK(args);
sdk.DEBUG = false;

switch (args.command) {
case "balance":
Expand All @@ -45,6 +48,17 @@ async function main() {
case "mine":
await mineBlocks(sdk, args.amount);
break;
case "setpriceabove":
case "setpriceover":
await setDeltaB(sdk, chain, "up", args.amount);
break;
case "setpricebelow":
case "setpriceunder":
await setDeltaB(sdk, chain, "down", args.amount);
break;
case "deltab":
await getDeltaB(sdk);
break;
case "help":
default:
await help();
Expand Down
7 changes: 7 additions & 0 deletions projects/cli/src/commands/getDeltaB.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
import { BeanstalkSDK } from "@beanstalk/sdk";
import chalk from "chalk";

export const getDeltaB = async (sdk: BeanstalkSDK) => {
const deltaB = await sdk.bean.getDeltaB();
console.log(`${chalk.bold.whiteBright("DeltaB: ")} ${chalk.greenBright(deltaB.toHuman())}`);
};
16 changes: 15 additions & 1 deletion projects/cli/src/commands/help.ts
Original file line number Diff line number Diff line change
Expand Up @@ -47,8 +47,22 @@ export const help = () => {
content: [
{ name: "{bold.greenBright balance}", summary: "Display balance(s). Optionally specify account or token" },
{ name: "{bold.greenBright setbalance}", summary: "Set balance(s). Optionally specify account, token, or amount" },
{ name: "{bold.greenBright setprice}", summary: "Set BEAN price by setting liquidity. Defaults to 20M BEAN and 20M 3CRV. Parameters are millions. See examples below" },
{
name: "{bold.greenBright setprice}",
summary: "Set BEAN price by setting liquidity. Defaults to 20M BEAN and 20M 3CRV. Parameters are millions. See examples below"
},
{ name: "{bold.greenBright sunrise}", summary: "Calls the sunrise() function" },
{ name: "{bold.greenBright mine}", summary: "Mines a block (or more)" },
{ name: "{bold.greenBright deltab}", summary: "Display current DeltaB" },
{
name: "{bold.greenBright setpriceover}",
summary: "Buys enough BEANs to set DeltaB over 0, and the price over 1.00. Multiplier may be applied"
},
{
name: "{bold.greenBright setpriceunder}",
summary: "Sells enough BEANs to set DeltaB under 0, and the price under 1.00. Multiplier may be applied"
},

{ name: "{bold.greenBright help}", summary: "You're looking at it :)" }
]
},
Expand Down
18 changes: 18 additions & 0 deletions projects/cli/src/commands/setDeltaB.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import { BeanstalkSDK } from "@beanstalk/sdk";
import { BlockchainUtils } from "@beanstalk/sdk/dist/types/utils/TestUtils";
import chalk from "chalk";
import { table } from "table";

export const setDeltaB = async (sdk: BeanstalkSDK, chain: BlockchainUtils, direction: string, amount) => {
const multiplier = amount === "50000" ? 2 : amount;
if (direction === "down") {
await chain.setPriceUnder1(multiplier);
} else if (direction === "up") {
await chain.setPriceOver1(multiplier);
} else {
console.log(`unknown input: ${direction}. Expected "up", or "down"`);
}

const deltaB = await sdk.bean.getDeltaB();
console.log(`${chalk.bold.whiteBright("New DeltaB: ")} ${chalk.greenBright(deltaB.toHuman())}`);
};
25 changes: 25 additions & 0 deletions projects/examples/src/deltaB.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
import { TokenValue } from "@beanstalk/sdk-core";
import { account as _account, impersonate, chain } from "./setup";
import { defaultAbiCoder } from "ethers/lib/utils";

main().catch((e) => {
console.log("FAILED:");
console.log(e);
});

async function main() {
const account = process.argv[3] || _account;
const { sdk, stop } = await impersonate(account);
sdk.DEBUG = false;

let deltaB = await sdk.bean.getDeltaB();

if (deltaB.gte(TokenValue.ZERO)) {
await chain.setPriceUnder1();
} else {
await chain.setPriceOver1();
}
// chain.mine()
deltaB = await sdk.bean.getDeltaB();
console.log("New DeltaB: ", deltaB.toHuman());
}
21 changes: 21 additions & 0 deletions projects/examples/src/graphs.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import chalk from "chalk";
import { account as _account, impersonate, chain } from "./setup";

main().catch((e) => {
console.log("FAILED:");
console.log(e);
});

async function main() {
const account = process.argv[3] || _account;
console.log(`${chalk.bold.whiteBright("Account:")} ${chalk.greenBright(account)}`);
const { sdk, stop } = await impersonate(account);

console.log("--- SWAP ---");
sdk.swap.getGraph();

console.log("\n\n--- DEPOSIT ----");
// @ts-ignore
sdk.silo.depositBuilder.getGraph();
await stop();
}
10 changes: 10 additions & 0 deletions projects/sdk-wells/src/constants/abi/UnwrapAndSendEthJunction.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
[
{
"inputs": [{ "internalType": "address", "name": "to", "type": "address" }],
"name": "unwrapAndSendETH",
"outputs": [],
"stateMutability": "nonpayable",
"type": "function"
},
{ "stateMutability": "payable", "type": "receive" }
]
3 changes: 2 additions & 1 deletion projects/sdk-wells/src/constants/addresses.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,5 +11,6 @@ export const addresses = {
// Contracts
DEPOT: Address.make("0xDEb0f00071497a5cc9b4A6B96068277e57A82Ae2"),
PIPELINE: Address.make("0xb1bE0000C6B3C62749b5F0c92480146452D15423"),
WETH9: Address.make("0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2")
WETH9: Address.make("0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2"),
UNWRAP_AND_SEND_JUNCTION: Address.make("0x737cad465b75cdc4c11b3e312eb3fe5bef793d96")
};
56 changes: 26 additions & 30 deletions projects/sdk-wells/src/lib/swap/Quote.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,14 @@
import { Token, TokenValue } from "@beanstalk/sdk-core";
import { Route } from "src/lib/routing";
import { Direction, SwapStep } from "src/lib/swap/SwapStep";
import { Depot, Depot__factory, ERC20, WETH9, WETH9__factory } from "src/constants/generated";
import {
Depot,
Depot__factory,
WETH9,
WETH9__factory,
UnwrapAndSendEthJunction__factory,
UnwrapAndSendEthJunction
} from "src/constants/generated";
import { addresses } from "src/constants/addresses";
import { WellsSDK } from "src/lib/WellsSDK";
import { TxOverrides } from "src/lib/Well";
Expand All @@ -12,7 +19,7 @@ import { Clipboard } from "src/lib/clipboard/clipboard";
import { UnWrapEthStep } from "./UnWrapStep";

const DEFAULT_DEADLINE = 60 * 5; // in seconds
const PIPELINE_ADDRESS = addresses.PIPELINE.get(1);
const UNWRAP_AND_SEND_JUNCTION = addresses.UNWRAP_AND_SEND_JUNCTION.get(1);

export type QuotePrepareResult = {
doSwap: (overrides?: TxOverrides) => Promise<ContractTransaction>;
Expand Down Expand Up @@ -44,6 +51,7 @@ export class Quote {
fullQuote: TokenValue | undefined;
slippage: number;
weth9: WETH9;
unwrapAndSendEthJunction: UnwrapAndSendEthJunction;
debug: boolean = false;

constructor(sdk: WellsSDK, fromToken: Token, toToken: Token, route: Route, account: string) {
Expand All @@ -56,6 +64,10 @@ export class Quote {
this.account = account;

this.weth9 = WETH9__factory.connect(addresses.WETH9.get(this.sdk.chainId), this.sdk.providerOrSigner);
this.unwrapAndSendEthJunction = UnwrapAndSendEthJunction__factory.connect(
addresses.UNWRAP_AND_SEND_JUNCTION.get(this.sdk.chainId),
this.sdk.providerOrSigner
);

for (const { from, to, well } of this.route) {
if (from.symbol === "ETH" && to.symbol === "WETH") {
Expand Down Expand Up @@ -212,8 +224,8 @@ export class Quote {
const step = steps[i];
let nextRecipient = steps[i + 1]?.well.contract.address ?? recipient;

// If this is a swap that ends in ETH, we need to send the amount of the last swap (which should be WETH) to pipeline
if (i === steps.length - 1 && this.toToken.symbol === "ETH") nextRecipient = PIPELINE_ADDRESS;
// If this is a swap that ends in ETH, we need to send the amount of the last swap (which should be WETH) to the Unwrap and Send ETH Junction
if (i === steps.length - 1 && this.toToken.symbol === "ETH") nextRecipient = UNWRAP_AND_SEND_JUNCTION;

const { contract, method, parameters } = step.swapMany(nextRecipient, step.quoteResultWithSlippage!);

Expand Down Expand Up @@ -271,8 +283,6 @@ export class Quote {
if (wethStep.toToken.symbol !== "WETH")
throw new Error("Last step of multi-swap should have been a swap to WETH if the overall swap is for ETH.");

const ethAmount = wethStep.quoteResultWithSlippage!;

const transferToFirstWell = this.depot.interface.encodeFunctionData("transferToken", [
this.fromToken.address,
steps[0].well.address,
Expand All @@ -281,19 +291,13 @@ export class Quote {
0
]);

const unwrapWeth = {
target: this.weth9.address,
callData: this.weth9.interface.encodeFunctionData("withdraw", [ethAmount.toBigNumber()]),
const unwrapAndSendEth = {
target: this.unwrapAndSendEthJunction.address,
callData: this.unwrapAndSendEthJunction.interface.encodeFunctionData("unwrapAndSendETH", [recipient]),
clipboard: Clipboard.encode([])
};

const sendEth = {
target: recipient,
callData: "0x",
clipboard: Clipboard.encode([], ethAmount.toBigNumber())
};

pipe = this.depot.interface.encodeFunctionData("advancedPipe", [[...shiftOps, unwrapWeth, sendEth], 0]);
pipe = this.depot.interface.encodeFunctionData("advancedPipe", [[...shiftOps, unwrapAndSendEth], 0]);

doSwap = (overrides: TxOverrides = {}): Promise<ContractTransaction> => {
return this.depot.farm([transferToFirstWell, pipe], overrides);
Expand Down Expand Up @@ -359,8 +363,8 @@ export class Quote {
const nextStep = steps[i + 1] || null;
let nextRecipient = i === steps.length - 1 ? recipient : pipelineAddress;

// If this is a swap that ends in ETH, we need to send the amount of the last swap (which should be WETH) to pipeline
if (i === steps.length - 1 && this.toToken.symbol === "ETH") nextRecipient = PIPELINE_ADDRESS;
// If this is a swap that ends in ETH, we need to send the amount of the last swap (which should be WETH) to the Unwrap and Send ETH Junction
if (i === steps.length - 1 && this.toToken.symbol === "ETH") nextRecipient = UNWRAP_AND_SEND_JUNCTION;

const amountWithSlippage = step.quoteResultWithSlippage!;
const maxAmountOut = amountWithSlippage;
Expand Down Expand Up @@ -423,8 +427,6 @@ export class Quote {
if (wethStep.toToken.symbol !== "WETH")
throw new Error("Last step of multi-swap should have been a swap to WETH if the overall swap is for ETH.");

const ethAmount = wethStep.quoteInput!;

const transferToPipeline = this.depot.interface.encodeFunctionData("transferToken", [
this.fromToken.address,
pipelineAddress,
Expand All @@ -433,19 +435,13 @@ export class Quote {
0
]);

const unwrapWeth = {
target: this.weth9.address,
callData: this.weth9.interface.encodeFunctionData("withdraw", [ethAmount.toBigNumber()]),
const unwrapAndSendEth = {
target: this.unwrapAndSendEthJunction.address,
callData: this.unwrapAndSendEthJunction.interface.encodeFunctionData("unwrapAndSendETH", [recipient]),
clipboard: Clipboard.encode([])
};

const sendEth = {
target: recipient,
callData: "0x",
clipboard: Clipboard.encode([], ethAmount.toBigNumber())
};

pipe = this.depot.interface.encodeFunctionData("advancedPipe", [[...operations, unwrapWeth, sendEth], 0]);
pipe = this.depot.interface.encodeFunctionData("advancedPipe", [[...operations, unwrapAndSendEth], 0]);

doSwap = (overrides: TxOverrides = {}): Promise<ContractTransaction> => {
return this.depot.farm([transferToPipeline, pipe], overrides);
Expand Down
Loading

0 comments on commit d9045ea

Please sign in to comment.