From 1efeac4f0c623c8c7a2694ee085fea1723aacd4d Mon Sep 17 00:00:00 2001 From: Spacebean Date: Mon, 5 Aug 2024 21:19:27 +0200 Subject: [PATCH 01/11] feat: update abi --- protocol/abi/Beanstalk.json | 381 +++++++++++++----------------------- 1 file changed, 138 insertions(+), 243 deletions(-) diff --git a/protocol/abi/Beanstalk.json b/protocol/abi/Beanstalk.json index 7bcc75a74e..79d529d0e0 100644 --- a/protocol/abi/Beanstalk.json +++ b/protocol/abi/Beanstalk.json @@ -357,30 +357,6 @@ "stateMutability": "view", "type": "function" }, - { - "inputs": [ - { - "internalType": "bytes", - "name": "cumulativeReserves", - "type": "bytes" - }, - { - "internalType": "uint40", - "name": "timestamp", - "type": "uint40" - } - ], - "name": "getLockedBeansFromTwaReserves", - "outputs": [ - { - "internalType": "uint256", - "name": "", - "type": "uint256" - } - ], - "stateMutability": "view", - "type": "function" - }, { "inputs": [], "name": "getLockedBeansUnderlyingUnripeBean", @@ -4653,6 +4629,35 @@ "stateMutability": "payable", "type": "function" }, + { + "inputs": [ + { + "internalType": "address", + "name": "owner", + "type": "address" + }, + { + "internalType": "address", + "name": "reciever", + "type": "address" + }, + { + "internalType": "uint256", + "name": "deadline", + "type": "uint256" + } + ], + "name": "getMigrationHash", + "outputs": [ + { + "internalType": "bytes32", + "name": "", + "type": "bytes32" + } + ], + "stateMutability": "view", + "type": "function" + }, { "inputs": [ { @@ -4735,6 +4740,101 @@ "stateMutability": "payable", "type": "function" }, + { + "inputs": [ + { + "internalType": "address", + "name": "account", + "type": "address" + }, + { + "components": [ + { + "internalType": "address", + "name": "token", + "type": "address" + }, + { + "internalType": "uint256[]", + "name": "depositIds", + "type": "uint256[]" + }, + { + "internalType": "uint128[]", + "name": "amounts", + "type": "uint128[]" + }, + { + "internalType": "uint128[]", + "name": "bdvs", + "type": "uint128[]" + } + ], + "internalType": "struct L2ContractMigrationFacet.AccountDepositData[]", + "name": "deposits", + "type": "tuple[]" + }, + { + "components": [ + { + "internalType": "address", + "name": "token", + "type": "address" + }, + { + "internalType": "uint256", + "name": "amount", + "type": "uint256" + } + ], + "internalType": "struct L2ContractMigrationFacet.AccountInternalBalance[]", + "name": "internalBalances", + "type": "tuple[]" + }, + { + "internalType": "uint256", + "name": "ownerRoots", + "type": "uint256" + }, + { + "internalType": "bytes32[]", + "name": "proof", + "type": "bytes32[]" + } + ], + "name": "verifyMigrationDepositsAndInternalBalances", + "outputs": [], + "stateMutability": "pure", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "address", + "name": "owner", + "type": "address" + }, + { + "internalType": "address", + "name": "reciever", + "type": "address" + }, + { + "internalType": "uint256", + "name": "deadline", + "type": "uint256" + }, + { + "internalType": "bytes", + "name": "signature", + "type": "bytes" + } + ], + "name": "verifyMigrationSignature", + "outputs": [], + "stateMutability": "view", + "type": "function" + }, { "anonymous": false, "inputs": [ @@ -7813,6 +7913,19 @@ "stateMutability": "view", "type": "function" }, + { + "inputs": [], + "name": "totalRainRoots", + "outputs": [ + { + "internalType": "uint256", + "name": "", + "type": "uint256" + } + ], + "stateMutability": "view", + "type": "function" + }, { "inputs": [], "name": "totalRoots", @@ -8440,224 +8553,6 @@ "stateMutability": "view", "type": "function" }, - { - "anonymous": false, - "inputs": [ - { - "indexed": true, - "internalType": "address", - "name": "account", - "type": "address" - }, - { - "indexed": false, - "internalType": "int256", - "name": "deltaGerminatingStalk", - "type": "int256" - }, - { - "indexed": false, - "internalType": "enum LibGerminate.Germinate", - "name": "germinationState", - "type": "uint8" - } - ], - "name": "FarmerGerminatingStalkBalanceChanged", - "type": "event" - }, - { - "anonymous": false, - "inputs": [ - { - "indexed": false, - "internalType": "uint256", - "name": "germinationSeason", - "type": "uint256" - }, - { - "indexed": true, - "internalType": "address", - "name": "token", - "type": "address" - }, - { - "indexed": false, - "internalType": "int256", - "name": "deltaAmount", - "type": "int256" - }, - { - "indexed": false, - "internalType": "int256", - "name": "deltaBdv", - "type": "int256" - } - ], - "name": "TotalGerminatingBalanceChanged", - "type": "event" - }, - { - "anonymous": false, - "inputs": [ - { - "indexed": false, - "internalType": "uint256", - "name": "germinationSeason", - "type": "uint256" - }, - { - "indexed": false, - "internalType": "int256", - "name": "deltaGerminatingStalk", - "type": "int256" - } - ], - "name": "TotalGerminatingStalkChanged", - "type": "event" - }, - { - "anonymous": false, - "inputs": [ - { - "indexed": false, - "internalType": "int256", - "name": "deltaStalk", - "type": "int256" - }, - { - "indexed": false, - "internalType": "int256", - "name": "deltaRoots", - "type": "int256" - } - ], - "name": "TotalStalkChangedFromGermination", - "type": "event" - }, - { - "anonymous": false, - "inputs": [ - { - "indexed": false, - "internalType": "address", - "name": "token", - "type": "address" - }, - { - "indexed": false, - "internalType": "uint256", - "name": "index", - "type": "uint256" - }, - { - "indexed": false, - "internalType": "bool", - "name": "isWhitelisted", - "type": "bool" - }, - { - "indexed": false, - "internalType": "bool", - "name": "isWhitelistedLp", - "type": "bool" - }, - { - "indexed": false, - "internalType": "bool", - "name": "isWhitelistedWell", - "type": "bool" - } - ], - "name": "AddWhitelistStatus", - "type": "event" - }, - { - "anonymous": false, - "inputs": [ - { - "indexed": false, - "internalType": "address", - "name": "token", - "type": "address" - }, - { - "indexed": false, - "internalType": "uint256", - "name": "index", - "type": "uint256" - } - ], - "name": "RemoveWhitelistStatus", - "type": "event" - }, - { - "anonymous": false, - "inputs": [ - { - "indexed": false, - "internalType": "address", - "name": "token", - "type": "address" - }, - { - "indexed": false, - "internalType": "uint256", - "name": "index", - "type": "uint256" - }, - { - "indexed": false, - "internalType": "bool", - "name": "isWhitelisted", - "type": "bool" - }, - { - "indexed": false, - "internalType": "bool", - "name": "isWhitelistedLp", - "type": "bool" - }, - { - "indexed": false, - "internalType": "bool", - "name": "isWhitelistedWell", - "type": "bool" - } - ], - "name": "UpdateWhitelistStatus", - "type": "event" - }, - { - "anonymous": false, - "inputs": [ - { - "indexed": true, - "internalType": "uint32", - "name": "season", - "type": "uint32" - }, - { - "indexed": false, - "internalType": "address", - "name": "well", - "type": "address" - }, - { - "indexed": false, - "internalType": "int256", - "name": "deltaB", - "type": "int256" - }, - { - "indexed": false, - "internalType": "bytes", - "name": "cumulativeReserves", - "type": "bytes" - } - ], - "name": "WellOracle", - "type": "event" - }, { "inputs": [], "name": "maxWeight", @@ -10300,4 +10195,4 @@ "stateMutability": "view", "type": "function" } -] \ No newline at end of file +] From 5d574d6421ef3987b6dfdbeeffbe55576ce3a38f Mon Sep 17 00:00:00 2001 From: Spacebean Date: Mon, 5 Aug 2024 21:20:19 +0200 Subject: [PATCH 02/11] feat: update mockbeanstalk.json --- protocol/abi/MockBeanstalk.json | 453 +++++++++++++++++++++----------- 1 file changed, 295 insertions(+), 158 deletions(-) diff --git a/protocol/abi/MockBeanstalk.json b/protocol/abi/MockBeanstalk.json index 9cfc80e746..39b0bae57a 100644 --- a/protocol/abi/MockBeanstalk.json +++ b/protocol/abi/MockBeanstalk.json @@ -4629,6 +4629,35 @@ "stateMutability": "payable", "type": "function" }, + { + "inputs": [ + { + "internalType": "address", + "name": "owner", + "type": "address" + }, + { + "internalType": "address", + "name": "reciever", + "type": "address" + }, + { + "internalType": "uint256", + "name": "deadline", + "type": "uint256" + } + ], + "name": "getMigrationHash", + "outputs": [ + { + "internalType": "bytes32", + "name": "", + "type": "bytes32" + } + ], + "stateMutability": "view", + "type": "function" + }, { "inputs": [ { @@ -4711,6 +4740,101 @@ "stateMutability": "payable", "type": "function" }, + { + "inputs": [ + { + "internalType": "address", + "name": "account", + "type": "address" + }, + { + "components": [ + { + "internalType": "address", + "name": "token", + "type": "address" + }, + { + "internalType": "uint256[]", + "name": "depositIds", + "type": "uint256[]" + }, + { + "internalType": "uint128[]", + "name": "amounts", + "type": "uint128[]" + }, + { + "internalType": "uint128[]", + "name": "bdvs", + "type": "uint128[]" + } + ], + "internalType": "struct L2ContractMigrationFacet.AccountDepositData[]", + "name": "deposits", + "type": "tuple[]" + }, + { + "components": [ + { + "internalType": "address", + "name": "token", + "type": "address" + }, + { + "internalType": "uint256", + "name": "amount", + "type": "uint256" + } + ], + "internalType": "struct L2ContractMigrationFacet.AccountInternalBalance[]", + "name": "internalBalances", + "type": "tuple[]" + }, + { + "internalType": "uint256", + "name": "ownerRoots", + "type": "uint256" + }, + { + "internalType": "bytes32[]", + "name": "proof", + "type": "bytes32[]" + } + ], + "name": "verifyMigrationDepositsAndInternalBalances", + "outputs": [], + "stateMutability": "pure", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "address", + "name": "owner", + "type": "address" + }, + { + "internalType": "address", + "name": "reciever", + "type": "address" + }, + { + "internalType": "uint256", + "name": "deadline", + "type": "uint256" + }, + { + "internalType": "bytes", + "name": "signature", + "type": "bytes" + } + ], + "name": "verifyMigrationSignature", + "outputs": [], + "stateMutability": "view", + "type": "function" + }, { "anonymous": false, "inputs": [ @@ -7207,6 +7331,44 @@ "stateMutability": "view", "type": "function" }, + { + "inputs": [ + { + "internalType": "address", + "name": "token", + "type": "address" + } + ], + "name": "getGerminatingStem", + "outputs": [ + { + "internalType": "int96", + "name": "germinatingStem", + "type": "int96" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "address[]", + "name": "tokens", + "type": "address[]" + } + ], + "name": "getGerminatingStems", + "outputs": [ + { + "internalType": "int96[]", + "name": "germinatingStems", + "type": "int96[]" + } + ], + "stateMutability": "view", + "type": "function" + }, { "inputs": [ { @@ -7751,6 +7913,19 @@ "stateMutability": "view", "type": "function" }, + { + "inputs": [], + "name": "totalRainRoots", + "outputs": [ + { + "internalType": "uint256", + "name": "", + "type": "uint256" + } + ], + "stateMutability": "view", + "type": "function" + }, { "inputs": [], "name": "totalRoots", @@ -10096,6 +10271,82 @@ "stateMutability": "nonpayable", "type": "function" }, + { + "inputs": [], + "name": "exploitFertilizer", + "outputs": [], + "stateMutability": "nonpayable", + "type": "function" + }, + { + "inputs": [], + "name": "exploitSop", + "outputs": [], + "stateMutability": "nonpayable", + "type": "function" + }, + { + "inputs": [], + "name": "exploitUserInternalTokenBalance", + "outputs": [], + "stateMutability": "nonpayable", + "type": "function" + }, + { + "inputs": [], + "name": "exploitUserSendTokenInternal", + "outputs": [], + "stateMutability": "nonpayable", + "type": "function" + }, + { + "inputs": [], + "name": "revert_netFlow", + "outputs": [], + "stateMutability": "nonpayable", + "type": "function" + }, + { + "inputs": [], + "name": "revert_oneOutFlow", + "outputs": [], + "stateMutability": "nonpayable", + "type": "function" + }, + { + "inputs": [], + "name": "revert_outFlow", + "outputs": [], + "stateMutability": "nonpayable", + "type": "function" + }, + { + "inputs": [], + "name": "revert_supplyChange", + "outputs": [], + "stateMutability": "nonpayable", + "type": "function" + }, + { + "inputs": [], + "name": "revert_supplyIncrease", + "outputs": [], + "stateMutability": "nonpayable", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "uint256", + "name": "amount", + "type": "uint256" + } + ], + "name": "stealBeans", + "outputs": [], + "stateMutability": "nonpayable", + "type": "function" + }, { "anonymous": false, "inputs": [ @@ -10215,130 +10466,6 @@ "stateMutability": "nonpayable", "type": "function" }, - { - "inputs": [], - "name": "entitlementsMatchBalances", - "outputs": [ - { - "internalType": "bool", - "name": "", - "type": "bool" - } - ], - "stateMutability": "view", - "type": "function" - }, - { - "inputs": [], - "name": "exploitBurnBeans", - "outputs": [], - "stateMutability": "nonpayable", - "type": "function" - }, - { - "inputs": [], - "name": "exploitBurnStalk0", - "outputs": [], - "stateMutability": "nonpayable", - "type": "function" - }, - { - "inputs": [], - "name": "exploitBurnStalk1", - "outputs": [], - "stateMutability": "nonpayable", - "type": "function" - }, - { - "inputs": [], - "name": "exploitFertilizer", - "outputs": [], - "stateMutability": "nonpayable", - "type": "function" - }, - { - "inputs": [], - "name": "exploitMintBeans0", - "outputs": [], - "stateMutability": "nonpayable", - "type": "function" - }, - { - "inputs": [], - "name": "exploitMintBeans1", - "outputs": [], - "stateMutability": "nonpayable", - "type": "function" - }, - { - "inputs": [], - "name": "exploitMintBeans2", - "outputs": [], - "stateMutability": "nonpayable", - "type": "function" - }, - { - "inputs": [], - "name": "exploitMintBeans3", - "outputs": [], - "stateMutability": "nonpayable", - "type": "function" - }, - { - "inputs": [ - { - "internalType": "address", - "name": "sopWell", - "type": "address" - } - ], - "name": "exploitSop", - "outputs": [], - "stateMutability": "nonpayable", - "type": "function" - }, - { - "inputs": [], - "name": "exploitTokenBalance", - "outputs": [], - "stateMutability": "nonpayable", - "type": "function" - }, - { - "inputs": [], - "name": "exploitUserDoubleSendTokenExternal", - "outputs": [], - "stateMutability": "nonpayable", - "type": "function" - }, - { - "inputs": [], - "name": "exploitUserInternalTokenBalance", - "outputs": [], - "stateMutability": "nonpayable", - "type": "function" - }, - { - "inputs": [], - "name": "exploitUserSendTokenExternal0", - "outputs": [], - "stateMutability": "nonpayable", - "type": "function" - }, - { - "inputs": [], - "name": "exploitUserSendTokenExternal1", - "outputs": [], - "stateMutability": "nonpayable", - "type": "function" - }, - { - "inputs": [], - "name": "exploitUserSendTokenInternal", - "outputs": [], - "stateMutability": "nonpayable", - "type": "function" - }, { "inputs": [ { @@ -11108,6 +11235,11 @@ }, { "inputs": [ + { + "internalType": "address", + "name": "account", + "type": "address" + }, { "internalType": "address", "name": "token", @@ -11134,39 +11266,6 @@ "stateMutability": "nonpayable", "type": "function" }, - { - "inputs": [ - { - "internalType": "address", - "name": "token", - "type": "address" - }, - { - "internalType": "bytes4", - "name": "gaugePointSelector", - "type": "bytes4" - }, - { - "internalType": "bytes4", - "name": "liquidityWeightSelector", - "type": "bytes4" - }, - { - "internalType": "uint96", - "name": "gaugePoints", - "type": "uint96" - }, - { - "internalType": "uint64", - "name": "optimalPercentDepositedBdv", - "type": "uint64" - } - ], - "name": "mockInitalizeGaugeForToken", - "outputs": [], - "stateMutability": "nonpayable", - "type": "function" - }, { "inputs": [ { @@ -11227,6 +11326,39 @@ "stateMutability": "nonpayable", "type": "function" }, + { + "inputs": [ + { + "internalType": "address", + "name": "token", + "type": "address" + }, + { + "internalType": "bytes4", + "name": "gaugePointSelector", + "type": "bytes4" + }, + { + "internalType": "bytes4", + "name": "liquidityWeightSelector", + "type": "bytes4" + }, + { + "internalType": "uint96", + "name": "gaugePoints", + "type": "uint96" + }, + { + "internalType": "uint64", + "name": "optimalPercentDepositedBdv", + "type": "uint64" + } + ], + "name": "mockinitializeGaugeForToken", + "outputs": [], + "stateMutability": "nonpayable", + "type": "function" + }, { "inputs": [ { @@ -11324,6 +11456,11 @@ "internalType": "uint256", "name": "caseId", "type": "uint256" + }, + { + "internalType": "bool", + "name": "oracleFailure", + "type": "bool" } ], "name": "seedGaugeSunSunrise", @@ -12075,4 +12212,4 @@ "stateMutability": "nonpayable", "type": "function" } -] \ No newline at end of file +] From 28967ae8abfabdc1c9790c706a5d1079d70ce08a Mon Sep 17 00:00:00 2001 From: Spacebean Date: Mon, 5 Aug 2024 23:18:09 +0200 Subject: [PATCH 03/11] feat: fix sdk --- projects/sdk/src/classes/Token/Token.ts | 28 ++++++++- projects/sdk/src/lib/events/EventManager.ts | 10 +++- projects/sdk/src/lib/events/processor.ts | 19 ++++-- .../sdk/src/lib/farm/actions/AddLiquidity.ts | 60 +++++++++++++------ .../src/lib/farm/actions/ClaimWithdrawal.ts | 17 +++--- .../src/lib/farm/actions/ClaimWithdrawals.ts | 17 +++--- projects/sdk/src/lib/farm/actions/Exchange.ts | 30 ++++++---- .../lib/farm/actions/ExchangeUnderlying.ts | 30 ++++++---- .../farm/actions/RemoveLiquidityOneToken.ts | 31 ++++++---- projects/sdk/src/lib/market/pods/pods.ts | 25 ++++---- projects/sdk/src/lib/silo.ts | 3 +- 11 files changed, 177 insertions(+), 93 deletions(-) diff --git a/projects/sdk/src/classes/Token/Token.ts b/projects/sdk/src/classes/Token/Token.ts index ebba0e4dc5..37d0310db1 100644 --- a/projects/sdk/src/classes/Token/Token.ts +++ b/projects/sdk/src/classes/Token/Token.ts @@ -5,19 +5,41 @@ import { BigNumber, ContractTransaction } from "ethers"; const STALK_DECIMALS = 10; const SEED_DECIMALS = 6; + declare module "@beanstalk/sdk-core" { - abstract class Token { - static _source: string; + interface Token { isUnripe: boolean; rewards?: { stalk: TokenValue; seeds: TokenValue | null }; getStalk(bdv?: TokenValue): TokenValue; getSeeds(bdv?: TokenValue): TokenValue; approveBeanstalk(amount: TokenValue | BigNumber): Promise; } + + namespace Token { + let _source: string; + } } +// Adding the static Token._source property Object.defineProperty(CoreToken, "_source", { - value: "BeanstalkSDK" + value: "BeanstalkSDK", + writable: false, + configurable: false, + enumerable: true +}); + +// define property Token.prototype.isUnripe +Object.defineProperty(CoreToken.prototype, "isUnripe", { + value: false, + writable: true, + configurable: true +}); + +// define property Token.prototype.rewards +Object.defineProperty(CoreToken.prototype, "rewards", { + value: undefined, + writable: true, + configurable: true }); /** diff --git a/projects/sdk/src/lib/events/EventManager.ts b/projects/sdk/src/lib/events/EventManager.ts index 78d8382ac7..52d323185f 100644 --- a/projects/sdk/src/lib/events/EventManager.ts +++ b/projects/sdk/src/lib/events/EventManager.ts @@ -88,11 +88,17 @@ export class EventManager { return Promise.all([ this.sdk.contracts.beanstalkRead.queryFilter( - this.sdk.contracts.beanstalkRead.filters["Sow(address,uint256,uint256,uint256)"](account), + this.sdk.contracts.beanstalkRead.filters["Sow(address,uint256,uint256,uint256,uint256)"]( + account + ), + fromBlock, + toBlock + ), + this.sdk.contracts.beanstalkRead.queryFilter( + this.sdk.contracts.beanstalkRead.filters.Harvest(account), fromBlock, toBlock ), - this.sdk.contracts.beanstalkRead.queryFilter(this.sdk.contracts.beanstalkRead.filters.Harvest(account), fromBlock, toBlock), this.sdk.contracts.beanstalkRead.queryFilter( this.sdk.contracts.beanstalkRead.filters.PlotTransfer(account, null), // from fromBlock, diff --git a/projects/sdk/src/lib/events/processor.ts b/projects/sdk/src/lib/events/processor.ts index e4f66261fe..14eb910f61 100644 --- a/projects/sdk/src/lib/events/processor.ts +++ b/projects/sdk/src/lib/events/processor.ts @@ -88,11 +88,11 @@ export class EventProcessor { if (!event.event) { return; } - if (!SupportedEventsSet.has(event.event as typeof SupportedEvents[number])) { + if (!SupportedEventsSet.has(event.event as (typeof SupportedEvents)[number])) { return; } // @ts-ignore - return this[event.event as typeof SupportedEvents[number]]?.(event as any); + return this[event.event as (typeof SupportedEvents)[number]]?.(event as any); } ingestAll(events: T[]) { @@ -169,8 +169,10 @@ export class EventProcessor { }); } - PlotTransfer(event: EventManager.Simplify) { + PlotTransfer(_event: EventManager.Simplify) { // Numerical "index" of the Plot. Absolute, with respect to Pod 0. + + const event = _event as any; const transferIndex = event.args.id; const podsTransferred = event.args.pods; @@ -371,9 +373,13 @@ export class EventProcessor { } _removeDeposit(stem: string, token: Token, amount: ethers.BigNumber) { - if (!this.whitelist.has(token)) throw new Error(`Attempted to process an event with an unknown token: ${token}`); + if (!this.whitelist.has(token)) + throw new Error(`Attempted to process an event with an unknown token: ${token}`); const existingDeposit = this.deposits.get(token)?.[stem]; - if (!existingDeposit) throw new Error(`Received a 'RemoveDeposit' event for an unknown deposit: ${token.address} ${stem}`); + if (!existingDeposit) + throw new Error( + `Received a 'RemoveDeposit' event for an unknown deposit: ${token.address} ${stem}` + ); // BDV scales linearly with the amount of the underlying token. // Ex. if we remove 60% of the `amount`, we also remove 60% of the BDV. @@ -397,7 +403,8 @@ export class EventProcessor { const token = this.getToken(event); const stem = this.migrateStem(event.args.stem); - if (!this.whitelist.has(token)) throw new Error(`Attempted to process an event with an unknown token: ${token}`); + if (!this.whitelist.has(token)) + throw new Error(`Attempted to process an event with an unknown token: ${token}`); const tokDeposits = this.deposits.get(token); this.deposits.set(token, { diff --git a/projects/sdk/src/lib/farm/actions/AddLiquidity.ts b/projects/sdk/src/lib/farm/actions/AddLiquidity.ts index d3f8402bd7..bc7e3b97d4 100644 --- a/projects/sdk/src/lib/farm/actions/AddLiquidity.ts +++ b/projects/sdk/src/lib/farm/actions/AddLiquidity.ts @@ -1,9 +1,19 @@ import { BigNumber, ethers } from "ethers"; -import { BasicPreparedResult, RunContext, RunMode, Step, StepClass, Workflow } from "src/classes/Workflow"; +import { + BasicPreparedResult, + RunContext, + RunMode, + Step, + StepClass, + Workflow +} from "src/classes/Workflow"; import { CurveMetaPool__factory, CurvePlainPool__factory } from "src/constants/generated"; import { assert } from "src/utils"; import { FarmFromMode, FarmToMode } from "../types"; +/** + * @deprecated + */ export class AddLiquidity extends StepClass { public name: string = "addLiquidity"; @@ -17,14 +27,19 @@ export class AddLiquidity extends StepClass { super(); } - async run(_amountInStep: ethers.BigNumber, context: RunContext): Promise> { + async run( + _amountInStep: ethers.BigNumber, + context: RunContext + ): Promise> { if (context.runMode === RunMode.EstimateReversed) { throw new Error("Reverse estimation is not yet supported for this action"); } /// [0, 0, 1] => [0, 0, amountIn] /// FIXME: this uses a binary approach instead of a multiplier. - const amountInStep = this._amounts.map((k) => (k === 1 ? _amountInStep : ethers.BigNumber.from(0))); + const amountInStep = this._amounts.map((k) => + k === 1 ? _amountInStep : ethers.BigNumber.from(0) + ); /// Get amount out based on the selected pool const poolAddr = this._pool.toLowerCase(); @@ -54,16 +69,22 @@ export class AddLiquidity extends StepClass { /// Case: Metapools else if (this._registry === AddLiquidity.sdk.contracts.curve.registries.metaFactory.address) { assert(amountInStep.length === 2); - amountOut = await CurveMetaPool__factory.connect(this._pool, AddLiquidity.sdk.provider).callStatic[ - "calc_token_amount(uint256[2],bool)" - ]( + amountOut = await CurveMetaPool__factory.connect( + this._pool, + AddLiquidity.sdk.provider + ).callStatic["calc_token_amount(uint256[2],bool)"]( amountInStep as [any, any], true, // _is_deposit { gasLimit: 10000000 } ); - } else if (this._registry === AddLiquidity.sdk.contracts.curve.registries.cryptoFactory.address) { + } else if ( + this._registry === AddLiquidity.sdk.contracts.curve.registries.cryptoFactory.address + ) { assert(amountInStep.length === 2); - amountOut = await CurvePlainPool__factory.connect(this._pool, AddLiquidity.sdk.provider).callStatic.calc_token_amount( + amountOut = await CurvePlainPool__factory.connect( + this._pool, + AddLiquidity.sdk.provider + ).callStatic.calc_token_amount( amountInStep as [any, any], true, // _is_deposit { gasLimit: 10000000 } @@ -99,18 +120,21 @@ export class AddLiquidity extends StepClass { if (!minAmountOut) throw new Error("AddLiquidity: missing minAmountOut"); return { target: AddLiquidity.sdk.contracts.beanstalk.address, - callData: AddLiquidity.sdk.contracts.beanstalk.interface.encodeFunctionData("addLiquidity", [ - this._pool, - this._registry, - amountInStep as any[], // could be 2 or 3 elems - minAmountOut, - this._fromMode, - this._toMode - ]) + callData: "" + // callData: AddLiquidity.sdk.contracts.beanstalk.interface.encodeFunctionData("addLiquidity", [ + // this._pool, + // this._registry, + // amountInStep as any[], // could be 2 or 3 elems + // minAmountOut, + // this._fromMode, + // this._toMode + // ]) }; }, - decode: (data: string) => AddLiquidity.sdk.contracts.beanstalk.interface.decodeFunctionData("addLiquidity", data), - decodeResult: (result: string) => AddLiquidity.sdk.contracts.beanstalk.interface.decodeFunctionResult("addLiquidity", result) + decode: (data: string) => undefined, + // decode: (data: string) => AddLiquidity.sdk.contracts.beanstalk.interface.decodeFunctionData("addLiquidity", data), + decodeResult: (result: string) => undefined + // decodeResult: (result: string) => AddLiquidity.sdk.contracts.beanstalk.interface.decodeFunctionResult("addLiquidity", result) }; } } diff --git a/projects/sdk/src/lib/farm/actions/ClaimWithdrawal.ts b/projects/sdk/src/lib/farm/actions/ClaimWithdrawal.ts index 15cc0d8711..4b4f017167 100644 --- a/projects/sdk/src/lib/farm/actions/ClaimWithdrawal.ts +++ b/projects/sdk/src/lib/farm/actions/ClaimWithdrawal.ts @@ -29,15 +29,18 @@ export class ClaimWithdrawal extends StepClass { }); return { target: ClaimWithdrawal.sdk.contracts.beanstalk.address, - callData: ClaimWithdrawal.sdk.contracts.beanstalk.interface.encodeFunctionData("claimWithdrawal", [ - this._tokenIn, // - this._season, // - this._to - ]) + callData: "" + // callData: ClaimWithdrawal.sdk.contracts.beanstalk.interface.encodeFunctionData("claimWithdrawal", [ + // this._tokenIn, // + // this._season, // + // this._to + // ]) }; }, - decode: (data: string) => ClaimWithdrawal.sdk.contracts.beanstalk.interface.decodeFunctionData("claimWithdrawal", data), - decodeResult: (result: string) => ClaimWithdrawal.sdk.contracts.beanstalk.interface.decodeFunctionResult("claimWithdrawal", result) + decode: (data: string) => undefined, + decodeResult: (result: string) => undefined + // decode: (data: string) => undefined, ClaimWithdrawal.sdk.contracts.beanstalk.interface.decodeFunctionData("claimWithdrawal", data), + // decodeResult: (result: string) => undefined, ClaimWithdrawal.sdk.contracts.beanstalk.interface.decodeFunctionResult("claimWithdrawal", result) }; } } diff --git a/projects/sdk/src/lib/farm/actions/ClaimWithdrawals.ts b/projects/sdk/src/lib/farm/actions/ClaimWithdrawals.ts index f94b3f60b2..d0580b0b4a 100644 --- a/projects/sdk/src/lib/farm/actions/ClaimWithdrawals.ts +++ b/projects/sdk/src/lib/farm/actions/ClaimWithdrawals.ts @@ -29,15 +29,18 @@ export class ClaimWithdrawals extends StepClass { }); return { target: ClaimWithdrawals.sdk.contracts.beanstalk.address, - callData: ClaimWithdrawals.sdk.contracts.beanstalk.interface.encodeFunctionData("claimWithdrawals", [ - this._tokenIn, // - this._seasons, // - this._to - ]) + callData: "" + // callData: ClaimWithdrawals.sdk.contracts.beanstalk.interface.encodeFunctionData("claimWithdrawals", [ + // this._tokenIn, // + // this._seasons, // + // this._to + // ]) }; }, - decode: (data: string) => ClaimWithdrawals.sdk.contracts.beanstalk.interface.decodeFunctionData("claimWithdrawals", data), - decodeResult: (result: string) => ClaimWithdrawals.sdk.contracts.beanstalk.interface.decodeFunctionResult("claimWithdrawals", result) + decode: (data: string) => undefined, + decodeResult: (result: string) => undefined + // decode: (data: string) => ClaimWithdrawals.sdk.contracts.beanstalk.interface.decodeFunctionData("claimWithdrawals", data), + // decodeResult: (result: string) => ClaimWithdrawals.sdk.contracts.beanstalk.interface.decodeFunctionResult("claimWithdrawals", result) }; } } diff --git a/projects/sdk/src/lib/farm/actions/Exchange.ts b/projects/sdk/src/lib/farm/actions/Exchange.ts index 06689d2aba..41607edc82 100644 --- a/projects/sdk/src/lib/farm/actions/Exchange.ts +++ b/projects/sdk/src/lib/farm/actions/Exchange.ts @@ -4,6 +4,9 @@ import { Token } from "src/classes/Token"; import { CurveMetaPool__factory, CurvePlainPool__factory } from "src/constants/generated"; import { FarmFromMode, FarmToMode } from "../types"; +/** + * @deprecated + */ export class Exchange extends StepClass implements StepClass { public name: string = "exchange"; @@ -87,20 +90,23 @@ export class Exchange extends StepClass implements StepClass Exchange.sdk.contracts.beanstalk.interface.decodeFunctionData("exchange", data), - decodeResult: (result: string) => Exchange.sdk.contracts.beanstalk.interface.decodeFunctionResult("exchange", result) + decode: () => undefined, + decodeResult: () => undefined + // decode: (data: string) => Exchange.sdk.contracts.beanstalk.interface.decodeFunctionData("exchange", data), + // decodeResult: (result: string) => Exchange.sdk.contracts.beanstalk.interface.decodeFunctionResult("exchange", result) }; } } diff --git a/projects/sdk/src/lib/farm/actions/ExchangeUnderlying.ts b/projects/sdk/src/lib/farm/actions/ExchangeUnderlying.ts index ca928c5606..af039292e0 100644 --- a/projects/sdk/src/lib/farm/actions/ExchangeUnderlying.ts +++ b/projects/sdk/src/lib/farm/actions/ExchangeUnderlying.ts @@ -4,6 +4,10 @@ import { Token } from "src/classes/Token"; import { CurveMetaPool__factory } from "src/constants/generated"; import { FarmFromMode, FarmToMode } from "../types"; +/** + * @deprecated + * deprecated after beanstalk3 upgrade + */ export class ExchangeUnderlying extends StepClass { public name: string = "exchangeUnderlying"; @@ -69,20 +73,22 @@ export class ExchangeUnderlying extends StepClass { if (!minAmountOut) throw new Error("ExchangeUnderlying: Missing minAmountOut"); return { target: ExchangeUnderlying.sdk.contracts.beanstalk.address, - callData: ExchangeUnderlying.sdk.contracts.beanstalk.interface.encodeFunctionData("exchangeUnderlying", [ - this.pool, - tokenIn.address, - tokenOut.address, - _amountInStep, - minAmountOut, - this.fromMode, - this.toMode - ]) + callData: "" + // callData: ExchangeUnderlying.sdk.contracts.beanstalk.interface.encodeFunctionData("exchangeUnderlying", [ + // this.pool, + // tokenIn.address, + // tokenOut.address, + // _amountInStep, + // minAmountOut, + // this.fromMode, + // this.toMode + // ]) }; }, - decode: (data: string) => ExchangeUnderlying.sdk.contracts.beanstalk.interface.decodeFunctionData("exchangeUnderlying", data), - decodeResult: (result: string) => - ExchangeUnderlying.sdk.contracts.beanstalk.interface.decodeFunctionResult("exchangeUnderlying", result) + decode: (data: string) => undefined, + // decode: (data: string) => ExchangeUnderlying.sdk.contracts.beanstalk.interface.decodeFunctionData("exchangeUnderlying", data), + decodeResult: (result: string) => undefined + // ExchangeUnderlying.sdk.contracts.beanstalk.interface.decodeFunctionResult("exchangeUnderlying", result) }; } } diff --git a/projects/sdk/src/lib/farm/actions/RemoveLiquidityOneToken.ts b/projects/sdk/src/lib/farm/actions/RemoveLiquidityOneToken.ts index bd622013de..85a73f5e9e 100644 --- a/projects/sdk/src/lib/farm/actions/RemoveLiquidityOneToken.ts +++ b/projects/sdk/src/lib/farm/actions/RemoveLiquidityOneToken.ts @@ -3,6 +3,10 @@ import { BasicPreparedResult, RunContext, RunMode, StepClass, Workflow } from "s import { CurveMetaPool__factory, CurvePlainPool__factory } from "src/constants/generated"; import { FarmFromMode, FarmToMode } from "../types"; +/** + * @deprecated + * deprecated after beanstalk3 upgrade + */ export class RemoveLiquidityOneToken extends StepClass { public name: string = "RemoveLiquidityOneToken"; @@ -74,21 +78,22 @@ export class RemoveLiquidityOneToken extends StepClass { if (!minAmountOut) throw new Error("RemoveLiquidityOneToken: missing minAmountOut"); return { target: RemoveLiquidityOneToken.sdk.contracts.beanstalk.address, - callData: RemoveLiquidityOneToken.sdk.contracts.beanstalk.interface.encodeFunctionData("removeLiquidityOneToken", [ - this._pool, - this._registry, - this._tokenOut, - _amountInStep, - minAmountOut, - this._fromMode, - this._toMode - ]) + callData: "" + // callData: RemoveLiquidityOneToken.sdk.contracts.beanstalk.interface.encodeFunctionData("removeLiquidityOneToken", [ + // this._pool, + // this._registry, + // this._tokenOut, + // _amountInStep, + // minAmountOut, + // this._fromMode, + // this._toMode + // ]) }; }, - decode: (data: string) => - RemoveLiquidityOneToken.sdk.contracts.beanstalk.interface.decodeFunctionData("removeLiquidityOneToken", data), - decodeResult: (result: string) => - RemoveLiquidityOneToken.sdk.contracts.beanstalk.interface.decodeFunctionResult("removeLiquidityOneToken", result) + decode: (data: string) => undefined, + // RemoveLiquidityOneToken.sdk.contracts.beanstalk.interface.decodeFunctionData("removeLiquidityOneToken", data), + decodeResult: (result: string) => undefined + // RemoveLiquidityOneToken.sdk.contracts.beanstalk.interface.decodeFunctionResult("removeLiquidityOneToken", result) }; } } diff --git a/projects/sdk/src/lib/market/pods/pods.ts b/projects/sdk/src/lib/market/pods/pods.ts index 6514677400..a5b9412065 100644 --- a/projects/sdk/src/lib/market/pods/pods.ts +++ b/projects/sdk/src/lib/market/pods/pods.ts @@ -15,6 +15,9 @@ class NotFoundError extends BaseError { } } +/** + * @deprecated + */ export class PodsMarket { static sdk: BeanstalkSDK; @@ -35,18 +38,16 @@ export class PodsMarket { validate: boolean; } ) { - const [isValid, query] = await Promise.all([ - options?.validate - ? PodsMarket.sdk.contracts.beanstalk.podListing(id).then((r) => ethers.BigNumber.from(r).gt(0)) - : Promise.resolve(true), - PodsMarket.sdk.queries.getListingByIndex({ index: id }) - ]); - - if (!isValid || !query.podListings[0]) { - throw new NotFoundError("Listing", id); - } - - return query.podListings[0]; // FIXME: cast + // const [isValid, query] = await Promise.all([ + // options?.validate + // ? PodsMarket.sdk.contracts.beanstalk.getPodListing(id).then((r) => ethers.BigNumber.from(r).gt(0)) + // : Promise.resolve(true), + // PodsMarket.sdk.queries.getListingByIndex({ index: id }) + // ]); + // if (!isValid || !query.podListings[0]) { + // throw new NotFoundError("Listing", id); + // } + // return query.podListings[0]; // FIXME: cast } /** diff --git a/projects/sdk/src/lib/silo.ts b/projects/sdk/src/lib/silo.ts index 7a01d6fa49..d1f106c9b4 100644 --- a/projects/sdk/src/lib/silo.ts +++ b/projects/sdk/src/lib/silo.ts @@ -405,7 +405,8 @@ export class Silo { */ async getSeeds(_account?: string) { const account = await Silo.sdk.getAccount(_account); - return Silo.sdk.contracts.beanstalk.balanceOfLegacySeeds(account).then((v) => Silo.sdk.tokens.SEEDS.fromBlockchain(v)); + return Silo.sdk.tokens.SEEDS.fromHuman(1); + // return Silo.sdk.contracts.beanstalk.balanceOfLegacySeeds(account).then((v) => Silo.sdk.tokens.SEEDS.fromBlockchain(v)); } /** From cb09129b08d7352550c2f71ab823af63bd88e7e6 Mon Sep 17 00:00:00 2001 From: Spacebean Date: Mon, 5 Aug 2024 23:23:31 +0200 Subject: [PATCH 04/11] fix: update farm --- projects/sdk/src/lib/farm/farm.ts | 52 +++++++++++++++++++++++-------- 1 file changed, 39 insertions(+), 13 deletions(-) diff --git a/projects/sdk/src/lib/farm/farm.ts b/projects/sdk/src/lib/farm/farm.ts index 0ddc565864..442409fdc0 100644 --- a/projects/sdk/src/lib/farm/farm.ts +++ b/projects/sdk/src/lib/farm/farm.ts @@ -16,7 +16,9 @@ type FarmPreparedResult = { callData: string }; * FarmWorkflow * => `beanstalk.farm()`. */ -export class FarmWorkflow extends Workflow< +export class FarmWorkflow< + RunData extends { slippage: number } = { slippage: number } +> extends Workflow< string, // EncodedResult FarmPreparedResult, // PreparedResult RunData // RunData @@ -24,7 +26,11 @@ export class FarmWorkflow { + async execute( + amountIn: ethers.BigNumber | TokenValue, + data: RunData, + overrides?: CallOverrides + ): Promise { const encodedSteps = await this.estimateAndEncodeSteps(amountIn, RunMode.Execute, data); if (overrides) { overrides.value = this.value; @@ -64,6 +74,7 @@ export class FarmWorkflow { + async estimateGas( + amountIn: ethers.BigNumber | TokenValue, + data: RunData + ): Promise { const encodedSteps = await this.estimateAndEncodeSteps(amountIn, RunMode.EstimateGas, data); return this.contract.estimateGas.farm(encodedSteps, { value: this.value }); } @@ -86,15 +100,16 @@ type AdvancedFarmPreparedResult = { callData: string; clipboard?: string; }; -export class AdvancedFarmWorkflow extends Workflow< - AdvancedFarmCallStruct, - AdvancedFarmPreparedResult, - RunData -> { +export class AdvancedFarmWorkflow< + RunData extends { slippage: number } = { slippage: number } +> extends Workflow { public readonly FUNCTION_NAME = "advancedFarm"; private contract: Beanstalk; - constructor(protected sdk: BeanstalkSDK, public name: string = "AdvancedFarm") { + constructor( + protected sdk: BeanstalkSDK, + public name: string = "AdvancedFarm" + ) { super(sdk, name); this.contract = Workflow.sdk.contracts.beanstalk; // ? } @@ -128,7 +143,11 @@ export class AdvancedFarmWorkflow { + async execute( + amountIn: ethers.BigNumber | TokenValue, + data: RunData, + overrides?: CallOverrides + ): Promise { const encoded = await this.estimateAndEncodeSteps(amountIn, RunMode.Execute, data); if (overrides) { overrides.value = this.value; @@ -136,6 +155,7 @@ export class AdvancedFarmWorkflow { + async estimateGas( + amountIn: ethers.BigNumber | TokenValue, + data: RunData + ): Promise { const encoded = await this.estimateAndEncodeSteps(amountIn, RunMode.EstimateGas, data); return this.contract.estimateGas.advancedFarm(encoded, { value: this.value }); } @@ -164,7 +187,10 @@ export class Farm { this.presets = new LibraryPresets(Farm.sdk); } - create>(name?: string, using: "beanstalk" | "depot" = "beanstalk"): FarmWorkflow<{ slippage: number } & T> { + create>( + name?: string, + using: "beanstalk" | "depot" = "beanstalk" + ): FarmWorkflow<{ slippage: number } & T> { return new FarmWorkflow(Farm.sdk, name, using); } From d4c925c3c0921ce622d0e69aca8217ef2f3964f7 Mon Sep 17 00:00:00 2001 From: Spacebean Date: Mon, 5 Aug 2024 23:28:59 +0200 Subject: [PATCH 05/11] feat: fix dex-ui build --- projects/dex-ui/package.json | 3 +++ projects/dex-ui/src/components/Dropdown.tsx | 6 +++--- 2 files changed, 6 insertions(+), 3 deletions(-) diff --git a/projects/dex-ui/package.json b/projects/dex-ui/package.json index b4eedbdd23..a01c41b755 100644 --- a/projects/dex-ui/package.json +++ b/projects/dex-ui/package.json @@ -21,9 +21,12 @@ }, "dependencies": { "@beanstalk/sdk": "workspace:*", + "@radix-ui/react-dialog": "1.0.5", + "@radix-ui/react-dropdown-menu": "2.1.1", "@tanstack/react-query": "5.28.4", "@tanstack/react-query-devtools": "5.28.4", "@typechain/ethers-v5": "10.2.1", + "alchemy-sdk": "3.3.1", "connectkit": "1.7.2", "ethers": "^5.7.2", "graphql-request": "5.2.0", diff --git a/projects/dex-ui/src/components/Dropdown.tsx b/projects/dex-ui/src/components/Dropdown.tsx index c2208c3409..3482e18224 100644 --- a/projects/dex-ui/src/components/Dropdown.tsx +++ b/projects/dex-ui/src/components/Dropdown.tsx @@ -21,8 +21,8 @@ const Dropdown = ({ open, children, trigger, offset, setOpen }: DropdownProps) = e.preventDefault()} - onClick={(e) => e.preventDefault()} + onMouseDown={(e: any) => e.preventDefault()} + onClick={(e: any) => e.preventDefault()} > {trigger} @@ -31,7 +31,7 @@ const Dropdown = ({ open, children, trigger, offset, setOpen }: DropdownProps) = e.preventDefault()} + onFocus={(e: any) => e.preventDefault()} > <>{children} From 34ef1b76694b408016f08dabc1470eb6d7c7abdb Mon Sep 17 00:00:00 2001 From: Spacebean Date: Tue, 6 Aug 2024 00:25:04 +0200 Subject: [PATCH 06/11] fix: create order / fill listing --- .../Common/Connection/WalletButton.tsx | 24 +- .../components/Farmer/Unripe/PickDialog.tsx | 530 ------------------ .../src/components/Field/Actions/Transfer.tsx | 30 +- .../Market/PodsV2/Actions/Buy/CreateOrder.tsx | 10 +- .../Market/PodsV2/Actions/Buy/FillListing.tsx | 2 +- .../PodsV2/Actions/Buy/FillListingForm.tsx | 24 +- .../src/components/Silo/Actions/Migrate.tsx | 234 -------- .../ui/src/components/Silo/MigrateTab.tsx | 85 +-- 8 files changed, 89 insertions(+), 850 deletions(-) delete mode 100644 projects/ui/src/components/Farmer/Unripe/PickDialog.tsx delete mode 100644 projects/ui/src/components/Silo/Actions/Migrate.tsx diff --git a/projects/ui/src/components/Common/Connection/WalletButton.tsx b/projects/ui/src/components/Common/Connection/WalletButton.tsx index 5e07e2f3e9..1bcb0c72e7 100644 --- a/projects/ui/src/components/Common/Connection/WalletButton.tsx +++ b/projects/ui/src/components/Common/Connection/WalletButton.tsx @@ -25,7 +25,6 @@ import useAnchor from '~/hooks/display/useAnchor'; import useToggle from '~/hooks/display/useToggle'; import useAccount from '~/hooks/ledger/useAccount'; import { CHAIN_INFO } from '~/constants'; -import PickBeansDialog from '~/components/Farmer/Unripe/PickDialog'; import AddressIcon from '~/components/Common/AddressIcon'; import useGlobal from '~/hooks/app/useGlobal'; import Row from '~/components/Common/Row'; @@ -56,7 +55,7 @@ const WalletButton: FC<{ showFullText?: boolean } & ButtonProps> = ({ const [selectingWallet, showWallets, hideWallets] = useToggle(); /// Dialog: Pick Unripe Beans - const [picking, showPick, hidePick] = useToggle(toggleMenuAnchor); + // const [picking, showPick, hidePick] = useToggle(toggleMenuAnchor); /// Dialog: Settings const [_, setSettingsOpen] = useGlobal('showSettings'); @@ -155,25 +154,6 @@ const WalletButton: FC<{ showFullText?: boolean } & ButtonProps> = ({ - - - - - - ))} + {step === 9 && ( + + + + You've Migrated! + + + + + )} ); From 98b35cfc42ad43c6689a1e2b913c80c17487b56b Mon Sep 17 00:00:00 2001 From: Spacebean Date: Tue, 6 Aug 2024 00:28:08 +0200 Subject: [PATCH 07/11] fix createlisting --- .../PodsV2/Actions/Sell/CreateListing.tsx | 37 ++++++++++++++----- 1 file changed, 27 insertions(+), 10 deletions(-) diff --git a/projects/ui/src/components/Market/PodsV2/Actions/Sell/CreateListing.tsx b/projects/ui/src/components/Market/PodsV2/Actions/Sell/CreateListing.tsx index 3dec3ea425..faf84803a2 100644 --- a/projects/ui/src/components/Market/PodsV2/Actions/Sell/CreateListing.tsx +++ b/projects/ui/src/components/Market/PodsV2/Actions/Sell/CreateListing.tsx @@ -37,6 +37,7 @@ import FieldWrapper from '~/components/Common/Form/FieldWrapper'; import { FC } from '~/types'; import useFormMiddleware from '~/hooks/ledger/useFormMiddleware'; import { useFetchFarmerMarketItems } from '~/hooks/farmer/market/useFarmerMarket2'; +import useAccount from '~/hooks/ledger/useAccount'; export type CreateListingFormValues = { plot: PlotFragment; @@ -201,6 +202,8 @@ const CreateListingV2: FC<{}> = () => { /// Tokens const getChainToken = useGetChainToken(); + const account = useAccount(); + /// Ledger const { data: signer } = useSigner(); const beanstalk = useBeanstalkContract(signer); @@ -279,15 +282,28 @@ const CreateListingV2: FC<{}> = () => { /// expiresAt is relative (ie 0 = front of pod line) /// add harvestableIndex to make it absolute const maxHarvestableIndex = expiresAt.plus(harvestableIndex); - const txn = await beanstalk.createPodListing( - toStringBaseUnitBN(index, Bean.decimals), // absolute plot index - toStringBaseUnitBN(start, Bean.decimals), // relative start index - toStringBaseUnitBN(amount, Bean.decimals), // relative amount - toStringBaseUnitBN(pricePerPod, Bean.decimals), // price per pod - toStringBaseUnitBN(maxHarvestableIndex, Bean.decimals), // absolute index of expiry - toStringBaseUnitBN(new BigNumber(1), Bean.decimals), // minFillAmount is measured in Beans - destination - ); + const txn = await beanstalk.createPodListing({ + lister: account || '', + fieldId: '0', + index: toStringBaseUnitBN(index, Bean.decimals), // absolute plot index + start: toStringBaseUnitBN(start, Bean.decimals), // relative start index + podAmount: toStringBaseUnitBN(amount, Bean.decimals), // relative amount + pricePerPod: toStringBaseUnitBN(pricePerPod, Bean.decimals), // price per pod + maxHarvestableIndex: toStringBaseUnitBN( + maxHarvestableIndex, + Bean.decimals + ), // absolute index of expiry + minFillAmount: toStringBaseUnitBN(new BigNumber(1), Bean.decimals), // minFillAmount is measured in Beans + mode: destination, + }); + + // toStringBaseUnitBN(start, Bean.decimals), // relative start index + // toStringBaseUnitBN(amount, Bean.decimals), // relative amount + // toStringBaseUnitBN(pricePerPod, Bean.decimals), // price per pod + // toStringBaseUnitBN(maxHarvestableIndex, Bean.decimals), // absolute index of expiry + // toStringBaseUnitBN(new BigNumber(1), Bean.decimals), // minFillAmount is measured in Beans + // destination + // ); txToast.confirming(txn); const receipt = await txn.wait(); @@ -306,12 +322,13 @@ const CreateListingV2: FC<{}> = () => { } }, [ + getChainToken, middleware, plots, harvestableIndex, beanstalk, + account, refetchFarmerMarketItems, - getChainToken, ] ); From 4b796c9e6b871baa51e325350e2e4d05e9d47509 Mon Sep 17 00:00:00 2001 From: Spacebean Date: Tue, 6 Aug 2024 00:29:54 +0200 Subject: [PATCH 08/11] fix: market fill order --- .../ui/src/components/Market/PodsV2/Actions/Sell/FillOrder.tsx | 2 +- .../components/Market/PodsV2/Actions/Sell/FillOrderForm.tsx | 3 ++- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/projects/ui/src/components/Market/PodsV2/Actions/Sell/FillOrder.tsx b/projects/ui/src/components/Market/PodsV2/Actions/Sell/FillOrder.tsx index 954f76ac67..5a75ae0131 100644 --- a/projects/ui/src/components/Market/PodsV2/Actions/Sell/FillOrder.tsx +++ b/projects/ui/src/components/Market/PodsV2/Actions/Sell/FillOrder.tsx @@ -23,7 +23,7 @@ const FillOrder: React.FC<{}> = () => { (async () => { try { const _order = await beanstalk - .podOrderById(orderID.toString()) + .getPodOrder(orderID.toString()) .then(bigNumberResult); console.debug('[pages/order] order = ', _order); setOrderValid(_order?.gt(0)); diff --git a/projects/ui/src/components/Market/PodsV2/Actions/Sell/FillOrderForm.tsx b/projects/ui/src/components/Market/PodsV2/Actions/Sell/FillOrderForm.tsx index 26ba75cb69..785cefc3ec 100644 --- a/projects/ui/src/components/Market/PodsV2/Actions/Sell/FillOrderForm.tsx +++ b/projects/ui/src/components/Market/PodsV2/Actions/Sell/FillOrderForm.tsx @@ -213,7 +213,8 @@ const FillOrderForm: FC<{ podOrder: PodOrder }> = ({ podOrder }) => { const txn = await beanstalk.fillPodOrder( { - account: podOrder.account, + orderer: podOrder.account, + fieldId: '0', maxPlaceInLine: Bean.stringify(podOrder.maxPlaceInLine), pricePerPod: Bean.stringify(podOrder.pricePerPod), minFillAmount: PODS.stringify(podOrder.minFillAmount || 0), // minFillAmount for Orders is measured in Pods From fdd457d3057acf48911666a63ed5cd8066492a87 Mon Sep 17 00:00:00 2001 From: Spacebean Date: Tue, 6 Aug 2024 00:35:30 +0200 Subject: [PATCH 09/11] fix: silo transfer, buy fert, cancel market --- .../src/components/Silo/Actions/Transfer.tsx | 63 +------------------ .../farmer/market/useFarmerMarketCancelTxn.ts | 21 +++++-- .../src/lib/Txn/FarmSteps/barn/BuyFarmStep.ts | 6 +- .../lib/Txn/FarmSteps/silo/ClaimFarmStep.ts | 25 ++++---- 4 files changed, 36 insertions(+), 79 deletions(-) diff --git a/projects/ui/src/components/Silo/Actions/Transfer.tsx b/projects/ui/src/components/Silo/Actions/Transfer.tsx index 9389bb9515..4d3425ccf0 100644 --- a/projects/ui/src/components/Silo/Actions/Transfer.tsx +++ b/projects/ui/src/components/Silo/Actions/Transfer.tsx @@ -1,5 +1,5 @@ -import React, { useCallback, useEffect, useMemo } from 'react'; -import { Box, Divider, Grid, Stack, Typography } from '@mui/material'; +import React, { useCallback, useMemo } from 'react'; +import { Box, Divider, Stack } from '@mui/material'; import { Form, Formik, FormikHelpers, FormikProps } from 'formik'; import BigNumber from 'bignumber.js'; import { @@ -80,34 +80,10 @@ const TransferForm: FC< plantAndDoX, }) => { const sdk = useSdk(); - const [migrationNeeded, setMigrationNeeded] = React.useState(false); const { BEAN, STALK, SEEDS } = sdk.tokens; // Check address on change - useEffect(() => { - const check = async (address: string) => { - try { - const needed = await sdk.contracts.beanstalk.migrationNeeded( - address.toLocaleLowerCase() - ); - setMigrationNeeded(needed); - } catch (err) { - console.error( - 'Error while checking if address needs migration: ', - address, - err - ); - } - }; - - if (values.to.length === 42) { - check(values.to); - } else { - setMigrationNeeded(false); - } - }, [sdk.contracts.beanstalk, values.to]); - /// Claim and Plant const txnActions = useFarmerFormTxnsActions({ mode: 'plantToggle' }); const isUsingPlant = Boolean( @@ -336,38 +312,6 @@ const TransferForm: FC< )} )} - {migrationNeeded && ( - // - // - // Migration Needed - // - // - // Transfers can only be made to accounts that have migrated to Silo - // v3. The account you are trying to transfer to has not migrated - // yet. - // - // - - - - Migration Required - -
- - Transfers can only be made to accounts that have migrated to - Silo v3. The account you are trying to transfer to has not - migrated yet. - -
-
-
- )} diff --git a/projects/ui/src/lib/Txn/FarmSteps/silo/ClaimFarmStep.ts b/projects/ui/src/lib/Txn/FarmSteps/silo/ClaimFarmStep.ts index 469f151692..2766432f0b 100644 --- a/projects/ui/src/lib/Txn/FarmSteps/silo/ClaimFarmStep.ts +++ b/projects/ui/src/lib/Txn/FarmSteps/silo/ClaimFarmStep.ts @@ -9,6 +9,9 @@ import { ethers } from 'ethers'; import { EstimatesGas, FarmStep } from '~/lib/Txn/Interface'; // TODO(silo-v3): something about this implementation chain breaks the typing of `this._sdk` +/** + * @deprecated + */ export class ClaimFarmStep extends FarmStep implements EstimatesGas { constructor( _sdk: BeanstalkSDK, @@ -22,20 +25,20 @@ export class ClaimFarmStep extends FarmStep implements EstimatesGas { async estimateGas() { const { beanstalk } = this._sdk.contracts; - let gasEstimate: ethers.BigNumber; + const gasEstimate: ethers.BigNumber = ethers.BigNumber.from(0); if (this._seasons.length === 1) { - gasEstimate = await beanstalk.estimateGas.claimWithdrawal( - this._tokenIn.address, - this._seasons[0], - FarmToMode.INTERNAL - ); + // gasEstimate = await beanstalk.estimateGas.claimWithdrawal( + // this._tokenIn.address, + // this._seasons[0], + // FarmToMode.INTERNAL + // ); } - gasEstimate = await beanstalk.estimateGas.claimWithdrawals( - this._tokenIn.address, - this._seasons, - FarmToMode.INTERNAL - ); + // gasEstimate = await beanstalk.estimateGas.claimWithdrawals( + // this._tokenIn.address, + // this._seasons, + // FarmToMode.INTERNAL + // ); console.debug(`[ClaimFarmStep][estimateGas]: `, gasEstimate.toString()); return gasEstimate; From 2d9bf09fe318fbfea7a67305fd77d10227b7714b Mon Sep 17 00:00:00 2001 From: Spacebean Date: Tue, 6 Aug 2024 00:38:21 +0200 Subject: [PATCH 10/11] fix: farm steps --- .../lib/Txn/FarmSteps/field/HarvestFarmStep.ts | 2 ++ .../lib/Txn/FarmSteps/market/BuyPlotsFarmStep.ts | 15 +++++++++++---- 2 files changed, 13 insertions(+), 4 deletions(-) diff --git a/projects/ui/src/lib/Txn/FarmSteps/field/HarvestFarmStep.ts b/projects/ui/src/lib/Txn/FarmSteps/field/HarvestFarmStep.ts index 579fe02742..781c9e4af3 100644 --- a/projects/ui/src/lib/Txn/FarmSteps/field/HarvestFarmStep.ts +++ b/projects/ui/src/lib/Txn/FarmSteps/field/HarvestFarmStep.ts @@ -14,6 +14,7 @@ export class HarvestFarmStep extends FarmStep implements EstimatesGas { async estimateGas() { const { beanstalk } = this._sdk.contracts; const gasEstimate = await beanstalk.estimateGas.harvest( + '0', this._plotIds, FarmToMode.INTERNAL ); @@ -33,6 +34,7 @@ export class HarvestFarmStep extends FarmStep implements EstimatesGas { prepare: () => ({ target: beanstalk.address, callData: beanstalk.interface.encodeFunctionData('harvest', [ + '0', this._plotIds, toMode, ]), diff --git a/projects/ui/src/lib/Txn/FarmSteps/market/BuyPlotsFarmStep.ts b/projects/ui/src/lib/Txn/FarmSteps/market/BuyPlotsFarmStep.ts index e82837e629..2c0aa42b42 100644 --- a/projects/ui/src/lib/Txn/FarmSteps/market/BuyPlotsFarmStep.ts +++ b/projects/ui/src/lib/Txn/FarmSteps/market/BuyPlotsFarmStep.ts @@ -15,7 +15,10 @@ import { ethers } from 'ethers'; import { toStringBaseUnitBN, tokenValueToBN } from '~/util'; export class BuyPlotsFarmStep extends FarmStep { - constructor(_sdk: BeanstalkSDK, private _account: string) { + constructor( + _sdk: BeanstalkSDK, + private _account: string + ) { super(_sdk); this._account = _account; } @@ -47,10 +50,14 @@ export class BuyPlotsFarmStep extends FarmStep { prepare: () => ({ target: beanstalk.address, callData: beanstalk.interface.encodeFunctionData('createPodOrder', [ + { + orderer: this._account, + fieldId: '0', + pricePerPod: BEAN[1].stringify(pricePerPod), + maxPlaceInLine: BEAN[1].stringify(placeInLine), + minFillAmount: toStringBaseUnitBN(new BigNumber(1), PODS.decimals), + }, BEAN[1].stringify(tokenValueToBN(beanAmountOut)), - BEAN[1].stringify(pricePerPod), - BEAN[1].stringify(placeInLine), - toStringBaseUnitBN(new BigNumber(1), PODS.decimals), FarmFromMode.INTERNAL_TOLERANT, ]), }), From dca3d881dab049cb671cfeaad6d5c92b26c8c78a Mon Sep 17 00:00:00 2001 From: Spacebean Date: Tue, 6 Aug 2024 10:05:18 +0200 Subject: [PATCH 11/11] fix: silo / field state --- .../ui/src/state/beanstalk/field/updater.ts | 6 +- .../ui/src/state/beanstalk/silo/updater.ts | 19 +- projects/ui/src/state/farmer/field/updater.ts | 8 +- projects/ui/src/state/farmer/silo/updater.ts | 223 ++++-------------- 4 files changed, 67 insertions(+), 189 deletions(-) diff --git a/projects/ui/src/state/beanstalk/field/updater.ts b/projects/ui/src/state/beanstalk/field/updater.ts index eaad83c05b..c97b346731 100644 --- a/projects/ui/src/state/beanstalk/field/updater.ts +++ b/projects/ui/src/state/beanstalk/field/updater.ts @@ -22,11 +22,11 @@ export const useFetchBeanstalkField = () => { adjustedTemperature, maxTemperature, ] = await Promise.all([ - beanstalk.harvestableIndex().then(tokenResult(BEAN)), // FIXME - beanstalk.podIndex().then(tokenResult(BEAN)), + beanstalk.harvestableIndex('0').then(tokenResult(BEAN)), // FIXME + beanstalk.podIndex('0').then(tokenResult(BEAN)), beanstalk.totalSoil().then(tokenResult(BEAN)), beanstalk.weather().then((_weather) => ({ - lastDSoil: tokenResult(BEAN)(_weather.lastDSoil), + lastDSoil: tokenResult(BEAN)(_weather.lastDeltaSoil), lastSowTime: bigNumberResult(_weather.lastSowTime), thisSowTime: bigNumberResult(_weather.thisSowTime), })), diff --git a/projects/ui/src/state/beanstalk/silo/updater.ts b/projects/ui/src/state/beanstalk/silo/updater.ts index bd0e0f791c..3bf94acd99 100644 --- a/projects/ui/src/state/beanstalk/silo/updater.ts +++ b/projects/ui/src/state/beanstalk/silo/updater.ts @@ -12,9 +12,9 @@ import { bigNumberResult } from '~/util/Ledger'; import { tokenResult, transform } from '~/util'; import { BEAN, STALK } from '~/constants/tokens'; import { useGetChainConstant } from '~/hooks/chain/useChainConstant'; +import useSdk from '~/hooks/sdk'; import { resetBeanstalkSilo, updateBeanstalkSilo } from './actions'; import { BeanstalkSiloBalance } from './index'; -import useSdk from '~/hooks/sdk'; export const useFetchBeanstalkSilo = () => { const dispatch = useDispatch(); @@ -52,9 +52,9 @@ export const useFetchBeanstalkSilo = () => { sdk.contracts.beanstalk .getTotalDeposited(token.address) .then((v) => transform(v, 'bnjs', token)), - sdk.contracts.beanstalk - .getTotalWithdrawn(token.address) - .then((v) => transform(v, 'bnjs', token)), + // sdk.contracts.beanstalk + // .getTotalWithdrawn(token.address) + // .then((v) => transform(v, 'bnjs', token)), // BEAN will always have a fixed BDV of 1, skip to save a network request token === sdk.tokens.BEAN @@ -76,10 +76,10 @@ export const useFetchBeanstalkSilo = () => { ]).then((data) => ({ address: token.address.toLowerCase(), deposited: data[0], - withdrawn: data[1], - bdvPerToken: data[2], - stemTip: data[3], - depositedBdv: data[4], + // withdrawn: data[1], + bdvPerToken: data[1], + stemTip: data[2], + depositedBdv: data[3], })) ) ), @@ -117,7 +117,8 @@ export const useFetchBeanstalkSilo = () => { amount: curr.deposited, }, withdrawn: { - amount: curr.withdrawn, + amount: ZERO_BN, + // amount: curr.withdrawn, }, }; diff --git a/projects/ui/src/state/farmer/field/updater.ts b/projects/ui/src/state/farmer/field/updater.ts index 55ce736be9..ffeb42c28d 100644 --- a/projects/ui/src/state/farmer/field/updater.ts +++ b/projects/ui/src/state/farmer/field/updater.ts @@ -4,15 +4,15 @@ import { EventProcessor } from '@beanstalk/sdk'; import useChainId from '~/hooks/chain/useChainId'; import useAccount from '~/hooks/ledger/useAccount'; import useHarvestableIndex from '~/hooks/beanstalk/useHarvestableIndex'; -import useEvents, { GetEventsFn } from '../events2/updater'; +import useSdk from '~/hooks/sdk'; +import { transform } from '~/util/BigNumber'; +import { FarmerField } from '~/state/farmer/field'; import { resetFarmerField, updateFarmerField, updateFarmerFieldLoading, } from './actions'; -import useSdk from '~/hooks/sdk'; -import { transform } from '~/util/BigNumber'; -import { FarmerField } from '~/state/farmer/field'; +import useEvents, { GetEventsFn } from '../events2/updater'; export const useFetchFarmerField = () => { /// Helpers diff --git a/projects/ui/src/state/farmer/silo/updater.ts b/projects/ui/src/state/farmer/silo/updater.ts index 6beb4eb9ff..2034bd5342 100644 --- a/projects/ui/src/state/farmer/silo/updater.ts +++ b/projects/ui/src/state/farmer/silo/updater.ts @@ -3,7 +3,6 @@ import { useDispatch } from 'react-redux'; import BigNumber from 'bignumber.js'; import axios from 'axios'; import { Deposit, Token, TokenValue } from '@beanstalk/sdk'; -import { ethers } from 'ethers'; import { TokenMap, ZERO_BN } from '~/constants'; import { useBeanstalkContract } from '~/hooks/ledger/useContract'; import useChainId from '~/hooks/chain/useChainId'; @@ -16,7 +15,6 @@ import { resetFarmerSilo, updateLegacyFarmerSiloBalances, UpdateFarmerSiloBalancesPayload, - updateFarmerMigrationStatus, updateLegacyFarmerSiloRewards, updateFarmerSiloBalanceSdk, updateFarmerSiloLoading, @@ -88,10 +86,10 @@ export const useFetchFarmerSilo = () => { { grownStalkBalance, grownStalkByToken }, rootBalance, earnedBeanBalance, - migrationNeeded, + // migrationNeeded, mowStatuses, lastUpdate, - stemTips + stemTips, ] = await Promise.all([ // `getStalk()` returns `stalk + earnedStalk` but NOT grown stalk sdk.silo.getStalk(account), @@ -120,7 +118,7 @@ export const useFetchFarmerSilo = () => { // FIXME: this only needs to get fetched once and then can probably be cached // in LocalStorage or at least moved to a separate updater to prevent it from // getting called every time the farmer refreshes their Silo - sdk.contracts.beanstalk.migrationNeeded(account), + // sdk.contracts.beanstalk.migrationNeeded(account), // Get the mowStatus struct for each whitelisted token Promise.all( @@ -138,168 +136,54 @@ export const useFetchFarmerSilo = () => { >(statuses) ), beanstalk.lastUpdate(account), - sdk.silo.getStemTips([...sdk.tokens.siloWhitelist]) + sdk.silo.getStemTips([...sdk.tokens.siloWhitelist]), ] as const); - dispatch(updateFarmerMigrationStatus(migrationNeeded)); + // dispatch(updateFarmerMigrationStatus(migrationNeeded)); // Transform the flatfile data into the legacy UI data structure const payload: UpdateFarmerSiloBalancesPayload = {}; let activeSeedBalance: TokenValue = TokenValue.ZERO; - - if (migrationNeeded) { - // After the migration block is locked in, no deposits can change in - // Silo V2, so we use a flatfile with silo data for each account to - // prevent the needed to support two different historical event schemas. - const [balances, _activeSeedBalance] = await Promise.all([ - fetchMigrationData(account), - sdk.silo.getSeeds(account), - ]); - - // Pre-migration, # of seeds is calc'd from the contract getter - activeSeedBalance = _activeSeedBalance; - - // const currentSeason = TokenValue.fromBlockchain(season.toString(), 0); - Object.entries(balances.deposits).forEach( - ([addr, depositsBySeason]) => { - // All of the tokens addresses in the flatfile - // should exist in the SDK already - const token = sdk.tokens.findByAddress(addr); - if (!token) return; - - // const mowStatus = mowStatuses.get(token); - // if (!mowStatus) return; - - payload[token.address] = { - mowStatus: undefined, - deposited: { - // Note that deposits in the flatfile are keyed by season - // instead of stem - ...Object.keys(depositsBySeason).reduce( - (dep, depositSeason) => { - const crate = depositsBySeason[depositSeason]; - - // For simplicity we operate here with TokenValues using the SDK - const bdvTV = sdk.tokens.BEAN.fromBlockchain(crate.bdv); - const amountTV = token.fromBlockchain(crate.amount); - - // HACK: since we set the seeds value to zero, need to - // use the old value here - let seedsTV; - if (token === sdk.tokens.UNRIPE_BEAN) { - seedsTV = sdk.tokens.SEEDS.amount(2).mul(bdvTV); - } else if (token === sdk.tokens.BEAN) { - seedsTV = sdk.tokens.SEEDS.amount(2).mul(bdvTV); - } else if (token === sdk.tokens.BEAN_CRV3_LP) { - seedsTV = sdk.tokens.SEEDS.amount(4).mul(bdvTV); - } else if (token === sdk.tokens.UNRIPE_BEAN_WETH) { - seedsTV = sdk.tokens.SEEDS.amount(4).mul(bdvTV); - } else { - seedsTV = token.getSeeds(bdvTV); - }; - - // This token's stem tip - const tokenStemTip = stemTips.get(token.address); - - // This token's base stalk - const baseStalkTV = bdvTV; - - // Delta between this account's last Silo update and Silo V3 deployment - const updateDelta = TokenValue.fromHuman(14210 - lastUpdate, 0); - - // Mown Stalk - const mownTV = sdk.silo.calculateGrownStalkSeeds(lastUpdate, depositSeason.toString(), seedsTV); - - // Stalk Grown between last Silo update and Silo V3 deployment - const grownBeforeStemsTV = TokenValue.fromBlockchain(seedsTV.mul(updateDelta).toBlockchain(), sdk.tokens.STALK.decimals); - - // Stalk Grown after Silo V3 deployment - const ethersZERO = TokenValue.ZERO.toBigNumber(); - const grownAfterStemsTV = sdk.silo.calculateGrownStalk(tokenStemTip || ethersZERO, ethersZERO, bdvTV); - - // Legacy BigNumberJS values - const bdv = transform(bdvTV, 'bnjs'); - const amount = transform(amountTV, 'bnjs'); - - // Update totals - dep.amount = dep.amount.plus(amount); - dep.bdv = dep.bdv.plus(bdv); - - // Create deposit crate - dep.crates.push({ - stem: ethers.BigNumber.from(depositSeason), - amount: amount, - bdv: bdv, - stalk: { - base: transform(baseStalkTV.add(mownTV), 'bnjs', sdk.tokens.STALK), - grown: transform(grownBeforeStemsTV.add(grownAfterStemsTV), 'bnjs', sdk.tokens.STALK), - total: transform( - baseStalkTV.add(mownTV).add(grownBeforeStemsTV).add(grownAfterStemsTV), - 'bnjs', - sdk.tokens.STALK - ), - }, - seeds: transform(seedsTV, 'bnjs'), - isGerminating: false - }); - return dep; - }, - { - amount: ZERO_BN, - convertibleAmount: ZERO_BN, - bdv: ZERO_BN, - crates: [] as LegacyDepositCrate[], // FIXME - convertibleCrates: [] as LegacyDepositCrate[], - } - ), - }, - }; - } - ); - } else { - const balances = await sdk.silo.getBalances(account); - balances.forEach((balance, token) => { - // Post-migration, # of active seeds is calc'd from BDV - activeSeedBalance = activeSeedBalance.add( - token.getSeeds(balance.bdv) - ); - const handleCrate = ( - crate: Deposit - ): LegacyDepositCrate => ({ - // stem: transform(crate.stem, 'bnjs'), // FIXME - // ALECKS: I changed above line to below line. Typescript was expecting stem to be ethers.BigNumber - // Leaving this comment here in case there's unexpected issues somewhere downstream. - stem: crate.stem, - amount: transform(crate.amount, 'bnjs', token), - bdv: transform(crate.bdv, 'bnjs', sdk.tokens.BEAN), - stalk: { - base: transform(crate.stalk.base, 'bnjs', sdk.tokens.STALK), - grown: transform(crate.stalk.grown, 'bnjs', sdk.tokens.STALK), - total: transform(crate.stalk.total, 'bnjs', sdk.tokens.STALK), - }, - seeds: transform(crate.seeds, 'bnjs'), - isGerminating: crate.isGerminating, - }); - - payload[token.address] = { - mowStatus: mowStatuses.get(token), - deposited: { - amount: transform(balance.amount, 'bnjs', token), - convertibleAmount: transform( - balance.convertibleAmount, - 'bnjs', - token - ), - bdv: transform(balance.bdv, 'bnjs', sdk.tokens.BEAN), - crates: balance.deposits.map(handleCrate), - convertibleCrates: balance.convertibleDeposits.map(handleCrate), - }, - }; + const balances = await sdk.silo.getBalances(account); + balances.forEach((balance, token) => { + // Post-migration, # of active seeds is calc'd from BDV + activeSeedBalance = activeSeedBalance.add(token.getSeeds(balance.bdv)); + const handleCrate = ( + crate: Deposit + ): LegacyDepositCrate => ({ + // stem: transform(crate.stem, 'bnjs'), // FIXME + // ALECKS: I changed above line to below line. Typescript was expecting stem to be ethers.BigNumber + // Leaving this comment here in case there's unexpected issues somewhere downstream. + stem: crate.stem, + amount: transform(crate.amount, 'bnjs', token), + bdv: transform(crate.bdv, 'bnjs', sdk.tokens.BEAN), + stalk: { + base: transform(crate.stalk.base, 'bnjs', sdk.tokens.STALK), + grown: transform(crate.stalk.grown, 'bnjs', sdk.tokens.STALK), + total: transform(crate.stalk.total, 'bnjs', sdk.tokens.STALK), + }, + seeds: transform(crate.seeds, 'bnjs'), + isGerminating: crate.isGerminating, }); - dispatch(updateFarmerSiloBalanceSdk(balances)); - } + payload[token.address] = { + mowStatus: mowStatuses.get(token), + deposited: { + amount: transform(balance.amount, 'bnjs', token), + convertibleAmount: transform( + balance.convertibleAmount, + 'bnjs', + token + ), + bdv: transform(balance.bdv, 'bnjs', sdk.tokens.BEAN), + crates: balance.deposits.map(handleCrate), + convertibleCrates: balance.convertibleDeposits.map(handleCrate), + }, + }; + }); + + dispatch(updateFarmerSiloBalanceSdk(balances)); /** * We need to calculate the stalk for un-migrated accounts differently than migrated ones @@ -349,9 +233,10 @@ export const useFetchFarmerSilo = () => { total: ZERO_BN, } ); - stalkForUnMigrated.total = stalkForUnMigrated.base - .plus(stalkForUnMigrated.grown) - // .plus(stalkForUnMigrated.earned); + stalkForUnMigrated.total = stalkForUnMigrated.base.plus( + stalkForUnMigrated.grown + ); + // .plus(stalkForUnMigrated.earned); // End of un-migrated stalk calculation const earnedStalkBalance = sdk.tokens.BEAN.getStalk(earnedBeanBalance); @@ -368,18 +253,10 @@ export const useFetchFarmerSilo = () => { earned: transform(earnedBeanBalance, 'bnjs', sdk.tokens.BEAN), }, stalk: { - active: migrationNeeded - ? stalkForUnMigrated.base // .plus(stalkForUnMigrated.earned) - : transform(activeStalkBalance, 'bnjs', sdk.tokens.STALK), - earned: migrationNeeded - ? stalkForUnMigrated.earned - : transform(earnedStalkBalance, 'bnjs', sdk.tokens.STALK), - grown: migrationNeeded - ? stalkForUnMigrated.grown - : transform(grownStalkBalance, 'bnjs', sdk.tokens.STALK), - total: migrationNeeded - ? stalkForUnMigrated.total - : transform(totalStalkBalance, 'bnjs', sdk.tokens.STALK), + active: transform(activeStalkBalance, 'bnjs', sdk.tokens.STALK), + earned: transform(earnedStalkBalance, 'bnjs', sdk.tokens.STALK), + grown: transform(grownStalkBalance, 'bnjs', sdk.tokens.STALK), + total: transform(totalStalkBalance, 'bnjs', sdk.tokens.STALK), grownByToken: grownStalkByToken, }, seeds: {