diff --git a/.env.example b/.env.example
new file mode 100644
index 00000000..731dcdf6
--- /dev/null
+++ b/.env.example
@@ -0,0 +1,13 @@
+NEXT_PUBLIC_NETWORK=testnet
+NEXT_PUBLIC_CHAIN_ID=osmo-test-4
+NEXT_PUBLIC_RPC=https://testnet-osmosis-node.marsprotocol.io/XF32UOOU55CX/osmosis-rpc-front/
+NEXT_PUBLIC_GQL=https://testnet-osmosis-node.marsprotocol.io/XF32UOOU55CX/osmosis-hive-front/graphql
+NEXT_PUBLIC_REST=https://testnet-osmosis-node.marsprotocol.io/XF32UOOU55CX/osmosis-lcd-front/
+NEXT_PUBLIC_SWAP=https://testnet.osmosis.zone
+NEXT_PUBLIC_WALLETS=keplr,cosmostation
+NEXT_PUBLIC_ACCOUNT_NFT=osmo1l8c3g6zy7kjhuh8d2kqyvxkw0myn4puxv0tzcdf9nwxd386r9l7s3vlhzq
+NEXT_PUBLIC_ORACLE=osmo1dqz2u3c8rs5e7w5fnchsr2mpzzsxew69wtdy0aq4jsd76w7upmsstqe0s8
+NEXT_PUBLIC_RED_BANK=osmo1g30recyv8pfy3qd4qn3dn7plc0rn5z68y5gn32j39e96tjhthzxsw3uvvu
+NEXT_PUBLIC_CREDIT_MANAGER=osmo12hgn4jec4tftahm7spf7c2aqsqrxzzk50hkq60e89atumyu0zvys7vzxdc
+NEXT_PUBLIC_ZAPPER=osmo1ua8dwc9v8qjh7n3qf8kg6xvrwjm5yu9xxln7yjvgmrvfzaxvzsuqfcdnjq
+NEXT_PUBLIC_SWAPPER=osmo1uj6r9tu440wwp2mhtagh48yvmeyeaqt2xa7kdnlhyrqcuthlj4ss7ghg6n
diff --git a/.gitignore b/.gitignore
index e3923e68..794f3e24 100644
--- a/.gitignore
+++ b/.gitignore
@@ -37,3 +37,7 @@ next-env.d.ts
# Sentry
.sentryclirc
+
+# Environment variables
+.env.local
+.env.production
\ No newline at end of file
diff --git a/.vscode/settings.json b/.vscode/settings.json
new file mode 100644
index 00000000..d0679104
--- /dev/null
+++ b/.vscode/settings.json
@@ -0,0 +1,4 @@
+{
+ "typescript.tsdk": "node_modules/typescript/lib",
+ "typescript.enablePromptUseWorkspaceTsdk": true
+}
\ No newline at end of file
diff --git a/Dockerfile b/Dockerfile
new file mode 100644
index 00000000..7f65997a
--- /dev/null
+++ b/Dockerfile
@@ -0,0 +1,59 @@
+FROM node:18-alpine AS base
+
+# Install dependencies only when needed
+FROM base AS deps
+# Check https://github.com/nodejs/docker-node/tree/b4117f9333da4138b03a546ec926ef50a31506c3#nodealpine to understand why libc6-compat might be needed.
+RUN apk add --no-cache libc6-compat
+WORKDIR /app
+
+# Install dependencies based on the preferred package manager
+COPY package.json yarn.lock* package-lock.json* pnpm-lock.yaml* ./
+RUN \
+ if [ -f yarn.lock ]; then yarn --frozen-lockfile; \
+ elif [ -f package-lock.json ]; then npm ci; \
+ elif [ -f pnpm-lock.yaml ]; then yarn global add pnpm && pnpm i --frozen-lockfile; \
+ else echo "Lockfile not found." && exit 1; \
+ fi
+
+
+# Rebuild the source code only when needed
+FROM base AS builder
+WORKDIR /app
+COPY --from=deps /app/node_modules ./node_modules
+COPY . .
+
+# Next.js collects completely anonymous telemetry data about general usage.
+# Learn more here: https://nextjs.org/telemetry
+# Uncomment the following line in case you want to disable telemetry during the build.
+# ENV NEXT_TELEMETRY_DISABLED 1
+
+RUN yarn build
+
+# If using npm comment out above and use below instead
+# RUN npm run build
+
+# Production image, copy all the files and run next
+FROM base AS runner
+WORKDIR /app
+
+ENV NODE_ENV production
+# Uncomment the following line in case you want to disable telemetry during runtime.
+# ENV NEXT_TELEMETRY_DISABLED 1
+
+RUN addgroup --system --gid 1001 nodejs
+RUN adduser --system --uid 1001 nextjs
+
+COPY --from=builder /app/public ./public
+
+# Automatically leverage output traces to reduce image size
+# https://nextjs.org/docs/advanced-features/output-file-tracing
+COPY --from=builder --chown=nextjs:nodejs /app/.next/standalone ./
+COPY --from=builder --chown=nextjs:nodejs /app/.next/static ./.next/static
+
+USER nextjs
+
+EXPOSE 3000
+
+ENV PORT 3000
+
+CMD ["node", "server.js"]
\ No newline at end of file
diff --git a/next.config.js b/next.config.js
index c1b68c05..f4677528 100644
--- a/next.config.js
+++ b/next.config.js
@@ -1,11 +1,11 @@
-const { withSentryConfig } = require('@sentry/nextjs')
/** @type {import('next').NextConfig} */
const nextConfig = {
- reactStrictMode: true,
- sentry: {
- hideSourceMaps: true,
+ output: 'standalone',
+ experimental: {
+ appDir: true,
},
+ reactStrictMode: true,
async redirects() {
return [
{
@@ -13,9 +13,34 @@ const nextConfig = {
destination: '/trade',
permanent: true,
},
+ {
+ source: '/wallets',
+ destination: '/trade',
+ permanent: true,
+ },
+ {
+ source: '/wallets/:wallet',
+ destination: '/wallets/:wallet/trade',
+ permanent: true,
+ },
+ {
+ source: '/wallets/:wallet/accounts',
+ destination: '/wallets/:wallet/accounts/trade',
+ permanent: true,
+ },
]
},
- webpack(config) {
+ webpack(config, {isServer}) {
+ if (isServer) {
+ config.resolve.fallback = {
+ ...config.resolve.fallback,
+ 'utf-8-validate': false,
+ bufferutil: false,
+ './build/Release/ecdh': false,
+ eccrypto: false,
+ }
+ }
+
config.module.rules.push({
test: /\.svg$/i,
issuer: /\.[jt]sx?$/,
@@ -40,4 +65,4 @@ const sentryWebpackPluginOptions = {
// Make sure adding Sentry options is the last code to run before exporting, to
// ensure that your source maps include changes from all other Webpack plugins
-module.exports = withSentryConfig(nextConfig, sentryWebpackPluginOptions)
+module.exports = nextConfig
diff --git a/package.json b/package.json
index b8834016..62ebc828 100644
--- a/package.json
+++ b/package.json
@@ -6,17 +6,16 @@
"build": "next build",
"dev": "next dev",
"lint": "eslint ./src/ && yarn prettier-check",
+ "index": "vscode-generate-index-standalone src/",
"format": "yarn index && eslint ./src/ --fix && prettier --write ./src/",
"prettier-check": "prettier --ignore-path .gitignore --check ./src/",
- "start": "next start",
- "index": "vscode-generate-index-standalone src/"
+ "start": "next start"
},
"dependencies": {
"@cosmjs/cosmwasm-stargate": "^0.29.4",
"@cosmjs/stargate": "^0.29.5",
"@headlessui/react": "^1.7.0",
- "@marsprotocol/wallet-connector": "^0.9.5",
- "@metamask/detect-provider": "^1.2.0",
+ "@marsprotocol/wallet-connector": "^1.4.2",
"@radix-ui/react-slider": "^1.0.0",
"@sentry/nextjs": "^7.12.1",
"@tanstack/react-query": "^4.3.4",
@@ -30,14 +29,16 @@
"graphql": "^16.6.0",
"graphql-request": "^5.0.0",
"moment": "^2.29.4",
- "next": "12.3.1",
- "react": "18.2.0",
- "react-dom": "18.2.0",
+ "next": "^13.1.6",
+ "react": "^18.2.0",
+ "react-device-detect": "^2.2.3",
+ "react-dom": "^18.2.0",
"react-number-format": "^5.1.0",
"react-spring": "^9.5.5",
"react-toastify": "^9.0.8",
"react-use-clipboard": "^1.0.9",
"recharts": "^2.2.0",
+ "swr": "^2.0.3",
"tailwindcss-border-gradient-radius": "^3.0.1",
"use-local-storage-state": "^18.1.1",
"zustand": "^4.1.4"
@@ -49,13 +50,16 @@
"@types/react-dom": "18.0.9",
"autoprefixer": "^10.4.13",
"eslint": "8.30.0",
- "eslint-config-next": "12.3.1",
+ "eslint-config-next": "^13.1.6",
"eslint-plugin-import": "^2.26.0",
"postcss": "^8.4.16",
"prettier": "^2.7.1",
"prettier-plugin-tailwindcss": "^0.1.13",
"tailwindcss": "^3.2.1",
- "typescript": "4.9.4",
- "vscode-generate-index-standalone": "^1.6.0"
+ "typescript": "4.9.4"
+ },
+ "resolutions": {
+ "@types/react": "18.0.26",
+ "@types/react-dom": "18.0.9"
}
}
diff --git a/src/app/borrow/loading.tsx b/src/app/borrow/loading.tsx
new file mode 100644
index 00000000..0597facd
--- /dev/null
+++ b/src/app/borrow/loading.tsx
@@ -0,0 +1,3 @@
+export default function laoding() {
+ return '...isLoading'
+}
diff --git a/src/app/borrow/page.tsx b/src/app/borrow/page.tsx
new file mode 100644
index 00000000..94d250b2
--- /dev/null
+++ b/src/app/borrow/page.tsx
@@ -0,0 +1,7 @@
+import { getBorrowData } from 'utils/api'
+
+export default async function page() {
+ const borrowData = await getBorrowData()
+
+ return `You are a guest`
+}
diff --git a/src/app/council/page.tsx b/src/app/council/page.tsx
new file mode 100644
index 00000000..8c592614
--- /dev/null
+++ b/src/app/council/page.tsx
@@ -0,0 +1,3 @@
+export default function page() {
+ return `You are a guest`
+}
diff --git a/src/app/earn/page.tsx b/src/app/earn/page.tsx
new file mode 100644
index 00000000..8c592614
--- /dev/null
+++ b/src/app/earn/page.tsx
@@ -0,0 +1,3 @@
+export default function page() {
+ return `You are a guest`
+}
diff --git a/src/app/head.tsx b/src/app/head.tsx
new file mode 100644
index 00000000..b632a7f4
--- /dev/null
+++ b/src/app/head.tsx
@@ -0,0 +1,30 @@
+export default function Head() {
+ return (
+ <>
+
Mars Protocol V2
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ >
+ )
+}
diff --git a/src/app/layout.tsx b/src/app/layout.tsx
new file mode 100644
index 00000000..353e6cec
--- /dev/null
+++ b/src/app/layout.tsx
@@ -0,0 +1,29 @@
+import Background from 'components/Background'
+import { Modals } from 'components/Modals'
+import DesktopNavigation from 'components/Navigation/DesktopNavigation'
+import Toaster from 'components/Toaster'
+import { WalletConnectProvider } from 'components/Wallet/WalletConnectProvider'
+import 'react-toastify/dist/ReactToastify.min.css'
+import 'styles/globals.css'
+
+export default function RootLayout({ children }: { children: React.ReactNode }) {
+ return (
+
+
+
+
+
+
+
+
+
+
+ {children}
+
+
+
+
+ )
+}
diff --git a/src/app/page.tsx b/src/app/page.tsx
new file mode 100644
index 00000000..9fd04b1c
--- /dev/null
+++ b/src/app/page.tsx
@@ -0,0 +1,3 @@
+export default function page() {
+ return 'Connect to your wallet'
+}
diff --git a/src/app/portfolio/page.tsx b/src/app/portfolio/page.tsx
new file mode 100644
index 00000000..8c592614
--- /dev/null
+++ b/src/app/portfolio/page.tsx
@@ -0,0 +1,3 @@
+export default function page() {
+ return `You are a guest`
+}
diff --git a/src/app/trade/page.tsx b/src/app/trade/page.tsx
new file mode 100644
index 00000000..8c592614
--- /dev/null
+++ b/src/app/trade/page.tsx
@@ -0,0 +1,3 @@
+export default function page() {
+ return `You are a guest`
+}
diff --git a/src/app/wallets/[wallet]/accounts/[account]/borrow/loading.tsx b/src/app/wallets/[wallet]/accounts/[account]/borrow/loading.tsx
new file mode 100644
index 00000000..8c8208af
--- /dev/null
+++ b/src/app/wallets/[wallet]/accounts/[account]/borrow/loading.tsx
@@ -0,0 +1,3 @@
+export default function Loading() {
+ return '...isLoading'
+}
diff --git a/src/app/wallets/[wallet]/accounts/[account]/borrow/page.tsx b/src/app/wallets/[wallet]/accounts/[account]/borrow/page.tsx
new file mode 100644
index 00000000..1a636668
--- /dev/null
+++ b/src/app/wallets/[wallet]/accounts/[account]/borrow/page.tsx
@@ -0,0 +1,31 @@
+import { BorrowTable } from 'components/BorrowTable'
+import { AccountDebtTable } from 'components/AccountDebtTable'
+import { Card } from 'components/Card'
+import Loading from 'components/Loading'
+import { Text } from 'components/Text'
+import { Suspense } from 'react'
+
+export default function page({ params }: { params: PageParams }) {
+ return (
+
+
+
+ Debt data
+
+ }>
+ {/* @ts-expect-error Server Component */}
+
+
+
+
+
+ Borrow data
+
+ }>
+ {/* @ts-expect-error Server Component */}
+
+
+
+
+ )
+}
diff --git a/src/app/wallets/[wallet]/accounts/[account]/council/loading.tsx b/src/app/wallets/[wallet]/accounts/[account]/council/loading.tsx
new file mode 100644
index 00000000..94ffa4c7
--- /dev/null
+++ b/src/app/wallets/[wallet]/accounts/[account]/council/loading.tsx
@@ -0,0 +1,3 @@
+export default function loading() {
+ return '...isLoading'
+}
diff --git a/src/pages/council.tsx b/src/app/wallets/[wallet]/accounts/[account]/council/page.tsx
similarity index 60%
rename from src/pages/council.tsx
rename to src/app/wallets/[wallet]/accounts/[account]/council/page.tsx
index 7f088971..eed5dfc7 100644
--- a/src/pages/council.tsx
+++ b/src/app/wallets/[wallet]/accounts/[account]/council/page.tsx
@@ -1,6 +1,7 @@
-import { Card, Text } from 'components'
+import { Card } from 'components/Card'
+import { Text } from 'components/Text'
-const Council = () => {
+export default function page() {
return (
@@ -11,5 +12,3 @@ const Council = () => {
)
}
-
-export default Council
diff --git a/src/app/wallets/[wallet]/accounts/[account]/earn/loading.tsx b/src/app/wallets/[wallet]/accounts/[account]/earn/loading.tsx
new file mode 100644
index 00000000..94ffa4c7
--- /dev/null
+++ b/src/app/wallets/[wallet]/accounts/[account]/earn/loading.tsx
@@ -0,0 +1,3 @@
+export default function loading() {
+ return '...isLoading'
+}
diff --git a/src/pages/earn.tsx b/src/app/wallets/[wallet]/accounts/[account]/earn/page.tsx
similarity index 74%
rename from src/pages/earn.tsx
rename to src/app/wallets/[wallet]/accounts/[account]/earn/page.tsx
index bf2c6022..0f22c202 100644
--- a/src/pages/earn.tsx
+++ b/src/app/wallets/[wallet]/accounts/[account]/earn/page.tsx
@@ -1,6 +1,7 @@
-import { Card, Text } from 'components'
+import { Card } from 'components/Card'
+import { Text } from 'components/Text'
-const Earn = () => {
+export default function page() {
return (
@@ -18,5 +19,3 @@ const Earn = () => {
)
}
-
-export default Earn
diff --git a/src/app/wallets/[wallet]/accounts/[account]/page.tsx b/src/app/wallets/[wallet]/accounts/[account]/page.tsx
new file mode 100644
index 00000000..992d70d9
--- /dev/null
+++ b/src/app/wallets/[wallet]/accounts/[account]/page.tsx
@@ -0,0 +1,3 @@
+export default function page() {
+ return 'Trade page'
+}
diff --git a/src/app/wallets/[wallet]/accounts/[account]/portfolio/error.tsx b/src/app/wallets/[wallet]/accounts/[account]/portfolio/error.tsx
new file mode 100644
index 00000000..7e85b0d2
--- /dev/null
+++ b/src/app/wallets/[wallet]/accounts/[account]/portfolio/error.tsx
@@ -0,0 +1,5 @@
+'use client'
+
+export default function page({ params }: { params: PageParams }) {
+ return 'error!'
+}
diff --git a/src/app/wallets/[wallet]/accounts/[account]/portfolio/page.tsx b/src/app/wallets/[wallet]/accounts/[account]/portfolio/page.tsx
new file mode 100644
index 00000000..b388a253
--- /dev/null
+++ b/src/app/wallets/[wallet]/accounts/[account]/portfolio/page.tsx
@@ -0,0 +1,15 @@
+import { getCreditAccounts } from 'utils/api'
+
+export default async function page({ params }: { params: PageParams }) {
+ const creditAccounts = await getCreditAccounts(params.wallet)
+
+ return (
+
+
+ {creditAccounts.map((account: string, index: number) => (
+ {account}
+ ))}
+
+
+ )
+}
diff --git a/src/app/wallets/[wallet]/accounts/[account]/trade/loading.tsx b/src/app/wallets/[wallet]/accounts/[account]/trade/loading.tsx
new file mode 100644
index 00000000..94ffa4c7
--- /dev/null
+++ b/src/app/wallets/[wallet]/accounts/[account]/trade/loading.tsx
@@ -0,0 +1,3 @@
+export default function loading() {
+ return '...isLoading'
+}
diff --git a/src/pages/trade.tsx b/src/app/wallets/[wallet]/accounts/[account]/trade/page.tsx
similarity index 73%
rename from src/pages/trade.tsx
rename to src/app/wallets/[wallet]/accounts/[account]/trade/page.tsx
index c90b599a..b073d940 100644
--- a/src/pages/trade.tsx
+++ b/src/app/wallets/[wallet]/accounts/[account]/trade/page.tsx
@@ -1,7 +1,7 @@
-import { Card, Text } from 'components'
-import { TradeActionModule } from 'components/Trade'
+import { Card } from 'components/Card'
+import { Text } from 'components/Text'
-const Trade = () => {
+export default function page() {
return (
@@ -11,9 +11,7 @@ const Trade = () => {
-
-
-
+ {/* */}
Orderbook module (optional)
@@ -29,5 +27,3 @@ const Trade = () => {
)
}
-
-export default Trade
diff --git a/src/app/wallets/[wallet]/borrow/council/page.tsx b/src/app/wallets/[wallet]/borrow/council/page.tsx
new file mode 100644
index 00000000..200bf3c3
--- /dev/null
+++ b/src/app/wallets/[wallet]/borrow/council/page.tsx
@@ -0,0 +1,3 @@
+export default function page() {
+ return `You are a viewer or a user`
+}
diff --git a/src/app/wallets/[wallet]/borrow/earn/page.tsx b/src/app/wallets/[wallet]/borrow/earn/page.tsx
new file mode 100644
index 00000000..200bf3c3
--- /dev/null
+++ b/src/app/wallets/[wallet]/borrow/earn/page.tsx
@@ -0,0 +1,3 @@
+export default function page() {
+ return `You are a viewer or a user`
+}
diff --git a/src/app/wallets/[wallet]/borrow/page.tsx b/src/app/wallets/[wallet]/borrow/page.tsx
new file mode 100644
index 00000000..200bf3c3
--- /dev/null
+++ b/src/app/wallets/[wallet]/borrow/page.tsx
@@ -0,0 +1,3 @@
+export default function page() {
+ return `You are a viewer or a user`
+}
diff --git a/src/app/wallets/[wallet]/borrow/portfolio/page.tsx b/src/app/wallets/[wallet]/borrow/portfolio/page.tsx
new file mode 100644
index 00000000..200bf3c3
--- /dev/null
+++ b/src/app/wallets/[wallet]/borrow/portfolio/page.tsx
@@ -0,0 +1,3 @@
+export default function page() {
+ return `You are a viewer or a user`
+}
diff --git a/src/app/wallets/[wallet]/borrow/trade/page.tsx b/src/app/wallets/[wallet]/borrow/trade/page.tsx
new file mode 100644
index 00000000..200bf3c3
--- /dev/null
+++ b/src/app/wallets/[wallet]/borrow/trade/page.tsx
@@ -0,0 +1,3 @@
+export default function page() {
+ return `You are a viewer or a user`
+}
diff --git a/src/app/wallets/[wallet]/council/page.tsx b/src/app/wallets/[wallet]/council/page.tsx
new file mode 100644
index 00000000..200bf3c3
--- /dev/null
+++ b/src/app/wallets/[wallet]/council/page.tsx
@@ -0,0 +1,3 @@
+export default function page() {
+ return `You are a viewer or a user`
+}
diff --git a/src/app/wallets/[wallet]/earn/page.tsx b/src/app/wallets/[wallet]/earn/page.tsx
new file mode 100644
index 00000000..200bf3c3
--- /dev/null
+++ b/src/app/wallets/[wallet]/earn/page.tsx
@@ -0,0 +1,3 @@
+export default function page() {
+ return `You are a viewer or a user`
+}
diff --git a/src/app/wallets/[wallet]/layout.tsx b/src/app/wallets/[wallet]/layout.tsx
new file mode 100644
index 00000000..cb2bedf8
--- /dev/null
+++ b/src/app/wallets/[wallet]/layout.tsx
@@ -0,0 +1,21 @@
+import { AccountNavigation } from 'components/Account/AccountNavigation'
+import { getCreditAccounts } from 'utils/api'
+
+export default async function RootLayout({
+ children,
+ params,
+}: {
+ children: React.ReactNode
+ params: PageParams
+}) {
+ const creditAccounts = await getCreditAccounts(params.wallet)
+
+ return (
+ <>
+
+ {children}
+ >
+ )
+}
diff --git a/src/app/wallets/[wallet]/portfolio/page.tsx b/src/app/wallets/[wallet]/portfolio/page.tsx
new file mode 100644
index 00000000..200bf3c3
--- /dev/null
+++ b/src/app/wallets/[wallet]/portfolio/page.tsx
@@ -0,0 +1,3 @@
+export default function page() {
+ return `You are a viewer or a user`
+}
diff --git a/src/app/wallets/[wallet]/trade/page.tsx b/src/app/wallets/[wallet]/trade/page.tsx
new file mode 100644
index 00000000..200bf3c3
--- /dev/null
+++ b/src/app/wallets/[wallet]/trade/page.tsx
@@ -0,0 +1,3 @@
+export default function page() {
+ return `You are a viewer or a user`
+}
diff --git a/src/components/Account/AccountDetails.tsx b/src/components/Account/AccountDetails.tsx
index 8b39a1a4..dd27b3d8 100644
--- a/src/components/Account/AccountDetails.tsx
+++ b/src/components/Account/AccountDetails.tsx
@@ -1,20 +1,27 @@
+'use client'
+
import classNames from 'classnames'
import { useEffect, useState } from 'react'
-import { Button, LabelValuePair, PositionsList } from 'components'
-import { AccountManageOverlay, RiskChart } from 'components/Account'
+import { AccountManageOverlay } from 'components/Account/AccountManageOverlay'
+import { RiskChart } from 'components/Account/RiskChart'
+import { Button } from 'components/Button'
import { ArrowRightLine, ChevronDown, ChevronLeft } from 'components/Icons'
-import { useAccountStats, useBalances } from 'hooks/data'
-import { useAccountDetailsStore, useNetworkConfigStore, useSettingsStore } from 'stores'
-import { lookup } from 'utils/formatters'
+import { LabelValuePair } from 'components/LabelValuePair'
+import { PositionsList } from 'components/PositionsList'
+import { useAccountStats } from 'hooks/data/useAccountStats'
+import { useBalances } from 'hooks/data/useBalances'
+import { convertFromGwei } from 'utils/formatters'
import { createRiskData } from 'utils/risk'
+import useStore from 'store'
+import { getBaseAsset, getMarketAssets } from 'utils/assets'
export const AccountDetails = () => {
- const enableAnimations = useSettingsStore((s) => s.enableAnimations)
- const selectedAccount = useAccountDetailsStore((s) => s.selectedAccount)
- const isOpen = useAccountDetailsStore((s) => s.isOpen)
- const whitelistedAssets = useNetworkConfigStore((s) => s.assets.whitelist)
- const baseAsset = useNetworkConfigStore((s) => s.assets.base)
+ const enableAnimations = useStore((s) => s.enableAnimations)
+ const selectedAccount = useStore((s) => s.selectedAccount)
+ const isOpen = useStore((s) => s.isOpen)
+ const marketAssets = getMarketAssets()
+ const baseAsset = getBaseAsset()
const balances = useBalances()
const accountStats = useAccountStats()
@@ -36,7 +43,7 @@ export const AccountDetails = () => {
>
{
- useAccountDetailsStore.setState({ isOpen: true })
+ useStore.setState({ isOpen: true })
}}
variant='text'
className={classNames(
@@ -75,7 +82,7 @@ export const AccountDetails = () => {
enableAnimations && 'transition-[color]',
)}
onClick={() => {
- useAccountDetailsStore.setState({ isOpen: false })
+ useStore.setState({ isOpen: false })
}}
>
@@ -93,7 +100,11 @@ export const AccountDetails = () => {
label='Total Position:'
value={{
format: 'number',
- amount: lookup(accountStats?.totalPosition ?? 0, baseAsset.denom, whitelistedAssets),
+ amount: convertFromGwei(
+ accountStats?.totalPosition ?? 0,
+ baseAsset.denom,
+ marketAssets,
+ ),
prefix: '$',
}}
/>
@@ -101,7 +112,7 @@ export const AccountDetails = () => {
label='Total Liabilities:'
value={{
format: 'number',
- amount: lookup(accountStats?.totalDebt ?? 0, baseAsset.denom, whitelistedAssets),
+ amount: convertFromGwei(accountStats?.totalDebt ?? 0, baseAsset.denom, marketAssets),
prefix: '$',
}}
/>
diff --git a/src/components/Account/AccountManageOverlay.tsx b/src/components/Account/AccountManageOverlay.tsx
index 184b3174..6f60786b 100644
--- a/src/components/Account/AccountManageOverlay.tsx
+++ b/src/components/Account/AccountManageOverlay.tsx
@@ -1,10 +1,15 @@
-import { useEffect } from 'react'
+'use client'
-import { Button, Text } from 'components'
+import { useRouter } from 'next/navigation'
+
+import { Button } from 'components/Button'
import { Add, ArrowDown, ArrowsLeftRight, ArrowUp, Rubbish } from 'components/Icons'
-import { Overlay, OverlayAction } from 'components/Overlay'
-import { useCreateCreditAccount, useDeleteCreditAccount } from 'hooks/mutations'
-import { useAccountDetailsStore, useModalStore } from 'stores'
+import { Overlay } from 'components/Overlay/Overlay'
+import { OverlayAction } from 'components/Overlay/OverlayAction'
+import { Text } from 'components/Text'
+import useParams from 'hooks/useParams'
+import useStore from 'store'
+import { hardcodedFee } from 'utils/contants'
interface Props {
className?: string
@@ -13,20 +18,22 @@ interface Props {
}
export const AccountManageOverlay = ({ className, setShow, show }: Props) => {
- const selectedAccount = useAccountDetailsStore((s) => s.selectedAccount)
+ const router = useRouter()
+ const params = useParams()
+ const createCreditAccount = useStore((s) => s.createCreditAccount)
+ const deleteCreditAccount = useStore((s) => s.deleteCreditAccount)
- const { mutate: createCreditAccount, isLoading: isLoadingCreate } = useCreateCreditAccount()
- const { mutate: deleteCreditAccount, isLoading: isLoadingDelete } = useDeleteCreditAccount(
- selectedAccount || '',
- )
+ async function createAccount() {
+ const newAccountId = await createCreditAccount({ fee: hardcodedFee })
+ router.push(`/wallets/${params.wallet}/accounts/${newAccountId}`)
+ }
- useEffect(() => {
- useModalStore.setState({ createAccountModal: isLoadingCreate })
- }, [isLoadingCreate])
-
- useEffect(() => {
- useModalStore.setState({ deleteAccountModal: isLoadingDelete })
- }, [isLoadingDelete])
+ async function deleteAccountHandler() {
+ const isSuccess = await deleteCreditAccount({ fee: hardcodedFee, accountId: params.account })
+ if (isSuccess) {
+ router.push(`/wallets/${params.wallet}/accounts`)
+ }
+ }
return (
@@ -38,7 +45,7 @@ export const AccountManageOverlay = ({ className, setShow, show }: Props) => {
{
- useModalStore.setState({ fundAccountModal: true })
+ useStore.setState({ fundAccountModal: true })
setShow(false)
}}
>
@@ -51,7 +58,7 @@ export const AccountManageOverlay = ({ className, setShow, show }: Props) => {
className='flex w-[115px] items-center justify-center pl-0 pr-2'
color='secondary'
onClick={() => {
- useModalStore.setState({ withdrawModal: true })
+ useStore.setState({ withdrawModal: true })
setShow(false)
}}
>
@@ -65,13 +72,13 @@ export const AccountManageOverlay = ({ className, setShow, show }: Props) => {
}
/>
}
/>
{
- const { firstCreditAccounts, restCreditAccounts } = useMemo(() => {
- return {
- firstCreditAccounts: creditAccountsList?.slice(0, MAX_VISIBLE_CREDIT_ACCOUNTS) ?? [],
- restCreditAccounts: creditAccountsList?.slice(MAX_VISIBLE_CREDIT_ACCOUNTS) ?? [],
- }
- }, [creditAccountsList])
+interface Props {
+ creditAccounts: string[]
+}
+
+export const AccountNavigation = (props: Props) => {
+ const router = useRouter()
+ const params = useParams()
+ const address = useStore((s) => s.client?.recentWallet.account?.address) || ''
+ const selectedAccount = params.account
+ const createCreditAccount = useStore((s) => s.createCreditAccount)
+
+ const hasCreditAccounts = !!props.creditAccounts?.length
+ const firstCreditAccounts = props.creditAccounts?.slice(0, MAX_VISIBLE_CREDIT_ACCOUNTS) ?? []
+ const restCreditAccounts = props.creditAccounts?.slice(MAX_VISIBLE_CREDIT_ACCOUNTS) ?? []
const [showManageMenu, setShowManageMenu] = useState(false)
const [showMoreMenu, setShowMoreMenu] = useState(false)
- return (
- <>
- {firstCreditAccounts.map((account) => (
- {
- useAccountDetailsStore.setState({ selectedAccount: account, isOpen: true })
- }}
- >
- Account {account}
-
- ))}
-
- {restCreditAccounts.length > 0 && (
- <>
-
setShowMoreMenu(!showMoreMenu)}
- >
- More
-
-
-
-
-
-
- {restCreditAccounts.map((account) => (
- {
- setShowMoreMenu(!showMoreMenu)
- useAccountDetailsStore.setState({ selectedAccount: account, isOpen: true })
- }}
- >
- Account {account}
-
- ))}
-
-
- >
- )}
-
-
-
setShowManageMenu(!showManageMenu)}
- variant='text'
- >
- Manage
-
-
-
-
+ async function createAccountHandler() {
+ const accountId = await createCreditAccount({ fee: hardcodedFee })
+ if (!accountId) return
+ router.push(`/wallets/${params.wallet}/accounts/${accountId}`)
+ }
-
-
- >
+ return (
+
+ <>
+ {hasCreditAccounts ? (
+ <>
+ {firstCreditAccounts.map((account) => (
+ {
+ router.push(`/wallets/${params.wallet}/accounts/${account}/${params.page}`)
+ }}
+ >
+ Account {account}
+
+ ))}
+
+ {restCreditAccounts.length > 0 && (
+ <>
+
setShowMoreMenu(!showMoreMenu)}
+ >
+ More
+
+
+
+
+
+
+ {restCreditAccounts.map((account) => (
+ {
+ setShowMoreMenu(!showMoreMenu)
+ router.push(`/wallets/${params.wallet}/accounts/${account}`)
+ }}
+ >
+ Account {account}
+
+ ))}
+
+
+ >
+ )}
+
+
+
setShowManageMenu(!showManageMenu)}
+ variant='text'
+ >
+ Manage
+
+
+
+
+
+
+
+ >
+ ) : (
+ <>{address ? Create Account : ''}>
+ )}
+ >
+
)
}
diff --git a/src/components/Account/AccountStatus.tsx b/src/components/Account/AccountStatus.tsx
index 6d5aa009..b29771db 100644
--- a/src/components/Account/AccountStatus.tsx
+++ b/src/components/Account/AccountStatus.tsx
@@ -1,22 +1,25 @@
-import BigNumber from 'bignumber.js'
-import { useEffect } from 'react'
+'use client'
+
+import BigNumber from 'bignumber.js'
-import { Button, FormattedNumber, Gauge, Text } from 'components'
import { BorrowCapacity } from 'components/BorrowCapacity'
-import { useAccountStats } from 'hooks/data'
-import { useCreateCreditAccount } from 'hooks/mutations'
-import { useCreditAccounts } from 'hooks/queries'
-import { useModalStore, useNetworkConfigStore } from 'stores'
+import { Button } from 'components/Button'
+import { FormattedNumber } from 'components/FormattedNumber'
+import { Gauge } from 'components/Gauge'
+import { Text } from 'components/Text'
+import { useAccountStats } from 'hooks/data/useAccountStats'
+import { useCreditAccounts } from 'hooks/queries/useCreditAccounts'
+import { getBaseAsset } from 'utils/assets'
import { formatValue } from 'utils/formatters'
export const AccountStatus = () => {
- const baseAsset = useNetworkConfigStore((s) => s.assets.base)
+ const baseAsset = getBaseAsset()
const accountStats = useAccountStats()
const { data: creditAccountsList } = useCreditAccounts()
- const { mutate: createCreditAccount, isLoading: isLoadingCreate } = useCreateCreditAccount()
- useEffect(() => {
- useModalStore.setState({ createAccountModal: isLoadingCreate })
- }, [isLoadingCreate])
+
+ const createCreditAccount = () => {
+ console.log('create credit account')
+ }
const hasCreditAccounts = creditAccountsList && creditAccountsList.length > 0
diff --git a/src/components/Account/ConfirmModal.tsx b/src/components/Account/ConfirmModal.tsx
index 2be37333..e33003ca 100644
--- a/src/components/Account/ConfirmModal.tsx
+++ b/src/components/Account/ConfirmModal.tsx
@@ -1,12 +1,16 @@
+'use client'
+
import classNames from 'classnames'
-import { CircularProgress, Modal, Text } from 'components'
+import { CircularProgress } from 'components/CircularProgress'
import { MarsProtocol } from 'components/Icons'
-import { useModalStore } from 'stores'
+import { Modal } from 'components/Modal'
+import { Text } from 'components/Text'
+import useStore from 'store'
export const ConfirmModal = () => {
- const createOpen = useModalStore((s) => s.createAccountModal)
- const deleteOpen = useModalStore((s) => s.deleteAccountModal)
+ const createOpen = useStore((s) => s.createAccountModal)
+ const deleteOpen = useStore((s) => s.deleteAccountModal)
return (
@@ -23,7 +27,7 @@ export const ConfirmModal = () => {
{createOpen &&
- 'A small step for a Smart Contracts but a big leap for your financial freedom.'}
+ 'A small step for a Smart Contract but a big leap for your financial freedom.'}
{deleteOpen && 'Some rovers have to be recycled once in a while...'}
diff --git a/src/components/Account/FundAccountModal.tsx b/src/components/Account/FundAccountModal.tsx
index ff7a752a..804d250c 100644
--- a/src/components/Account/FundAccountModal.tsx
+++ b/src/components/Account/FundAccountModal.tsx
@@ -1,28 +1,36 @@
-import { Switch } from '@headlessui/react'
-import BigNumber from 'bignumber.js'
-import { useEffect, useMemo, useState } from 'react'
-import { toast } from 'react-toastify'
-import useLocalStorageState from 'use-local-storage-state'
+'use client'
-import { Button, CircularProgress, Modal, Slider, Text } from 'components'
+import { Switch } from '@headlessui/react'
+import { useEffect, useMemo, useState } from 'react'
+import useSWR from 'swr'
+
+import { Button } from 'components/Button'
+import { CircularProgress } from 'components/CircularProgress'
import { MarsProtocol } from 'components/Icons'
-import { useDepositCreditAccount } from 'hooks/mutations'
-import { useAllBalances, useAllowedCoins } from 'hooks/queries'
-import { useAccountDetailsStore, useModalStore, useNetworkConfigStore } from 'stores'
+import { Modal } from 'components/Modal'
+import { Slider } from 'components/Slider'
+import { Text } from 'components/Text'
+import useParams from 'hooks/useParams'
+import useStore from 'store'
+import { getMarketAssets } from 'utils/assets'
+import { hardcodedFee } from 'utils/contants'
+import { convertFromGwei, convertToGwei } from 'utils/formatters'
import { getTokenDecimals, getTokenSymbol } from 'utils/tokens'
+import { getAccountDeposits } from 'utils/api'
export const FundAccountModal = () => {
// ---------------
// STORE
// ---------------
- const open = useModalStore((s) => s.fundAccountModal)
-
- const selectedAccount = useAccountDetailsStore((s) => s.selectedAccount)
- const whitelistedAssets = useNetworkConfigStore((s) => s.assets.whitelist)
- const [lendAssets, setLendAssets] = useLocalStorageState(`lendAssets_${selectedAccount}`, {
- defaultValue: false,
- })
+ const open = useStore((s) => s.fundAccountModal)
+ const params = useParams()
+ const depositCreditAccount = useStore((s) => s.depositCreditAccount)
+ const address = useStore((s) => s.client?.recentWallet.account?.address)
+ const { data: balancesData, isLoading: balanceIsLoading } = useSWR(address, getAccountDeposits)
+ const selectedAccount = useStore((s) => s.selectedAccount)
+ const marketAssets = getMarketAssets()
+ const [lendAssets, setLendAssets] = useState(false)
// ---------------
// LOCAL STATE
// ---------------
@@ -30,41 +38,45 @@ export const FundAccountModal = () => {
const [selectedToken, setSelectedToken] = useState('')
// ---------------
- // EXTERNAL HOOKS
+ // FUNCTIONS
// ---------------
- const { data: balancesData } = useAllBalances()
- const { data: allowedCoinsData, isLoading: isLoadingAllowedCoins } = useAllowedCoins()
- const { mutate, isLoading } = useDepositCreditAccount(
- selectedAccount || '',
- selectedToken,
- BigNumber(amount)
- .times(10 ** getTokenDecimals(selectedToken, whitelistedAssets))
- .toNumber(),
- {
- onSuccess: () => {
- setAmount(0)
- toast.success(
- `${amount} ${getTokenSymbol(selectedToken, whitelistedAssets)} successfully Deposited`,
- )
- useModalStore.setState({ fundAccountModal: false })
- },
- },
- )
+ async function depositAccountHandler() {
+ if (!selectedToken) return
+ const deposit = {
+ amount: convertToGwei(amount, selectedToken, marketAssets).toString(),
+ denom: selectedToken,
+ }
+ const isSuccess = await depositCreditAccount({
+ fee: hardcodedFee,
+ accountId: params.account,
+ deposit,
+ })
+ if (isSuccess) {
+ useStore.setState({ fundAccountModal: false })
+ }
+ }
useEffect(() => {
- if (allowedCoinsData && allowedCoinsData.length > 0) {
- // initialize selected token when allowedCoins fetch data is available
- setSelectedToken(allowedCoinsData[0])
- }
- }, [allowedCoinsData])
+ if (!marketAssets || !balancesData || selectedToken !== '') return
+ let found = false
+ marketAssets.map((asset) => {
+ if (found) return
+ if (balancesData?.find((balance) => balance.denom === asset.denom)?.amount ?? 0 > 0) {
+ setSelectedToken(asset.denom)
+ found = true
+ }
+ })
+ }, [marketAssets, balancesData])
+ // ---------------
+ // VARIABLES
+ // ---------------
const walletAmount = useMemo(() => {
if (!selectedToken) return 0
-
- return BigNumber(balancesData?.find((balance) => balance.denom === selectedToken)?.amount ?? 0)
- .div(10 ** getTokenDecimals(selectedToken, whitelistedAssets))
- .toNumber()
- }, [balancesData, selectedToken, whitelistedAssets])
+ const walletAmount =
+ balancesData?.find((balance) => balance.denom === selectedToken)?.amount ?? 0
+ return convertFromGwei(walletAmount, selectedToken, marketAssets)
+ }, [balancesData, selectedToken, marketAssets])
const handleValueChange = (value: number) => {
if (value > walletAmount) {
@@ -76,16 +88,15 @@ export const FundAccountModal = () => {
}
const setOpen = (open: boolean) => {
- useModalStore.setState({ fundAccountModal: open })
+ useStore.setState({ fundAccountModal: open })
}
- const maxValue = walletAmount
- const percentageValue = isNaN(amount) ? 0 : (amount * 100) / maxValue
+ const percentageValue = isNaN(amount) ? 0 : (amount * 100) / walletAmount
return (
- {isLoading && (
+ {balanceIsLoading && (
@@ -118,68 +129,69 @@ export const FundAccountModal = () => {
have any assets in your osmosis wallet use the osmosis bridge to transfer funds to
your osmosis wallet.
- {isLoadingAllowedCoins ? (
-
Loading...
- ) : (
- <>
-
-
-
- Asset:
-
-
{
- setSelectedToken(e.target.value)
+ <>
+
+
+
+ Asset:
+
+ {
+ setSelectedToken(e.target.value)
- if (e.target.value !== selectedToken) setAmount(0)
- }}
- value={selectedToken}
- >
- {allowedCoinsData?.map((entry) => (
-
- {getTokenSymbol(entry, whitelistedAssets)}
-
- ))}
-
-
-
-
- Amount:
-
- handleValueChange(e.target.valueAsNumber)}
- onBlur={(e) => {
- if (e.target.value === '') setAmount(0)
- }}
- />
-
+ if (e.target.value !== selectedToken) setAmount(0)
+ }}
+ value={selectedToken}
+ >
+ {/* {marketAssets?.map((entry) => {
+ const entrySymbol = getTokenSymbol(entry, marketAssets)
+ return (
+ entrySymbol !== '' && (
+
+ {getTokenSymbol(entry, marketAssets)}
+
+ )
+ ) */}
+ {/* })} */}
+
-
- {`In wallet: ${walletAmount.toLocaleString()} ${getTokenSymbol(
- selectedToken,
- whitelistedAssets,
- )}`}
-
- {
- const decimal = value[0] / 100
- const tokenDecimals = getTokenDecimals(selectedToken, whitelistedAssets)
- // limit decimal precision based on token contract decimals
- const newAmount = Number((decimal * maxValue).toFixed(tokenDecimals))
+
+
+ Amount:
+
+ handleValueChange(e.target.valueAsNumber)}
+ onBlur={(e) => {
+ if (e.target.value === '') setAmount(0)
+ }}
+ />
+
+
+ >
+
+ {`In wallet: ${walletAmount.toLocaleString()} ${getTokenSymbol(
+ selectedToken,
+ marketAssets,
+ )}`}
+
+
{
+ const decimal = value[0] / 100
+ const tokenDecimals = getTokenDecimals(selectedToken, marketAssets)
+ // limit decimal precision based on token contract decimals
+ const newAmount = Number((decimal * walletAmount).toFixed(tokenDecimals))
- setAmount(newAmount)
- }}
- onMaxClick={() => setAmount(maxValue)}
- />
- >
- )}
+ setAmount(newAmount)
+ }}
+ onMaxClick={() => setAmount(walletAmount)}
+ />
@@ -207,7 +219,7 @@ export const FundAccountModal = () => {
mutate()}
+ onClick={depositAccountHandler}
disabled={amount === 0 || !amount}
>
Fund Account
diff --git a/src/components/Account/RiskChart.tsx b/src/components/Account/RiskChart.tsx
index 5b23de83..13092e53 100644
--- a/src/components/Account/RiskChart.tsx
+++ b/src/components/Account/RiskChart.tsx
@@ -9,13 +9,14 @@ import {
YAxis,
} from 'recharts'
-import { FormattedNumber, Text } from 'components'
-import { useAccountStats } from 'hooks/data'
-import { useSettingsStore } from 'stores'
import { formatValue } from 'utils/formatters'
+import { FormattedNumber } from 'components/FormattedNumber'
+import { Text } from 'components/Text'
+import { useAccountStats } from 'hooks/data/useAccountStats'
+import useStore from 'store'
export const RiskChart = ({ data }: RiskChartProps) => {
- const enableAnimations = useSettingsStore((s) => s.enableAnimations)
+ const enableAnimations = useStore((s) => s.enableAnimations)
const accountStats = useAccountStats()
const currentRisk = accountStats?.risk ?? 0
diff --git a/src/components/Account/WithdrawModal.tsx b/src/components/Account/WithdrawModal.tsx
index f05c670e..1192caaa 100644
--- a/src/components/Account/WithdrawModal.tsx
+++ b/src/components/Account/WithdrawModal.tsx
@@ -4,40 +4,36 @@ import classNames from 'classnames'
import React, { useEffect, useMemo, useState } from 'react'
import { toast } from 'react-toastify'
-import {
- Button,
- CircularProgress,
- FormattedNumber,
- Gauge,
- LabelValuePair,
- Modal,
- PositionsList,
- Slider,
- Text,
-} from 'components'
import { BorrowCapacity } from 'components/BorrowCapacity'
-import { useAccountStats, useBalances, useCalculateMaxWithdrawAmount } from 'hooks/data'
-import { useWithdrawFunds } from 'hooks/mutations'
-import { useCreditAccountPositions, useTokenPrices } from 'hooks/queries'
-import {
- useAccountDetailsStore,
- useModalStore,
- useNetworkConfigStore,
- useWalletStore,
-} from 'stores'
-import { formatValue, lookup } from 'utils/formatters'
+import { convertFromGwei, formatValue } from 'utils/formatters'
import { getTokenDecimals, getTokenSymbol } from 'utils/tokens'
+import { CircularProgress } from 'components/CircularProgress'
+import { Button } from 'components/Button'
+import { Text } from 'components/Text'
+import { Slider } from 'components/Slider'
+import { FormattedNumber } from 'components/FormattedNumber'
+import { Gauge } from 'components/Gauge'
+import { LabelValuePair } from 'components/LabelValuePair'
+import { Modal } from 'components/Modal'
+import { PositionsList } from 'components/PositionsList'
+import { useAccountStats } from 'hooks/data/useAccountStats'
+import { useBalances } from 'hooks/data/useBalances'
+import { useCalculateMaxWithdrawAmount } from 'hooks/data/useCalculateMaxWithdrawAmount'
+import { useWithdrawFunds } from 'hooks/mutations/useWithdrawFunds'
+import { useCreditAccountPositions } from 'hooks/queries/useCreditAccountPositions'
+import { useTokenPrices } from 'hooks/queries/useTokenPrices'
+import useStore from 'store'
+import { getBaseAsset, getMarketAssets } from 'utils/assets'
export const WithdrawModal = () => {
// ---------------
// STORE
// ---------------
- const open = useModalStore((s) => s.withdrawModal)
- const chainInfo = useWalletStore((s) => s.chainInfo)
- const selectedAccount = useAccountDetailsStore((s) => s.selectedAccount)
+ const open = useStore((s) => s.withdrawModal)
+ const selectedAccount = useStore((s) => s.selectedAccount)
const { data: positionsData } = useCreditAccountPositions(selectedAccount ?? '')
- const whitelistedAssets = useNetworkConfigStore((s) => s.assets.whitelist)
- const baseAsset = useNetworkConfigStore((s) => s.assets.base)
+ const marketAssets = getMarketAssets()
+ const baseAsset = getBaseAsset()
// ---------------
// LOCAL STATE
@@ -52,8 +48,8 @@ export const WithdrawModal = () => {
const { data: tokenPrices } = useTokenPrices()
const balances = useBalances()
- const selectedTokenSymbol = getTokenSymbol(selectedToken, whitelistedAssets)
- const selectedTokenDecimals = getTokenDecimals(selectedToken, whitelistedAssets)
+ const selectedTokenSymbol = getTokenSymbol(selectedToken, marketAssets)
+ const selectedTokenDecimals = getTokenDecimals(selectedToken, marketAssets)
const tokenAmountInCreditAccount = useMemo(() => {
return BigNumber(positionsData?.coins.find((coin) => coin.denom === selectedToken)?.amount ?? 0)
@@ -96,7 +92,7 @@ export const WithdrawModal = () => {
const { mutate, isLoading } = useWithdrawFunds(withdrawAmount, borrowAmount, selectedToken, {
onSuccess: () => {
- useModalStore.setState({ withdrawModal: false })
+ useStore.setState({ withdrawModal: false })
toast.success(`${amount} ${selectedTokenSymbol} successfully withdrawn`)
},
})
@@ -131,13 +127,13 @@ export const WithdrawModal = () => {
setAmount(0)
}
- const getTokenTotalUSDValue = (amount: string, denom: string, whitelistedAssets: Asset[]) => {
+ const getTokenTotalUSDValue = (amount: string, denom: string, marketAssets: Asset[]) => {
// early return if prices are not fetched yet
if (!tokenPrices) return 0
return (
BigNumber(amount)
- .div(10 ** getTokenDecimals(denom, whitelistedAssets))
+ .div(10 ** getTokenDecimals(denom, marketAssets))
.toNumber() * tokenPrices[denom]
)
}
@@ -149,7 +145,7 @@ export const WithdrawModal = () => {
}, [amount, maxWithdrawAmount])
const setOpen = (open: boolean) => {
- useModalStore.setState({ withdrawModal: open })
+ useStore.setState({ withdrawModal: open })
}
return (
@@ -183,7 +179,7 @@ export const WithdrawModal = () => {
>
{positionsData?.coins?.map((coin) => (
- {getTokenSymbol(coin.denom, whitelistedAssets)}
+ {getTokenSymbol(coin.denom, marketAssets)}
))}
@@ -310,10 +306,10 @@ export const WithdrawModal = () => {
label='Total Position:'
value={{
format: 'number',
- amount: lookup(
+ amount: convertFromGwei(
accountStats?.totalPosition ?? 0,
baseAsset.denom,
- whitelistedAssets,
+ marketAssets,
),
prefix: '$',
}}
@@ -322,7 +318,11 @@ export const WithdrawModal = () => {
label='Total Liabilities:'
value={{
format: 'number',
- amount: lookup(accountStats?.totalDebt ?? 0, baseAsset.denom, whitelistedAssets),
+ amount: convertFromGwei(
+ accountStats?.totalDebt ?? 0,
+ baseAsset.denom,
+ marketAssets,
+ ),
prefix: '$',
}}
/>
diff --git a/src/components/Account/index.ts b/src/components/Account/index.ts
deleted file mode 100644
index 34946daa..00000000
--- a/src/components/Account/index.ts
+++ /dev/null
@@ -1,10 +0,0 @@
-// @index(['./*.tsx'], f => `export { ${f.name} } from '${f.path}'`)
-export { AccountDetails } from './AccountDetails'
-export { AccountManageOverlay } from './AccountManageOverlay'
-export { AccountNavigation } from './AccountNavigation'
-export { AccountStatus } from './AccountStatus'
-export { ConfirmModal } from './ConfirmModal'
-export { FundAccountModal } from './FundAccountModal'
-export { RiskChart } from './RiskChart'
-export { WithdrawModal } from './WithdrawModal'
-// @endindex
diff --git a/src/components/AccountDebtTable.tsx b/src/components/AccountDebtTable.tsx
new file mode 100644
index 00000000..0024ac55
--- /dev/null
+++ b/src/components/AccountDebtTable.tsx
@@ -0,0 +1,17 @@
+import { getAccountDebts } from 'utils/api'
+
+interface Props {
+ account: string
+}
+
+export async function AccountDebtTable(props: Props) {
+ const debtData = await getAccountDebts(props.account)
+
+ return debtData.map((debt) => {
+ return (
+
+ {debt.denom} {debt.amount}
+
+ )
+ })
+}
diff --git a/src/components/Background.tsx b/src/components/Background.tsx
new file mode 100644
index 00000000..18094a06
--- /dev/null
+++ b/src/components/Background.tsx
@@ -0,0 +1,21 @@
+'use client'
+
+import { useWalletManager, WalletConnectionStatus } from '@marsprotocol/wallet-connector'
+import classNames from 'classnames'
+
+const filter = {
+ day: 'brightness-100 hue-rotate-0',
+ night: '-hue-rotate-82 brightness-30',
+}
+
+export default function Background() {
+ const { status } = useWalletManager()
+
+ const backgroundClasses = classNames(
+ status === WalletConnectionStatus.Connected ? filter.day : filter.night,
+ 'top-0 left-0 absolute block h-full w-full flex-col bg-body bg-mars bg-desktop bg-top bg-no-repeat filter',
+ true && 'transition-background duration-3000 ease-linear',
+ )
+
+ return
+}
diff --git a/src/components/Borrow/AssetRow.tsx b/src/components/Borrow/AssetRow.tsx
index 8e30ae08..b6b4a847 100644
--- a/src/components/Borrow/AssetRow.tsx
+++ b/src/components/Borrow/AssetRow.tsx
@@ -1,9 +1,9 @@
import Image from 'next/image'
import React, { useState } from 'react'
-import { Button } from 'components'
import { ChevronDown, ChevronUp } from 'components/Icons'
import { formatCurrency } from 'utils/formatters'
+import { Button } from 'components/Button'
type AssetRowProps = {
data: {
diff --git a/src/components/Borrow/BorrowTable.tsx b/src/components/Borrow/BorrowTable.tsx
index 6b5d4bf3..8280502a 100644
--- a/src/components/Borrow/BorrowTable.tsx
+++ b/src/components/Borrow/BorrowTable.tsx
@@ -9,7 +9,7 @@ import {
import Image from 'next/image'
import React from 'react'
-import { AssetRow } from 'components/Borrow'
+import { AssetRow } from 'components/Borrow/AssetRow'
import { ChevronDown, ChevronUp } from 'components/Icons'
import { formatCurrency } from 'utils/formatters'
diff --git a/src/components/Borrow/index.ts b/src/components/Borrow/index.ts
deleted file mode 100644
index edf81c9e..00000000
--- a/src/components/Borrow/index.ts
+++ /dev/null
@@ -1,4 +0,0 @@
-// @index(['./**/*.tsx'], f => `export { ${f.name} } from '${f.path}'`)
-export { AssetRow } from './AssetRow'
-export { BorrowTable } from './BorrowTable'
-// @endindex
diff --git a/src/components/BorrowCapacity.tsx b/src/components/BorrowCapacity.tsx
index 9f140b1c..8d3c0ed3 100644
--- a/src/components/BorrowCapacity.tsx
+++ b/src/components/BorrowCapacity.tsx
@@ -1,8 +1,10 @@
import classNames from 'classnames'
import { useEffect, useState } from 'react'
-import { FormattedNumber, Text, Tooltip } from 'components'
-import { useSettingsStore } from 'stores'
+import { FormattedNumber } from 'components/FormattedNumber'
+import { Text } from 'components/Text'
+import { Tooltip } from 'components/Tooltip'
+import useStore from 'store'
interface Props {
balance: number
@@ -27,7 +29,7 @@ export const BorrowCapacity = ({
hideValues,
decimals = 2,
}: Props) => {
- const enableAnimations = useSettingsStore((s) => s.enableAnimations)
+ const enableAnimations = useStore((s) => s.enableAnimations)
const [percentOfMaxRound, setPercentOfMaxRound] = useState(0)
const [percentOfMaxRange, setPercentOfMaxRange] = useState(0)
diff --git a/src/components/BorrowModal.tsx b/src/components/BorrowModal.tsx
index f34331de..01d9da43 100644
--- a/src/components/BorrowModal.tsx
+++ b/src/components/BorrowModal.tsx
@@ -4,23 +4,26 @@ import React, { useMemo, useState } from 'react'
import { NumericFormat } from 'react-number-format'
import { toast } from 'react-toastify'
-import {
- Button,
- CircularProgress,
- ContainerSecondary,
- Gauge,
- PositionsList,
- ProgressBar,
- Slider,
- Text,
- Tooltip,
-} from 'components'
-import { useAccountStats, useBalances, useCalculateMaxBorrowAmount } from 'hooks/data'
-import { useBorrowFunds } from 'hooks/mutations'
-import { useAllBalances, useMarkets, useTokenPrices } from 'hooks/queries'
-import { useAccountDetailsStore, useNetworkConfigStore } from 'stores'
+import { Button } from 'components/Button'
+import { CircularProgress } from 'components/CircularProgress'
+import { ContainerSecondary } from 'components/ContainerSecondary'
+import { Gauge } from 'components/Gauge'
+import { PositionsList } from 'components/PositionsList'
+import { ProgressBar } from 'components/ProgressBar'
+import { Slider } from 'components/Slider'
+import { Text } from 'components/Text'
+import { Tooltip } from 'components/Tooltip'
+import { useAccountStats } from 'hooks/data/useAccountStats'
+import { useBalances } from 'hooks/data/useBalances'
+import { useCalculateMaxBorrowAmount } from 'hooks/data/useCalculateMaxBorrowAmount'
+import { useBorrowFunds } from 'hooks/mutations/useBorrowFunds'
+import { useAllBalances } from 'hooks/queries/useAllBalances'
+import { useMarkets } from 'hooks/queries/useMarkets'
+import { useTokenPrices } from 'hooks/queries/useTokenPrices'
import { formatCurrency, formatValue } from 'utils/formatters'
import { getTokenDecimals, getTokenSymbol } from 'utils/tokens'
+import useStore from 'store'
+import { getBaseAsset, getMarketAssets } from 'utils/assets'
type Props = {
show: boolean
@@ -32,15 +35,15 @@ export const BorrowModal = ({ show, onClose, tokenDenom }: Props) => {
const [amount, setAmount] = useState(0)
const [isBorrowToCreditAccount, setIsBorrowToCreditAccount] = useState(false)
- const selectedAccount = useAccountDetailsStore((s) => s.selectedAccount)
- const whitelistedAssets = useNetworkConfigStore((s) => s.assets.whitelist)
- const baseAsset = useNetworkConfigStore((s) => s.assets.base)
+ const selectedAccount = useStore((s) => s.selectedAccount)
+ const marketAssets = getMarketAssets()
+ const baseAsset = getBaseAsset()
const balances = useBalances()
const { actions, borrowAmount } = useMemo(() => {
const borrowAmount = BigNumber(amount)
- .times(10 ** getTokenDecimals(tokenDenom, whitelistedAssets))
+ .times(10 ** getTokenDecimals(tokenDenom, marketAssets))
.toNumber()
const withdrawAmount = isBorrowToCreditAccount ? 0 : borrowAmount
@@ -61,11 +64,11 @@ export const BorrowModal = ({ show, onClose, tokenDenom }: Props) => {
},
] as AccountStatsAction[],
}
- }, [amount, isBorrowToCreditAccount, tokenDenom, whitelistedAssets])
+ }, [amount, isBorrowToCreditAccount, tokenDenom, marketAssets])
const accountStats = useAccountStats(actions)
- const tokenSymbol = getTokenSymbol(tokenDenom, whitelistedAssets)
+ const tokenSymbol = getTokenSymbol(tokenDenom, marketAssets)
const { mutate, isLoading } = useBorrowFunds(borrowAmount, tokenDenom, !isBorrowToCreditAccount, {
onSuccess: () => {
@@ -84,9 +87,9 @@ export const BorrowModal = ({ show, onClose, tokenDenom }: Props) => {
const walletAmount = useMemo(() => {
return BigNumber(balancesData?.find((balance) => balance.denom === tokenDenom)?.amount ?? 0)
- .div(10 ** getTokenDecimals(tokenDenom, whitelistedAssets))
+ .div(10 ** getTokenDecimals(tokenDenom, marketAssets))
.toNumber()
- }, [balancesData, tokenDenom, whitelistedAssets])
+ }, [balancesData, tokenDenom, marketAssets])
const tokenPrice = tokenPrices?.[tokenDenom] ?? 0
const borrowRate = Number(marketsData?.[tokenDenom]?.borrow_rate)
@@ -110,7 +113,7 @@ export const BorrowModal = ({ show, onClose, tokenDenom }: Props) => {
const handleSliderValueChange = (value: number[]) => {
const decimal = value[0] / 100
- const tokenDecimals = getTokenDecimals(tokenDenom, whitelistedAssets)
+ const tokenDecimals = getTokenDecimals(tokenDenom, marketAssets)
// limit decimal precision based on token contract decimals
const newAmount = Number((decimal * maxValue).toFixed(tokenDecimals))
@@ -175,7 +178,7 @@ export const BorrowModal = ({ show, onClose, tokenDenom }: Props) => {
allowNegative={false}
onValueChange={(v) => handleValueChange(v.floatValue || 0)}
suffix={` ${tokenSymbol}`}
- decimalScale={getTokenDecimals(tokenDenom, whitelistedAssets)}
+ decimalScale={getTokenDecimals(tokenDenom, marketAssets)}
/>
diff --git a/src/components/BorrowTable.tsx b/src/components/BorrowTable.tsx
new file mode 100644
index 00000000..e15d5291
--- /dev/null
+++ b/src/components/BorrowTable.tsx
@@ -0,0 +1,13 @@
+import { getBorrowData } from 'utils/api'
+
+export async function BorrowTable() {
+ const borrowData = await getBorrowData()
+
+ return borrowData.map((borrow) => {
+ return (
+
+ {borrow.denom} {borrow.borrowRate} {borrow.marketLiquidity}
+
+ )
+ })
+}
diff --git a/src/components/Button.tsx b/src/components/Button.tsx
index c05ed085..5eac448d 100644
--- a/src/components/Button.tsx
+++ b/src/components/Button.tsx
@@ -1,8 +1,8 @@
import classNames from 'classnames'
import React, { LegacyRef, ReactNode } from 'react'
-import { CircularProgress } from 'components'
-import { useSettingsStore } from 'stores'
+import { CircularProgress } from 'components/CircularProgress'
+import useStore from 'store'
interface Props {
children?: string | ReactNode
@@ -74,7 +74,7 @@ export const Button = React.forwardRef(function Button(
ref,
) {
const buttonClasses = []
- const enableAnimations = useSettingsStore((s) => s.enableAnimations)
+ const enableAnimations = useStore((s) => s.enableAnimations)
switch (variant) {
case 'round':
diff --git a/src/components/CircularProgress.tsx b/src/components/CircularProgress.tsx
index b09e7891..3a33249c 100644
--- a/src/components/CircularProgress.tsx
+++ b/src/components/CircularProgress.tsx
@@ -1,7 +1,7 @@
import classNames from 'classnames'
-import { Text } from 'components'
-import { useSettingsStore } from 'stores'
+import { Text } from 'components/Text'
+import useStore from 'store'
interface Props {
color?: string
@@ -10,7 +10,7 @@ interface Props {
}
export const CircularProgress = ({ color = '#FFFFFF', size = 20, className }: Props) => {
- const enableAnimations = useSettingsStore((s) => s.enableAnimations)
+ const enableAnimations = useStore((s) => s.enableAnimations)
const borderWidth = `${size / 10}px`
const borderColor = `${color} transparent transparent transparent`
diff --git a/src/components/CookieConsent.tsx b/src/components/CookieConsent.tsx
deleted file mode 100644
index 92925af3..00000000
--- a/src/components/CookieConsent.tsx
+++ /dev/null
@@ -1,60 +0,0 @@
-import classNames from 'classnames'
-import { useEffect, useState } from 'react'
-
-import { DocURL } from 'types/enums/docURL'
-
-import { Button } from './Button'
-
-export const CookieConsent = () => {
- const [cookieConsent, setCookieConsent] = useState
(true)
-
- const createCookie = () => {
- setCookieConsent(true)
- document.cookie = 'viewed_cookie_policy=yes; path=/'
- }
-
- useEffect(() => {
- setCookieConsent(!!document.cookie.match(new RegExp('(^| )viewed_cookie_policy=([^;]+)')))
- }, [])
-
- return cookieConsent ? null : (
-
-
-
- This website uses cookies to improve its functionality and optimize content delivery. By
- using this website, you agree to the use of cookies for these purposes. Learn more,
- including how to modify your cookie settings, in Marsprotocol.io's{' '}
-
- privacy
- {' '}
- and{' '}
-
- cookie
- {' '}
- policies.
-
-
-
-
- )
-}
diff --git a/src/components/FormattedNumber.tsx b/src/components/FormattedNumber.tsx
index 94b87a82..78b14cc7 100644
--- a/src/components/FormattedNumber.tsx
+++ b/src/components/FormattedNumber.tsx
@@ -1,8 +1,10 @@
+'use client'
+
import classNames from 'classnames'
import React, { useEffect, useRef } from 'react'
import { animated, useSpring } from 'react-spring'
-import { useSettingsStore } from 'stores'
+import useStore from 'store'
import { formatValue } from 'utils/formatters'
export const FormattedNumber = React.memo(
@@ -18,7 +20,7 @@ export const FormattedNumber = React.memo(
rounded = false,
abbreviated = false,
}: FormattedNumberProps) => {
- const enableAnimations = useSettingsStore((s) => s.enableAnimations)
+ const enableAnimations = useStore((s) => s.enableAnimations)
const prevAmountRef = useRef(0)
useEffect(() => {
diff --git a/src/components/Gauge.tsx b/src/components/Gauge.tsx
index 1e0669b4..9c07fca6 100644
--- a/src/components/Gauge.tsx
+++ b/src/components/Gauge.tsx
@@ -1,8 +1,8 @@
import classNames from 'classnames'
import { ReactNode } from 'react'
-import { Tooltip } from 'components'
-import { useSettingsStore } from 'stores'
+import { Tooltip } from 'components/Tooltip'
+import useStore from 'store'
interface Props {
tooltip: string | ReactNode
@@ -20,7 +20,7 @@ export const Gauge = ({
label,
tooltip,
}: Props) => {
- const enableAnimations = useSettingsStore((s) => s.enableAnimations)
+ const enableAnimations = useStore((s) => s.enableAnimations)
const percentage = value * 100
const percentageValue = percentage > 100 ? 100 : percentage < 0 ? 0 : percentage
diff --git a/src/components/Icons/index.ts b/src/components/Icons/index.ts
index 1c1b0662..ef272fd4 100644
--- a/src/components/Icons/index.ts
+++ b/src/components/Icons/index.ts
@@ -1,48 +1,48 @@
-// @index(['./*.svg'], f => `export { default as ${f.name} } from '${f.path}.svg'`)
-export { default as Add } from './Add.svg'
-export { default as ArrowBack } from './ArrowBack.svg'
-export { default as ArrowDown } from './ArrowDown.svg'
-export { default as ArrowLeftLine } from './ArrowLeftLine.svg'
-export { default as ArrowRightLine } from './ArrowRightLine.svg'
-export { default as ArrowsLeftRight } from './ArrowsLeftRight.svg'
-export { default as ArrowsUpDown } from './ArrowsUpDown.svg'
-export { default as ArrowUp } from './ArrowUp.svg'
-export { default as BurgerMenu } from './BurgerMenu.svg'
-export { default as Check } from './Check.svg'
-export { default as ChevronDown } from './ChevronDown.svg'
-export { default as ChevronLeft } from './ChevronLeft.svg'
-export { default as ChevronRight } from './ChevronRight.svg'
-export { default as ChevronUp } from './ChevronUp.svg'
-export { default as Close } from './Close.svg'
-export { default as Copy } from './Copy.svg'
-export { default as Deposit } from './Deposit.svg'
-export { default as Discord } from './Discord.svg'
-export { default as Edit } from './Edit.svg'
-export { default as Ellipsis } from './Ellipsis.svg'
-export { default as ExternalLink } from './ExternalLink.svg'
-export { default as Failed } from './Failed.svg'
-export { default as Github } from './Github.svg'
-export { default as Info } from './Info.svg'
-export { default as Logo } from './Logo.svg'
-export { default as MarsProtocol } from './MarsProtocol.svg'
-export { default as Medium } from './Medium.svg'
-export { default as Osmo } from './Osmo.svg'
-export { default as Questionmark } from './Questionmark.svg'
-export { default as Reddit } from './Reddit.svg'
-export { default as Rubbish } from './Rubbish.svg'
-export { default as Search } from './Search.svg'
-export { default as SmallClose } from './SmallClose.svg'
-export { default as SortAsc } from './SortAsc.svg'
-export { default as SortDesc } from './SortDesc.svg'
-export { default as SortNone } from './SortNone.svg'
-export { default as Subtract } from './Subtract.svg'
-export { default as Success } from './Success.svg'
-export { default as Telegram } from './Telegram.svg'
-export { default as TriangleDown } from './TriangleDown.svg'
-export { default as Twitter } from './Twitter.svg'
-export { default as Wallet } from './Wallet.svg'
-export { default as WalletConnect } from './WalletConnect.svg'
-export { default as Warning } from './Warning.svg'
-export { default as Withdraw } from './Withdraw.svg'
-export { default as YouTube } from './YouTube.svg'
+// @index(['./*.svg'], f => `export { default as ${f.name} } from 'components/Icons/${f.name}.svg'`)
+export { default as Add } from 'components/Icons/Add.svg'
+export { default as ArrowBack } from 'components/Icons/ArrowBack.svg'
+export { default as ArrowDown } from 'components/Icons/ArrowDown.svg'
+export { default as ArrowLeftLine } from 'components/Icons/ArrowLeftLine.svg'
+export { default as ArrowRightLine } from 'components/Icons/ArrowRightLine.svg'
+export { default as ArrowsLeftRight } from 'components/Icons/ArrowsLeftRight.svg'
+export { default as ArrowsUpDown } from 'components/Icons/ArrowsUpDown.svg'
+export { default as ArrowUp } from 'components/Icons/ArrowUp.svg'
+export { default as BurgerMenu } from 'components/Icons/BurgerMenu.svg'
+export { default as Check } from 'components/Icons/Check.svg'
+export { default as ChevronDown } from 'components/Icons/ChevronDown.svg'
+export { default as ChevronLeft } from 'components/Icons/ChevronLeft.svg'
+export { default as ChevronRight } from 'components/Icons/ChevronRight.svg'
+export { default as ChevronUp } from 'components/Icons/ChevronUp.svg'
+export { default as Close } from 'components/Icons/Close.svg'
+export { default as Copy } from 'components/Icons/Copy.svg'
+export { default as Deposit } from 'components/Icons/Deposit.svg'
+export { default as Discord } from 'components/Icons/Discord.svg'
+export { default as Edit } from 'components/Icons/Edit.svg'
+export { default as Ellipsis } from 'components/Icons/Ellipsis.svg'
+export { default as ExternalLink } from 'components/Icons/ExternalLink.svg'
+export { default as Failed } from 'components/Icons/Failed.svg'
+export { default as Github } from 'components/Icons/Github.svg'
+export { default as Info } from 'components/Icons/Info.svg'
+export { default as Logo } from 'components/Icons/Logo.svg'
+export { default as MarsProtocol } from 'components/Icons/MarsProtocol.svg'
+export { default as Medium } from 'components/Icons/Medium.svg'
+export { default as Osmo } from 'components/Icons/Osmo.svg'
+export { default as Questionmark } from 'components/Icons/Questionmark.svg'
+export { default as Reddit } from 'components/Icons/Reddit.svg'
+export { default as Rubbish } from 'components/Icons/Rubbish.svg'
+export { default as Search } from 'components/Icons/Search.svg'
+export { default as SmallClose } from 'components/Icons/SmallClose.svg'
+export { default as SortAsc } from 'components/Icons/SortAsc.svg'
+export { default as SortDesc } from 'components/Icons/SortDesc.svg'
+export { default as SortNone } from 'components/Icons/SortNone.svg'
+export { default as Subtract } from 'components/Icons/Subtract.svg'
+export { default as Success } from 'components/Icons/Success.svg'
+export { default as Telegram } from 'components/Icons/Telegram.svg'
+export { default as TriangleDown } from 'components/Icons/TriangleDown.svg'
+export { default as Twitter } from 'components/Icons/Twitter.svg'
+export { default as Wallet } from 'components/Icons/Wallet.svg'
+export { default as WalletConnect } from 'components/Icons/WalletConnect.svg'
+export { default as Warning } from 'components/Icons/Warning.svg'
+export { default as Withdraw } from 'components/Icons/Withdraw.svg'
+export { default as YouTube } from 'components/Icons/YouTube.svg'
// @endindex
diff --git a/src/components/LabelValuePair.tsx b/src/components/LabelValuePair.tsx
index 0e7d76f1..bd240bbf 100644
--- a/src/components/LabelValuePair.tsx
+++ b/src/components/LabelValuePair.tsx
@@ -1,6 +1,7 @@
import classNames from 'classnames'
-import { FormattedNumber, Text } from 'components'
+import { Text } from 'components/Text'
+import { FormattedNumber } from 'components/FormattedNumber'
interface ValueData extends FormattedNumberProps {
format?: 'number' | 'string'
diff --git a/src/components/Layout.tsx b/src/components/Layout.tsx
deleted file mode 100644
index 5730540c..00000000
--- a/src/components/Layout.tsx
+++ /dev/null
@@ -1,49 +0,0 @@
-import { useWallet, WalletConnectionStatus } from '@marsprotocol/wallet-connector'
-import classNames from 'classnames'
-import React, { useEffect } from 'react'
-
-import { AccountDetails } from 'components/Account'
-import { DesktopNavigation } from 'components/Navigation'
-import { useCreditAccounts } from 'hooks/queries'
-import { useSettingsStore, useWalletStore } from 'stores'
-
-import { CookieConsent } from './CookieConsent'
-
-const filter = {
- day: 'brightness-100 hue-rotate-0',
- night: '-hue-rotate-82 brightness-30',
-}
-
-export const Layout = ({ children }: { children: React.ReactNode }) => {
- const enableAnimations = useSettingsStore((s) => s.enableAnimations)
-
- const { data: creditAccountsList } = useCreditAccounts()
- const hasCreditAccounts = creditAccountsList && creditAccountsList.length > 0
-
- const { status, signingCosmWasmClient, chainInfo, address, name } = useWallet()
- const initialize = useWalletStore((s) => s.actions.initialize)
-
- useEffect(() => {
- initialize(status, signingCosmWasmClient, address, name, chainInfo)
- }, [status, signingCosmWasmClient, chainInfo, address, name, initialize])
-
- const isConnected = status === WalletConnectionStatus.Connected
-
- const backgroundClasses = classNames(
- isConnected ? filter.day : filter.night,
- 'top-0 left-0 absolute block h-full w-full flex-col bg-body bg-mars bg-desktop bg-top bg-no-repeat filter',
- enableAnimations && 'transition-background duration-3000 ease-linear',
- )
-
- return (
-
-
-
-
- {children}
- {hasCreditAccounts && }
-
-
-
- )
-}
diff --git a/src/components/Loading.tsx b/src/components/Loading.tsx
new file mode 100644
index 00000000..6322b116
--- /dev/null
+++ b/src/components/Loading.tsx
@@ -0,0 +1,28 @@
+import classNames from 'classnames'
+
+interface Props {
+ className?: string
+ count?: number
+ height?: number
+ width?: number
+}
+
+export default function Loading(props: Props) {
+ return (
+ <>
+ {Array.from({ length: props.count ?? 1 }, (_, i) => (
+
+ ))}
+ Loading...
+ >
+ )
+}
diff --git a/src/components/Modal.tsx b/src/components/Modal.tsx
index 96ac42f9..a3f9660f 100644
--- a/src/components/Modal.tsx
+++ b/src/components/Modal.tsx
@@ -1,8 +1,8 @@
import classNames from 'classnames'
import { ReactNode } from 'react'
-import { Card } from 'components'
import { Close } from 'components/Icons'
+import { Card } from 'components/Card'
interface Props {
children?: ReactNode | string
diff --git a/src/components/Modals.tsx b/src/components/Modals.tsx
index c0ecde5e..7a0cb4af 100644
--- a/src/components/Modals.tsx
+++ b/src/components/Modals.tsx
@@ -1,9 +1,12 @@
-import { ConfirmModal, FundAccountModal, WithdrawModal } from './Account'
+'use client'
+
+import { ConfirmModal } from 'components/Account/ConfirmModal'
+import { FundAccountModal } from 'components/Account/FundAccountModal'
export const Modals = () => (
<>
-
+ {/* */}
>
)
diff --git a/src/components/Navigation/DesktopNavigation.tsx b/src/components/Navigation/DesktopNavigation.tsx
index 5c462c99..2b733b34 100644
--- a/src/components/Navigation/DesktopNavigation.tsx
+++ b/src/components/Navigation/DesktopNavigation.tsx
@@ -1,33 +1,36 @@
+'use client'
+
import Link from 'next/link'
+import { usePathname } from 'next/navigation'
-import { AccountNavigation, AccountStatus } from 'components/Account'
import { Logo } from 'components/Icons'
-import { menuTree, NavLink, SearchInput } from 'components/Navigation'
-import { Wallet } from 'components/Wallet'
-import { useCreditAccounts } from 'hooks/queries'
-import { useAccountDetailsStore, useWalletStore } from 'stores'
+import { NavLink } from 'components/Navigation/NavLink'
+import Wallet from 'components/Wallet/Wallet'
+import { getRoute } from 'utils/route'
-export const DesktopNavigation = () => {
- const address = useWalletStore((s) => s.address)
- const selectedAccount = useAccountDetailsStore((s) => s.selectedAccount)
+export const menuTree: { href: RouteSegment; label: string }[] = [
+ { href: 'trade', label: 'Trade' },
+ { href: 'earn', label: 'Earn' },
+ { href: 'borrow', label: 'Borrow' },
+ { href: 'portfolio', label: 'Portfolio' },
+ { href: 'council', label: 'Council' },
+]
- const { data: creditAccountsList } = useCreditAccounts()
-
- const isConnected = !!address
- const hasCreditAccounts = creditAccountsList && creditAccountsList.length > 0
+export default function DesktopNavigation() {
+ const pathname = usePathname() || ''
return (
-
-
+
+
{menuTree.map((item, index) => (
-
+
{item.label}
))}
@@ -35,19 +38,6 @@ export const DesktopNavigation = () => {
- {/* Sub navigation bar */}
-
-
-
- {isConnected && hasCreditAccounts && (
-
- )}
-
- {isConnected &&
}
-
)
}
diff --git a/src/components/Navigation/NavLink.tsx b/src/components/Navigation/NavLink.tsx
index 3ea7ec7f..7c8e8aef 100644
--- a/src/components/Navigation/NavLink.tsx
+++ b/src/components/Navigation/NavLink.tsx
@@ -1,5 +1,7 @@
+'use client'
+
import Link from 'next/link'
-import { useRouter } from 'next/router'
+import { usePathname } from 'next/navigation'
import { ReactNode } from 'react'
import classNames from 'classnames'
@@ -9,19 +11,18 @@ interface Props {
}
export const NavLink = ({ href, children }: Props) => {
- const router = useRouter()
- const isActive = router.pathname === href
+ const pathname = usePathname()
+ const isActive = pathname === href
return (
-
-
- {children}
-
+
+ {children}
)
}
diff --git a/src/components/Navigation/SearchInput.tsx b/src/components/Navigation/SearchInput.tsx
deleted file mode 100644
index b5c10949..00000000
--- a/src/components/Navigation/SearchInput.tsx
+++ /dev/null
@@ -1,12 +0,0 @@
-import { Search } from 'components/Icons'
-export const SearchInput = () => (
-
-
-
-
-
-
-)
diff --git a/src/components/Navigation/index.ts b/src/components/Navigation/index.ts
deleted file mode 100644
index 89a98d65..00000000
--- a/src/components/Navigation/index.ts
+++ /dev/null
@@ -1,6 +0,0 @@
-// @index(['./*.ts*'], f => `export { ${f.name} } from '${f.path}'`)
-export { DesktopNavigation } from './DesktopNavigation'
-export { menuTree } from './menuTree'
-export { NavLink } from './NavLink'
-export { SearchInput } from './SearchInput'
-// @endindex
diff --git a/src/components/Navigation/menuTree.ts b/src/components/Navigation/menuTree.ts
deleted file mode 100644
index 016d6a20..00000000
--- a/src/components/Navigation/menuTree.ts
+++ /dev/null
@@ -1,7 +0,0 @@
-export const menuTree = [
- { href: '/trade', label: 'Trade' },
- { href: '/earn', label: 'Earn' },
- { href: '/borrow', label: 'Borrow' },
- { href: '/portfolio', label: 'Portfolio' },
- { href: '/council', label: 'Council' },
-]
diff --git a/src/components/Overlay/OverlayAction.tsx b/src/components/Overlay/OverlayAction.tsx
index 117340ea..2ef3a8bd 100644
--- a/src/components/Overlay/OverlayAction.tsx
+++ b/src/components/Overlay/OverlayAction.tsx
@@ -1,7 +1,7 @@
import classNames from 'classnames'
import { ReactNode } from 'react'
-import { Button } from 'components'
+import { Button } from 'components/Button'
interface Props {
className?: string
diff --git a/src/components/Overlay/index.ts b/src/components/Overlay/index.ts
deleted file mode 100644
index c35f4561..00000000
--- a/src/components/Overlay/index.ts
+++ /dev/null
@@ -1,4 +0,0 @@
-// @index(['./*.tsx'], f => `export { ${f.name} } from '${f.path}'`)
-export { Overlay } from './Overlay'
-export { OverlayAction } from './OverlayAction'
-// @endindex
diff --git a/src/components/PositionsList.tsx b/src/components/PositionsList.tsx
index 6b5f8db3..367df25f 100644
--- a/src/components/PositionsList.tsx
+++ b/src/components/PositionsList.tsx
@@ -1,6 +1,7 @@
import classNames from 'classnames'
-import { FormattedNumber, Text } from 'components'
+import { Text } from 'components/Text'
+import { FormattedNumber } from 'components/FormattedNumber'
interface Props {
title: string
diff --git a/src/components/RepayModal.tsx b/src/components/RepayModal.tsx
index 58c011f8..e70d7fc2 100644
--- a/src/components/RepayModal.tsx
+++ b/src/components/RepayModal.tsx
@@ -5,12 +5,18 @@ import React, { useMemo, useState } from 'react'
import { NumericFormat } from 'react-number-format'
import { toast } from 'react-toastify'
-import { Button, CircularProgress, ContainerSecondary, Slider } from 'components'
-import { useRepayFunds } from 'hooks/mutations'
-import { useAllBalances, useCreditAccountPositions, useTokenPrices } from 'hooks/queries'
-import { useAccountDetailsStore, useNetworkConfigStore } from 'stores'
+import { Button } from 'components/Button'
+import { CircularProgress } from 'components/CircularProgress'
+import { ContainerSecondary } from 'components/ContainerSecondary'
+import { Slider } from 'components/Slider'
+import { useRepayFunds } from 'hooks/mutations/useRepayFunds'
+import { useAllBalances } from 'hooks/queries/useAllBalances'
+import { useCreditAccountPositions } from 'hooks/queries/useCreditAccountPositions'
+import { useTokenPrices } from 'hooks/queries/useTokenPrices'
import { formatCurrency } from 'utils/formatters'
import { getTokenDecimals, getTokenSymbol } from 'utils/tokens'
+import { getMarketAssets } from 'utils/assets'
+import useStore from 'store'
// 0.001% buffer / slippage to avoid repay action from not fully repaying the debt amount
const REPAY_BUFFER = 1.00001
@@ -24,11 +30,11 @@ type Props = {
export const RepayModal = ({ show, onClose, tokenDenom }: Props) => {
const [amount, setAmount] = useState(0)
- const selectedAccount = useAccountDetailsStore((s) => s.selectedAccount)
+ const selectedAccount = useStore((s) => s.selectedAccount)
const { data: positionsData } = useCreditAccountPositions(selectedAccount ?? '')
- const whitelistedAssets = useNetworkConfigStore((s) => s.assets.whitelist)
+ const marketAssets = getMarketAssets()
- const tokenSymbol = getTokenSymbol(tokenDenom, whitelistedAssets)
+ const tokenSymbol = getTokenSymbol(tokenDenom, marketAssets)
const maxRepayAmount = useMemo(() => {
const tokenDebtAmount =
@@ -37,13 +43,13 @@ export const RepayModal = ({ show, onClose, tokenDenom }: Props) => {
return BigNumber(tokenDebtAmount)
.times(REPAY_BUFFER)
.decimalPlaces(0)
- .div(10 ** getTokenDecimals(tokenDenom, whitelistedAssets))
+ .div(10 ** getTokenDecimals(tokenDenom, marketAssets))
.toNumber()
- }, [positionsData, tokenDenom, whitelistedAssets])
+ }, [positionsData, tokenDenom, marketAssets])
const { mutate, isLoading } = useRepayFunds(
BigNumber(amount)
- .times(10 ** getTokenDecimals(tokenDenom, whitelistedAssets))
+ .times(10 ** getTokenDecimals(tokenDenom, marketAssets))
.toNumber(),
tokenDenom,
{
@@ -63,9 +69,9 @@ export const RepayModal = ({ show, onClose, tokenDenom }: Props) => {
const walletAmount = useMemo(() => {
return BigNumber(balancesData?.find((balance) => balance.denom === tokenDenom)?.amount ?? 0)
- .div(10 ** getTokenDecimals(tokenDenom, whitelistedAssets))
+ .div(10 ** getTokenDecimals(tokenDenom, marketAssets))
.toNumber()
- }, [balancesData, tokenDenom, whitelistedAssets])
+ }, [balancesData, tokenDenom, marketAssets])
const tokenPrice = tokenPrices?.[tokenDenom] ?? 0
@@ -143,7 +149,7 @@ export const RepayModal = ({ show, onClose, tokenDenom }: Props) => {
allowNegative={false}
onValueChange={(v) => handleValueChange(v.floatValue || 0)}
suffix={` ${tokenSymbol}`}
- decimalScale={getTokenDecimals(tokenDenom, whitelistedAssets)}
+ decimalScale={getTokenDecimals(tokenDenom, marketAssets)}
/>
@@ -158,7 +164,7 @@ export const RepayModal = ({ show, onClose, tokenDenom }: Props) => {
value={percentageValue}
onChange={(value) => {
const decimal = value[0] / 100
- const tokenDecimals = getTokenDecimals(tokenDenom, whitelistedAssets)
+ const tokenDecimals = getTokenDecimals(tokenDenom, marketAssets)
// limit decimal precision based on token contract decimals
const newAmount = Number((decimal * maxValue).toFixed(tokenDecimals))
diff --git a/src/components/Toaster.tsx b/src/components/Toaster.tsx
new file mode 100644
index 00000000..f37dc8de
--- /dev/null
+++ b/src/components/Toaster.tsx
@@ -0,0 +1,18 @@
+'use client'
+import { Slide, ToastContainer } from 'react-toastify'
+
+import useStore from 'store'
+
+export default function Toaster() {
+ const enableAnimations = useStore((s) => s.enableAnimations)
+
+ return (
+
+ )
+}
diff --git a/src/components/Tooltip.tsx b/src/components/Tooltip.tsx
index a8e1e55d..b552fe8b 100644
--- a/src/components/Tooltip.tsx
+++ b/src/components/Tooltip.tsx
@@ -3,7 +3,7 @@ import classNames from 'classnames'
import { ReactNode } from 'react'
import { Questionmark } from 'components/Icons'
-import { useSettingsStore } from 'stores'
+import useStore from 'store'
interface Props {
children?: ReactNode | string
@@ -22,7 +22,7 @@ export const Tooltip = ({
inderactive = false,
underline = false,
}: Props) => {
- const enableAnimations = useSettingsStore((s) => s.enableAnimations)
+ const enableAnimations = useStore((s) => s.enableAnimations)
return (
{
- const whitelistedAssets = useNetworkConfigStore((s) => s.assets.whitelist)
+ const marketAssets = getMarketAssets()
const [selectedTokenIn, setSelectedTokenIn] = useState('')
const [selectedTokenOut, setSelectedTokenOut] = useState('')
@@ -34,7 +37,7 @@ export const TradeActionModule = () => {
const [isMarginEnabled, setIsMarginEnabled] = React.useState(false)
- const selectedAccount = useAccountDetailsStore((s) => s.selectedAccount)
+ const selectedAccount = useStore((s) => s.selectedAccount)
const { data: allowedCoinsData } = useAllowedCoins()
const { data: balancesData } = useAllBalances()
@@ -96,8 +99,8 @@ export const TradeActionModule = () => {
toast.success(
`${amountIn} ${getTokenSymbol(
selectedTokenIn,
- whitelistedAssets,
- )} swapped for ${amountOut} ${getTokenSymbol(selectedTokenOut, whitelistedAssets)}`,
+ marketAssets,
+ )} swapped for ${amountOut} ${getTokenSymbol(selectedTokenOut, marketAssets)}`,
)
resetAmounts()
},
@@ -192,20 +195,20 @@ export const TradeActionModule = () => {
>
{allowedCoinsData?.map((entry) => (
- {getTokenSymbol(entry, whitelistedAssets)}
+ {getTokenSymbol(entry, marketAssets)}
))}
{
const valueAsNumber = e.target.valueAsNumber
const valueWithDecimals =
- valueAsNumber * 10 ** getTokenDecimals(selectedTokenIn, whitelistedAssets)
+ valueAsNumber * 10 ** getTokenDecimals(selectedTokenIn, marketAssets)
handleAmountChange(valueWithDecimals, 'in')
}}
@@ -232,20 +235,20 @@ export const TradeActionModule = () => {
>
{allowedCoinsData?.map((entry) => (
- {getTokenSymbol(entry, whitelistedAssets)}
+ {getTokenSymbol(entry, marketAssets)}
))}
{
const valueAsNumber = e.target.valueAsNumber
const valueWithDecimals =
- valueAsNumber * 10 ** getTokenDecimals(selectedTokenOut, whitelistedAssets)
+ valueAsNumber * 10 ** getTokenDecimals(selectedTokenOut, marketAssets)
handleAmountChange(valueWithDecimals, 'out')
}}
@@ -255,29 +258,29 @@ export const TradeActionModule = () => {
In Wallet:{' '}
{BigNumber(walletAmount)
- .dividedBy(10 ** getTokenDecimals(selectedTokenIn, whitelistedAssets))
+ .dividedBy(10 ** getTokenDecimals(selectedTokenIn, marketAssets))
.toNumber()
.toLocaleString(undefined, {
- maximumFractionDigits: getTokenDecimals(selectedTokenIn, whitelistedAssets),
+ maximumFractionDigits: getTokenDecimals(selectedTokenIn, marketAssets),
})}{' '}
- {getTokenSymbol(selectedTokenIn, whitelistedAssets)}
+ {getTokenSymbol(selectedTokenIn, marketAssets)}
In Account:{' '}
{BigNumber(accountAmount)
- .dividedBy(10 ** getTokenDecimals(selectedTokenIn, whitelistedAssets))
+ .dividedBy(10 ** getTokenDecimals(selectedTokenIn, marketAssets))
.toNumber()
.toLocaleString(undefined, {
- maximumFractionDigits: getTokenDecimals(selectedTokenIn, whitelistedAssets),
+ maximumFractionDigits: getTokenDecimals(selectedTokenIn, marketAssets),
})}{' '}
- {getTokenSymbol(selectedTokenIn, whitelistedAssets)}
+ {getTokenSymbol(selectedTokenIn, marketAssets)}
{
const decimal = value[0] / 100
- const tokenDecimals = getTokenDecimals(selectedTokenIn, whitelistedAssets)
+ const tokenDecimals = getTokenDecimals(selectedTokenIn, marketAssets)
// limit decimal precision based on token contract decimals
const newAmount = Number((decimal * maxAmount).toFixed(0))
@@ -313,10 +316,10 @@ export const TradeActionModule = () => {
{isMarginEnabled
? BigNumber(borrowAmount)
- .dividedBy(10 ** getTokenDecimals(selectedTokenIn, whitelistedAssets))
+ .dividedBy(10 ** getTokenDecimals(selectedTokenIn, marketAssets))
.toNumber()
.toLocaleString(undefined, {
- maximumFractionDigits: getTokenDecimals(selectedTokenIn, whitelistedAssets),
+ maximumFractionDigits: getTokenDecimals(selectedTokenIn, marketAssets),
})
: '-'}
diff --git a/src/components/Trade/index.ts b/src/components/Trade/index.ts
deleted file mode 100644
index 92560f88..00000000
--- a/src/components/Trade/index.ts
+++ /dev/null
@@ -1,3 +0,0 @@
-// @index(['./*.tsx'], f => `export { ${f.name} } from '${f.path}'`)
-export { TradeActionModule } from './TradeActionModule'
-// @endindex
diff --git a/src/components/Wallet/ConnectButton.tsx b/src/components/Wallet/ConnectButton.tsx
index a38e39cd..69fc7a44 100644
--- a/src/components/Wallet/ConnectButton.tsx
+++ b/src/components/Wallet/ConnectButton.tsx
@@ -1,7 +1,7 @@
import { useWalletManager, WalletConnectionStatus } from '@marsprotocol/wallet-connector'
import { ReactNode } from 'react'
-import { CircularProgress } from 'components'
+import { CircularProgress } from 'components/CircularProgress'
import { Wallet } from 'components/Icons'
interface Props {
@@ -10,17 +10,17 @@ interface Props {
status?: WalletConnectionStatus
}
-export const ConnectButton = ({ textOverride, disabled = false, status }: Props) => {
+export default function ConnectButton(props: Props) {
const { connect } = useWalletManager()
return (
- {status === WalletConnectionStatus.Connecting ? (
+ {props.status === WalletConnectionStatus.Connecting ? (
@@ -29,7 +29,7 @@ export const ConnectButton = ({ textOverride, disabled = false, status }: Props)
- {textOverride || 'Connect Wallet'}
+ {props.textOverride || 'Connect Wallet'}
>
)}
diff --git a/src/components/Wallet/ConnectedButton.tsx b/src/components/Wallet/ConnectedButton.tsx
index a254a0b9..2da452e5 100644
--- a/src/components/Wallet/ConnectedButton.tsx
+++ b/src/components/Wallet/ConnectedButton.tsx
@@ -1,61 +1,69 @@
-import { ChainInfoID, SimpleChainInfoList, useWalletManager } from '@marsprotocol/wallet-connector'
+import { Coin } from '@cosmjs/stargate'
+import {
+ ChainInfoID,
+ SimpleChainInfoList,
+ useWallet,
+ useWalletManager,
+} from '@marsprotocol/wallet-connector'
import BigNumber from 'bignumber.js'
import classNames from 'classnames'
import { useCallback, useEffect, useState } from 'react'
import useClipboard from 'react-use-clipboard'
+import useSWR from 'swr'
-import { Button, CircularProgress, FormattedNumber, Text } from 'components'
-import { Check, Copy, ExternalLink, Osmo, Wallet } from 'components/Icons'
-import { Overlay } from 'components/Overlay'
-import { useAllBalances } from 'hooks/queries'
-import { useNetworkConfigStore, useWalletStore } from 'stores'
+import { Button } from 'components/Button'
+import { CircularProgress } from 'components/CircularProgress'
+import { FormattedNumber } from 'components/FormattedNumber'
+import { Check, Copy, ExternalLink, Osmo } from 'components/Icons'
+import { Overlay } from 'components/Overlay/Overlay'
+import { Text } from 'components/Text'
+import useStore from 'store'
+import { getBaseAsset } from 'utils/assets'
import { formatValue, truncate } from 'utils/formatters'
+import { getWalletBalances } from 'utils/api'
-export const ConnectedButton = () => {
+export default function ConnectedButton() {
// ---------------
// EXTERNAL HOOKS
// ---------------
- const { disconnect } = useWalletManager()
- const address = useWalletStore((s) => s.address)
- const chainInfo = useWalletStore((s) => s.chainInfo)
- const name = useWalletStore((s) => s.name)
- const baseAsset = useNetworkConfigStore((s) => s.assets.base)
+ const { disconnect } = useWallet()
+ const { disconnect: terminate } = useWalletManager()
+ const address = useStore((s) => s.client?.recentWallet.account?.address)
+ const network = useStore((s) => s.client?.recentWallet.network)
+ const name = useStore((s) => s.name)
+ const baseAsset = getBaseAsset()
- // ---------------
- // LOCAL HOOKS
- // ---------------
- const { data } = useAllBalances()
+ const { data, isLoading } = useSWR(address, getWalletBalances)
// ---------------
// LOCAL STATE
// ---------------
- const [isLoading, setIsLoading] = useState(false)
const [showDetails, setShowDetails] = useState(false)
const [walletAmount, setWalletAmount] = useState(0)
const [isCopied, setCopied] = useClipboard(address || '', {
successDuration: 1000 * 5,
})
-
// ---------------
// VARIABLES
// ---------------
- const explorerName =
- chainInfo && SimpleChainInfoList[chainInfo.chainId as ChainInfoID].explorerName
+ const explorerName = network && SimpleChainInfoList[network.chainId as ChainInfoID].explorerName
const viewOnFinder = useCallback(() => {
- const explorerUrl = chainInfo && SimpleChainInfoList[chainInfo.chainId as ChainInfoID].explorer
+ const explorerUrl = network && SimpleChainInfoList[network.chainId as ChainInfoID].explorer
- window.open(`${explorerUrl}account/${address}`, '_blank')
- }, [chainInfo, address])
-
- useEffect(() => {
- const loading = !(address && name && chainInfo)
- setIsLoading(loading)
- }, [address, name, chainInfo])
+ window.open(`${explorerUrl}/account/${address}`, '_blank')
+ }, [network, address])
+
+ const disconnectWallet = () => {
+ disconnect()
+ terminate()
+ useStore.setState({ client: undefined })
+ }
useEffect(() => {
+ if (!data || data.length === 0) return
setWalletAmount(
- BigNumber(data?.find((balance) => balance.denom === baseAsset.denom)?.amount ?? 0)
+ BigNumber(data?.find((coin: Coin) => coin.denom === baseAsset.denom)?.amount ?? 0)
.div(10 ** baseAsset.decimals)
.toNumber(),
)
@@ -63,13 +71,13 @@ export const ConnectedButton = () => {
return (
- {chainInfo?.chainId !== ChainInfoID.Osmosis1 && (
+ {network?.chainId !== ChainInfoID.Osmosis1 && (
- {chainInfo?.chainId}
+ {network?.chainId}
)}
@@ -84,12 +92,7 @@ export const ConnectedButton = () => {
}}
>
- {chainInfo?.chainId === ChainInfoID.Osmosis1 ||
- chainInfo?.chainId === ChainInfoID.OsmosisTestnet ? (
-
- ) : (
-
- )}
+
{name ? name : truncate(address, [2, 4])}
{
'before:content-[" "] before:absolute before:top-1.5 before:bottom-1.5 before:left-0 before:h-[calc(100%-12px)] before:border-l before:border-white',
)}
>
- {!isLoading ? (
- `${formatValue(walletAmount, 2, 2, true, false, ` ${baseAsset.symbol}`)}`
- ) : (
+ {isLoading ? (
+ ) : (
+ `${formatValue(walletAmount, 2, 2, true, false, ` ${baseAsset.symbol}`)}`
)}
@@ -121,7 +124,7 @@ export const ConnectedButton = () => {
-
+
diff --git a/src/components/Wallet/Wallet.tsx b/src/components/Wallet/Wallet.tsx
index 53cc5c01..fc428f64 100644
--- a/src/components/Wallet/Wallet.tsx
+++ b/src/components/Wallet/Wallet.tsx
@@ -1,18 +1,65 @@
-import { useWallet, WalletConnectionStatus } from '@marsprotocol/wallet-connector'
+'use client'
+
+import {
+ getClient,
+ useWallet,
+ useWalletManager,
+ WalletConnectionStatus,
+} from '@marsprotocol/wallet-connector'
import { useEffect, useState } from 'react'
+import { useRouter } from 'next/navigation'
-import { ConnectButton, ConnectedButton } from 'components/Wallet'
+import ConnectButton from 'components/Wallet/ConnectButton'
+import ConnectedButton from 'components/Wallet/ConnectedButton'
+import useParams from 'hooks/useParams'
+import useStore from 'store'
-export const Wallet = () => {
- const { status } = useWallet()
+export default function Wallet() {
+ const router = useRouter()
+ const params = useParams()
+ const { status } = useWalletManager()
const [isConnected, setIsConnected] = useState(false)
+ const { recentWallet, simulate, sign, broadcast } = useWallet()
+ const client = useStore((s) => s.client)
useEffect(() => {
const connectedStatus = status === WalletConnectionStatus.Connected
- if (connectedStatus !== isConnected) {
- setIsConnected(connectedStatus)
- }
+ if (connectedStatus === isConnected) return
+ setIsConnected(connectedStatus)
}, [status, isConnected])
- return !isConnected ?
:
+ useEffect(() => {
+ if (!isConnected && !params.wallet) {
+ router.push('/')
+ return
+ }
+
+ const address = client?.recentWallet.account.address
+ if (!address || address === params.wallet) return
+
+ router.push(`/wallets/${client.recentWallet.account.address}`)
+ }, [client, params, isConnected])
+
+ useEffect(() => {
+ if (!recentWallet) return
+ if (!client) {
+ const getCosmWasmClient = async () => {
+ const cosmClient = await getClient(recentWallet.network.rpc)
+
+ const client = {
+ broadcast,
+ cosmWasmClient: cosmClient,
+ recentWallet,
+ sign,
+ simulate,
+ }
+ useStore.setState({ client })
+ }
+
+ getCosmWasmClient()
+
+ return
+ }
+ }, [simulate, sign, recentWallet, broadcast])
+ return isConnected ?
:
}
diff --git a/src/components/Wallet/WalletConnectProvider.tsx b/src/components/Wallet/WalletConnectProvider.tsx
index 20b1d77b..5071c368 100644
--- a/src/components/Wallet/WalletConnectProvider.tsx
+++ b/src/components/Wallet/WalletConnectProvider.tsx
@@ -1,89 +1,40 @@
-import { ChainInfoID, WalletManagerProvider, WalletType } from '@marsprotocol/wallet-connector'
-import classNames from 'classnames'
+'use client'
+
+import { WalletManagerProvider } from '@marsprotocol/wallet-connector'
import { FC } from 'react'
-import { CircularProgress } from 'components'
-import { buttonColorClasses, buttonSizeClasses, buttonVariantClasses } from 'components/Button'
-import { Close } from 'components/Icons'
-// TODO: get networkConfig source dynamically
-import { networkConfig } from 'config/osmo-test-4'
-import KeplrImage from 'images/wallets/keplr-wallet-extension.png'
-import WalletConnectImage from 'images/wallets/walletconnect-keplr.png'
-import { useSettingsStore } from 'stores'
+import { CircularProgress } from 'components/CircularProgress'
+import { CHAIN_ID, ENV_MISSING_MESSAGE, URL_REST, URL_RPC, WALLETS } from 'constants/env'
type Props = {
children?: React.ReactNode
}
export const WalletConnectProvider: FC
= ({ children }) => {
- const enableAnimations = useSettingsStore((s) => s.enableAnimations)
+ if (!CHAIN_ID || !URL_REST || !URL_RPC || !WALLETS) {
+ console.error(ENV_MISSING_MESSAGE)
+ return null
+ }
+
+ const chainInfoOverrides = {
+ rpc: URL_RPC,
+ rest: URL_REST,
+ chainID: CHAIN_ID,
+ }
+ const enabledWallets: string[] = WALLETS
+
return (
-
-
- }
- defaultChainId={ChainInfoID.OsmosisTestnet}
- enabledWalletTypes={[WalletType.Keplr, WalletType.WalletConnectKeplr]}
- enablingMeta={{
- text: 'If nothing shows up in your wallet try to connect again, by clicking on the button below. Refresh the page if the problem persists.',
- textClassName: 'block w-full text-center text-base text-white',
- buttonText: 'Retry the Connection',
- buttonClassName: classNames(
- 'cursor-pointer appearance-none break-normal rounded-3xl outline-none',
- enableAnimations && 'transition-colors',
- buttonColorClasses.primary,
- buttonSizeClasses.small,
- buttonVariantClasses.solid,
- ),
- contentClassName: 'flex flex-wrap w-full justify-center',
- }}
- enablingStringOverride='connecting to wallet'
- localStorageKey='walletConnection'
+ chainInfoOverrides={chainInfoOverrides}
+ // closeIcon={ }
+ defaultChainId={chainInfoOverrides.chainID}
+ enabledWallets={enabledWallets}
+ persistent
renderLoader={() => (
-
+
)}
- walletConnectClientMeta={{
- name: 'Mars Protocol',
- description: 'Mars V2 Description',
- url: 'https://marsprotocol.io',
- icons: ['https://marsprotocol.io/favicon.svg'],
- }}
- walletMetaOverride={{
- [WalletType.Keplr]: {
- description: 'Keplr browser extension',
- imageUrl: KeplrImage.src,
- },
- [WalletType.WalletConnectKeplr]: {
- name: 'Wallet Connect',
- description: 'Keplr mobile WalletConnect',
- imageUrl: WalletConnectImage.src,
- },
- }}
>
{children}
diff --git a/src/components/Wallet/index.ts b/src/components/Wallet/index.ts
deleted file mode 100644
index 7d19ade0..00000000
--- a/src/components/Wallet/index.ts
+++ /dev/null
@@ -1,6 +0,0 @@
-// @index(['./*.tsx'], f => `export { ${f.name} } from '${f.path}'`)
-export { ConnectButton } from './ConnectButton'
-export { ConnectedButton } from './ConnectedButton'
-export { Wallet } from './Wallet'
-export { WalletConnectProvider } from './WalletConnectProvider'
-// @endindex
diff --git a/src/pages/borrow.tsx b/src/components/borrow_page.tsx
similarity index 78%
rename from src/pages/borrow.tsx
rename to src/components/borrow_page.tsx
index 7f2f5626..ca23c7be 100644
--- a/src/pages/borrow.tsx
+++ b/src/components/borrow_page.tsx
@@ -1,17 +1,19 @@
import BigNumber from 'bignumber.js'
import { useMemo, useRef, useState } from 'react'
-import { BorrowModal, Card, RepayModal, Text } from 'components'
-import { BorrowTable } from 'components/Borrow'
-import {
- useAllowedCoins,
- useCreditAccountPositions,
- useMarkets,
- useRedbankBalances,
- useTokenPrices,
-} from 'hooks/queries'
-import { useAccountDetailsStore, useNetworkConfigStore } from 'stores'
+import { BorrowTable } from 'components/Borrow/BorrowTable'
+import { BorrowModal } from 'components/BorrowModal'
+import { Card } from 'components/Card'
+import { RepayModal } from 'components/RepayModal'
+import { useAllowedCoins } from 'hooks/queries/useAllowedCoins'
+import { useCreditAccountPositions } from 'hooks/queries/useCreditAccountPositions'
+import { useMarkets } from 'hooks/queries/useMarkets'
+import { useRedbankBalances } from 'hooks/queries/useRedbankBalances'
+import { useTokenPrices } from 'hooks/queries/useTokenPrices'
+import { Text } from 'components/Text'
import { getTokenDecimals, getTokenInfo } from 'utils/tokens'
+import useStore from 'store'
+import { getMarketAssets } from 'utils/assets'
type ModalState = {
show: 'borrow' | 'repay' | false
@@ -21,14 +23,14 @@ type ModalState = {
}
const Borrow = () => {
- const whitelistedAssets = useNetworkConfigStore((s) => s.assets.whitelist)
+ const marketAssets = getMarketAssets()
const [modalState, setModalState] = useState
({
show: false,
data: { tokenDenom: '' },
})
- const selectedAccount = useAccountDetailsStore((s) => s.selectedAccount)
+ const selectedAccount = useStore((s) => s.selectedAccount)
const { data: allowedCoinsData } = useAllowedCoins()
const { data: positionsData } = useCreditAccountPositions(selectedAccount ?? '')
@@ -55,17 +57,17 @@ const Borrow = () => {
allowedCoinsData
?.filter((denom) => borrowedAssetsMap.has(denom))
.map((denom) => {
- const { symbol, name, logo } = getTokenInfo(denom, whitelistedAssets)
+ const { symbol, name, logo } = getTokenInfo(denom, marketAssets)
const borrowRate = Number(marketsData?.[denom].borrow_rate) || 0
const marketLiquidity = BigNumber(
redbankBalances?.find((asset) => asset.denom.toLowerCase() === denom.toLowerCase())
?.amount || 0,
)
- .div(10 ** getTokenDecimals(denom, whitelistedAssets))
+ .div(10 ** getTokenDecimals(denom, marketAssets))
.toNumber()
const borrowAmount = BigNumber(borrowedAssetsMap.get(denom) as string)
- .div(10 ** getTokenDecimals(denom, whitelistedAssets))
+ .div(10 ** getTokenDecimals(denom, marketAssets))
.toNumber()
const borrowValue = borrowAmount * (tokenPrices?.[denom] ?? 0)
@@ -88,13 +90,13 @@ const Borrow = () => {
allowedCoinsData
?.filter((denom) => !borrowedAssetsMap.has(denom))
.map((denom) => {
- const { symbol, name, logo } = getTokenInfo(denom, whitelistedAssets)
+ const { symbol, name, logo } = getTokenInfo(denom, marketAssets)
const borrowRate = Number(marketsData?.[denom].borrow_rate) || 0
const marketLiquidity = BigNumber(
redbankBalances?.find((asset) => asset.denom.toLowerCase() === denom.toLowerCase())
?.amount || 0,
)
- .div(10 ** getTokenDecimals(denom, whitelistedAssets))
+ .div(10 ** getTokenDecimals(denom, marketAssets))
.toNumber()
const rowData = {
@@ -110,14 +112,7 @@ const Borrow = () => {
return rowData
}) ?? [],
}
- }, [
- allowedCoinsData,
- borrowedAssetsMap,
- marketsData,
- redbankBalances,
- tokenPrices,
- whitelistedAssets,
- ])
+ }, [allowedCoinsData, borrowedAssetsMap, marketsData, redbankBalances, tokenPrices, marketAssets])
const handleBorrowClick = (denom: string) => {
setModalState({ show: 'borrow', data: { tokenDenom: denom } })
diff --git a/src/components/index.ts b/src/components/index.ts
deleted file mode 100644
index 6cfdd217..00000000
--- a/src/components/index.ts
+++ /dev/null
@@ -1,22 +0,0 @@
-// @index(['./*.tsx'], f => `export { ${f.name} } from '${f.path}'`)
-export { BorrowCapacity } from './BorrowCapacity'
-export { BorrowModal } from './BorrowModal'
-export { Button } from './Button'
-export { Card } from './Card'
-export { CircularProgress } from './CircularProgress'
-export { ContainerSecondary } from './ContainerSecondary'
-export { CookieConsent } from './CookieConsent'
-export { FormattedNumber } from './FormattedNumber'
-export { Gauge } from './Gauge'
-export { LabelValuePair } from './LabelValuePair'
-export { Layout } from './Layout'
-export { Modal } from './Modal'
-export { Modals } from './Modals'
-export { PositionsList } from './PositionsList'
-export { ProgressBar } from './ProgressBar'
-export { RepayModal } from './RepayModal'
-export { Slider } from './Slider'
-export { Text } from './Text'
-export { TextLink } from './TextLink'
-export { Tooltip } from './Tooltip'
-// @endindex
diff --git a/src/config/osmo-test-4.ts b/src/config/osmo-test-4.ts
deleted file mode 100644
index 858d1b37..00000000
--- a/src/config/osmo-test-4.ts
+++ /dev/null
@@ -1,68 +0,0 @@
-import { ChainInfoID } from '@marsprotocol/wallet-connector'
-
-const Assets: { [key: string]: Asset } = {
- osmo: {
- symbol: 'OSMO',
- name: 'Osmosis',
- denom: 'uosmo',
- color: '#9f1ab9',
- decimals: 6,
- hasOraclePrice: true,
- logo: '/tokens/osmo.svg',
- },
- atom: {
- symbol: 'ATOM',
- name: 'Atom',
- denom: 'ibc/27394FB092D2ECCD56123C74F36E4C1F926001CEADA9CA97EA622B25F41E5EB2',
- color: '#6f7390',
- logo: '/tokens/atom.svg',
- decimals: 6,
- hasOraclePrice: true,
- },
- cro: {
- symbol: 'CRO',
- name: 'Cronos',
- denom: 'ibc/E6931F78057F7CC5DA0FD6CEF82FF39373A6E0452BF1FD76910B93292CF356C1',
- color: '#002D74',
- logo: '/tokens/cro.svg',
- decimals: 8,
- hasOraclePrice: true,
- },
-}
-
-const OtherAssets: { [key: string]: OtherAsset } = {
- mars: {
- symbol: 'MARS',
- name: 'Mars',
- denom: 'ibc/EA3E1640F9B1532AB129A571203A0B9F789A7F14BB66E350DCBFA18E1A1931F0',
- //denom: 'ibc/1BF910A3C8A30C8E3331764FA0113B920AE14B913F487DF7E1989FD75EFE61FD'
- color: '#a03b45',
- logo: '/tokens/mars.svg',
- decimals: 6,
- hasOraclePrice: true,
- poolId: 601,
- },
-}
-
-export const networkConfig: NetworkConfig = {
- name: ChainInfoID.OsmosisTestnet,
- hiveUrl: 'https://osmosis-delphi-testnet-1.simply-vc.com.mt/XF32UOOU55CX/osmosis-hive/graphql',
- rpcUrl: 'https://osmosis-delphi-testnet-1.simply-vc.com.mt/XF32UOOU55CX/osmosis-rpc',
- restUrl: 'https://osmosis-delphi-testnet-1.simply-vc.com.mt/XF32UOOU55CX/osmosis-lcd',
- contracts: {
- accountNft: 'osmo1xvne7u9svgy9vtqtqnaet4nvn8zcpp984zzrlezfzgk4798tps8srkf5wa',
- mockVault: 'osmo1yqgjaehalz0pv5j22fdnaaekuprlggd7hth8m66jmdxe58ztqs4sjqtrlk',
- marsOracleAdapter: 'osmo1tlad2hj9rm7az7atx2qq8pdpl2007hrhpzua42j8wgxr0kc0ct4sahuyh7',
- swapper: 'osmo15kxcpvjaqlrj8ezecnghf2qs2x87veqx0fcemye0jpdr8jq7qkvsnyvuuf',
- mockZapper: 'osmo1axad429tgnvzvfax08s4ytmf7ndg0f9z4jy355zyh4m6nasgtnzs5aw8u7',
- creditManager: 'osmo1krz37p6xkkyu0f240enyt4ccxk7ds69kfgc5pnldsmpmmuvn3vpsnmpjaf',
- redBank: 'osmo1g30recyv8pfy3qd4qn3dn7plc0rn5z68y5gn32j39e96tjhthzxsw3uvvu',
- oracle: 'osmo1hkkx42777dyfz7wc8acjjhfdh9x2ugcjvdt7shtft6ha9cn420cquz3u3j',
- },
- assets: {
- base: Assets.osmo,
- whitelist: [Assets.osmo, Assets.atom, Assets.cro],
- other: [OtherAssets.mars],
- },
- appUrl: 'https://testnet.osmosis.zone',
-}
diff --git a/src/constants/assets.ts b/src/constants/assets.ts
new file mode 100644
index 00000000..7a23cebb
--- /dev/null
+++ b/src/constants/assets.ts
@@ -0,0 +1,62 @@
+import { IS_TESTNET } from 'constants/env'
+
+export const ASSETS: Asset[] = [
+ {
+ symbol: 'OSMO',
+ name: 'Osmosis',
+ denom: 'uosmo',
+ color: '#9f1ab9',
+ decimals: 6,
+ hasOraclePrice: true,
+ logo: '/tokens/osmo.svg',
+ isEnabled: true,
+ isMarket: true,
+ },
+ {
+ symbol: 'ATOM',
+ name: 'Atom',
+ denom: 'ibc/27394FB092D2ECCD56123C74F36E4C1F926001CEADA9CA97EA622B25F41E5EB2',
+ color: '#6f7390',
+ logo: '/tokens/atom.svg',
+ decimals: 6,
+ hasOraclePrice: true,
+ isEnabled: IS_TESTNET ? true : false,
+ isMarket: true,
+ },
+ {
+ symbol: 'CRO',
+ name: 'Cronos',
+ denom: 'ibc/E6931F78057F7CC5DA0FD6CEF82FF39373A6E0452BF1FD76910B93292CF356C1',
+ color: '#002D74',
+ logo: '/tokens/cro.svg',
+ decimals: 8,
+ hasOraclePrice: true,
+ isEnabled: false,
+ isMarket: true,
+ },
+ {
+ symbol: 'MARS',
+ name: 'Mars',
+ denom: IS_TESTNET
+ ? 'ibc/ACA4C8A815A053CC027DB90D15915ADA31939FA331CE745862CDD00A2904FA17'
+ : 'ibc/573FCD90FACEE750F55A8864EF7D38265F07E5A9273FA0E8DAFD39951332B580',
+ color: '#dd5b65',
+ logo: '/tokens/mars.svg',
+ decimals: 6,
+ poolId: IS_TESTNET ? 768 : 907,
+ hasOraclePrice: true,
+ isMarket: false,
+ isEnabled: true,
+ },
+ {
+ symbol: 'JUNO',
+ name: 'Juno',
+ denom: 'ibc/46B44899322F3CD854D2D46DEEF881958467CDD4B3B10086DA49296BBED94BED',
+ color: 'black',
+ logo: '/tokens/juno.svg',
+ decimals: 6,
+ hasOraclePrice: true,
+ isMarket: IS_TESTNET,
+ isEnabled: false,
+ },
+]
diff --git a/src/constants/env.ts b/src/constants/env.ts
new file mode 100644
index 00000000..00d52699
--- /dev/null
+++ b/src/constants/env.ts
@@ -0,0 +1,18 @@
+export const ADDRESS_ACCOUNT_NFT = process.env.NEXT_PUBLIC_ACCOUNT_NFT
+export const ADDRESS_CREDIT_MANAGER = process.env.NEXT_PUBLIC_CREDIT_MANAGER
+export const ADDRESS_INCENTIVES = process.env.NEXT_PUBLIC_INCENTIVES
+export const ADDRESS_ORACLE = process.env.NEXT_PUBLIC_ORACLE
+export const ADDRESS_RED_BANK = process.env.NEXT_PUBLIC_RED_BANK
+export const ADDRESS_SWAPPER = process.env.NEXT_PUBLIC_SWAPPER
+export const ADDRESS_ZAPPER = process.env.NEXT_PUBLIC_ZAPPER
+
+export const CHAIN_ID = process.env.NEXT_PUBLIC_CHAIN_ID
+export const NETWORK = process.env.NEXT_PUBLIC_NETWORK
+export const IS_TESTNET = NETWORK !== 'mainnet'
+export const URL_GQL = process.env.NEXT_PUBLIC_GQL
+export const URL_REST = process.env.NEXT_PUBLIC_REST
+export const URL_RPC = process.env.NEXT_PUBLIC_RPC
+export const URL_API = process.env.NEXT_PUBLIC_API
+export const WALLETS = process.env.NEXT_PUBLIC_WALLETS?.split(',') ?? []
+
+export const ENV_MISSING_MESSAGE = 'Environment variable missing'
diff --git a/src/constants/gas.ts b/src/constants/gas.ts
new file mode 100644
index 00000000..61d01e01
--- /dev/null
+++ b/src/constants/gas.ts
@@ -0,0 +1,2 @@
+export const GAS_ADJUSTMENT = 1.3
+export const GAS_PRICE = '0.025uosmo'
diff --git a/src/hooks/data/index.ts b/src/hooks/data/index.ts
deleted file mode 100644
index b46daceb..00000000
--- a/src/hooks/data/index.ts
+++ /dev/null
@@ -1,8 +0,0 @@
-// @index(['./*.tsx'], f => `export { ${f.name} } from '${f.path}'`)
-export { useAccountStats } from './useAccountStats'
-export { useAnimations } from './useAnimations'
-export { useBalances } from './useBalances'
-export { useCalculateMaxBorrowAmount } from './useCalculateMaxBorrowAmount'
-export { useCalculateMaxTradeAmount } from './useCalculateMaxTradeAmount'
-export { useCalculateMaxWithdrawAmount } from './useCalculateMaxWithdrawAmount'
-// @endindex
diff --git a/src/hooks/data/useAccountStats.tsx b/src/hooks/data/useAccountStats.tsx
index 712a8b23..5a4b763f 100644
--- a/src/hooks/data/useAccountStats.tsx
+++ b/src/hooks/data/useAccountStats.tsx
@@ -1,8 +1,10 @@
import BigNumber from 'bignumber.js'
import { useMemo } from 'react'
-import { useCreditAccountPositions, useMarkets, useTokenPrices } from 'hooks/queries'
-import { useAccountDetailsStore } from 'stores'
+import { useCreditAccountPositions } from 'hooks/queries/useCreditAccountPositions'
+import { useMarkets } from 'hooks/queries/useMarkets'
+import { useTokenPrices } from 'hooks/queries/useTokenPrices'
+import useStore from 'store'
// displaying 3 levels of risk based on the weighted average of liquidation LTVs
// 0.85 -> 25% risk
@@ -80,7 +82,7 @@ const calculateStatsFromAccountPositions = (assets: Asset[], debts: Debt[]) => {
}
export const useAccountStats = (actions?: AccountStatsAction[]) => {
- const selectedAccount = useAccountDetailsStore((s) => s.selectedAccount)
+ const selectedAccount = useStore((s) => s.selectedAccount)
const { data: positionsData } = useCreditAccountPositions(selectedAccount ?? '')
const { data: marketsData } = useMarkets()
diff --git a/src/hooks/data/useAnimations.tsx b/src/hooks/data/useAnimations.tsx
index 613f8cb2..a5afd9ff 100644
--- a/src/hooks/data/useAnimations.tsx
+++ b/src/hooks/data/useAnimations.tsx
@@ -1,19 +1,19 @@
import { useEffect } from 'react'
-import { useSettingsStore } from 'stores'
+import useStore from 'store'
export const useAnimations = () => {
- const enableAnimations = useSettingsStore((s) => s.enableAnimations)
+ const enableAnimations = useStore((s) => s.enableAnimations)
const queryChangeHandler = (event: MediaQueryListEvent) => {
- useSettingsStore.setState({ enableAnimations: !event?.matches ?? true })
+ useStore.setState({ enableAnimations: !event?.matches ?? true })
}
useEffect(() => {
const mediaQuery: MediaQueryList = window.matchMedia('(prefers-reduced-motion: reduce)')
if (mediaQuery) {
- useSettingsStore.setState({ enableAnimations: !mediaQuery.matches })
+ useStore.setState({ enableAnimations: !mediaQuery.matches })
mediaQuery.addEventListener('change', queryChangeHandler)
return () => mediaQuery.removeEventListener('change', queryChangeHandler)
}
diff --git a/src/hooks/data/useBalances.tsx b/src/hooks/data/useBalances.tsx
index d6d616f4..23eb2791 100644
--- a/src/hooks/data/useBalances.tsx
+++ b/src/hooks/data/useBalances.tsx
@@ -1,16 +1,19 @@
import { useEffect, useState } from 'react'
-import { useCreditAccountPositions, useMarkets, useTokenPrices } from 'hooks/queries'
-import { useAccountDetailsStore, useNetworkConfigStore } from 'stores'
+import { useCreditAccountPositions } from 'hooks/queries/useCreditAccountPositions'
+import { useMarkets } from 'hooks/queries/useMarkets'
+import { useTokenPrices } from 'hooks/queries/useTokenPrices'
import { formatBalances } from 'utils/balances'
+import useStore from 'store'
+import { getMarketAssets } from 'utils/assets'
export const useBalances = () => {
const [balanceData, setBalanceData] = useState()
const { data: marketsData } = useMarkets()
const { data: tokenPrices } = useTokenPrices()
- const selectedAccount = useAccountDetailsStore((s) => s.selectedAccount)
- const whitelistedAssets = useNetworkConfigStore((s) => s.assets.whitelist)
+ const selectedAccount = useStore((s) => s.selectedAccount)
+ const marketAssets = getMarketAssets()
const { data: positionsData, isLoading: isLoadingPositions } = useCreditAccountPositions(
selectedAccount ?? '',
@@ -19,15 +22,15 @@ export const useBalances = () => {
useEffect(() => {
const balances =
positionsData?.coins && tokenPrices
- ? formatBalances(positionsData.coins, tokenPrices, false, whitelistedAssets)
+ ? formatBalances(positionsData.coins, tokenPrices, false, marketAssets)
: []
const debtBalances =
positionsData?.debts && tokenPrices
- ? formatBalances(positionsData.debts, tokenPrices, true, whitelistedAssets, marketsData)
+ ? formatBalances(positionsData.debts, tokenPrices, true, marketAssets, marketsData)
: []
setBalanceData([...balances, ...debtBalances])
- }, [positionsData, marketsData, tokenPrices, whitelistedAssets])
+ }, [positionsData, marketsData, tokenPrices, marketAssets])
return balanceData
}
diff --git a/src/hooks/data/useCalculateMaxBorrowAmount.tsx b/src/hooks/data/useCalculateMaxBorrowAmount.tsx
index 8f1bfbad..2086d054 100644
--- a/src/hooks/data/useCalculateMaxBorrowAmount.tsx
+++ b/src/hooks/data/useCalculateMaxBorrowAmount.tsx
@@ -1,14 +1,13 @@
import BigNumber from 'bignumber.js'
import { useCallback, useMemo } from 'react'
-import {
- useCreditAccountPositions,
- useMarkets,
- useRedbankBalances,
- useTokenPrices,
-} from 'hooks/queries'
-import { useAccountDetailsStore, useNetworkConfigStore } from 'stores'
+import { useCreditAccountPositions } from 'hooks/queries/useCreditAccountPositions'
+import { useMarkets } from 'hooks/queries/useMarkets'
+import { useRedbankBalances } from 'hooks/queries/useRedbankBalances'
+import { useTokenPrices } from 'hooks/queries/useTokenPrices'
import { getTokenDecimals } from 'utils/tokens'
+import useStore from 'store'
+import { getMarketAssets } from 'utils/assets'
const getApproximateHourlyInterest = (amount: string, borrowAPY: string) => {
const hourlyAPY = BigNumber(borrowAPY).div(24 * 365)
@@ -17,8 +16,8 @@ const getApproximateHourlyInterest = (amount: string, borrowAPY: string) => {
}
export const useCalculateMaxBorrowAmount = (denom: string, isUnderCollateralized: boolean) => {
- const selectedAccount = useAccountDetailsStore((s) => s.selectedAccount)
- const whitelistedAssets = useNetworkConfigStore((s) => s.assets.whitelist)
+ const selectedAccount = useStore((s) => s.selectedAccount)
+ const marketAssets = getMarketAssets()
const { data: positionsData } = useCreditAccountPositions(selectedAccount ?? '')
const { data: marketsData } = useMarkets()
@@ -62,7 +61,7 @@ export const useCalculateMaxBorrowAmount = (denom: string, isUnderCollateralized
}, 0)
const borrowTokenPrice = tokenPrices[denom]
- const tokenDecimals = getTokenDecimals(denom, whitelistedAssets)
+ const tokenDecimals = getTokenDecimals(denom, marketAssets)
let maxAmountCapacity
if (isUnderCollateralized) {
@@ -100,6 +99,6 @@ export const useCalculateMaxBorrowAmount = (denom: string, isUnderCollateralized
positionsData,
redbankBalances,
tokenPrices,
- whitelistedAssets,
+ marketAssets,
])
}
diff --git a/src/hooks/data/useCalculateMaxTradeAmount.tsx b/src/hooks/data/useCalculateMaxTradeAmount.tsx
index 79954042..caf8fce3 100644
--- a/src/hooks/data/useCalculateMaxTradeAmount.tsx
+++ b/src/hooks/data/useCalculateMaxTradeAmount.tsx
@@ -1,13 +1,11 @@
import BigNumber from 'bignumber.js'
import { useCallback, useMemo } from 'react'
-import {
- useCreditAccountPositions,
- useMarkets,
- useRedbankBalances,
- useTokenPrices,
-} from 'hooks/queries'
-import { useAccountDetailsStore } from 'stores'
+import { useCreditAccountPositions } from 'hooks/queries/useCreditAccountPositions'
+import { useMarkets } from 'hooks/queries/useMarkets'
+import { useRedbankBalances } from 'hooks/queries/useRedbankBalances'
+import { useTokenPrices } from 'hooks/queries/useTokenPrices'
+import useStore from 'store'
const getApproximateHourlyInterest = (amount: string, borrowAPY: string) => {
const hourlyAPY = BigNumber(borrowAPY).div(24 * 365)
@@ -22,7 +20,7 @@ export const useCalculateMaxTradeAmount = (
tokenOut: string,
isMargin: boolean,
) => {
- const selectedAccount = useAccountDetailsStore((s) => s.selectedAccount)
+ const selectedAccount = useStore((s) => s.selectedAccount)
const { data: positionsData } = useCreditAccountPositions(selectedAccount ?? '')
const { data: marketsData } = useMarkets()
diff --git a/src/hooks/data/useCalculateMaxWithdrawAmount.tsx b/src/hooks/data/useCalculateMaxWithdrawAmount.tsx
index 7a8000e5..bb9d05dd 100644
--- a/src/hooks/data/useCalculateMaxWithdrawAmount.tsx
+++ b/src/hooks/data/useCalculateMaxWithdrawAmount.tsx
@@ -1,14 +1,13 @@
import BigNumber from 'bignumber.js'
import { useCallback, useMemo } from 'react'
-import {
- useCreditAccountPositions,
- useMarkets,
- useRedbankBalances,
- useTokenPrices,
-} from 'hooks/queries'
-import { useAccountDetailsStore, useNetworkConfigStore } from 'stores'
+import { useCreditAccountPositions } from 'hooks/queries/useCreditAccountPositions'
+import { useMarkets } from 'hooks/queries/useMarkets'
+import { useRedbankBalances } from 'hooks/queries/useRedbankBalances'
+import { useTokenPrices } from 'hooks/queries/useTokenPrices'
import { getTokenDecimals } from 'utils/tokens'
+import useStore from 'store'
+import { getMarketAssets } from 'utils/assets'
const getApproximateHourlyInterest = (amount: string, borrowAPY: string) => {
const hourlyAPY = BigNumber(borrowAPY).div(24 * 365)
@@ -17,15 +16,15 @@ const getApproximateHourlyInterest = (amount: string, borrowAPY: string) => {
}
export const useCalculateMaxWithdrawAmount = (denom: string, borrow: boolean) => {
- const selectedAccount = useAccountDetailsStore((s) => s.selectedAccount)
- const whitelistedAssets = useNetworkConfigStore((s) => s.assets.whitelist)
+ const selectedAccount = useStore((s) => s.selectedAccount)
+ const marketAssets = getMarketAssets()
const { data: positionsData } = useCreditAccountPositions(selectedAccount ?? '')
const { data: marketsData } = useMarkets()
const { data: tokenPrices } = useTokenPrices()
const { data: redbankBalances } = useRedbankBalances()
- const tokenDecimals = getTokenDecimals(denom, whitelistedAssets)
+ const tokenDecimals = getTokenDecimals(denom, marketAssets)
const getTokenValue = useCallback(
(amount: string, denom: string) => {
diff --git a/src/hooks/mutations/index.ts b/src/hooks/mutations/index.ts
deleted file mode 100644
index 6efd700e..00000000
--- a/src/hooks/mutations/index.ts
+++ /dev/null
@@ -1,9 +0,0 @@
-// @index(['./*.tsx'], f => `export { ${f.name} } from '${f.path}'`)
-export { useBorrowFunds } from './useBorrowFunds'
-export { useCreateCreditAccount } from './useCreateCreditAccount'
-export { useDeleteCreditAccount } from './useDeleteCreditAccount'
-export { useDepositCreditAccount } from './useDepositCreditAccount'
-export { useRepayFunds } from './useRepayFunds'
-export { useTradeAsset } from './useTradeAsset'
-export { useWithdrawFunds } from './useWithdrawFunds'
-// @endindex
diff --git a/src/hooks/mutations/useBorrowFunds.tsx b/src/hooks/mutations/useBorrowFunds.tsx
index ebfec481..66f20f4f 100644
--- a/src/hooks/mutations/useBorrowFunds.tsx
+++ b/src/hooks/mutations/useBorrowFunds.tsx
@@ -2,7 +2,7 @@ import { useMutation, UseMutationOptions, useQueryClient } from '@tanstack/react
import { useMemo } from 'react'
import { toast } from 'react-toastify'
-import { useAccountDetailsStore, useWalletStore } from 'stores'
+import useStore from 'store'
import { queryKeys } from 'types/query-keys-factory'
import { hardcodedFee } from 'utils/contants'
@@ -12,12 +12,10 @@ export const useBorrowFunds = (
withdraw = false,
options: Omit,
) => {
- const creditManagerClient = useWalletStore((s) => s.clients.creditManager)
- const selectedAccount = useAccountDetailsStore((s) => s.selectedAccount ?? '')
- const address = useWalletStore((s) => s.address)
-
+ const creditManagerClient = useStore((s) => s.clients.creditManager)
+ const selectedAccount = useStore((s) => s.selectedAccount ?? '')
+ const address = useStore((s) => s.address)
const queryClient = useQueryClient()
-
const actions = useMemo(() => {
if (!withdraw) {
return [
@@ -29,7 +27,6 @@ export const useBorrowFunds = (
},
]
}
-
return [
{
borrow: {
@@ -45,7 +42,6 @@ export const useBorrowFunds = (
},
]
}, [withdraw, denom, amount])
-
return useMutation(
async () =>
await creditManagerClient?.updateCreditAccount(
@@ -56,7 +52,6 @@ export const useBorrowFunds = (
onSettled: () => {
queryClient.invalidateQueries(queryKeys.creditAccountsPositions(selectedAccount))
queryClient.invalidateQueries(queryKeys.redbankBalances())
-
// if withdrawing to wallet, need to explicility invalidate balances queries
if (withdraw) {
queryClient.invalidateQueries(queryKeys.tokenBalance(address ?? '', denom))
diff --git a/src/hooks/mutations/useCreateCreditAccount.tsx b/src/hooks/mutations/useCreateCreditAccount.tsx
deleted file mode 100644
index 342c6e94..00000000
--- a/src/hooks/mutations/useCreateCreditAccount.tsx
+++ /dev/null
@@ -1,45 +0,0 @@
-import { useMutation, useQueryClient } from '@tanstack/react-query'
-import { toast } from 'react-toastify'
-
-import {
- useAccountDetailsStore,
- useModalStore,
- useNetworkConfigStore,
- useWalletStore,
-} from 'stores'
-import { queryKeys } from 'types/query-keys-factory'
-import { hardcodedFee } from 'utils/contants'
-
-// 200000 gas used
-const executeMsg = {
- create_credit_account: {},
-}
-
-export const useCreateCreditAccount = () => {
- const signingClient = useWalletStore((s) => s.signingClient)
- const address = useWalletStore((s) => s.address)
- const creditManagerAddress = useNetworkConfigStore((s) => s.contracts.creditManager)
-
- const queryClient = useQueryClient()
-
- return useMutation(
- async () =>
- await signingClient?.execute(address ?? '', creditManagerAddress, executeMsg, hardcodedFee),
- {
- onSettled: () => {
- queryClient.invalidateQueries(queryKeys.creditAccounts(address ?? ''))
- },
- onError: (err: Error) => {
- toast.error(err.message)
- },
- onSuccess: (data) => {
- if (!data) return
-
- // TODO: is there some better way to parse response to extract token id???
- const createdID = data.logs[0].events[2].attributes[6].value
- useAccountDetailsStore.setState({ selectedAccount: createdID })
- useModalStore.setState({ fundAccountModal: true })
- },
- },
- )
-}
diff --git a/src/hooks/mutations/useDeleteCreditAccount.tsx b/src/hooks/mutations/useDeleteCreditAccount.tsx
deleted file mode 100644
index 92248a27..00000000
--- a/src/hooks/mutations/useDeleteCreditAccount.tsx
+++ /dev/null
@@ -1,39 +0,0 @@
-import { useMutation, useQueryClient } from '@tanstack/react-query'
-import { toast } from 'react-toastify'
-
-import { useNetworkConfigStore, useWalletStore } from 'stores'
-import { queryKeys } from 'types/query-keys-factory'
-import { hardcodedFee } from 'utils/contants'
-
-export const useDeleteCreditAccount = (accountId: string) => {
- const signingClient = useWalletStore((s) => s.signingClient)
- const address = useWalletStore((s) => s.address)
- const accountNftAddress = useNetworkConfigStore((s) => s.contracts.accountNft)
-
- const queryClient = useQueryClient()
-
- return useMutation(
- async () =>
- await signingClient?.execute(
- address ?? '',
- accountNftAddress,
- {
- burn: {
- token_id: accountId,
- },
- },
- hardcodedFee,
- ),
- {
- onSettled: () => {
- queryClient.invalidateQueries(queryKeys.creditAccounts(address ?? ''))
- },
- onError: (err: Error) => {
- toast.error(err.message)
- },
- onSuccess: () => {
- toast.success('Credit Account Deleted')
- },
- },
- )
-}
diff --git a/src/hooks/mutations/useDepositCreditAccount.tsx b/src/hooks/mutations/useDepositCreditAccount.tsx
deleted file mode 100644
index 7fca6bcc..00000000
--- a/src/hooks/mutations/useDepositCreditAccount.tsx
+++ /dev/null
@@ -1,62 +0,0 @@
-import { useMutation, useQueryClient } from '@tanstack/react-query'
-import { toast } from 'react-toastify'
-
-import { useNetworkConfigStore, useWalletStore } from 'stores'
-import { queryKeys } from 'types/query-keys-factory'
-import { hardcodedFee } from 'utils/contants'
-
-export const useDepositCreditAccount = (
- accountId: string,
- denom: string,
- amount: number,
- options?: {
- onSuccess?: () => void
- },
-) => {
- const signingClient = useWalletStore((s) => s.signingClient)
- const address = useWalletStore((s) => s.address)
- const creditManagerAddress = useNetworkConfigStore((s) => s.contracts.creditManager)
-
- const queryClient = useQueryClient()
-
- return useMutation(
- async () =>
- await signingClient?.execute(
- address ?? '',
- creditManagerAddress,
- {
- update_credit_account: {
- account_id: accountId,
- actions: [
- {
- deposit: {
- denom,
- amount: String(amount),
- },
- },
- ],
- },
- },
- hardcodedFee,
- undefined,
- [
- {
- denom,
- amount: String(amount),
- },
- ],
- ),
- {
- onError: (err: Error) => {
- toast.error(err.message)
- },
- onSuccess: () => {
- queryClient.invalidateQueries(queryKeys.allBalances(address ?? ''))
- queryClient.invalidateQueries(queryKeys.tokenBalance(address ?? '', denom))
- queryClient.invalidateQueries(queryKeys.creditAccountsPositions(accountId))
-
- options?.onSuccess && options.onSuccess()
- },
- },
- )
-}
diff --git a/src/hooks/mutations/useRepayFunds.tsx b/src/hooks/mutations/useRepayFunds.tsx
index f181c9da..7d375444 100644
--- a/src/hooks/mutations/useRepayFunds.tsx
+++ b/src/hooks/mutations/useRepayFunds.tsx
@@ -2,7 +2,7 @@ import { useMutation, UseMutationOptions, useQueryClient } from '@tanstack/react
import { useMemo } from 'react'
import { toast } from 'react-toastify'
-import { useAccountDetailsStore, useWalletStore } from 'stores'
+import useStore from 'store'
import { queryKeys } from 'types/query-keys-factory'
import { hardcodedFee } from 'utils/contants'
@@ -11,12 +11,10 @@ export const useRepayFunds = (
denom: string,
options: Omit,
) => {
- const creditManagerClient = useWalletStore((s) => s.clients.creditManager)
- const selectedAccount = useAccountDetailsStore((s) => s.selectedAccount ?? '')
- const address = useWalletStore((s) => s.address)
-
+ const creditManagerClient = useStore((s) => s.clients.creditManager)
+ const selectedAccount = useStore((s) => s.selectedAccount ?? '')
+ const address = useStore((s) => s.address)
const queryClient = useQueryClient()
-
const actions = useMemo(() => {
return [
{
@@ -28,12 +26,13 @@ export const useRepayFunds = (
{
repay: {
denom: denom,
- amount: String(amount),
+ amount: {
+ exact: String(amount),
+ },
},
},
]
}, [amount, denom])
-
return useMutation(
async () =>
await creditManagerClient?.updateCreditAccount(
diff --git a/src/hooks/mutations/useTradeAsset.tsx b/src/hooks/mutations/useTradeAsset.tsx
index e8bd13a1..f167b531 100644
--- a/src/hooks/mutations/useTradeAsset.tsx
+++ b/src/hooks/mutations/useTradeAsset.tsx
@@ -2,7 +2,7 @@ import { useMutation, UseMutationOptions, useQueryClient } from '@tanstack/react
import { useMemo } from 'react'
import { toast } from 'react-toastify'
-import { useAccountDetailsStore, useWalletStore } from 'stores'
+import useStore from 'store'
import { Action } from 'types/generated/mars-credit-manager/MarsCreditManager.types'
import { queryKeys } from 'types/query-keys-factory'
import { hardcodedFee } from 'utils/contants'
@@ -16,11 +16,9 @@ export const useTradeAsset = (
slippage: number,
options?: Omit,
) => {
- const creditManagerClient = useWalletStore((s) => s.clients.creditManager)
- const selectedAccount = useAccountDetailsStore((s) => s.selectedAccount ?? '')
-
+ const creditManagerClient = useStore((s) => s.clients.creditManager)
+ const selectedAccount = useStore((s) => s.selectedAccount ?? '')
const queryClient = useQueryClient()
-
// actions need to be executed in order deposit -> borrow -> swap
// first two are optional
const actions = useMemo(() => {
@@ -33,7 +31,6 @@ export const useTradeAsset = (
},
},
] as Action[]
-
if (borrowAmount > 0) {
actionsBase.unshift({
borrow: {
@@ -42,7 +39,6 @@ export const useTradeAsset = (
},
})
}
-
if (depositAmount > 0) {
actionsBase.unshift({
deposit: {
@@ -51,10 +47,8 @@ export const useTradeAsset = (
},
})
}
-
return actionsBase
}, [amount, tokenIn, tokenOut, slippage, borrowAmount, depositAmount])
-
return useMutation(
async () =>
await creditManagerClient?.updateCreditAccount(
diff --git a/src/hooks/mutations/useWithdrawFunds.tsx b/src/hooks/mutations/useWithdrawFunds.tsx
index 63170021..b9592a72 100644
--- a/src/hooks/mutations/useWithdrawFunds.tsx
+++ b/src/hooks/mutations/useWithdrawFunds.tsx
@@ -2,7 +2,7 @@ import { useMutation, useQueryClient } from '@tanstack/react-query'
import { useMemo } from 'react'
import { toast } from 'react-toastify'
-import { useAccountDetailsStore, useWalletStore } from 'stores'
+import useStore from 'store'
import { queryKeys } from 'types/query-keys-factory'
import { hardcodedFee } from 'utils/contants'
@@ -14,12 +14,10 @@ export const useWithdrawFunds = (
onSuccess?: () => void
},
) => {
- const selectedAccount = useAccountDetailsStore((s) => s.selectedAccount ?? '')
- const address = useWalletStore((s) => s.address)
- const creditManagerClient = useWalletStore((s) => s.clients.creditManager)
-
+ const selectedAccount = useStore((s) => s.selectedAccount ?? '')
+ const address = useStore((s) => s.address)
+ const creditManagerClient = useStore((s) => s.clients.creditManager)
const queryClient = useQueryClient()
-
const actions = useMemo(() => {
if (borrowAmount > 0) {
return [
@@ -37,7 +35,6 @@ export const useWithdrawFunds = (
},
]
}
-
return [
{
withdraw: {
@@ -47,9 +44,7 @@ export const useWithdrawFunds = (
},
]
}, [amount, borrowAmount, denom])
-
const { onSuccess } = { ...options }
-
return useMutation(
async () =>
creditManagerClient?.updateCreditAccount(
@@ -62,7 +57,6 @@ export const useWithdrawFunds = (
queryClient.invalidateQueries(queryKeys.tokenBalance(address ?? '', denom))
queryClient.invalidateQueries(queryKeys.allBalances(address ?? ''))
queryClient.invalidateQueries(queryKeys.redbankBalances())
-
onSuccess && onSuccess()
},
onError: (err: Error) => {
diff --git a/src/hooks/queries/index.ts b/src/hooks/queries/index.ts
deleted file mode 100644
index 6a6ee8a6..00000000
--- a/src/hooks/queries/index.ts
+++ /dev/null
@@ -1,9 +0,0 @@
-// @index(['./*.tsx'], f => `export { ${f.name} } from '${f.path}'`)
-export { useAllBalances } from './useAllBalances'
-export { useAllowedCoins } from './useAllowedCoins'
-export { useCreditAccountPositions } from './useCreditAccountPositions'
-export { useCreditAccounts } from './useCreditAccounts'
-export { useMarkets } from './useMarkets'
-export { useRedbankBalances } from './useRedbankBalances'
-export { useTokenPrices } from './useTokenPrices'
-// @endindex
diff --git a/src/hooks/queries/useAllBalances.tsx b/src/hooks/queries/useAllBalances.tsx
index a4674e08..76efe365 100644
--- a/src/hooks/queries/useAllBalances.tsx
+++ b/src/hooks/queries/useAllBalances.tsx
@@ -3,7 +3,8 @@ import { useQuery } from '@tanstack/react-query'
import request, { gql } from 'graphql-request'
import { useMemo } from 'react'
-import { useNetworkConfigStore, useWalletStore } from 'stores'
+import { URL_GQL } from 'constants/env'
+import useStore from 'store'
import { queryKeys } from 'types/query-keys-factory'
interface UserBalanceData {
@@ -13,14 +14,13 @@ interface UserBalanceData {
}
export const useAllBalances = () => {
- const address = useWalletStore((s) => s.address)
- const hiveUrl = useNetworkConfigStore((s) => s.hiveUrl)
+ const address = useStore((s) => s.address)
const result = useQuery(
queryKeys.allBalances(address ?? ''),
async () => {
return await request(
- hiveUrl!,
+ URL_GQL!,
gql`
query UserBalanceQuery {
balance: bank {
@@ -36,7 +36,7 @@ export const useAllBalances = () => {
)
},
{
- enabled: !!hiveUrl && !!address,
+ enabled: !!address,
staleTime: 30000,
refetchInterval: 30000,
},
diff --git a/src/hooks/queries/useAllowedCoins.tsx b/src/hooks/queries/useAllowedCoins.tsx
index becfa8a7..525e86d5 100644
--- a/src/hooks/queries/useAllowedCoins.tsx
+++ b/src/hooks/queries/useAllowedCoins.tsx
@@ -1,6 +1,7 @@
import { useQuery } from '@tanstack/react-query'
-import { useNetworkConfigStore, useWalletStore } from 'stores'
+import { ADDRESS_CREDIT_MANAGER } from 'constants/env'
+import useStore from 'store'
import { queryKeys } from 'types/query-keys-factory'
type Result = string[]
@@ -10,12 +11,12 @@ const queryMsg = {
}
export const useAllowedCoins = () => {
- const client = useWalletStore((s) => s.signingClient)
- const creditManagerAddress = useNetworkConfigStore((s) => s.contracts.creditManager)
+ const client = useStore((s) => s.signingClient)
+ const creditManagerAddress = ADDRESS_CREDIT_MANAGER
const result = useQuery(
queryKeys.allowedCoins(),
- async () => client?.queryContractSmart(creditManagerAddress, queryMsg),
+ async () => client?.queryContractSmart(creditManagerAddress || '', queryMsg),
{
enabled: !!client,
staleTime: Infinity,
diff --git a/src/hooks/queries/useBroadcast.tsx b/src/hooks/queries/useBroadcast.tsx
new file mode 100644
index 00000000..4ae3603e
--- /dev/null
+++ b/src/hooks/queries/useBroadcast.tsx
@@ -0,0 +1,49 @@
+import { MsgExecuteContract } from '@marsprotocol/wallet-connector'
+import { useQuery } from '@tanstack/react-query'
+import { isMobile } from 'react-device-detect'
+
+import useStore from 'store'
+import { queryKeys } from 'types/query-keys-factory'
+
+export const useBroadcast = (props: UseBroadcast) => {
+ const client = useStore((s) => s.client)
+ const userWalletAddress = useStore((s) => s.client?.recentWallet.account?.address)
+ const sender = props.sender ?? userWalletAddress
+
+ return useQuery(
+ [queryKeys.broadcastMessages(), props.msg],
+ async () => {
+ if (!client || !props.contract || !props.msg || !props.fee || !sender) return
+
+ try {
+ const broadcastOptions = {
+ messages: [
+ new MsgExecuteContract({
+ sender: sender,
+ contract: props.contract,
+ msg: props.msg,
+ funds: props.funds,
+ }),
+ ],
+ feeAmount: props.fee.amount[0].amount,
+ gasLimit: props.fee.gas,
+ memo: undefined,
+ wallet: client.recentWallet,
+ mobile: isMobile,
+ }
+
+ const result = await client.broadcast(broadcastOptions)
+
+ if (result.hash) {
+ return result
+ }
+ throw result.rawLogs
+ } catch (e) {
+ throw e
+ }
+ },
+ {
+ enabled: !!sender && !!client && !!props.msg && !!props.contract && !!props.fee,
+ },
+ )
+}
diff --git a/src/hooks/queries/useCreditAccountPositions.tsx b/src/hooks/queries/useCreditAccountPositions.tsx
index 4b678eda..5b6c659b 100644
--- a/src/hooks/queries/useCreditAccountPositions.tsx
+++ b/src/hooks/queries/useCreditAccountPositions.tsx
@@ -2,7 +2,8 @@ import { Coin } from '@cosmjs/stargate'
import { useQuery } from '@tanstack/react-query'
import { useMemo } from 'react'
-import { useNetworkConfigStore, useWalletStore } from 'stores'
+import { ADDRESS_CREDIT_MANAGER } from 'constants/env'
+import useStore from 'store'
import { queryKeys } from 'types/query-keys-factory'
interface DebtAmount {
@@ -24,14 +25,14 @@ interface Result {
}
export const useCreditAccountPositions = (accountId: string) => {
- const address = useWalletStore((s) => s.address)
- const client = useWalletStore((s) => s.signingClient)
- const creditManagerAddress = useNetworkConfigStore((s) => s.contracts.creditManager)
+ const address = useStore((s) => s.address)
+ const client = useStore((s) => s.signingClient)
+ const creditManagerAddress = ADDRESS_CREDIT_MANAGER
const result = useQuery(
queryKeys.creditAccountsPositions(accountId),
async () =>
- client?.queryContractSmart(creditManagerAddress, {
+ client?.queryContractSmart(creditManagerAddress || '', {
positions: {
account_id: accountId,
},
diff --git a/src/hooks/queries/useCreditAccounts.tsx b/src/hooks/queries/useCreditAccounts.tsx
index 307c9c8d..2cbc856d 100644
--- a/src/hooks/queries/useCreditAccounts.tsx
+++ b/src/hooks/queries/useCreditAccounts.tsx
@@ -1,7 +1,10 @@
+'use client'
+
import { useQuery } from '@tanstack/react-query'
import { useMemo } from 'react'
-import { useAccountDetailsStore, useNetworkConfigStore, useWalletStore } from 'stores'
+import { ADDRESS_ACCOUNT_NFT } from 'constants/env'
+import useStore from 'store'
import { queryKeys } from 'types/query-keys-factory'
type Result = {
@@ -9,12 +12,12 @@ type Result = {
}
export const useCreditAccounts = () => {
- const address = useWalletStore((s) => s.address)
- const client = useWalletStore((s) => s.signingClient)
- const selectedAccount = useAccountDetailsStore((s) => s.selectedAccount)
- const accountNftAddress = useNetworkConfigStore((s) => s.contracts.accountNft)
+ const address = useStore((s) => s.address)
+ const client = useStore((s) => s.signingClient)
+ const selectedAccount = useStore((s) => s.selectedAccount)
+ const accountNftAddress = ADDRESS_ACCOUNT_NFT
const setSelectedAccount = (account: string) => {
- useAccountDetailsStore.setState({ selectedAccount: account })
+ useStore.setState({ selectedAccount: account })
}
const queryMsg = useMemo(() => {
@@ -27,7 +30,7 @@ export const useCreditAccounts = () => {
const result = useQuery(
queryKeys.creditAccounts(address ?? ''),
- async () => client?.queryContractSmart(accountNftAddress, queryMsg),
+ async () => client?.queryContractSmart(accountNftAddress || '', queryMsg),
{
staleTime: Infinity,
enabled: !!address && !!client,
diff --git a/src/hooks/queries/useEstimateFee.tsx b/src/hooks/queries/useEstimateFee.tsx
new file mode 100644
index 00000000..fb242a05
--- /dev/null
+++ b/src/hooks/queries/useEstimateFee.tsx
@@ -0,0 +1,53 @@
+import { MsgExecuteContract } from '@marsprotocol/wallet-connector'
+import { useQuery } from '@tanstack/react-query'
+import BigNumber from 'bignumber.js'
+
+import { GAS_ADJUSTMENT } from 'constants/gas'
+import useStore from 'store'
+import { queryKeys } from 'types/query-keys-factory'
+
+export const useEstimateFee = (props: UseEstimateFee) => {
+ const client = useStore((s) => s.client)
+ const userWalletAddress = useStore((s) => s.client?.recentWallet.account?.address)
+ const sender = props.sender ?? userWalletAddress
+
+ return useQuery(
+ [queryKeys.estimateFee(), props.msg],
+ async () => {
+ const gasAdjustment = GAS_ADJUSTMENT
+
+ if (!client || !props.contract || !props.msg || !sender) return
+
+ try {
+ const simulateOptions = {
+ messages: [
+ new MsgExecuteContract({
+ sender: sender,
+ contract: props.contract,
+ msg: props.msg,
+ funds: props.funds,
+ }),
+ ],
+ wallet: client.recentWallet,
+ }
+
+ const result = await client.simulate(simulateOptions)
+
+ if (result.success) {
+ return {
+ amount: result.fee ? result.fee.amount : [],
+ gas: new BigNumber(result.fee ? result.fee.gas : 0)
+ .multipliedBy(gasAdjustment)
+ .toFixed(0),
+ }
+ }
+ throw result.error
+ } catch (e) {
+ throw e
+ }
+ },
+ {
+ enabled: !!sender && !!client && !!props.msg && !!props.contract,
+ },
+ )
+}
diff --git a/src/hooks/queries/useRedbankBalances.tsx b/src/hooks/queries/useRedbankBalances.tsx
index 0b4fa38b..4ae5d3d2 100644
--- a/src/hooks/queries/useRedbankBalances.tsx
+++ b/src/hooks/queries/useRedbankBalances.tsx
@@ -3,7 +3,7 @@ import { useQuery } from '@tanstack/react-query'
import request, { gql } from 'graphql-request'
import { useMemo } from 'react'
-import { useNetworkConfigStore } from 'stores'
+import { ADDRESS_RED_BANK, URL_GQL } from 'constants/env'
import { queryKeys } from 'types/query-keys-factory'
interface Result {
@@ -13,13 +13,12 @@ interface Result {
}
export const useRedbankBalances = () => {
- const hiveUrl = useNetworkConfigStore((s) => s.hiveUrl)
- const redBankAddress = useNetworkConfigStore((s) => s.contracts.redBank)
+ const redBankAddress = ADDRESS_RED_BANK
const result = useQuery(
queryKeys.redbankBalances(),
async () => {
return await request(
- hiveUrl!,
+ URL_GQL!,
gql`
query RedbankBalances {
bank {
@@ -35,7 +34,7 @@ export const useRedbankBalances = () => {
)
},
{
- enabled: !!hiveUrl && !!redBankAddress,
+ enabled: !!redBankAddress,
staleTime: 30000,
refetchInterval: 30000,
},
diff --git a/src/hooks/queries/useTokenPrices.tsx b/src/hooks/queries/useTokenPrices.tsx
index 0720a389..d7d0cd92 100644
--- a/src/hooks/queries/useTokenPrices.tsx
+++ b/src/hooks/queries/useTokenPrices.tsx
@@ -2,20 +2,17 @@ import { useQuery } from '@tanstack/react-query'
import { gql, request } from 'graphql-request'
import { useMemo } from 'react'
-import { useNetworkConfigStore } from 'stores'
+import { ADDRESS_ORACLE, URL_GQL } from 'constants/env'
import { queryKeys } from 'types/query-keys-factory'
+import { getMarketAssets } from 'utils/assets'
-const fetchTokenPrices = async (
- hiveUrl: string,
- whitelistedTokens: Asset[],
- oracleAddress: string,
-) => {
+const fetchTokenPrices = async (hiveUrl: string, marketAssets: Asset[], oracleAddress: string) => {
return request(
hiveUrl,
gql`
query PriceOracle {
prices: wasm {
- ${whitelistedTokens.map((token) => {
+ ${marketAssets.map((token) => {
return `${token.symbol}: contractQuery(
contractAddress: "${oracleAddress}"
query: {
@@ -32,12 +29,10 @@ const fetchTokenPrices = async (
}
export const useTokenPrices = () => {
- const hiveUrl = useNetworkConfigStore((s) => s.hiveUrl)
- const whitelistedTokens = useNetworkConfigStore((s) => s.assets.whitelist)
- const oracleAddress = useNetworkConfigStore((s) => s.contracts.oracle)
+ const marketAssets = getMarketAssets()
const result = useQuery(
queryKeys.tokenPrices(),
- async () => await fetchTokenPrices(hiveUrl, whitelistedTokens, oracleAddress),
+ async () => await fetchTokenPrices(URL_GQL!, marketAssets, ADDRESS_ORACLE || ''),
{
refetchInterval: 30000,
staleTime: Infinity,
diff --git a/src/hooks/useParams.ts b/src/hooks/useParams.ts
new file mode 100644
index 00000000..01e07adc
--- /dev/null
+++ b/src/hooks/useParams.ts
@@ -0,0 +1,26 @@
+import { usePathname } from 'next/navigation'
+
+export default function useParams() {
+ const pathname = usePathname()
+ const params = {
+ wallet: '',
+ account: '',
+ page: '',
+ }
+
+ if (!pathname) return params
+
+ const segments = pathname.split('/')
+
+ segments.forEach((segment, index) => {
+ if (segment === 'wallets' && segments[index + 1]) {
+ params.wallet = segments[index + 1]
+ } else if (segment === 'accounts' && segments[index + 1]) {
+ params.account = segments[index + 1]
+ } else if (index === 5) {
+ params.page = segment
+ }
+ })
+
+ return params
+}
diff --git a/src/images/wallets/keplr-wallet-extension.png b/src/images/wallets/keplr-wallet-extension.png
deleted file mode 100644
index 44ccea79..00000000
Binary files a/src/images/wallets/keplr-wallet-extension.png and /dev/null differ
diff --git a/src/images/wallets/walletconnect-keplr.png b/src/images/wallets/walletconnect-keplr.png
deleted file mode 100644
index d3810d22..00000000
Binary files a/src/images/wallets/walletconnect-keplr.png and /dev/null differ
diff --git a/src/pages/404.tsx b/src/pages/404.tsx
deleted file mode 100644
index 02ba2d75..00000000
--- a/src/pages/404.tsx
+++ /dev/null
@@ -1,19 +0,0 @@
-import { Button, Card, Text } from 'components'
-
-const Error404 = () => {
- return (
-
-
-
- Oooops...
-
- Looks like this page doesn't exist!
-
- (location.href = '/trade')} text='Home'>
-
-
-
- )
-}
-
-export default Error404
diff --git a/src/pages/_app.tsx b/src/pages/_app.tsx
deleted file mode 100644
index 371c9c63..00000000
--- a/src/pages/_app.tsx
+++ /dev/null
@@ -1,68 +0,0 @@
-import 'react-toastify/dist/ReactToastify.min.css'
-import '../styles/globals.css'
-
-import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
-import { ReactQueryDevtools } from '@tanstack/react-query-devtools'
-import type { AppProps } from 'next/app'
-import Head from 'next/head'
-import { ToastContainer, Zoom } from 'react-toastify'
-
-import { Layout, Modals } from 'components'
-import { WalletConnectProvider } from 'components/Wallet'
-import { useAnimations } from 'hooks/data'
-
-const queryClient = new QueryClient()
-
-const App = ({ Component, pageProps }: AppProps) => {
- const animations = useAnimations()
-
- return (
- <>
-
- Mars Protocol V2
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- >
- )
-}
-
-export default App
diff --git a/src/pages/_error.js b/src/pages/_error.js
deleted file mode 100644
index 66488b60..00000000
--- a/src/pages/_error.js
+++ /dev/null
@@ -1,39 +0,0 @@
-/**
- * NOTE: This requires `@sentry/nextjs` version 7.3.0 or higher.
- *
- * NOTE: If using this with `next` version 12.2.0 or lower, uncomment the
- * penultimate line in `CustomErrorComponent`.
- *
- * This page is loaded by Nextjs:
- * - on the server, when data-fetching methods throw or reject
- * - on the client, when `getInitialProps` throws or rejects
- * - on the client, when a React lifecycle method throws or rejects, and it's
- * caught by the built-in Nextjs error boundary
- *
- * See:
- * - https://nextjs.org/docs/basic-features/data-fetching/overview
- * - https://nextjs.org/docs/api-reference/data-fetching/get-initial-props
- * - https://reactjs.org/docs/error-boundaries.html
- */
-
-import * as Sentry from '@sentry/nextjs'
-import NextErrorComponent from 'next/error'
-
-const CustomErrorComponent = (props) => {
- // If you're using a Nextjs version prior to 12.2.1, uncomment this to
- // compensate for https://github.com/vercel/next.js/issues/8592
- // Sentry.captureUnderscoreErrorException(props);
-
- return
-}
-
-CustomErrorComponent.getInitialProps = async (contextData) => {
- // In case this is running in a serverless function, await this in order to give Sentry
- // time to send the error before the lambda exits
- await Sentry.captureUnderscoreErrorException(contextData)
-
- // This will contain the status code of the response
- return NextErrorComponent.getInitialProps(contextData)
-}
-
-export default CustomErrorComponent
diff --git a/src/pages/api/accounts/[id]/debts.ts b/src/pages/api/accounts/[id]/debts.ts
new file mode 100644
index 00000000..598dec1c
--- /dev/null
+++ b/src/pages/api/accounts/[id]/debts.ts
@@ -0,0 +1,19 @@
+import { NextApiRequest, NextApiResponse } from 'next'
+
+import { ADDRESS_CREDIT_MANAGER, ENV_MISSING_MESSAGE, URL_API, URL_RPC } from 'constants/env'
+
+export default async function handler(req: NextApiRequest, res: NextApiResponse) {
+ if (!URL_RPC || !ADDRESS_CREDIT_MANAGER || !URL_API) {
+ return res.status(404).json(ENV_MISSING_MESSAGE)
+ }
+
+ const accountId = req.query.id
+
+ const account = await (await fetch(`${URL_API}/accounts/${accountId}`)).json()
+
+ if (account) {
+ return res.status(200).json(account.debts)
+ }
+
+ return res.status(404)
+}
diff --git a/src/pages/api/accounts/[id]/deposits.ts b/src/pages/api/accounts/[id]/deposits.ts
new file mode 100644
index 00000000..c057bfe7
--- /dev/null
+++ b/src/pages/api/accounts/[id]/deposits.ts
@@ -0,0 +1,19 @@
+import { NextApiRequest, NextApiResponse } from 'next'
+
+import { ADDRESS_CREDIT_MANAGER, ENV_MISSING_MESSAGE, URL_API, URL_RPC } from 'constants/env'
+
+export default async function handler(req: NextApiRequest, res: NextApiResponse) {
+ if (!URL_RPC || !ADDRESS_CREDIT_MANAGER || !URL_API) {
+ return res.status(404).json(ENV_MISSING_MESSAGE)
+ }
+
+ const accountId = req.query.id
+
+ const account = await (await fetch(`${URL_API}/accounts/${accountId}`)).json()
+
+ if (account) {
+ return res.status(200).json(account.deposits)
+ }
+
+ return res.status(404)
+}
diff --git a/src/pages/api/accounts/[id]/index.ts b/src/pages/api/accounts/[id]/index.ts
new file mode 100644
index 00000000..187bef1f
--- /dev/null
+++ b/src/pages/api/accounts/[id]/index.ts
@@ -0,0 +1,26 @@
+import { CosmWasmClient } from '@cosmjs/cosmwasm-stargate'
+import { NextApiRequest, NextApiResponse } from 'next'
+
+import { ADDRESS_CREDIT_MANAGER, ENV_MISSING_MESSAGE, URL_RPC } from 'constants/env'
+
+export default async function handler(req: NextApiRequest, res: NextApiResponse) {
+ if (!URL_RPC || !ADDRESS_CREDIT_MANAGER) {
+ return res.status(404).json(ENV_MISSING_MESSAGE)
+ }
+
+ const accountId = req.query.id
+
+ const client = await CosmWasmClient.connect(URL_RPC)
+
+ const data = await client.queryContractSmart(ADDRESS_CREDIT_MANAGER, {
+ positions: {
+ account_id: accountId,
+ },
+ })
+
+ if (data) {
+ return res.status(200).json(data)
+ }
+
+ return res.status(404)
+}
diff --git a/src/pages/api/markets/balances.ts b/src/pages/api/markets/balances.ts
new file mode 100644
index 00000000..0f71affd
--- /dev/null
+++ b/src/pages/api/markets/balances.ts
@@ -0,0 +1,35 @@
+import { Coin } from '@cosmjs/stargate'
+import { gql, request as gqlRequest } from 'graphql-request'
+import { NextApiRequest, NextApiResponse } from 'next'
+
+import { ADDRESS_RED_BANK, ENV_MISSING_MESSAGE, URL_GQL } from 'constants/env'
+
+export default async function handler(req: NextApiRequest, res: NextApiResponse) {
+ if (!URL_GQL || !ADDRESS_RED_BANK) {
+ return res.status(404).json(ENV_MISSING_MESSAGE)
+ }
+
+ const result = await gqlRequest(
+ URL_GQL,
+ gql`
+ query RedbankBalances {
+ bank {
+ balance(
+ address: "${ADDRESS_RED_BANK}"
+ ) {
+ amount
+ denom
+ }
+ }
+ }
+ `,
+ )
+
+ return res.status(200).json(result.bank.balance)
+}
+
+interface Result {
+ bank: {
+ balance: Coin[]
+ }
+}
diff --git a/src/pages/api/markets/borrow.ts b/src/pages/api/markets/borrow.ts
new file mode 100644
index 00000000..1b358828
--- /dev/null
+++ b/src/pages/api/markets/borrow.ts
@@ -0,0 +1,43 @@
+import { NextApiRequest, NextApiResponse } from 'next'
+
+import { ENV_MISSING_MESSAGE, URL_API } from 'constants/env'
+import { getMarketAssets } from 'utils/assets'
+import { Coin } from '@cosmjs/stargate'
+
+export default async function handler(req: NextApiRequest, res: NextApiResponse) {
+ if (!URL_API) {
+ return res.status(404).json(ENV_MISSING_MESSAGE)
+ }
+
+ const marketAssets = getMarketAssets()
+ const $liquidity = fetch(`${URL_API}/markets/liquidity`)
+ const $markets = fetch(`${URL_API}/markets`)
+
+ const borrow: BorrowData[] = await Promise.all([$liquidity, $markets]).then(
+ async ([$liquidity, $markets]) => {
+ const liquidity: Coin[] = await $liquidity.json()
+ const markets: Market[] = await $markets.json()
+
+ return marketAssets.map((asset) => {
+ const currentMarket = markets.find((market) => market.denom === asset.denom)
+ return {
+ denom: asset.denom,
+ borrowRate: currentMarket?.borrow_rate ?? '0',
+ marketLiquidity: liquidity.find((coin) => coin.denom === asset.denom)?.amount ?? '0',
+ }
+ })
+ },
+ )
+
+ if (borrow) {
+ return res.status(200).json(borrow)
+ }
+
+ return res.status(404)
+}
+
+export interface BorrowData {
+ denom: string
+ borrowRate: string
+ marketLiquidity: string
+}
diff --git a/src/pages/api/markets/debts.ts b/src/pages/api/markets/debts.ts
new file mode 100644
index 00000000..88b95616
--- /dev/null
+++ b/src/pages/api/markets/debts.ts
@@ -0,0 +1,59 @@
+import { NextApiRequest, NextApiResponse } from 'next'
+
+import { ADDRESS_RED_BANK, ENV_MISSING_MESSAGE, URL_API, URL_GQL } from 'constants/env'
+import { gql, request as gqlRequest } from 'graphql-request'
+
+import { getContractQuery } from 'utils/query'
+
+export default async function handler(req: NextApiRequest, res: NextApiResponse) {
+ if (!URL_API || !ADDRESS_RED_BANK || !URL_GQL) {
+ return res.status(404).json(ENV_MISSING_MESSAGE)
+ }
+
+ const markets: Market[] = await (await fetch(`${URL_API}/markets`)).json()
+
+ let query = ''
+
+ markets.forEach((asset: any) => {
+ query += getContractQuery(
+ asset.denom,
+ ADDRESS_RED_BANK || '',
+ `
+ {
+ underlying_debt_amount: {
+ denom: "${asset.denom}"
+ amount_scaled: "${asset.debt_total_scaled}"
+ }
+ }`,
+ )
+ })
+
+ const result = await gqlRequest(
+ URL_GQL,
+ gql`
+ query RedbankBalances {
+ debts: wasm {
+ ${query}
+ }
+ }
+ `,
+ )
+
+ if (result) {
+ const debts = Object.keys(result.debts).map((key) => {
+ return {
+ denom: key,
+ amount: result.debts[key],
+ }
+ })
+ return res.status(200).json(debts)
+ }
+
+ return res.status(404)
+}
+
+interface DebtsQuery {
+ debts: {
+ [key: string]: string
+ }
+}
diff --git a/src/pages/api/markets/deposits.ts b/src/pages/api/markets/deposits.ts
new file mode 100644
index 00000000..ceec966c
--- /dev/null
+++ b/src/pages/api/markets/deposits.ts
@@ -0,0 +1,59 @@
+import { NextApiRequest, NextApiResponse } from 'next'
+
+import { ADDRESS_RED_BANK, ENV_MISSING_MESSAGE, URL_API, URL_GQL, URL_RPC } from 'constants/env'
+import { gql, request as gqlRequest } from 'graphql-request'
+
+import { getContractQuery } from 'utils/query'
+
+export default async function handler(req: NextApiRequest, res: NextApiResponse) {
+ if (!URL_RPC || !ADDRESS_RED_BANK || !URL_GQL || !URL_API) {
+ return res.status(404).json(ENV_MISSING_MESSAGE)
+ }
+
+ const markets = await (await fetch(`${URL_API}/markets`)).json()
+
+ let query = ''
+
+ markets.forEach((asset: any) => {
+ query += getContractQuery(
+ asset.denom,
+ ADDRESS_RED_BANK || '',
+ `
+ {
+ underlying_liquidity_amount: {
+ denom: "${asset.denom}"
+ amount_scaled: "${asset.collateral_total_scaled}"
+ }
+ }`,
+ )
+ })
+
+ const result = await gqlRequest(
+ URL_GQL,
+ gql`
+ query RedbankBalances {
+ deposits: wasm {
+ ${query}
+ }
+ }
+ `,
+ )
+
+ if (result) {
+ const deposits = Object.keys(result.deposits).map((key) => {
+ return {
+ denom: key,
+ amount: result.deposits[key],
+ }
+ })
+ return res.status(200).json(deposits)
+ }
+
+ return res.status(404)
+}
+
+interface DepositsQuery {
+ deposits: {
+ [key: string]: string
+ }
+}
diff --git a/src/pages/api/markets/index.ts b/src/pages/api/markets/index.ts
new file mode 100644
index 00000000..1ae673a8
--- /dev/null
+++ b/src/pages/api/markets/index.ts
@@ -0,0 +1,44 @@
+import { gql, request as gqlRequest } from 'graphql-request'
+import { NextApiRequest, NextApiResponse } from 'next'
+
+import { ADDRESS_INCENTIVES, ADDRESS_RED_BANK, ENV_MISSING_MESSAGE, URL_GQL } from 'constants/env'
+import { getMarketAssets } from 'utils/assets'
+
+export default async function handler(req: NextApiRequest, res: NextApiResponse) {
+ if (!URL_GQL || !ADDRESS_RED_BANK || !ADDRESS_INCENTIVES) {
+ return res.status(404).json(ENV_MISSING_MESSAGE)
+ }
+
+ const marketAssets = getMarketAssets()
+
+ const marketQueries = marketAssets.map(
+ (asset: Asset) =>
+ `${asset.denom}: contractQuery(
+ contractAddress: "${ADDRESS_RED_BANK}"
+ query: { market: { denom: "${asset.denom}" } }
+ )`,
+ )
+
+ const result = await gqlRequest(
+ URL_GQL,
+ gql`
+ query RedbankQuery {
+ rbwasmkey: wasm {
+ ${marketQueries}
+ }
+ }
+ `,
+ )
+
+ const markets = marketAssets.map((asset) => {
+ const market = result.rbwasmkey[`${asset.denom}`]
+ return market
+ })
+ return res.status(200).json(markets)
+}
+
+interface RedBankData {
+ rbwasmkey: {
+ [key: string]: Market
+ }
+}
diff --git a/src/pages/api/markets/liquidity.ts b/src/pages/api/markets/liquidity.ts
new file mode 100644
index 00000000..cf5f688a
--- /dev/null
+++ b/src/pages/api/markets/liquidity.ts
@@ -0,0 +1,42 @@
+import { NextApiRequest, NextApiResponse } from 'next'
+
+import { Coin } from '@cosmjs/stargate'
+import { ENV_MISSING_MESSAGE, URL_API } from 'constants/env'
+
+export default async function handler(req: NextApiRequest, res: NextApiResponse) {
+ if (!URL_API) {
+ return res.status(404).json(ENV_MISSING_MESSAGE)
+ }
+
+ const $deposits = fetch(`${URL_API}/markets/deposits`)
+ const $debts = fetch(`${URL_API}/markets/debts`)
+
+ const liquidity: Coin[] = await Promise.all([$deposits, $debts]).then(
+ async ([$deposits, $debts]) => {
+ const deposits: Coin[] = await $deposits.json()
+ const debts: Coin[] = await $debts.json()
+
+ return deposits.map((deposit) => {
+ const debt = debts.find((debt) => debt.denom === deposit.denom)
+
+ if (debt) {
+ return {
+ denom: deposit.denom,
+ amount: (Number(deposit.amount) - Number(debt.amount)).toString(),
+ }
+ }
+
+ return {
+ denom: deposit.denom,
+ amount: '0',
+ }
+ })
+ },
+ )
+
+ if (liquidity) {
+ return res.status(200).json(liquidity)
+ }
+
+ return res.status(404)
+}
diff --git a/src/pages/api/prices/index.ts b/src/pages/api/prices/index.ts
new file mode 100644
index 00000000..ff4f20c5
--- /dev/null
+++ b/src/pages/api/prices/index.ts
@@ -0,0 +1,43 @@
+import { gql, request as gqlRequest } from 'graphql-request'
+import { NextApiRequest, NextApiResponse } from 'next'
+
+import { ADDRESS_ORACLE, ENV_MISSING_MESSAGE, URL_GQL } from 'constants/env'
+import { getMarketAssets } from 'utils/assets'
+
+export default async function handler(req: NextApiRequest, res: NextApiResponse) {
+ if (!URL_GQL || !ADDRESS_ORACLE) {
+ return res.status(404).json(ENV_MISSING_MESSAGE)
+ }
+
+ const marketAssets = getMarketAssets()
+
+ const result = await gqlRequest(
+ URL_GQL,
+ gql`
+ query PriceOracle {
+ prices: wasm {
+ ${marketAssets.map((asset) => {
+ return `${asset.symbol}: contractQuery(
+ contractAddress: "${ADDRESS_ORACLE}"
+ query: {
+ price: {
+ denom: "${asset.denom}"
+ }
+ }
+ )`
+ })}
+ }
+ }
+ `,
+ )
+
+ const data = Object.values(result?.prices).reduce(
+ (acc, entry) => ({
+ ...acc,
+ [entry.denom]: Number(entry.price),
+ }),
+ {},
+ ) as { [key in string]: number }
+
+ return res.status(200).json(data)
+}
diff --git a/src/pages/api/vaults/index.ts b/src/pages/api/vaults/index.ts
new file mode 100644
index 00000000..7c4ecd8e
--- /dev/null
+++ b/src/pages/api/vaults/index.ts
@@ -0,0 +1,21 @@
+import { CosmWasmClient } from '@cosmjs/cosmwasm-stargate'
+import { NextApiRequest, NextApiResponse } from 'next'
+
+import { ADDRESS_CREDIT_MANAGER, ENV_MISSING_MESSAGE, URL_RPC } from 'constants/env'
+
+export default async function handler(req: NextApiRequest, res: NextApiResponse) {
+ if (!URL_RPC || !ADDRESS_CREDIT_MANAGER) {
+ return res.status(404).json(ENV_MISSING_MESSAGE)
+ }
+ const client = await CosmWasmClient.connect(URL_RPC)
+
+ const data = await client.queryContractSmart(ADDRESS_CREDIT_MANAGER, {
+ vaults_info: { limit: 5, start_after: undefined },
+ })
+
+ if (data) {
+ return res.status(200).json(data)
+ }
+
+ return res.status(404)
+}
diff --git a/src/pages/api/wallets/[address]/accounts.ts b/src/pages/api/wallets/[address]/accounts.ts
new file mode 100644
index 00000000..4a004d02
--- /dev/null
+++ b/src/pages/api/wallets/[address]/accounts.ts
@@ -0,0 +1,26 @@
+import { CosmWasmClient } from '@cosmjs/cosmwasm-stargate'
+import { NextApiRequest, NextApiResponse } from 'next'
+
+import { ADDRESS_ACCOUNT_NFT, ENV_MISSING_MESSAGE, URL_RPC } from 'constants/env'
+
+export default async function handler(req: NextApiRequest, res: NextApiResponse) {
+ if (!URL_RPC || !ADDRESS_ACCOUNT_NFT) {
+ return res.status(404).json(ENV_MISSING_MESSAGE)
+ }
+
+ const address = req.query.address
+
+ const client = await CosmWasmClient.connect(URL_RPC)
+
+ const data = await client.queryContractSmart(ADDRESS_ACCOUNT_NFT, {
+ tokens: {
+ owner: address,
+ },
+ })
+
+ if (data.tokens) {
+ return res.status(200).json(data.tokens)
+ }
+
+ return res.status(404)
+}
diff --git a/src/pages/api/wallets/[address]/balances.ts b/src/pages/api/wallets/[address]/balances.ts
new file mode 100644
index 00000000..a8528a60
--- /dev/null
+++ b/src/pages/api/wallets/[address]/balances.ts
@@ -0,0 +1,21 @@
+import { NextApiRequest, NextApiResponse } from 'next'
+
+import { ENV_MISSING_MESSAGE, URL_REST } from 'constants/env'
+
+export default async function handler(req: NextApiRequest, res: NextApiResponse) {
+ if (!URL_REST) {
+ return res.status(404).json(ENV_MISSING_MESSAGE)
+ }
+
+ const address = req.query.address
+ const uri = '/cosmos/bank/v1beta1/balances/'
+
+ const response = await fetch(`${URL_REST}${uri}${address}`)
+
+ if (response.ok) {
+ const data = await response.json()
+ return res.status(200).json(data.balances)
+ }
+
+ return res.status(404)
+}
diff --git a/src/pages/portfolio.tsx b/src/pages/portfolio.tsx
deleted file mode 100644
index c0353bb5..00000000
--- a/src/pages/portfolio.tsx
+++ /dev/null
@@ -1,121 +0,0 @@
-import { Card, FormattedNumber, Text } from 'components'
-
-const mockedAccounts = [
- {
- id: 1,
- label: 'Account 1',
- networth: 100000,
- totalPositionValue: 150000,
- debt: 50000,
- profit: 25000,
- leverage: 3,
- maxLeverage: 5,
- },
- {
- id: 2,
- label: 'Account 2',
- networth: 33000,
- totalPositionValue: 11000,
- debt: 20000,
- profit: -11366,
- leverage: 2,
- maxLeverage: 10,
- },
- {
- id: 3,
- label: 'Account 3',
- networth: 0,
- totalPositionValue: 12938129,
- debt: 9999999999,
- profit: -99999999,
- leverage: 3,
- maxLeverage: 5,
- },
- {
- id: 4,
- label: 'Account 4',
- networth: 33653.22,
- totalPositionValue: 100000,
- debt: 50001.9,
- profit: 25000,
- leverage: 3,
- maxLeverage: 5,
- },
-]
-
-const Portfolio = () => {
- return (
-
-
-
- Portfolio Module
-
-
-
- {mockedAccounts.map((account) => (
-
-
- {account.label}
-
-
-
-
-
-
-
- Net worth
-
-
-
-
-
-
-
- Total Position Value
-
-
-
-
-
-
-
- Debt
-
-
-
- 0 ? 'text-green-400' : 'text-red-500'}>
- 0 ? '+$' : '$'}
- />
-
-
- P&L
-
-
-
-
-
-
-
- Current Leverage
-
-
-
-
-
-
-
- Max Leverage
-
-
-
-
- ))}
-
-
- )
-}
-
-export default Portfolio
diff --git a/src/store/index.ts b/src/store/index.ts
new file mode 100644
index 00000000..0e1525db
--- /dev/null
+++ b/src/store/index.ts
@@ -0,0 +1,24 @@
+import create, { GetState, SetState, StoreApi, UseBoundStore } from 'zustand'
+import { devtools } from 'zustand/middleware'
+
+import { BroadcastSlice, createBroadcastSlice } from 'store/slices/broadcast'
+import { CommonSlice, createCommonSlice } from 'store/slices/common'
+import { createWalletSlice, WalletSlice } from 'store/slices/wallet'
+
+export interface Store extends CommonSlice, WalletSlice, BroadcastSlice {}
+
+const store = (set: SetState, get: GetState) => ({
+ ...createCommonSlice(set, get),
+ ...createWalletSlice(set, get),
+ ...createBroadcastSlice(set, get),
+})
+
+let useStore: UseBoundStore>
+
+if (process.env.NODE_ENV !== 'production') {
+ useStore = create(devtools(store))
+} else {
+ useStore = create(store)
+}
+
+export default useStore
diff --git a/src/store/slices/broadcast.ts b/src/store/slices/broadcast.ts
new file mode 100644
index 00000000..9c890f0d
--- /dev/null
+++ b/src/store/slices/broadcast.ts
@@ -0,0 +1,144 @@
+import { Coin, StdFee } from '@cosmjs/stargate'
+import { MsgExecuteContract, TxBroadcastResult } from '@marsprotocol/wallet-connector'
+import { isMobile } from 'react-device-detect'
+import { toast } from 'react-toastify'
+import { GetState, SetState } from 'zustand'
+
+import { ADDRESS_CREDIT_MANAGER, ENV_MISSING_MESSAGE } from 'constants/env'
+import { Store } from 'store'
+import { getMarketAssets } from 'utils/assets'
+import { getSingleValueFromBroadcastResult } from 'utils/broadcast'
+import { convertFromGwei } from 'utils/formatters'
+import { getTokenSymbol } from 'utils/tokens'
+
+interface BroadcastResult {
+ result?: TxBroadcastResult
+ error?: string
+}
+
+export interface BroadcastSlice {
+ executeMsg: (options: {
+ msg: Record
+ fee: StdFee
+ funds?: Coin[]
+ }) => Promise
+ createCreditAccount: (options: { fee: StdFee }) => Promise
+ deleteCreditAccount: (options: { fee: StdFee; accountId: string }) => Promise
+ depositCreditAccount: (options: {
+ fee: StdFee
+ accountId: string
+ deposit: Coin
+ }) => Promise
+}
+
+export function createBroadcastSlice(set: SetState, get: GetState): BroadcastSlice {
+ const marketAssets = getMarketAssets()
+ return {
+ createCreditAccount: async (options: { fee: StdFee }) => {
+ const msg = {
+ create_credit_account: {},
+ }
+ set({ createAccountModal: true })
+ const response = await get().executeMsg({ msg, fee: options.fee })
+
+ if (response.result) {
+ set({ createAccountModal: false })
+ const id = getSingleValueFromBroadcastResult(response.result, 'wasm', 'token_id')
+ toast.success(`Account ${id} Created`)
+ set({ fundAccountModal: true })
+ return id
+ } else {
+ set({ createAccountModal: false })
+ toast.error(response.error)
+ return null
+ }
+ },
+ deleteCreditAccount: async (options: { fee: StdFee; accountId: string }) => {
+ const msg = {
+ burn: {
+ token_id: options.accountId,
+ },
+ }
+ set({ deleteAccountModal: true })
+ const response = await get().executeMsg({ msg, fee: options.fee })
+
+ set({ deleteAccountModal: false })
+ if (response.result) {
+ toast.success(`Account ${options.accountId} deleted`)
+ } else {
+ toast.error(response.error)
+ }
+ return !!response.result
+ },
+ depositCreditAccount: async (options: { fee: StdFee; accountId: string; deposit: Coin }) => {
+ const deposit = {
+ denom: options.deposit.denom,
+ amount: String(options.deposit.amount),
+ }
+ const msg = {
+ update_credit_account: {
+ account_id: options.accountId,
+ actions: [
+ {
+ deposit: deposit,
+ },
+ ],
+ },
+ }
+ const funds = [deposit]
+
+ const response = await get().executeMsg({ msg, fee: options.fee, funds })
+ if (response.result) {
+ toast.success(
+ `Deposited ${convertFromGwei(
+ deposit.amount,
+ deposit.denom,
+ marketAssets,
+ )} ${getTokenSymbol(deposit.denom, marketAssets)} to Account ${options.accountId}`,
+ )
+ } else {
+ toast.error(response.error)
+ }
+ return !!response.result
+ },
+ executeMsg: async (options: {
+ fee: StdFee
+ msg: Record
+ funds?: Coin[]
+ }): Promise => {
+ const funds = options.funds ?? []
+
+ try {
+ const client = get().client
+ if (!ADDRESS_CREDIT_MANAGER) return { error: ENV_MISSING_MESSAGE }
+ if (!client) return { error: 'no client detected' }
+
+ const broadcastOptions = {
+ messages: [
+ new MsgExecuteContract({
+ sender: client.recentWallet.account.address,
+ contract: ADDRESS_CREDIT_MANAGER,
+ msg: options.msg,
+ funds,
+ }),
+ ],
+ feeAmount: options.fee.amount[0].amount,
+ gasLimit: options.fee.gas,
+ memo: undefined,
+ wallet: client.recentWallet,
+ mobile: isMobile,
+ }
+
+ const result = await client.broadcast(broadcastOptions)
+
+ if (result.hash) {
+ return { result }
+ }
+ return { result: undefined, error: 'broadcast failed' }
+ } catch (e: unknown) {
+ const error = typeof e === 'string' ? e : 'broadcast failed'
+ return { result: undefined, error }
+ }
+ },
+ }
+}
diff --git a/src/store/slices/common.ts b/src/store/slices/common.ts
new file mode 100644
index 00000000..28e15fc0
--- /dev/null
+++ b/src/store/slices/common.ts
@@ -0,0 +1,23 @@
+import { GetState, SetState } from 'zustand'
+
+export interface CommonSlice {
+ createAccountModal: boolean
+ deleteAccountModal: boolean
+ enableAnimations: boolean
+ fundAccountModal: boolean
+ isOpen: boolean
+ selectedAccount: string | null
+ withdrawModal: boolean
+}
+
+export function createCommonSlice(set: SetState, get: GetState) {
+ return {
+ createAccountModal: false,
+ deleteAccountModal: false,
+ enableAnimations: true,
+ fundAccountModal: false,
+ isOpen: true,
+ selectedAccount: null,
+ withdrawModal: false,
+ }
+}
diff --git a/src/store/slices/wallet.ts b/src/store/slices/wallet.ts
new file mode 100644
index 00000000..8d002818
--- /dev/null
+++ b/src/store/slices/wallet.ts
@@ -0,0 +1,79 @@
+import { WalletClient, WalletConnectionStatus } from '@marsprotocol/wallet-connector'
+import { GetState, SetState } from 'zustand'
+import { SigningCosmWasmClient } from '@cosmjs/cosmwasm-stargate'
+
+import { MarsAccountNftClient } from 'types/generated/mars-account-nft/MarsAccountNft.client'
+import { MarsCreditManagerClient } from 'types/generated/mars-credit-manager/MarsCreditManager.client'
+import { MarsSwapperBaseClient } from 'types/generated/mars-swapper-base/MarsSwapperBase.client'
+import { ADDRESS_ACCOUNT_NFT, ADDRESS_CREDIT_MANAGER, ADDRESS_SWAPPER } from 'constants/env'
+
+export interface WalletSlice {
+ address?: string
+ client?: WalletClient
+ name?: string
+ status: WalletConnectionStatus
+ signingClient?: SigningCosmWasmClient
+ clients: {
+ accountNft?: MarsAccountNftClient
+ creditManager?: MarsCreditManagerClient
+ swapperBase?: MarsSwapperBaseClient
+ }
+ actions: {
+ initClients: (address: string, signingClient: SigningCosmWasmClient) => void
+ initialize: (
+ status: WalletConnectionStatus,
+ signingCosmWasmClient?: SigningCosmWasmClient,
+ address?: string,
+ name?: string,
+ ) => void
+ }
+}
+
+export function createWalletSlice(set: SetState, get: GetState) {
+ return {
+ status: WalletConnectionStatus.Unconnected,
+ clients: {},
+ actions: {
+ // TODO: work with slices in one global store instead
+ initClients: (address: string, signingClient: SigningCosmWasmClient) => {
+ if (!signingClient) return
+ const accountNft = new MarsAccountNftClient(
+ signingClient,
+ address,
+ ADDRESS_ACCOUNT_NFT || '',
+ )
+ const creditManager = new MarsCreditManagerClient(
+ signingClient,
+ address,
+ ADDRESS_CREDIT_MANAGER || '',
+ )
+ const swapperBase = new MarsSwapperBaseClient(signingClient, address, ADDRESS_SWAPPER || '')
+
+ set(() => ({
+ clients: {
+ accountNft,
+ creditManager,
+ swapperBase,
+ },
+ }))
+ },
+ initialize: async (
+ status: WalletConnectionStatus,
+ signingCosmWasmClient?: SigningCosmWasmClient,
+ address?: string,
+ name?: string,
+ ) => {
+ if (address && signingCosmWasmClient) {
+ get().actions.initClients(address, signingCosmWasmClient)
+ }
+
+ set({
+ signingClient: signingCosmWasmClient,
+ address,
+ status,
+ name,
+ })
+ },
+ },
+ }
+}
diff --git a/src/stores/index.ts b/src/stores/index.ts
deleted file mode 100644
index b1c798ee..00000000
--- a/src/stores/index.ts
+++ /dev/null
@@ -1,7 +0,0 @@
-// @index(['./*.tsx'], f => `export { ${f.name} } from '${f.path}'`)
-export { useAccountDetailsStore } from './useAccountDetailsStore'
-export { useModalStore } from './useModalStore'
-export { useNetworkConfigStore } from './useNetworkConfigStore'
-export { useSettingsStore } from './useSettingsStore'
-export { useWalletStore } from './useWalletStore'
-// @endindex
diff --git a/src/stores/useAccountDetailsStore.tsx b/src/stores/useAccountDetailsStore.tsx
deleted file mode 100644
index b945602c..00000000
--- a/src/stores/useAccountDetailsStore.tsx
+++ /dev/null
@@ -1,11 +0,0 @@
-import create from 'zustand'
-
-interface AccountDetailsStore {
- isOpen: boolean
- selectedAccount: string | null
-}
-
-export const useAccountDetailsStore = create()(() => ({
- isOpen: true,
- selectedAccount: null,
-}))
diff --git a/src/stores/useModalStore.tsx b/src/stores/useModalStore.tsx
deleted file mode 100644
index 19183bb6..00000000
--- a/src/stores/useModalStore.tsx
+++ /dev/null
@@ -1,15 +0,0 @@
-import create from 'zustand'
-
-interface AccountDetailsStore {
- fundAccountModal: boolean
- withdrawModal: boolean
- createAccountModal: boolean
- deleteAccountModal: boolean
-}
-
-export const useModalStore = create()(() => ({
- fundAccountModal: false,
- withdrawModal: false,
- createAccountModal: false,
- deleteAccountModal: false,
-}))
diff --git a/src/stores/useNetworkConfigStore.tsx b/src/stores/useNetworkConfigStore.tsx
deleted file mode 100644
index 5a1198d9..00000000
--- a/src/stores/useNetworkConfigStore.tsx
+++ /dev/null
@@ -1,8 +0,0 @@
-import create from 'zustand'
-
-import { networkConfig } from 'config/osmo-test-4'
-
-// TODO: Create dynamic network import
-export const useNetworkConfigStore = create()(() => {
- return networkConfig
-})
diff --git a/src/stores/useSettingsStore.tsx b/src/stores/useSettingsStore.tsx
deleted file mode 100644
index 3887d21d..00000000
--- a/src/stores/useSettingsStore.tsx
+++ /dev/null
@@ -1,9 +0,0 @@
-import create from 'zustand'
-
-interface SettingsStore {
- enableAnimations: boolean
-}
-
-export const useSettingsStore = create()(() => ({
- enableAnimations: true,
-}))
diff --git a/src/stores/useWalletStore.tsx b/src/stores/useWalletStore.tsx
deleted file mode 100644
index 28439c10..00000000
--- a/src/stores/useWalletStore.tsx
+++ /dev/null
@@ -1,91 +0,0 @@
-import {
- WalletChainInfo,
- WalletConnectionStatus,
- WalletSigningCosmWasmClient,
-} from '@marsprotocol/wallet-connector'
-import create from 'zustand'
-
-import { networkConfig } from 'config/osmo-test-4'
-import { MarsAccountNftClient } from 'types/generated/mars-account-nft/MarsAccountNft.client'
-import { MarsCreditManagerClient } from 'types/generated/mars-credit-manager/MarsCreditManager.client'
-import { MarsSwapperBaseClient } from 'types/generated/mars-swapper-base/MarsSwapperBase.client'
-
-interface WalletStore {
- address?: string
- chainInfo?: WalletChainInfo
- metamaskInstalled: boolean
- name?: string
- status: WalletConnectionStatus
- signingClient?: WalletSigningCosmWasmClient
- clients: {
- accountNft?: MarsAccountNftClient
- creditManager?: MarsCreditManagerClient
- swapperBase?: MarsSwapperBaseClient
- }
- actions: {
- initClients: (address: string, signingClient: WalletSigningCosmWasmClient) => void
- initialize: (
- status: WalletConnectionStatus,
- signingCosmWasmClient?: WalletSigningCosmWasmClient,
- address?: string,
- name?: string,
- chainInfo?: WalletChainInfo,
- ) => void
- setMetamaskInstalledStatus: (value: boolean) => void
- }
-}
-
-export const useWalletStore = create()((set, get) => ({
- metamaskInstalled: false,
- status: WalletConnectionStatus.ReadyForConnection,
- clients: {},
- actions: {
- // TODO: work with slices in one global store instead
- initClients: (address, signingClient) => {
- if (!signingClient) return
- const accountNft = new MarsAccountNftClient(
- signingClient,
- address,
- networkConfig.contracts.accountNft,
- )
- const creditManager = new MarsCreditManagerClient(
- signingClient,
- address,
- networkConfig.contracts.creditManager,
- )
- const swapperBase = new MarsSwapperBaseClient(
- signingClient,
- address,
- networkConfig.contracts.swapper,
- )
-
- set(() => ({
- clients: {
- accountNft,
- creditManager,
- swapperBase,
- },
- }))
- },
- initialize: async (
- status: WalletConnectionStatus,
- signingCosmWasmClient?: WalletSigningCosmWasmClient,
- address?: string,
- name?: string,
- chainInfo?: WalletChainInfo,
- ) => {
- if (address && signingCosmWasmClient) {
- get().actions.initClients(address, signingCosmWasmClient)
- }
-
- set({
- signingClient: signingCosmWasmClient,
- address,
- status,
- name,
- chainInfo,
- })
- },
- setMetamaskInstalledStatus: (value: boolean) => set(() => ({ metamaskInstalled: value })),
- },
-}))
diff --git a/src/types/generated/mars-account-nft/MarsAccountNft.client.ts b/src/types/generated/mars-account-nft/MarsAccountNft.client.ts
index f0240173..eae631ba 100644
--- a/src/types/generated/mars-account-nft/MarsAccountNft.client.ts
+++ b/src/types/generated/mars-account-nft/MarsAccountNft.client.ts
@@ -1,6 +1,6 @@
// @ts-nocheck
/**
- * This file was automatically generated by @cosmwasm/ts-codegen@0.20.0.
+ * This file was automatically generated by @cosmwasm/ts-codegen@0.24.0.
* DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file,
* and run the @cosmwasm/ts-codegen generate command to regenerate this file.
*/
@@ -20,19 +20,22 @@ import {
Expiration,
InstantiateMsg,
MinterResponse,
+ NftConfigBaseForString,
+ NftConfigUpdates,
NftInfoResponseForEmpty,
NumTokensResponse,
OperatorsResponse,
OwnerOfResponse,
QueryMsg,
- String,
Timestamp,
TokensResponse,
+ Uint128,
Uint64,
} from './MarsAccountNft.types'
export interface MarsAccountNftReadOnlyInterface {
contractAddress: string
- proposedNewOwner: () => Promise
+ config: () => Promise
+ nextId: () => Promise
ownerOf: ({
includeExpired,
tokenId,
@@ -102,7 +105,8 @@ export class MarsAccountNftQueryClient implements MarsAccountNftReadOnlyInterfac
constructor(client: CosmWasmClient, contractAddress: string) {
this.client = client
this.contractAddress = contractAddress
- this.proposedNewOwner = this.proposedNewOwner.bind(this)
+ this.config = this.config.bind(this)
+ this.nextId = this.nextId.bind(this)
this.ownerOf = this.ownerOf.bind(this)
this.approval = this.approval.bind(this)
this.approvals = this.approvals.bind(this)
@@ -116,9 +120,14 @@ export class MarsAccountNftQueryClient implements MarsAccountNftReadOnlyInterfac
this.minter = this.minter.bind(this)
}
- proposedNewOwner = async (): Promise => {
+ config = async (): Promise => {
return this.client.queryContractSmart(this.contractAddress, {
- proposed_new_owner: {},
+ config: {},
+ })
+ }
+ nextId = async (): Promise => {
+ return this.client.queryContractSmart(this.contractAddress, {
+ next_id: {},
})
}
ownerOf = async ({
@@ -257,17 +266,17 @@ export class MarsAccountNftQueryClient implements MarsAccountNftReadOnlyInterfac
export interface MarsAccountNftInterface extends MarsAccountNftReadOnlyInterface {
contractAddress: string
sender: string
- proposeNewOwner: (
+ updateConfig: (
{
- newOwner,
+ updates,
}: {
- newOwner: string
+ updates: NftConfigUpdates
},
fee?: number | StdFee | 'auto',
memo?: string,
funds?: Coin[],
) => Promise
- acceptOwnership: (
+ acceptMinterRole: (
fee?: number | StdFee | 'auto',
memo?: string,
funds?: Coin[],
@@ -282,6 +291,16 @@ export interface MarsAccountNftInterface extends MarsAccountNftReadOnlyInterface
memo?: string,
funds?: Coin[],
) => Promise
+ burn: (
+ {
+ tokenId,
+ }: {
+ tokenId: string
+ },
+ fee?: number | StdFee | 'auto',
+ memo?: string,
+ funds?: Coin[],
+ ) => Promise
transferNft: (
{
recipient,
@@ -356,16 +375,6 @@ export interface MarsAccountNftInterface extends MarsAccountNftReadOnlyInterface
memo?: string,
funds?: Coin[],
) => Promise
- burn: (
- {
- tokenId,
- }: {
- tokenId: string
- },
- fee?: number | StdFee | 'auto',
- memo?: string,
- funds?: Coin[],
- ) => Promise
}
export class MarsAccountNftClient
extends MarsAccountNftQueryClient
@@ -380,23 +389,23 @@ export class MarsAccountNftClient
this.client = client
this.sender = sender
this.contractAddress = contractAddress
- this.proposeNewOwner = this.proposeNewOwner.bind(this)
- this.acceptOwnership = this.acceptOwnership.bind(this)
+ this.updateConfig = this.updateConfig.bind(this)
+ this.acceptMinterRole = this.acceptMinterRole.bind(this)
this.mint = this.mint.bind(this)
+ this.burn = this.burn.bind(this)
this.transferNft = this.transferNft.bind(this)
this.sendNft = this.sendNft.bind(this)
this.approve = this.approve.bind(this)
this.revoke = this.revoke.bind(this)
this.approveAll = this.approveAll.bind(this)
this.revokeAll = this.revokeAll.bind(this)
- this.burn = this.burn.bind(this)
}
- proposeNewOwner = async (
+ updateConfig = async (
{
- newOwner,
+ updates,
}: {
- newOwner: string
+ updates: NftConfigUpdates
},
fee: number | StdFee | 'auto' = 'auto',
memo?: string,
@@ -406,8 +415,8 @@ export class MarsAccountNftClient
this.sender,
this.contractAddress,
{
- propose_new_owner: {
- new_owner: newOwner,
+ update_config: {
+ updates,
},
},
fee,
@@ -415,7 +424,7 @@ export class MarsAccountNftClient
funds,
)
}
- acceptOwnership = async (
+ acceptMinterRole = async (
fee: number | StdFee | 'auto' = 'auto',
memo?: string,
funds?: Coin[],
@@ -424,7 +433,7 @@ export class MarsAccountNftClient
this.sender,
this.contractAddress,
{
- accept_ownership: {},
+ accept_minter_role: {},
},
fee,
memo,
@@ -454,6 +463,29 @@ export class MarsAccountNftClient
funds,
)
}
+ burn = async (
+ {
+ tokenId,
+ }: {
+ tokenId: string
+ },
+ fee: number | StdFee | 'auto' = 'auto',
+ memo?: string,
+ funds?: Coin[],
+ ): Promise => {
+ return await this.client.execute(
+ this.sender,
+ this.contractAddress,
+ {
+ burn: {
+ token_id: tokenId,
+ },
+ },
+ fee,
+ memo,
+ funds,
+ )
+ }
transferNft = async (
{
recipient,
@@ -613,27 +645,4 @@ export class MarsAccountNftClient
funds,
)
}
- burn = async (
- {
- tokenId,
- }: {
- tokenId: string
- },
- fee: number | StdFee | 'auto' = 'auto',
- memo?: string,
- funds?: Coin[],
- ): Promise => {
- return await this.client.execute(
- this.sender,
- this.contractAddress,
- {
- burn: {
- token_id: tokenId,
- },
- },
- fee,
- memo,
- funds,
- )
- }
}
diff --git a/src/types/generated/mars-account-nft/MarsAccountNft.message-composer.ts b/src/types/generated/mars-account-nft/MarsAccountNft.message-composer.ts
index de58e069..2368d7b2 100644
--- a/src/types/generated/mars-account-nft/MarsAccountNft.message-composer.ts
+++ b/src/types/generated/mars-account-nft/MarsAccountNft.message-composer.ts
@@ -1,6 +1,6 @@
// @ts-nocheck
/**
- * This file was automatically generated by @cosmwasm/ts-codegen@0.20.0.
+ * This file was automatically generated by @cosmwasm/ts-codegen@0.24.0.
* DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file,
* and run the @cosmwasm/ts-codegen generate command to regenerate this file.
*/
@@ -22,28 +22,30 @@ import {
Expiration,
InstantiateMsg,
MinterResponse,
+ NftConfigBaseForString,
+ NftConfigUpdates,
NftInfoResponseForEmpty,
NumTokensResponse,
OperatorsResponse,
OwnerOfResponse,
QueryMsg,
- String,
Timestamp,
TokensResponse,
+ Uint128,
Uint64,
} from './MarsAccountNft.types'
export interface MarsAccountNftMessage {
contractAddress: string
sender: string
- proposeNewOwner: (
+ updateConfig: (
{
- newOwner,
+ updates,
}: {
- newOwner: string
+ updates: NftConfigUpdates
},
funds?: Coin[],
) => MsgExecuteContractEncodeObject
- acceptOwnership: (funds?: Coin[]) => MsgExecuteContractEncodeObject
+ acceptMinterRole: (funds?: Coin[]) => MsgExecuteContractEncodeObject
mint: (
{
user,
@@ -52,6 +54,14 @@ export interface MarsAccountNftMessage {
},
funds?: Coin[],
) => MsgExecuteContractEncodeObject
+ burn: (
+ {
+ tokenId,
+ }: {
+ tokenId: string
+ },
+ funds?: Coin[],
+ ) => MsgExecuteContractEncodeObject
transferNft: (
{
recipient,
@@ -114,14 +124,6 @@ export interface MarsAccountNftMessage {
},
funds?: Coin[],
) => MsgExecuteContractEncodeObject
- burn: (
- {
- tokenId,
- }: {
- tokenId: string
- },
- funds?: Coin[],
- ) => MsgExecuteContractEncodeObject
}
export class MarsAccountNftMessageComposer implements MarsAccountNftMessage {
sender: string
@@ -130,23 +132,23 @@ export class MarsAccountNftMessageComposer implements MarsAccountNftMessage {
constructor(sender: string, contractAddress: string) {
this.sender = sender
this.contractAddress = contractAddress
- this.proposeNewOwner = this.proposeNewOwner.bind(this)
- this.acceptOwnership = this.acceptOwnership.bind(this)
+ this.updateConfig = this.updateConfig.bind(this)
+ this.acceptMinterRole = this.acceptMinterRole.bind(this)
this.mint = this.mint.bind(this)
+ this.burn = this.burn.bind(this)
this.transferNft = this.transferNft.bind(this)
this.sendNft = this.sendNft.bind(this)
this.approve = this.approve.bind(this)
this.revoke = this.revoke.bind(this)
this.approveAll = this.approveAll.bind(this)
this.revokeAll = this.revokeAll.bind(this)
- this.burn = this.burn.bind(this)
}
- proposeNewOwner = (
+ updateConfig = (
{
- newOwner,
+ updates,
}: {
- newOwner: string
+ updates: NftConfigUpdates
},
funds?: Coin[],
): MsgExecuteContractEncodeObject => {
@@ -157,8 +159,8 @@ export class MarsAccountNftMessageComposer implements MarsAccountNftMessage {
contract: this.contractAddress,
msg: toUtf8(
JSON.stringify({
- propose_new_owner: {
- new_owner: newOwner,
+ update_config: {
+ updates,
},
}),
),
@@ -166,7 +168,7 @@ export class MarsAccountNftMessageComposer implements MarsAccountNftMessage {
}),
}
}
- acceptOwnership = (funds?: Coin[]): MsgExecuteContractEncodeObject => {
+ acceptMinterRole = (funds?: Coin[]): MsgExecuteContractEncodeObject => {
return {
typeUrl: '/cosmwasm.wasm.v1.MsgExecuteContract',
value: MsgExecuteContract.fromPartial({
@@ -174,7 +176,7 @@ export class MarsAccountNftMessageComposer implements MarsAccountNftMessage {
contract: this.contractAddress,
msg: toUtf8(
JSON.stringify({
- accept_ownership: {},
+ accept_minter_role: {},
}),
),
funds,
@@ -205,6 +207,30 @@ export class MarsAccountNftMessageComposer implements MarsAccountNftMessage {
}),
}
}
+ burn = (
+ {
+ tokenId,
+ }: {
+ tokenId: string
+ },
+ funds?: Coin[],
+ ): MsgExecuteContractEncodeObject => {
+ return {
+ typeUrl: '/cosmwasm.wasm.v1.MsgExecuteContract',
+ value: MsgExecuteContract.fromPartial({
+ sender: this.sender,
+ contract: this.contractAddress,
+ msg: toUtf8(
+ JSON.stringify({
+ burn: {
+ token_id: tokenId,
+ },
+ }),
+ ),
+ funds,
+ }),
+ }
+ }
transferNft = (
{
recipient,
@@ -370,28 +396,4 @@ export class MarsAccountNftMessageComposer implements MarsAccountNftMessage {
}),
}
}
- burn = (
- {
- tokenId,
- }: {
- tokenId: string
- },
- funds?: Coin[],
- ): MsgExecuteContractEncodeObject => {
- return {
- typeUrl: '/cosmwasm.wasm.v1.MsgExecuteContract',
- value: MsgExecuteContract.fromPartial({
- sender: this.sender,
- contract: this.contractAddress,
- msg: toUtf8(
- JSON.stringify({
- burn: {
- token_id: tokenId,
- },
- }),
- ),
- funds,
- }),
- }
- }
}
diff --git a/src/types/generated/mars-account-nft/MarsAccountNft.react-query.ts b/src/types/generated/mars-account-nft/MarsAccountNft.react-query.ts
index 29534412..2d9f8b27 100644
--- a/src/types/generated/mars-account-nft/MarsAccountNft.react-query.ts
+++ b/src/types/generated/mars-account-nft/MarsAccountNft.react-query.ts
@@ -1,6 +1,6 @@
// @ts-nocheck
/**
- * This file was automatically generated by @cosmwasm/ts-codegen@0.20.0.
+ * This file was automatically generated by @cosmwasm/ts-codegen@0.24.0.
* DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file,
* and run the @cosmwasm/ts-codegen generate command to regenerate this file.
*/
@@ -21,14 +21,16 @@ import {
Expiration,
InstantiateMsg,
MinterResponse,
+ NftConfigBaseForString,
+ NftConfigUpdates,
NftInfoResponseForEmpty,
NumTokensResponse,
OperatorsResponse,
OwnerOfResponse,
QueryMsg,
- String,
Timestamp,
TokensResponse,
+ Uint128,
Uint64,
} from './MarsAccountNft.types'
import { MarsAccountNftClient, MarsAccountNftQueryClient } from './MarsAccountNft.client'
@@ -40,14 +42,10 @@ export const marsAccountNftQueryKeys = {
] as const,
address: (contractAddress: string | undefined) =>
[{ ...marsAccountNftQueryKeys.contract[0], address: contractAddress }] as const,
- proposedNewOwner: (contractAddress: string | undefined, args?: Record) =>
- [
- {
- ...marsAccountNftQueryKeys.address(contractAddress)[0],
- method: 'proposed_new_owner',
- args,
- },
- ] as const,
+ config: (contractAddress: string | undefined, args?: Record) =>
+ [{ ...marsAccountNftQueryKeys.address(contractAddress)[0], method: 'config', args }] as const,
+ nextId: (contractAddress: string | undefined, args?: Record) =>
+ [{ ...marsAccountNftQueryKeys.address(contractAddress)[0], method: 'next_id', args }] as const,
ownerOf: (contractAddress: string | undefined, args?: Record) =>
[{ ...marsAccountNftQueryKeys.address(contractAddress)[0], method: 'owner_of', args }] as const,
approval: (contractAddress: string | undefined, args?: Record) =>
@@ -326,38 +324,27 @@ export function useMarsAccountNftOwnerOfQuery({
{ ...options, enabled: !!client && (options?.enabled != undefined ? options.enabled : true) },
)
}
-export interface MarsAccountNftProposedNewOwnerQuery
- extends MarsAccountNftReactQuery {}
-export function useMarsAccountNftProposedNewOwnerQuery({
+export interface MarsAccountNftNextIdQuery extends MarsAccountNftReactQuery {}
+export function useMarsAccountNftNextIdQuery({
client,
options,
-}: MarsAccountNftProposedNewOwnerQuery) {
- return useQuery(
- marsAccountNftQueryKeys.proposedNewOwner(client?.contractAddress),
- () => (client ? client.proposedNewOwner() : Promise.reject(new Error('Invalid client'))),
+}: MarsAccountNftNextIdQuery) {
+ return useQuery(
+ marsAccountNftQueryKeys.nextId(client?.contractAddress),
+ () => (client ? client.nextId() : Promise.reject(new Error('Invalid client'))),
{ ...options, enabled: !!client && (options?.enabled != undefined ? options.enabled : true) },
)
}
-export interface MarsAccountNftBurnMutation {
- client: MarsAccountNftClient
- msg: {
- tokenId: string
- }
- args?: {
- fee?: number | StdFee | 'auto'
- memo?: string
- funds?: Coin[]
- }
-}
-export function useMarsAccountNftBurnMutation(
- options?: Omit<
- UseMutationOptions,
- 'mutationFn'
- >,
-) {
- return useMutation(
- ({ client, msg, args: { fee, memo, funds } = {} }) => client.burn(msg, fee, memo, funds),
- options,
+export interface MarsAccountNftConfigQuery
+ extends MarsAccountNftReactQuery {}
+export function useMarsAccountNftConfigQuery({
+ client,
+ options,
+}: MarsAccountNftConfigQuery) {
+ return useQuery(
+ marsAccountNftQueryKeys.config(client?.contractAddress),
+ () => (client ? client.config() : Promise.reject(new Error('Invalid client'))),
+ { ...options, enabled: !!client && (options?.enabled != undefined ? options.enabled : true) },
)
}
export interface MarsAccountNftRevokeAllMutation {
@@ -499,6 +486,28 @@ export function useMarsAccountNftTransferNftMutation(
options,
)
}
+export interface MarsAccountNftBurnMutation {
+ client: MarsAccountNftClient
+ msg: {
+ tokenId: string
+ }
+ args?: {
+ fee?: number | StdFee | 'auto'
+ memo?: string
+ funds?: Coin[]
+ }
+}
+export function useMarsAccountNftBurnMutation(
+ options?: Omit<
+ UseMutationOptions,
+ 'mutationFn'
+ >,
+) {
+ return useMutation(
+ ({ client, msg, args: { fee, memo, funds } = {} }) => client.burn(msg, fee, memo, funds),
+ options,
+ )
+}
export interface MarsAccountNftMintMutation {
client: MarsAccountNftClient
msg: {
@@ -521,7 +530,7 @@ export function useMarsAccountNftMintMutation(
options,
)
}
-export interface MarsAccountNftAcceptOwnershipMutation {
+export interface MarsAccountNftAcceptMinterRoleMutation {
client: MarsAccountNftClient
args?: {
fee?: number | StdFee | 'auto'
@@ -529,21 +538,21 @@ export interface MarsAccountNftAcceptOwnershipMutation {
funds?: Coin[]
}
}
-export function useMarsAccountNftAcceptOwnershipMutation(
+export function useMarsAccountNftAcceptMinterRoleMutation(
options?: Omit<
- UseMutationOptions,
+ UseMutationOptions,
'mutationFn'
>,
) {
- return useMutation(
- ({ client, args: { fee, memo, funds } = {} }) => client.acceptOwnership(fee, memo, funds),
+ return useMutation(
+ ({ client, args: { fee, memo, funds } = {} }) => client.acceptMinterRole(fee, memo, funds),
options,
)
}
-export interface MarsAccountNftProposeNewOwnerMutation {
+export interface MarsAccountNftUpdateConfigMutation {
client: MarsAccountNftClient
msg: {
- newOwner: string
+ updates: NftConfigUpdates
}
args?: {
fee?: number | StdFee | 'auto'
@@ -551,15 +560,15 @@ export interface MarsAccountNftProposeNewOwnerMutation {
funds?: Coin[]
}
}
-export function useMarsAccountNftProposeNewOwnerMutation(
+export function useMarsAccountNftUpdateConfigMutation(
options?: Omit<
- UseMutationOptions,
+ UseMutationOptions,
'mutationFn'
>,
) {
- return useMutation(
+ return useMutation(
({ client, msg, args: { fee, memo, funds } = {} }) =>
- client.proposeNewOwner(msg, fee, memo, funds),
+ client.updateConfig(msg, fee, memo, funds),
options,
)
}
diff --git a/src/types/generated/mars-account-nft/MarsAccountNft.types.ts b/src/types/generated/mars-account-nft/MarsAccountNft.types.ts
index 062be620..54dd22b6 100644
--- a/src/types/generated/mars-account-nft/MarsAccountNft.types.ts
+++ b/src/types/generated/mars-account-nft/MarsAccountNft.types.ts
@@ -1,29 +1,37 @@
// @ts-nocheck
/**
- * This file was automatically generated by @cosmwasm/ts-codegen@0.20.0.
+ * This file was automatically generated by @cosmwasm/ts-codegen@0.24.0.
* DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file,
* and run the @cosmwasm/ts-codegen generate command to regenerate this file.
*/
+export type Uint128 = string
export interface InstantiateMsg {
+ health_contract?: string | null
+ max_value_for_burn: Uint128
minter: string
name: string
symbol: string
}
export type ExecuteMsg =
| {
- propose_new_owner: {
- new_owner: string
+ update_config: {
+ updates: NftConfigUpdates
}
}
| {
- accept_ownership: {}
+ accept_minter_role: {}
}
| {
mint: {
user: string
}
}
+ | {
+ burn: {
+ token_id: string
+ }
+ }
| {
transfer_nft: {
recipient: string
@@ -61,11 +69,6 @@ export type ExecuteMsg =
operator: string
}
}
- | {
- burn: {
- token_id: string
- }
- }
export type Binary = string
export type Expiration =
| {
@@ -79,9 +82,17 @@ export type Expiration =
}
export type Timestamp = Uint64
export type Uint64 = string
+export interface NftConfigUpdates {
+ health_contract_addr?: string | null
+ max_value_for_burn?: Uint128 | null
+ proposed_new_minter?: string | null
+}
export type QueryMsg =
| {
- proposed_new_owner: {}
+ config: {}
+ }
+ | {
+ next_id: {}
}
| {
owner_of: {
@@ -174,6 +185,11 @@ export interface ApprovalResponse {
export interface ApprovalsResponse {
approvals: Approval[]
}
+export interface NftConfigBaseForString {
+ health_contract_addr?: string | null
+ max_value_for_burn: Uint128
+ proposed_new_minter?: string | null
+}
export interface ContractInfoResponse {
name: string
symbol: string
@@ -184,4 +200,3 @@ export interface MinterResponse {
export interface NumTokensResponse {
count: number
}
-export type String = string
diff --git a/src/types/generated/mars-account-nft/bundle.ts b/src/types/generated/mars-account-nft/bundle.ts
index b6237eba..3fef9c89 100644
--- a/src/types/generated/mars-account-nft/bundle.ts
+++ b/src/types/generated/mars-account-nft/bundle.ts
@@ -1,6 +1,6 @@
// @ts-nocheck
/**
- * This file was automatically generated by @cosmwasm/ts-codegen@0.20.0.
+ * This file was automatically generated by @cosmwasm/ts-codegen@0.24.0.
* DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file,
* and run the @cosmwasm/ts-codegen generate command to regenerate this file.
*/
diff --git a/src/types/generated/mars-credit-manager/MarsCreditManager.client.ts b/src/types/generated/mars-credit-manager/MarsCreditManager.client.ts
index 0a8c10e0..0a9c7e3f 100644
--- a/src/types/generated/mars-credit-manager/MarsCreditManager.client.ts
+++ b/src/types/generated/mars-credit-manager/MarsCreditManager.client.ts
@@ -1,6 +1,6 @@
// @ts-nocheck
/**
- * This file was automatically generated by @cosmwasm/ts-codegen@0.20.0.
+ * This file was automatically generated by @cosmwasm/ts-codegen@0.24.0.
* DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file,
* and run the @cosmwasm/ts-codegen generate command to regenerate this file.
*/
@@ -10,28 +10,36 @@ import { StdFee } from '@cosmjs/amino'
import {
Action,
+ ActionAmount,
+ ActionCoin,
Addr,
ArrayOfCoin,
ArrayOfCoinBalanceResponseItem,
ArrayOfDebtShares,
+ ArrayOfLentShares,
ArrayOfSharesResponseItem,
ArrayOfString,
- ArrayOfVaultInstantiateConfig,
+ ArrayOfVaultInfoResponse,
ArrayOfVaultPositionResponseItem,
ArrayOfVaultWithBalance,
CallbackMsg,
Coin,
CoinBalanceResponseItem,
+ CoinValue,
ConfigResponse,
ConfigUpdates,
DebtAmount,
DebtShares,
Decimal,
ExecuteMsg,
- HealthResponse,
+ HealthContractBaseForString,
InstantiateMsg,
+ LentAmount,
+ LentShares,
LockingVaultAmount,
+ NftConfigUpdates,
OracleBaseForString,
+ OwnerUpdate,
Positions,
QueryMsg,
RedBankBaseForString,
@@ -44,10 +52,13 @@ import {
VaultBaseForAddr,
VaultBaseForString,
VaultConfig,
+ VaultInfoResponse,
VaultInstantiateConfig,
VaultPosition,
VaultPositionAmount,
VaultPositionResponseItem,
+ VaultPositionType,
+ VaultPositionValue,
VaultUnlockingPosition,
VaultWithBalance,
ZapperBaseForString,
@@ -55,13 +66,14 @@ import {
export interface MarsCreditManagerReadOnlyInterface {
contractAddress: string
config: () => Promise
- vaultConfigs: ({
+ vaultInfo: ({ vault }: { vault: VaultBaseForString }) => Promise
+ vaultsInfo: ({
limit,
startAfter,
}: {
limit?: number
startAfter?: VaultBaseForString
- }) => Promise
+ }) => Promise
allowedCoins: ({
limit,
startAfter,
@@ -70,7 +82,6 @@ export interface MarsCreditManagerReadOnlyInterface {
startAfter?: string
}) => Promise
positions: ({ accountId }: { accountId: string }) => Promise
- health: ({ accountId }: { accountId: string }) => Promise
allCoinBalances: ({
limit,
startAfter,
@@ -93,6 +104,21 @@ export interface MarsCreditManagerReadOnlyInterface {
limit?: number
startAfter?: string
}) => Promise
+ allLentShares: ({
+ limit,
+ startAfter,
+ }: {
+ limit?: number
+ startAfter?: string[][]
+ }) => Promise
+ totalLentShares: () => Promise
+ allTotalLentShares: ({
+ limit,
+ startAfter,
+ }: {
+ limit?: number
+ startAfter?: string
+ }) => Promise
allVaultPositions: ({
limit,
startAfter,
@@ -116,6 +142,11 @@ export interface MarsCreditManagerReadOnlyInterface {
lpTokenOut: string
}) => Promise
estimateWithdrawLiquidity: ({ lpToken }: { lpToken: Coin }) => Promise
+ vaultPositionValue: ({
+ vaultPosition,
+ }: {
+ vaultPosition: VaultPosition
+ }) => Promise
}
export class MarsCreditManagerQueryClient implements MarsCreditManagerReadOnlyInterface {
client: CosmWasmClient
@@ -125,19 +156,23 @@ export class MarsCreditManagerQueryClient implements MarsCreditManagerReadOnlyIn
this.client = client
this.contractAddress = contractAddress
this.config = this.config.bind(this)
- this.vaultConfigs = this.vaultConfigs.bind(this)
+ this.vaultInfo = this.vaultInfo.bind(this)
+ this.vaultsInfo = this.vaultsInfo.bind(this)
this.allowedCoins = this.allowedCoins.bind(this)
this.positions = this.positions.bind(this)
- this.health = this.health.bind(this)
this.allCoinBalances = this.allCoinBalances.bind(this)
this.allDebtShares = this.allDebtShares.bind(this)
this.totalDebtShares = this.totalDebtShares.bind(this)
this.allTotalDebtShares = this.allTotalDebtShares.bind(this)
+ this.allLentShares = this.allLentShares.bind(this)
+ this.totalLentShares = this.totalLentShares.bind(this)
+ this.allTotalLentShares = this.allTotalLentShares.bind(this)
this.allVaultPositions = this.allVaultPositions.bind(this)
this.totalVaultCoinBalance = this.totalVaultCoinBalance.bind(this)
this.allTotalVaultCoinBalances = this.allTotalVaultCoinBalances.bind(this)
this.estimateProvideLiquidity = this.estimateProvideLiquidity.bind(this)
this.estimateWithdrawLiquidity = this.estimateWithdrawLiquidity.bind(this)
+ this.vaultPositionValue = this.vaultPositionValue.bind(this)
}
config = async (): Promise => {
@@ -145,15 +180,22 @@ export class MarsCreditManagerQueryClient implements MarsCreditManagerReadOnlyIn
config: {},
})
}
- vaultConfigs = async ({
+ vaultInfo = async ({ vault }: { vault: VaultBaseForString }): Promise => {
+ return this.client.queryContractSmart(this.contractAddress, {
+ vault_info: {
+ vault,
+ },
+ })
+ }
+ vaultsInfo = async ({
limit,
startAfter,
}: {
limit?: number
startAfter?: VaultBaseForString
- }): Promise => {
+ }): Promise => {
return this.client.queryContractSmart(this.contractAddress, {
- vault_configs: {
+ vaults_info: {
limit,
start_after: startAfter,
},
@@ -180,13 +222,6 @@ export class MarsCreditManagerQueryClient implements MarsCreditManagerReadOnlyIn
},
})
}
- health = async ({ accountId }: { accountId: string }): Promise => {
- return this.client.queryContractSmart(this.contractAddress, {
- health: {
- account_id: accountId,
- },
- })
- }
allCoinBalances = async ({
limit,
startAfter,
@@ -234,6 +269,39 @@ export class MarsCreditManagerQueryClient implements MarsCreditManagerReadOnlyIn
},
})
}
+ allLentShares = async ({
+ limit,
+ startAfter,
+ }: {
+ limit?: number
+ startAfter?: string[][]
+ }): Promise => {
+ return this.client.queryContractSmart(this.contractAddress, {
+ all_lent_shares: {
+ limit,
+ start_after: startAfter,
+ },
+ })
+ }
+ totalLentShares = async (): Promise => {
+ return this.client.queryContractSmart(this.contractAddress, {
+ total_lent_shares: {},
+ })
+ }
+ allTotalLentShares = async ({
+ limit,
+ startAfter,
+ }: {
+ limit?: number
+ startAfter?: string
+ }): Promise => {
+ return this.client.queryContractSmart(this.contractAddress, {
+ all_total_lent_shares: {
+ limit,
+ start_after: startAfter,
+ },
+ })
+ }
allVaultPositions = async ({
limit,
startAfter,
@@ -290,6 +358,17 @@ export class MarsCreditManagerQueryClient implements MarsCreditManagerReadOnlyIn
},
})
}
+ vaultPositionValue = async ({
+ vaultPosition,
+ }: {
+ vaultPosition: VaultPosition
+ }): Promise => {
+ return this.client.queryContractSmart(this.contractAddress, {
+ vault_position_value: {
+ vault_position: vaultPosition,
+ },
+ })
+ }
}
export interface MarsCreditManagerInterface extends MarsCreditManagerReadOnlyInterface {
contractAddress: string
@@ -313,9 +392,24 @@ export interface MarsCreditManagerInterface extends MarsCreditManagerReadOnlyInt
) => Promise
updateConfig: (
{
- newConfig,
+ updates,
}: {
- newConfig: ConfigUpdates
+ updates: ConfigUpdates
+ },
+ fee?: number | StdFee | 'auto',
+ memo?: string,
+ funds?: Coin[],
+ ) => Promise
+ updateOwner: (
+ fee?: number | StdFee | 'auto',
+ memo?: string,
+ funds?: Coin[],
+ ) => Promise
+ updateNftConfig: (
+ {
+ updates,
+ }: {
+ updates: NftConfigUpdates
},
fee?: number | StdFee | 'auto',
memo?: string,
@@ -343,6 +437,8 @@ export class MarsCreditManagerClient
this.createCreditAccount = this.createCreditAccount.bind(this)
this.updateCreditAccount = this.updateCreditAccount.bind(this)
this.updateConfig = this.updateConfig.bind(this)
+ this.updateOwner = this.updateOwner.bind(this)
+ this.updateNftConfig = this.updateNftConfig.bind(this)
this.callback = this.callback.bind(this)
}
@@ -390,9 +486,9 @@ export class MarsCreditManagerClient
}
updateConfig = async (
{
- newConfig,
+ updates,
}: {
- newConfig: ConfigUpdates
+ updates: ConfigUpdates
},
fee: number | StdFee | 'auto' = 'auto',
memo?: string,
@@ -403,7 +499,46 @@ export class MarsCreditManagerClient
this.contractAddress,
{
update_config: {
- new_config: newConfig,
+ updates,
+ },
+ },
+ fee,
+ memo,
+ funds,
+ )
+ }
+ updateOwner = async (
+ fee: number | StdFee | 'auto' = 'auto',
+ memo?: string,
+ funds?: Coin[],
+ ): Promise => {
+ return await this.client.execute(
+ this.sender,
+ this.contractAddress,
+ {
+ update_owner: {},
+ },
+ fee,
+ memo,
+ funds,
+ )
+ }
+ updateNftConfig = async (
+ {
+ updates,
+ }: {
+ updates: NftConfigUpdates
+ },
+ fee: number | StdFee | 'auto' = 'auto',
+ memo?: string,
+ funds?: Coin[],
+ ): Promise => {
+ return await this.client.execute(
+ this.sender,
+ this.contractAddress,
+ {
+ update_nft_config: {
+ updates,
},
},
fee,
diff --git a/src/types/generated/mars-credit-manager/MarsCreditManager.message-composer.ts b/src/types/generated/mars-credit-manager/MarsCreditManager.message-composer.ts
index 2d9a7314..a42bb2f8 100644
--- a/src/types/generated/mars-credit-manager/MarsCreditManager.message-composer.ts
+++ b/src/types/generated/mars-credit-manager/MarsCreditManager.message-composer.ts
@@ -1,6 +1,6 @@
// @ts-nocheck
/**
- * This file was automatically generated by @cosmwasm/ts-codegen@0.20.0.
+ * This file was automatically generated by @cosmwasm/ts-codegen@0.24.0.
* DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file,
* and run the @cosmwasm/ts-codegen generate command to regenerate this file.
*/
@@ -11,28 +11,36 @@ import { toUtf8 } from '@cosmjs/encoding'
import {
Action,
+ ActionAmount,
+ ActionCoin,
Addr,
ArrayOfCoin,
ArrayOfCoinBalanceResponseItem,
ArrayOfDebtShares,
+ ArrayOfLentShares,
ArrayOfSharesResponseItem,
ArrayOfString,
- ArrayOfVaultInstantiateConfig,
+ ArrayOfVaultInfoResponse,
ArrayOfVaultPositionResponseItem,
ArrayOfVaultWithBalance,
CallbackMsg,
Coin,
CoinBalanceResponseItem,
+ CoinValue,
ConfigResponse,
ConfigUpdates,
DebtAmount,
DebtShares,
Decimal,
ExecuteMsg,
- HealthResponse,
+ HealthContractBaseForString,
InstantiateMsg,
+ LentAmount,
+ LentShares,
LockingVaultAmount,
+ NftConfigUpdates,
OracleBaseForString,
+ OwnerUpdate,
Positions,
QueryMsg,
RedBankBaseForString,
@@ -45,10 +53,13 @@ import {
VaultBaseForAddr,
VaultBaseForString,
VaultConfig,
+ VaultInfoResponse,
VaultInstantiateConfig,
VaultPosition,
VaultPositionAmount,
VaultPositionResponseItem,
+ VaultPositionType,
+ VaultPositionValue,
VaultUnlockingPosition,
VaultWithBalance,
ZapperBaseForString,
@@ -69,9 +80,18 @@ export interface MarsCreditManagerMessage {
) => MsgExecuteContractEncodeObject
updateConfig: (
{
- newConfig,
+ updates,
}: {
- newConfig: ConfigUpdates
+ updates: ConfigUpdates
+ },
+ funds?: Coin[],
+ ) => MsgExecuteContractEncodeObject
+ updateOwner: (funds?: Coin[]) => MsgExecuteContractEncodeObject
+ updateNftConfig: (
+ {
+ updates,
+ }: {
+ updates: NftConfigUpdates
},
funds?: Coin[],
) => MsgExecuteContractEncodeObject
@@ -87,6 +107,8 @@ export class MarsCreditManagerMessageComposer implements MarsCreditManagerMessag
this.createCreditAccount = this.createCreditAccount.bind(this)
this.updateCreditAccount = this.updateCreditAccount.bind(this)
this.updateConfig = this.updateConfig.bind(this)
+ this.updateOwner = this.updateOwner.bind(this)
+ this.updateNftConfig = this.updateNftConfig.bind(this)
this.callback = this.callback.bind(this)
}
@@ -134,9 +156,9 @@ export class MarsCreditManagerMessageComposer implements MarsCreditManagerMessag
}
updateConfig = (
{
- newConfig,
+ updates,
}: {
- newConfig: ConfigUpdates
+ updates: ConfigUpdates
},
funds?: Coin[],
): MsgExecuteContractEncodeObject => {
@@ -148,7 +170,46 @@ export class MarsCreditManagerMessageComposer implements MarsCreditManagerMessag
msg: toUtf8(
JSON.stringify({
update_config: {
- new_config: newConfig,
+ updates,
+ },
+ }),
+ ),
+ funds,
+ }),
+ }
+ }
+ updateOwner = (funds?: Coin[]): MsgExecuteContractEncodeObject => {
+ return {
+ typeUrl: '/cosmwasm.wasm.v1.MsgExecuteContract',
+ value: MsgExecuteContract.fromPartial({
+ sender: this.sender,
+ contract: this.contractAddress,
+ msg: toUtf8(
+ JSON.stringify({
+ update_owner: {},
+ }),
+ ),
+ funds,
+ }),
+ }
+ }
+ updateNftConfig = (
+ {
+ updates,
+ }: {
+ updates: NftConfigUpdates
+ },
+ funds?: Coin[],
+ ): MsgExecuteContractEncodeObject => {
+ return {
+ typeUrl: '/cosmwasm.wasm.v1.MsgExecuteContract',
+ value: MsgExecuteContract.fromPartial({
+ sender: this.sender,
+ contract: this.contractAddress,
+ msg: toUtf8(
+ JSON.stringify({
+ update_nft_config: {
+ updates,
},
}),
),
diff --git a/src/types/generated/mars-credit-manager/MarsCreditManager.react-query.ts b/src/types/generated/mars-credit-manager/MarsCreditManager.react-query.ts
index 062ed033..907f8a1d 100644
--- a/src/types/generated/mars-credit-manager/MarsCreditManager.react-query.ts
+++ b/src/types/generated/mars-credit-manager/MarsCreditManager.react-query.ts
@@ -1,6 +1,6 @@
// @ts-nocheck
/**
- * This file was automatically generated by @cosmwasm/ts-codegen@0.20.0.
+ * This file was automatically generated by @cosmwasm/ts-codegen@0.24.0.
* DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file,
* and run the @cosmwasm/ts-codegen generate command to regenerate this file.
*/
@@ -11,28 +11,36 @@ import { StdFee } from '@cosmjs/amino'
import {
Action,
+ ActionAmount,
+ ActionCoin,
Addr,
ArrayOfCoin,
ArrayOfCoinBalanceResponseItem,
ArrayOfDebtShares,
+ ArrayOfLentShares,
ArrayOfSharesResponseItem,
ArrayOfString,
- ArrayOfVaultInstantiateConfig,
+ ArrayOfVaultInfoResponse,
ArrayOfVaultPositionResponseItem,
ArrayOfVaultWithBalance,
CallbackMsg,
Coin,
CoinBalanceResponseItem,
+ CoinValue,
ConfigResponse,
ConfigUpdates,
DebtAmount,
DebtShares,
Decimal,
ExecuteMsg,
- HealthResponse,
+ HealthContractBaseForString,
InstantiateMsg,
+ LentAmount,
+ LentShares,
LockingVaultAmount,
+ NftConfigUpdates,
OracleBaseForString,
+ OwnerUpdate,
Positions,
QueryMsg,
RedBankBaseForString,
@@ -45,10 +53,13 @@ import {
VaultBaseForAddr,
VaultBaseForString,
VaultConfig,
+ VaultInfoResponse,
VaultInstantiateConfig,
VaultPosition,
VaultPositionAmount,
VaultPositionResponseItem,
+ VaultPositionType,
+ VaultPositionValue,
VaultUnlockingPosition,
VaultWithBalance,
ZapperBaseForString,
@@ -66,9 +77,13 @@ export const marsCreditManagerQueryKeys = {
[
{ ...marsCreditManagerQueryKeys.address(contractAddress)[0], method: 'config', args },
] as const,
- vaultConfigs: (contractAddress: string | undefined, args?: Record) =>
+ vaultInfo: (contractAddress: string | undefined, args?: Record) =>
[
- { ...marsCreditManagerQueryKeys.address(contractAddress)[0], method: 'vault_configs', args },
+ { ...marsCreditManagerQueryKeys.address(contractAddress)[0], method: 'vault_info', args },
+ ] as const,
+ vaultsInfo: (contractAddress: string | undefined, args?: Record) =>
+ [
+ { ...marsCreditManagerQueryKeys.address(contractAddress)[0], method: 'vaults_info', args },
] as const,
allowedCoins: (contractAddress: string | undefined, args?: Record) =>
[
@@ -78,10 +93,6 @@ export const marsCreditManagerQueryKeys = {
[
{ ...marsCreditManagerQueryKeys.address(contractAddress)[0], method: 'positions', args },
] as const,
- health: (contractAddress: string | undefined, args?: Record) =>
- [
- { ...marsCreditManagerQueryKeys.address(contractAddress)[0], method: 'health', args },
- ] as const,
allCoinBalances: (contractAddress: string | undefined, args?: Record) =>
[
{
@@ -114,6 +125,30 @@ export const marsCreditManagerQueryKeys = {
args,
},
] as const,
+ allLentShares: (contractAddress: string | undefined, args?: Record) =>
+ [
+ {
+ ...marsCreditManagerQueryKeys.address(contractAddress)[0],
+ method: 'all_lent_shares',
+ args,
+ },
+ ] as const,
+ totalLentShares: (contractAddress: string | undefined, args?: Record) =>
+ [
+ {
+ ...marsCreditManagerQueryKeys.address(contractAddress)[0],
+ method: 'total_lent_shares',
+ args,
+ },
+ ] as const,
+ allTotalLentShares: (contractAddress: string | undefined, args?: Record) =>
+ [
+ {
+ ...marsCreditManagerQueryKeys.address(contractAddress)[0],
+ method: 'all_total_lent_shares',
+ args,
+ },
+ ] as const,
allVaultPositions: (contractAddress: string | undefined, args?: Record) =>
[
{
@@ -160,6 +195,14 @@ export const marsCreditManagerQueryKeys = {
args,
},
] as const,
+ vaultPositionValue: (contractAddress: string | undefined, args?: Record) =>
+ [
+ {
+ ...marsCreditManagerQueryKeys.address(contractAddress)[0],
+ method: 'vault_position_value',
+ args,
+ },
+ ] as const,
}
export interface MarsCreditManagerReactQuery {
client: MarsCreditManagerQueryClient | undefined
@@ -170,6 +213,28 @@ export interface MarsCreditManagerReactQuery {
initialData?: undefined
}
}
+export interface MarsCreditManagerVaultPositionValueQuery
+ extends MarsCreditManagerReactQuery {
+ args: {
+ vaultPosition: VaultPosition
+ }
+}
+export function useMarsCreditManagerVaultPositionValueQuery({
+ client,
+ args,
+ options,
+}: MarsCreditManagerVaultPositionValueQuery) {
+ return useQuery(
+ marsCreditManagerQueryKeys.vaultPositionValue(client?.contractAddress, args),
+ () =>
+ client
+ ? client.vaultPositionValue({
+ vaultPosition: args.vaultPosition,
+ })
+ : Promise.reject(new Error('Invalid client')),
+ { ...options, enabled: !!client && (options?.enabled != undefined ? options.enabled : true) },
+ )
+}
export interface MarsCreditManagerEstimateWithdrawLiquidityQuery
extends MarsCreditManagerReactQuery {
args: {
@@ -282,6 +347,66 @@ export function useMarsCreditManagerAllVaultPositionsQuery<
{ ...options, enabled: !!client && (options?.enabled != undefined ? options.enabled : true) },
)
}
+export interface MarsCreditManagerAllTotalLentSharesQuery
+ extends MarsCreditManagerReactQuery {
+ args: {
+ limit?: number
+ startAfter?: string
+ }
+}
+export function useMarsCreditManagerAllTotalLentSharesQuery({
+ client,
+ args,
+ options,
+}: MarsCreditManagerAllTotalLentSharesQuery) {
+ return useQuery(
+ marsCreditManagerQueryKeys.allTotalLentShares(client?.contractAddress, args),
+ () =>
+ client
+ ? client.allTotalLentShares({
+ limit: args.limit,
+ startAfter: args.startAfter,
+ })
+ : Promise.reject(new Error('Invalid client')),
+ { ...options, enabled: !!client && (options?.enabled != undefined ? options.enabled : true) },
+ )
+}
+export interface MarsCreditManagerTotalLentSharesQuery
+ extends MarsCreditManagerReactQuery {}
+export function useMarsCreditManagerTotalLentSharesQuery({
+ client,
+ options,
+}: MarsCreditManagerTotalLentSharesQuery) {
+ return useQuery(
+ marsCreditManagerQueryKeys.totalLentShares(client?.contractAddress),
+ () => (client ? client.totalLentShares() : Promise.reject(new Error('Invalid client'))),
+ { ...options, enabled: !!client && (options?.enabled != undefined ? options.enabled : true) },
+ )
+}
+export interface MarsCreditManagerAllLentSharesQuery
+ extends MarsCreditManagerReactQuery {
+ args: {
+ limit?: number
+ startAfter?: string[][]
+ }
+}
+export function useMarsCreditManagerAllLentSharesQuery({
+ client,
+ args,
+ options,
+}: MarsCreditManagerAllLentSharesQuery) {
+ return useQuery(
+ marsCreditManagerQueryKeys.allLentShares(client?.contractAddress, args),
+ () =>
+ client
+ ? client.allLentShares({
+ limit: args.limit,
+ startAfter: args.startAfter,
+ })
+ : Promise.reject(new Error('Invalid client')),
+ { ...options, enabled: !!client && (options?.enabled != undefined ? options.enabled : true) },
+ )
+}
export interface MarsCreditManagerAllTotalDebtSharesQuery
extends MarsCreditManagerReactQuery {
args: {
@@ -366,28 +491,6 @@ export function useMarsCreditManagerAllCoinBalancesQuery
- extends MarsCreditManagerReactQuery {
- args: {
- accountId: string
- }
-}
-export function useMarsCreditManagerHealthQuery({
- client,
- args,
- options,
-}: MarsCreditManagerHealthQuery) {
- return useQuery(
- marsCreditManagerQueryKeys.health(client?.contractAddress, args),
- () =>
- client
- ? client.health({
- accountId: args.accountId,
- })
- : Promise.reject(new Error('Invalid client')),
- { ...options, enabled: !!client && (options?.enabled != undefined ? options.enabled : true) },
- )
-}
export interface MarsCreditManagerPositionsQuery
extends MarsCreditManagerReactQuery {
args: {
@@ -434,23 +537,23 @@ export function useMarsCreditManagerAllowedCoinsQuery({
{ ...options, enabled: !!client && (options?.enabled != undefined ? options.enabled : true) },
)
}
-export interface MarsCreditManagerVaultConfigsQuery
- extends MarsCreditManagerReactQuery {
+export interface MarsCreditManagerVaultsInfoQuery
+ extends MarsCreditManagerReactQuery {
args: {
limit?: number
startAfter?: VaultBaseForString
}
}
-export function useMarsCreditManagerVaultConfigsQuery({
+export function useMarsCreditManagerVaultsInfoQuery({
client,
args,
options,
-}: MarsCreditManagerVaultConfigsQuery) {
- return useQuery(
- marsCreditManagerQueryKeys.vaultConfigs(client?.contractAddress, args),
+}: MarsCreditManagerVaultsInfoQuery) {
+ return useQuery(
+ marsCreditManagerQueryKeys.vaultsInfo(client?.contractAddress, args),
() =>
client
- ? client.vaultConfigs({
+ ? client.vaultsInfo({
limit: args.limit,
startAfter: args.startAfter,
})
@@ -458,6 +561,28 @@ export function useMarsCreditManagerVaultConfigsQuery
+ extends MarsCreditManagerReactQuery {
+ args: {
+ vault: VaultBaseForString
+ }
+}
+export function useMarsCreditManagerVaultInfoQuery({
+ client,
+ args,
+ options,
+}: MarsCreditManagerVaultInfoQuery) {
+ return useQuery(
+ marsCreditManagerQueryKeys.vaultInfo(client?.contractAddress, args),
+ () =>
+ client
+ ? client.vaultInfo({
+ vault: args.vault,
+ })
+ : Promise.reject(new Error('Invalid client')),
+ { ...options, enabled: !!client && (options?.enabled != undefined ? options.enabled : true) },
+ )
+}
export interface MarsCreditManagerConfigQuery
extends MarsCreditManagerReactQuery {}
export function useMarsCreditManagerConfigQuery({
@@ -472,7 +597,6 @@ export function useMarsCreditManagerConfigQuery({
}
export interface MarsCreditManagerCallbackMutation {
client: MarsCreditManagerClient
- msg: CallbackMsg
args?: {
fee?: number | StdFee | 'auto'
memo?: string
@@ -490,10 +614,52 @@ export function useMarsCreditManagerCallbackMutation(
options,
)
}
+export interface MarsCreditManagerUpdateNftConfigMutation {
+ client: MarsCreditManagerClient
+ msg: {
+ updates: NftConfigUpdates
+ }
+ args?: {
+ fee?: number | StdFee | 'auto'
+ memo?: string
+ funds?: Coin[]
+ }
+}
+export function useMarsCreditManagerUpdateNftConfigMutation(
+ options?: Omit<
+ UseMutationOptions,
+ 'mutationFn'
+ >,
+) {
+ return useMutation(
+ ({ client, msg, args: { fee, memo, funds } = {} }) =>
+ client.updateNftConfig(msg, fee, memo, funds),
+ options,
+ )
+}
+export interface MarsCreditManagerUpdateOwnerMutation {
+ client: MarsCreditManagerClient
+ args?: {
+ fee?: number | StdFee | 'auto'
+ memo?: string
+ funds?: Coin[]
+ }
+}
+export function useMarsCreditManagerUpdateOwnerMutation(
+ options?: Omit<
+ UseMutationOptions,
+ 'mutationFn'
+ >,
+) {
+ return useMutation(
+ ({ client, msg, args: { fee, memo, funds } = {} }) => client.updateOwner(msg, fee, memo, funds),
+ options,
+ )
+}
export interface MarsCreditManagerUpdateConfigMutation {
client: MarsCreditManagerClient
msg: {
- newConfig: ConfigUpdates
+ updates: ConfigUpdates
}
args?: {
fee?: number | StdFee | 'auto'
diff --git a/src/types/generated/mars-credit-manager/MarsCreditManager.types.ts b/src/types/generated/mars-credit-manager/MarsCreditManager.types.ts
index 5cefad83..db115e1c 100644
--- a/src/types/generated/mars-credit-manager/MarsCreditManager.types.ts
+++ b/src/types/generated/mars-credit-manager/MarsCreditManager.types.ts
@@ -1,25 +1,27 @@
// @ts-nocheck
/**
- * This file was automatically generated by @cosmwasm/ts-codegen@0.20.0.
+ * This file was automatically generated by @cosmwasm/ts-codegen@0.24.0.
* DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file,
* and run the @cosmwasm/ts-codegen generate command to regenerate this file.
*/
-export type Uint128 = string
+export type HealthContractBaseForString = string
export type Decimal = string
+export type Uint128 = string
export type OracleBaseForString = string
export type RedBankBaseForString = string
export type SwapperBaseForString = string
export type ZapperBaseForString = string
export interface InstantiateMsg {
allowed_coins: string[]
- allowed_vaults: VaultInstantiateConfig[]
+ health_contract: HealthContractBaseForString
max_close_factor: Decimal
- max_liquidation_bonus: Decimal
+ max_unlocking_positions: Uint128
oracle: OracleBaseForString
owner: string
red_bank: RedBankBaseForString
swapper: SwapperBaseForString
+ vault_configs: VaultInstantiateConfig[]
zapper: ZapperBaseForString
}
export interface VaultInstantiateConfig {
@@ -52,7 +54,15 @@ export type ExecuteMsg =
}
| {
update_config: {
- new_config: ConfigUpdates
+ updates: ConfigUpdates
+ }
+ }
+ | {
+ update_owner: OwnerUpdate
+ }
+ | {
+ update_nft_config: {
+ updates: NftConfigUpdates
}
}
| {
@@ -69,12 +79,14 @@ export type Action =
borrow: Coin
}
| {
- repay: Coin
+ lend: Coin
+ }
+ | {
+ repay: ActionCoin
}
| {
enter_vault: {
- amount?: Uint128 | null
- denom: string
+ coin: ActionCoin
vault: VaultBaseForString
}
}
@@ -107,31 +119,47 @@ export type Action =
liquidate_vault: {
debt_coin: Coin
liquidatee_account_id: string
+ position_type: VaultPositionType
request_vault: VaultBaseForString
}
}
| {
swap_exact_in: {
- coin_in: Coin
+ coin_in: ActionCoin
denom_out: string
slippage: Decimal
}
}
| {
provide_liquidity: {
- coins_in: Coin[]
+ coins_in: ActionCoin[]
lp_token_out: string
minimum_receive: Uint128
}
}
| {
withdraw_liquidity: {
- lp_token: Coin
+ lp_token: ActionCoin
}
}
| {
refund_all_coin_balances: {}
}
+export type ActionAmount =
+ | 'account_balance'
+ | {
+ exact: Uint128
+ }
+export type VaultPositionType = 'u_n_l_o_c_k_e_d' | 'l_o_c_k_e_d' | 'u_n_l_o_c_k_i_n_g'
+export type OwnerUpdate =
+ | {
+ propose_new_owner: {
+ proposed: string
+ }
+ }
+ | 'clear_proposed'
+ | 'accept_proposed'
+ | 'abolish_owner_role'
export type CallbackMsg =
| {
withdraw: {
@@ -148,20 +176,26 @@ export type CallbackMsg =
}
| {
repay: {
+ account_id: string
+ coin: ActionCoin
+ }
+ }
+ | {
+ lend: {
account_id: string
coin: Coin
}
}
| {
- assert_below_max_l_t_v: {
+ assert_max_ltv: {
account_id: string
+ prev_max_ltv_health_factor?: Decimal | null
}
}
| {
enter_vault: {
account_id: string
- amount?: Uint128 | null
- denom: string
+ coin: ActionCoin
vault: VaultBaseForAddr
}
}
@@ -179,13 +213,6 @@ export type CallbackMsg =
vault: VaultBaseForAddr
}
}
- | {
- force_exit_vault: {
- account_id: string
- amount: Uint128
- vault: VaultBaseForAddr
- }
- }
| {
request_vault_unlock: {
account_id: string
@@ -213,13 +240,14 @@ export type CallbackMsg =
debt_coin: Coin
liquidatee_account_id: string
liquidator_account_id: string
+ position_type: VaultPositionType
request_vault: VaultBaseForAddr
}
}
| {
swap_exact_in: {
account_id: string
- coin_in: Coin
+ coin_in: ActionCoin
denom_out: string
slippage: Decimal
}
@@ -233,7 +261,7 @@ export type CallbackMsg =
| {
provide_liquidity: {
account_id: string
- coins_in: Coin[]
+ coins_in: ActionCoin[]
lp_token_out: string
minimum_receive: Uint128
}
@@ -241,12 +269,7 @@ export type CallbackMsg =
| {
withdraw_liquidity: {
account_id: string
- lp_token: Coin
- }
- }
- | {
- assert_one_vault_position_only: {
- account_id: string
+ lp_token: ActionCoin
}
}
| {
@@ -255,18 +278,26 @@ export type CallbackMsg =
}
}
export type Addr = string
+export interface ActionCoin {
+ amount: ActionAmount
+ denom: string
+}
export interface ConfigUpdates {
account_nft?: string | null
allowed_coins?: string[] | null
+ health_contract?: HealthContractBaseForString | null
max_close_factor?: Decimal | null
- max_liquidation_bonus?: Decimal | null
+ max_unlocking_positions?: Uint128 | null
oracle?: OracleBaseForString | null
- owner?: string | null
- red_bank?: RedBankBaseForString | null
swapper?: SwapperBaseForString | null
vault_configs?: VaultInstantiateConfig[] | null
zapper?: ZapperBaseForString | null
}
+export interface NftConfigUpdates {
+ health_contract_addr?: string | null
+ max_value_for_burn?: Uint128 | null
+ proposed_new_minter?: string | null
+}
export interface VaultBaseForAddr {
address: Addr
}
@@ -275,7 +306,12 @@ export type QueryMsg =
config: {}
}
| {
- vault_configs: {
+ vault_info: {
+ vault: VaultBaseForString
+ }
+ }
+ | {
+ vaults_info: {
limit?: number | null
start_after?: VaultBaseForString | null
}
@@ -291,11 +327,6 @@ export type QueryMsg =
account_id: string
}
}
- | {
- health: {
- account_id: string
- }
- }
| {
all_coin_balances: {
limit?: number | null
@@ -317,6 +348,21 @@ export type QueryMsg =
start_after?: string | null
}
}
+ | {
+ all_lent_shares: {
+ limit?: number | null
+ start_after?: [string, string] | null
+ }
+ }
+ | {
+ total_lent_shares: string
+ }
+ | {
+ all_total_lent_shares: {
+ limit?: number | null
+ start_after?: string | null
+ }
+ }
| {
all_vault_positions: {
limit?: number | null
@@ -345,6 +391,33 @@ export type QueryMsg =
lp_token: Coin
}
}
+ | {
+ vault_position_value: {
+ vault_position: VaultPosition
+ }
+ }
+export type VaultPositionAmount =
+ | {
+ unlocked: VaultAmount
+ }
+ | {
+ locking: LockingVaultAmount
+ }
+export type VaultAmount = string
+export type VaultAmount1 = string
+export type UnlockingPositions = VaultUnlockingPosition[]
+export interface VaultPosition {
+ amount: VaultPositionAmount
+ vault: VaultBaseForAddr
+}
+export interface LockingVaultAmount {
+ locked: VaultAmount1
+ unlocking: UnlockingPositions
+}
+export interface VaultUnlockingPosition {
+ coin: Coin
+ id: number
+}
export type ArrayOfCoinBalanceResponseItem = CoinBalanceResponseItem[]
export interface CoinBalanceResponseItem {
account_id: string
@@ -362,64 +435,40 @@ export interface DebtShares {
denom: string
shares: Uint128
}
+export type ArrayOfLentShares = LentShares[]
+export interface LentShares {
+ denom: string
+ shares: Uint128
+}
export type ArrayOfVaultWithBalance = VaultWithBalance[]
export interface VaultWithBalance {
balance: Uint128
vault: VaultBaseForAddr
}
-export type VaultPositionAmount =
- | {
- unlocked: VaultAmount
- }
- | {
- locking: LockingVaultAmount
- }
-export type VaultAmount = string
-export type VaultAmount1 = string
-export type UnlockingPositions = VaultUnlockingPosition[]
export type ArrayOfVaultPositionResponseItem = VaultPositionResponseItem[]
export interface VaultPositionResponseItem {
account_id: string
position: VaultPosition
}
-export interface VaultPosition {
- amount: VaultPositionAmount
- vault: VaultBaseForAddr
-}
-export interface LockingVaultAmount {
- locked: VaultAmount1
- unlocking: UnlockingPositions
-}
-export interface VaultUnlockingPosition {
- coin: Coin
- id: number
-}
export type ArrayOfString = string[]
export interface ConfigResponse {
account_nft?: string | null
+ health_contract: string
max_close_factor: Decimal
- max_liquidation_bonus: Decimal
+ max_unlocking_positions: Uint128
oracle: string
- owner: string
+ owner?: string | null
+ proposed_new_owner?: string | null
red_bank: string
swapper: string
zapper: string
}
export type ArrayOfCoin = Coin[]
-export interface HealthResponse {
- above_max_ltv: boolean
- liquidatable: boolean
- liquidation_health_factor?: Decimal | null
- liquidation_threshold_adjusted_collateral: Decimal
- max_ltv_adjusted_collateral: Decimal
- max_ltv_health_factor?: Decimal | null
- total_collateral_value: Decimal
- total_debt_value: Decimal
-}
export interface Positions {
account_id: string
- coins: Coin[]
debts: DebtAmount[]
+ deposits: Coin[]
+ lends: LentAmount[]
vaults: VaultPosition[]
}
export interface DebtAmount {
@@ -427,4 +476,23 @@ export interface DebtAmount {
denom: string
shares: Uint128
}
-export type ArrayOfVaultInstantiateConfig = VaultInstantiateConfig[]
+export interface LentAmount {
+ amount: Uint128
+ denom: string
+ shares: Uint128
+}
+export interface VaultInfoResponse {
+ config: VaultConfig
+ utilization: Coin
+ vault: VaultBaseForString
+}
+export interface VaultPositionValue {
+ base_coin: CoinValue
+ vault_coin: CoinValue
+}
+export interface CoinValue {
+ amount: Uint128
+ denom: string
+ value: Uint128
+}
+export type ArrayOfVaultInfoResponse = VaultInfoResponse[]
diff --git a/src/types/generated/mars-credit-manager/bundle.ts b/src/types/generated/mars-credit-manager/bundle.ts
index 5878326c..fbcf26e0 100644
--- a/src/types/generated/mars-credit-manager/bundle.ts
+++ b/src/types/generated/mars-credit-manager/bundle.ts
@@ -1,6 +1,6 @@
// @ts-nocheck
/**
- * This file was automatically generated by @cosmwasm/ts-codegen@0.20.0.
+ * This file was automatically generated by @cosmwasm/ts-codegen@0.24.0.
* DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file,
* and run the @cosmwasm/ts-codegen generate command to regenerate this file.
*/
diff --git a/src/types/generated/mars-mock-credit-manager/MarsMockCreditManager.client.ts b/src/types/generated/mars-mock-credit-manager/MarsMockCreditManager.client.ts
new file mode 100644
index 00000000..d72a2220
--- /dev/null
+++ b/src/types/generated/mars-mock-credit-manager/MarsMockCreditManager.client.ts
@@ -0,0 +1,478 @@
+// @ts-nocheck
+/**
+ * This file was automatically generated by @cosmwasm/ts-codegen@0.24.0.
+ * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file,
+ * and run the @cosmwasm/ts-codegen generate command to regenerate this file.
+ */
+
+import { CosmWasmClient, ExecuteResult, SigningCosmWasmClient } from '@cosmjs/cosmwasm-stargate'
+import { StdFee } from '@cosmjs/amino'
+
+import {
+ Addr,
+ ArrayOfCoin,
+ ArrayOfCoinBalanceResponseItem,
+ ArrayOfDebtShares,
+ ArrayOfLentShares,
+ ArrayOfSharesResponseItem,
+ ArrayOfString,
+ ArrayOfVaultInfoResponse,
+ ArrayOfVaultPositionResponseItem,
+ ArrayOfVaultWithBalance,
+ Coin,
+ CoinBalanceResponseItem,
+ CoinValue,
+ ConfigResponse,
+ DebtAmount,
+ DebtShares,
+ Decimal,
+ ExecuteMsg,
+ InstantiateMsg,
+ LentAmount,
+ LentShares,
+ LockingVaultAmount,
+ Positions,
+ QueryMsg,
+ SharesResponseItem,
+ Uint128,
+ UnlockingPositions,
+ VaultAmount,
+ VaultAmount1,
+ VaultBaseForAddr,
+ VaultBaseForString,
+ VaultConfig,
+ VaultInfoResponse,
+ VaultPosition,
+ VaultPositionAmount,
+ VaultPositionResponseItem,
+ VaultPositionValue,
+ VaultUnlockingPosition,
+ VaultWithBalance,
+} from './MarsMockCreditManager.types'
+export interface MarsMockCreditManagerReadOnlyInterface {
+ contractAddress: string
+ config: () => Promise
+ vaultInfo: ({ vault }: { vault: VaultBaseForString }) => Promise
+ vaultsInfo: ({
+ limit,
+ startAfter,
+ }: {
+ limit?: number
+ startAfter?: VaultBaseForString
+ }) => Promise
+ allowedCoins: ({
+ limit,
+ startAfter,
+ }: {
+ limit?: number
+ startAfter?: string
+ }) => Promise
+ positions: ({ accountId }: { accountId: string }) => Promise
+ allCoinBalances: ({
+ limit,
+ startAfter,
+ }: {
+ limit?: number
+ startAfter?: string[][]
+ }) => Promise
+ allDebtShares: ({
+ limit,
+ startAfter,
+ }: {
+ limit?: number
+ startAfter?: string[][]
+ }) => Promise
+ totalDebtShares: () => Promise
+ allTotalDebtShares: ({
+ limit,
+ startAfter,
+ }: {
+ limit?: number
+ startAfter?: string
+ }) => Promise
+ allLentShares: ({
+ limit,
+ startAfter,
+ }: {
+ limit?: number
+ startAfter?: string[][]
+ }) => Promise
+ totalLentShares: () => Promise
+ allTotalLentShares: ({
+ limit,
+ startAfter,
+ }: {
+ limit?: number
+ startAfter?: string
+ }) => Promise
+ allVaultPositions: ({
+ limit,
+ startAfter,
+ }: {
+ limit?: number
+ startAfter?: string[][]
+ }) => Promise
+ totalVaultCoinBalance: ({ vault }: { vault: VaultBaseForString }) => Promise
+ allTotalVaultCoinBalances: ({
+ limit,
+ startAfter,
+ }: {
+ limit?: number
+ startAfter?: VaultBaseForString
+ }) => Promise
+ estimateProvideLiquidity: ({
+ coinsIn,
+ lpTokenOut,
+ }: {
+ coinsIn: Coin[]
+ lpTokenOut: string
+ }) => Promise
+ estimateWithdrawLiquidity: ({ lpToken }: { lpToken: Coin }) => Promise
+ vaultPositionValue: ({
+ vaultPosition,
+ }: {
+ vaultPosition: VaultPosition
+ }) => Promise
+}
+export class MarsMockCreditManagerQueryClient implements MarsMockCreditManagerReadOnlyInterface {
+ client: CosmWasmClient
+ contractAddress: string
+
+ constructor(client: CosmWasmClient, contractAddress: string) {
+ this.client = client
+ this.contractAddress = contractAddress
+ this.config = this.config.bind(this)
+ this.vaultInfo = this.vaultInfo.bind(this)
+ this.vaultsInfo = this.vaultsInfo.bind(this)
+ this.allowedCoins = this.allowedCoins.bind(this)
+ this.positions = this.positions.bind(this)
+ this.allCoinBalances = this.allCoinBalances.bind(this)
+ this.allDebtShares = this.allDebtShares.bind(this)
+ this.totalDebtShares = this.totalDebtShares.bind(this)
+ this.allTotalDebtShares = this.allTotalDebtShares.bind(this)
+ this.allLentShares = this.allLentShares.bind(this)
+ this.totalLentShares = this.totalLentShares.bind(this)
+ this.allTotalLentShares = this.allTotalLentShares.bind(this)
+ this.allVaultPositions = this.allVaultPositions.bind(this)
+ this.totalVaultCoinBalance = this.totalVaultCoinBalance.bind(this)
+ this.allTotalVaultCoinBalances = this.allTotalVaultCoinBalances.bind(this)
+ this.estimateProvideLiquidity = this.estimateProvideLiquidity.bind(this)
+ this.estimateWithdrawLiquidity = this.estimateWithdrawLiquidity.bind(this)
+ this.vaultPositionValue = this.vaultPositionValue.bind(this)
+ }
+
+ config = async (): Promise => {
+ return this.client.queryContractSmart(this.contractAddress, {
+ config: {},
+ })
+ }
+ vaultInfo = async ({ vault }: { vault: VaultBaseForString }): Promise => {
+ return this.client.queryContractSmart(this.contractAddress, {
+ vault_info: {
+ vault,
+ },
+ })
+ }
+ vaultsInfo = async ({
+ limit,
+ startAfter,
+ }: {
+ limit?: number
+ startAfter?: VaultBaseForString
+ }): Promise => {
+ return this.client.queryContractSmart(this.contractAddress, {
+ vaults_info: {
+ limit,
+ start_after: startAfter,
+ },
+ })
+ }
+ allowedCoins = async ({
+ limit,
+ startAfter,
+ }: {
+ limit?: number
+ startAfter?: string
+ }): Promise => {
+ return this.client.queryContractSmart(this.contractAddress, {
+ allowed_coins: {
+ limit,
+ start_after: startAfter,
+ },
+ })
+ }
+ positions = async ({ accountId }: { accountId: string }): Promise => {
+ return this.client.queryContractSmart(this.contractAddress, {
+ positions: {
+ account_id: accountId,
+ },
+ })
+ }
+ allCoinBalances = async ({
+ limit,
+ startAfter,
+ }: {
+ limit?: number
+ startAfter?: string[][]
+ }): Promise => {
+ return this.client.queryContractSmart(this.contractAddress, {
+ all_coin_balances: {
+ limit,
+ start_after: startAfter,
+ },
+ })
+ }
+ allDebtShares = async ({
+ limit,
+ startAfter,
+ }: {
+ limit?: number
+ startAfter?: string[][]
+ }): Promise => {
+ return this.client.queryContractSmart(this.contractAddress, {
+ all_debt_shares: {
+ limit,
+ start_after: startAfter,
+ },
+ })
+ }
+ totalDebtShares = async (): Promise => {
+ return this.client.queryContractSmart(this.contractAddress, {
+ total_debt_shares: {},
+ })
+ }
+ allTotalDebtShares = async ({
+ limit,
+ startAfter,
+ }: {
+ limit?: number
+ startAfter?: string
+ }): Promise => {
+ return this.client.queryContractSmart(this.contractAddress, {
+ all_total_debt_shares: {
+ limit,
+ start_after: startAfter,
+ },
+ })
+ }
+ allLentShares = async ({
+ limit,
+ startAfter,
+ }: {
+ limit?: number
+ startAfter?: string[][]
+ }): Promise => {
+ return this.client.queryContractSmart(this.contractAddress, {
+ all_lent_shares: {
+ limit,
+ start_after: startAfter,
+ },
+ })
+ }
+ totalLentShares = async (): Promise => {
+ return this.client.queryContractSmart(this.contractAddress, {
+ total_lent_shares: {},
+ })
+ }
+ allTotalLentShares = async ({
+ limit,
+ startAfter,
+ }: {
+ limit?: number
+ startAfter?: string
+ }): Promise => {
+ return this.client.queryContractSmart(this.contractAddress, {
+ all_total_lent_shares: {
+ limit,
+ start_after: startAfter,
+ },
+ })
+ }
+ allVaultPositions = async ({
+ limit,
+ startAfter,
+ }: {
+ limit?: number
+ startAfter?: string[][]
+ }): Promise => {
+ return this.client.queryContractSmart(this.contractAddress, {
+ all_vault_positions: {
+ limit,
+ start_after: startAfter,
+ },
+ })
+ }
+ totalVaultCoinBalance = async ({ vault }: { vault: VaultBaseForString }): Promise => {
+ return this.client.queryContractSmart(this.contractAddress, {
+ total_vault_coin_balance: {
+ vault,
+ },
+ })
+ }
+ allTotalVaultCoinBalances = async ({
+ limit,
+ startAfter,
+ }: {
+ limit?: number
+ startAfter?: VaultBaseForString
+ }): Promise => {
+ return this.client.queryContractSmart(this.contractAddress, {
+ all_total_vault_coin_balances: {
+ limit,
+ start_after: startAfter,
+ },
+ })
+ }
+ estimateProvideLiquidity = async ({
+ coinsIn,
+ lpTokenOut,
+ }: {
+ coinsIn: Coin[]
+ lpTokenOut: string
+ }): Promise => {
+ return this.client.queryContractSmart(this.contractAddress, {
+ estimate_provide_liquidity: {
+ coins_in: coinsIn,
+ lp_token_out: lpTokenOut,
+ },
+ })
+ }
+ estimateWithdrawLiquidity = async ({ lpToken }: { lpToken: Coin }): Promise => {
+ return this.client.queryContractSmart(this.contractAddress, {
+ estimate_withdraw_liquidity: {
+ lp_token: lpToken,
+ },
+ })
+ }
+ vaultPositionValue = async ({
+ vaultPosition,
+ }: {
+ vaultPosition: VaultPosition
+ }): Promise => {
+ return this.client.queryContractSmart(this.contractAddress, {
+ vault_position_value: {
+ vault_position: vaultPosition,
+ },
+ })
+ }
+}
+export interface MarsMockCreditManagerInterface extends MarsMockCreditManagerReadOnlyInterface {
+ contractAddress: string
+ sender: string
+ setPositionsResponse: (
+ {
+ accountId,
+ positions,
+ }: {
+ accountId: string
+ positions: Positions
+ },
+ fee?: number | StdFee | 'auto',
+ memo?: string,
+ funds?: Coin[],
+ ) => Promise
+ setAllowedCoins: (
+ fee?: number | StdFee | 'auto',
+ memo?: string,
+ funds?: Coin[],
+ ) => Promise
+ setVaultConfig: (
+ {
+ address,
+ config,
+ }: {
+ address: string
+ config: VaultConfig
+ },
+ fee?: number | StdFee | 'auto',
+ memo?: string,
+ funds?: Coin[],
+ ) => Promise
+}
+export class MarsMockCreditManagerClient
+ extends MarsMockCreditManagerQueryClient
+ implements MarsMockCreditManagerInterface
+{
+ client: SigningCosmWasmClient
+ sender: string
+ contractAddress: string
+
+ constructor(client: SigningCosmWasmClient, sender: string, contractAddress: string) {
+ super(client, contractAddress)
+ this.client = client
+ this.sender = sender
+ this.contractAddress = contractAddress
+ this.setPositionsResponse = this.setPositionsResponse.bind(this)
+ this.setAllowedCoins = this.setAllowedCoins.bind(this)
+ this.setVaultConfig = this.setVaultConfig.bind(this)
+ }
+
+ setPositionsResponse = async (
+ {
+ accountId,
+ positions,
+ }: {
+ accountId: string
+ positions: Positions
+ },
+ fee: number | StdFee | 'auto' = 'auto',
+ memo?: string,
+ funds?: Coin[],
+ ): Promise => {
+ return await this.client.execute(
+ this.sender,
+ this.contractAddress,
+ {
+ set_positions_response: {
+ account_id: accountId,
+ positions,
+ },
+ },
+ fee,
+ memo,
+ funds,
+ )
+ }
+ setAllowedCoins = async (
+ fee: number | StdFee | 'auto' = 'auto',
+ memo?: string,
+ funds?: Coin[],
+ ): Promise => {
+ return await this.client.execute(
+ this.sender,
+ this.contractAddress,
+ {
+ set_allowed_coins: {},
+ },
+ fee,
+ memo,
+ funds,
+ )
+ }
+ setVaultConfig = async (
+ {
+ address,
+ config,
+ }: {
+ address: string
+ config: VaultConfig
+ },
+ fee: number | StdFee | 'auto' = 'auto',
+ memo?: string,
+ funds?: Coin[],
+ ): Promise => {
+ return await this.client.execute(
+ this.sender,
+ this.contractAddress,
+ {
+ set_vault_config: {
+ address,
+ config,
+ },
+ },
+ fee,
+ memo,
+ funds,
+ )
+ }
+}
diff --git a/src/types/generated/mars-mock-credit-manager/MarsMockCreditManager.message-composer.ts b/src/types/generated/mars-mock-credit-manager/MarsMockCreditManager.message-composer.ts
new file mode 100644
index 00000000..11f60322
--- /dev/null
+++ b/src/types/generated/mars-mock-credit-manager/MarsMockCreditManager.message-composer.ts
@@ -0,0 +1,159 @@
+// @ts-nocheck
+/**
+ * This file was automatically generated by @cosmwasm/ts-codegen@0.24.0.
+ * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file,
+ * and run the @cosmwasm/ts-codegen generate command to regenerate this file.
+ */
+
+import { MsgExecuteContractEncodeObject } from 'cosmwasm'
+import { MsgExecuteContract } from 'cosmjs-types/cosmwasm/wasm/v1/tx'
+import { toUtf8 } from '@cosmjs/encoding'
+
+import {
+ Addr,
+ ArrayOfCoin,
+ ArrayOfCoinBalanceResponseItem,
+ ArrayOfDebtShares,
+ ArrayOfLentShares,
+ ArrayOfSharesResponseItem,
+ ArrayOfString,
+ ArrayOfVaultInfoResponse,
+ ArrayOfVaultPositionResponseItem,
+ ArrayOfVaultWithBalance,
+ Coin,
+ CoinBalanceResponseItem,
+ CoinValue,
+ ConfigResponse,
+ DebtAmount,
+ DebtShares,
+ Decimal,
+ ExecuteMsg,
+ InstantiateMsg,
+ LentAmount,
+ LentShares,
+ LockingVaultAmount,
+ Positions,
+ QueryMsg,
+ SharesResponseItem,
+ Uint128,
+ UnlockingPositions,
+ VaultAmount,
+ VaultAmount1,
+ VaultBaseForAddr,
+ VaultBaseForString,
+ VaultConfig,
+ VaultInfoResponse,
+ VaultPosition,
+ VaultPositionAmount,
+ VaultPositionResponseItem,
+ VaultPositionValue,
+ VaultUnlockingPosition,
+ VaultWithBalance,
+} from './MarsMockCreditManager.types'
+export interface MarsMockCreditManagerMessage {
+ contractAddress: string
+ sender: string
+ setPositionsResponse: (
+ {
+ accountId,
+ positions,
+ }: {
+ accountId: string
+ positions: Positions
+ },
+ funds?: Coin[],
+ ) => MsgExecuteContractEncodeObject
+ setAllowedCoins: (funds?: Coin[]) => MsgExecuteContractEncodeObject
+ setVaultConfig: (
+ {
+ address,
+ config,
+ }: {
+ address: string
+ config: VaultConfig
+ },
+ funds?: Coin[],
+ ) => MsgExecuteContractEncodeObject
+}
+export class MarsMockCreditManagerMessageComposer implements MarsMockCreditManagerMessage {
+ sender: string
+ contractAddress: string
+
+ constructor(sender: string, contractAddress: string) {
+ this.sender = sender
+ this.contractAddress = contractAddress
+ this.setPositionsResponse = this.setPositionsResponse.bind(this)
+ this.setAllowedCoins = this.setAllowedCoins.bind(this)
+ this.setVaultConfig = this.setVaultConfig.bind(this)
+ }
+
+ setPositionsResponse = (
+ {
+ accountId,
+ positions,
+ }: {
+ accountId: string
+ positions: Positions
+ },
+ funds?: Coin[],
+ ): MsgExecuteContractEncodeObject => {
+ return {
+ typeUrl: '/cosmwasm.wasm.v1.MsgExecuteContract',
+ value: MsgExecuteContract.fromPartial({
+ sender: this.sender,
+ contract: this.contractAddress,
+ msg: toUtf8(
+ JSON.stringify({
+ set_positions_response: {
+ account_id: accountId,
+ positions,
+ },
+ }),
+ ),
+ funds,
+ }),
+ }
+ }
+ setAllowedCoins = (funds?: Coin[]): MsgExecuteContractEncodeObject => {
+ return {
+ typeUrl: '/cosmwasm.wasm.v1.MsgExecuteContract',
+ value: MsgExecuteContract.fromPartial({
+ sender: this.sender,
+ contract: this.contractAddress,
+ msg: toUtf8(
+ JSON.stringify({
+ set_allowed_coins: {},
+ }),
+ ),
+ funds,
+ }),
+ }
+ }
+ setVaultConfig = (
+ {
+ address,
+ config,
+ }: {
+ address: string
+ config: VaultConfig
+ },
+ funds?: Coin[],
+ ): MsgExecuteContractEncodeObject => {
+ return {
+ typeUrl: '/cosmwasm.wasm.v1.MsgExecuteContract',
+ value: MsgExecuteContract.fromPartial({
+ sender: this.sender,
+ contract: this.contractAddress,
+ msg: toUtf8(
+ JSON.stringify({
+ set_vault_config: {
+ address,
+ config,
+ },
+ }),
+ ),
+ funds,
+ }),
+ }
+ }
+}
diff --git a/src/types/generated/mars-mock-credit-manager/MarsMockCreditManager.react-query.ts b/src/types/generated/mars-mock-credit-manager/MarsMockCreditManager.react-query.ts
new file mode 100644
index 00000000..7a80faca
--- /dev/null
+++ b/src/types/generated/mars-mock-credit-manager/MarsMockCreditManager.react-query.ts
@@ -0,0 +1,659 @@
+// @ts-nocheck
+/**
+ * This file was automatically generated by @cosmwasm/ts-codegen@0.24.0.
+ * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file,
+ * and run the @cosmwasm/ts-codegen generate command to regenerate this file.
+ */
+
+import { useMutation, UseMutationOptions, useQuery, UseQueryOptions } from '@tanstack/react-query'
+import { ExecuteResult } from '@cosmjs/cosmwasm-stargate'
+import { StdFee } from '@cosmjs/amino'
+
+import {
+ Addr,
+ ArrayOfCoin,
+ ArrayOfCoinBalanceResponseItem,
+ ArrayOfDebtShares,
+ ArrayOfLentShares,
+ ArrayOfSharesResponseItem,
+ ArrayOfString,
+ ArrayOfVaultInfoResponse,
+ ArrayOfVaultPositionResponseItem,
+ ArrayOfVaultWithBalance,
+ Coin,
+ CoinBalanceResponseItem,
+ CoinValue,
+ ConfigResponse,
+ DebtAmount,
+ DebtShares,
+ Decimal,
+ ExecuteMsg,
+ InstantiateMsg,
+ LentAmount,
+ LentShares,
+ LockingVaultAmount,
+ Positions,
+ QueryMsg,
+ SharesResponseItem,
+ Uint128,
+ UnlockingPositions,
+ VaultAmount,
+ VaultAmount1,
+ VaultBaseForAddr,
+ VaultBaseForString,
+ VaultConfig,
+ VaultInfoResponse,
+ VaultPosition,
+ VaultPositionAmount,
+ VaultPositionResponseItem,
+ VaultPositionValue,
+ VaultUnlockingPosition,
+ VaultWithBalance,
+} from './MarsMockCreditManager.types'
+import {
+ MarsMockCreditManagerClient,
+ MarsMockCreditManagerQueryClient,
+} from './MarsMockCreditManager.client'
+export const marsMockCreditManagerQueryKeys = {
+ contract: [
+ {
+ contract: 'marsMockCreditManager',
+ },
+ ] as const,
+ address: (contractAddress: string | undefined) =>
+ [{ ...marsMockCreditManagerQueryKeys.contract[0], address: contractAddress }] as const,
+ config: (contractAddress: string | undefined, args?: Record) =>
+ [
+ { ...marsMockCreditManagerQueryKeys.address(contractAddress)[0], method: 'config', args },
+ ] as const,
+ vaultInfo: (contractAddress: string | undefined, args?: Record) =>
+ [
+ { ...marsMockCreditManagerQueryKeys.address(contractAddress)[0], method: 'vault_info', args },
+ ] as const,
+ vaultsInfo: (contractAddress: string | undefined, args?: Record) =>
+ [
+ {
+ ...marsMockCreditManagerQueryKeys.address(contractAddress)[0],
+ method: 'vaults_info',
+ args,
+ },
+ ] as const,
+ allowedCoins: (contractAddress: string | undefined, args?: Record) =>
+ [
+ {
+ ...marsMockCreditManagerQueryKeys.address(contractAddress)[0],
+ method: 'allowed_coins',
+ args,
+ },
+ ] as const,
+ positions: (contractAddress: string | undefined, args?: Record) =>
+ [
+ { ...marsMockCreditManagerQueryKeys.address(contractAddress)[0], method: 'positions', args },
+ ] as const,
+ allCoinBalances: (contractAddress: string | undefined, args?: Record) =>
+ [
+ {
+ ...marsMockCreditManagerQueryKeys.address(contractAddress)[0],
+ method: 'all_coin_balances',
+ args,
+ },
+ ] as const,
+ allDebtShares: (contractAddress: string | undefined, args?: Record) =>
+ [
+ {
+ ...marsMockCreditManagerQueryKeys.address(contractAddress)[0],
+ method: 'all_debt_shares',
+ args,
+ },
+ ] as const,
+ totalDebtShares: (contractAddress: string | undefined, args?: Record) =>
+ [
+ {
+ ...marsMockCreditManagerQueryKeys.address(contractAddress)[0],
+ method: 'total_debt_shares',
+ args,
+ },
+ ] as const,
+ allTotalDebtShares: (contractAddress: string | undefined, args?: Record) =>
+ [
+ {
+ ...marsMockCreditManagerQueryKeys.address(contractAddress)[0],
+ method: 'all_total_debt_shares',
+ args,
+ },
+ ] as const,
+ allLentShares: (contractAddress: string | undefined, args?: Record) =>
+ [
+ {
+ ...marsMockCreditManagerQueryKeys.address(contractAddress)[0],
+ method: 'all_lent_shares',
+ args,
+ },
+ ] as const,
+ totalLentShares: (contractAddress: string | undefined, args?: Record) =>
+ [
+ {
+ ...marsMockCreditManagerQueryKeys.address(contractAddress)[0],
+ method: 'total_lent_shares',
+ args,
+ },
+ ] as const,
+ allTotalLentShares: (contractAddress: string | undefined, args?: Record) =>
+ [
+ {
+ ...marsMockCreditManagerQueryKeys.address(contractAddress)[0],
+ method: 'all_total_lent_shares',
+ args,
+ },
+ ] as const,
+ allVaultPositions: (contractAddress: string | undefined, args?: Record) =>
+ [
+ {
+ ...marsMockCreditManagerQueryKeys.address(contractAddress)[0],
+ method: 'all_vault_positions',
+ args,
+ },
+ ] as const,
+ totalVaultCoinBalance: (contractAddress: string | undefined, args?: Record) =>
+ [
+ {
+ ...marsMockCreditManagerQueryKeys.address(contractAddress)[0],
+ method: 'total_vault_coin_balance',
+ args,
+ },
+ ] as const,
+ allTotalVaultCoinBalances: (
+ contractAddress: string | undefined,
+ args?: Record,
+ ) =>
+ [
+ {
+ ...marsMockCreditManagerQueryKeys.address(contractAddress)[0],
+ method: 'all_total_vault_coin_balances',
+ args,
+ },
+ ] as const,
+ estimateProvideLiquidity: (contractAddress: string | undefined, args?: Record) =>
+ [
+ {
+ ...marsMockCreditManagerQueryKeys.address(contractAddress)[0],
+ method: 'estimate_provide_liquidity',
+ args,
+ },
+ ] as const,
+ estimateWithdrawLiquidity: (
+ contractAddress: string | undefined,
+ args?: Record,
+ ) =>
+ [
+ {
+ ...marsMockCreditManagerQueryKeys.address(contractAddress)[0],
+ method: 'estimate_withdraw_liquidity',
+ args,
+ },
+ ] as const,
+ vaultPositionValue: (contractAddress: string | undefined, args?: Record