Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
117 changes: 117 additions & 0 deletions docs/smart-accounts/guides/typescript-viem.mdx
Original file line number Diff line number Diff line change
@@ -0,0 +1,117 @@
---
title: TypeScript + Viem
description: TypeScript and Viem guides for Flare Smart Accounts on Coston2
keywords:
[
flare-smart-accounts,
viem,
typescript,
xrpl,
account-abstraction,
flare-network,
]
---

import DocCardList from "@theme/DocCardList";
import DocCard from "@theme/DocCard";

Use [Viem](https://viem.sh/) and the [`xrpl`](https://js.xrpl.org) library to read smart-account state on Flare and drive on-chain actions from an XRPL wallet.

Example code is maintained in the [flare-viem-starter](https://github.com/flare-foundation/flare-viem-starter) repository.
Read the [Smart Accounts overview](/smart-accounts/overview) and [Custom Instruction](/smart-accounts/custom-instruction) pages first if you are new to the protocol.

## Getting started

Read on-chain state and send arbitrary contract calls through XRPL memo-field instructions.

<DocCardList
items={[
{
type: "link",
label: "State Lookup",
href: "/smart-accounts/guides/typescript-viem/state-lookup-ts",
docId: "smart-accounts/guides/typescript-viem/state-lookup",
},
{
type: "link",
label: "Custom Instruction",
href: "/smart-accounts/guides/typescript-viem/custom-instruction-ts",
docId: "smart-accounts/guides/typescript-viem/custom-instruction",
},
]}
/>

## Cross-chain FXRP (LayerZero)

Mint [FXRP](/fxrp/overview) on Flare from XRPL and bridge to Sepolia testnet, or send FXRP back and redeem to XRP.

<div className="row">
<div className="col col--4 margin-bottom--lg">
<DocCard
item={{
type: "link",
label: "Cross-Chain Mint",
href: "/smart-accounts/guides/typescript-viem/cross-chain-mint-ts",
docId: "smart-accounts/guides/typescript-viem/cross-chain-mint",
}}
/>
</div>
<div className="col col--4 margin-bottom--lg">
<DocCard
item={{
type: "link",
label: "Cross-Chain Redeem",
href: "/smart-accounts/guides/typescript-viem/cross-chain-redeem-ts",
docId: "smart-accounts/guides/typescript-viem/cross-chain-redeem",
}}
/>
</div>
<div className="col col--4 margin-bottom--lg">
<DocCard
item={{
type: "link",
label: "Cross-Chain Redeem to Tag",
href: "/smart-accounts/guides/typescript-viem/cross-chain-redeem-to-tag-ts",
docId:
"smart-accounts/guides/typescript-viem/cross-chain-redeem-to-tag",
}}
/>
</div>
</div>

## Morpho Blue

Borrow and repay on a Coston2 Morpho Blue test market through a smart account.

<div className="row">
<div className="col col--4 margin-bottom--lg">
<DocCard
item={{
type: "link",
label: "Morpho Setup",
href: "/smart-accounts/guides/typescript-viem/morpho-setup-ts",
docId: "smart-accounts/guides/typescript-viem/morpho-setup",
}}
/>
</div>
<div className="col col--4 margin-bottom--lg">
<DocCard
item={{
type: "link",
label: "Morpho Borrow",
href: "/smart-accounts/guides/typescript-viem/morpho-borrow-ts",
docId: "smart-accounts/guides/typescript-viem/morpho-borrow",
}}
/>
</div>
<div className="col col--4 margin-bottom--lg">
<DocCard
item={{
type: "link",
label: "Morpho Repay",
href: "/smart-accounts/guides/typescript-viem/morpho-repay-ts",
docId: "smart-accounts/guides/typescript-viem/morpho-repay",
}}
/>
</div>
</div>
152 changes: 152 additions & 0 deletions docs/smart-accounts/guides/typescript-viem/06-morpho-setup.mdx
Original file line number Diff line number Diff line change
@@ -0,0 +1,152 @@
---
sidebar_position: 6
slug: morpho-setup-ts
title: Morpho Setup
authors: [nikerzetic]
description: Fund a smart account and authorize Morpho Blue lending via the MorphoMarketShim on Coston2.
tags: [intermediate, ethereum, flare-smart-accounts]
keywords:
[
ethereum,
flare-smart-accounts,
evm,
flare-network,
account-abstraction,
morpho,
defi,
]
unlisted: false
---

import CodeBlock from "@theme/CodeBlock";
import MorphoSetupScript from "!!raw-loader!/examples/developer-hub-javascript/smart-accounts/morpho/setup.ts";

This guide walks through the one-shot setup script for [Morpho Blue](https://docs.morpho.org/), leveraging a Flare smart account.
The smart account is the borrower's end-to-end: it holds tokens, supplies collateral, borrows, and later repays via the XRPL memo field [custom instructions](/smart-accounts/custom-instruction).

The setup script does two kinds of work:

1. **Flare EOA transactions** — mint mock ERC-20 collateral and loan tokens to the personal account via permissionless `setBalance`.
2. **XRPL memo instructions** — up to three payments that approve the `MorphoMarketShim` for both tokens and call `setAuthorization` on Morpho Blue.

:::warning
Run this script once before the [Morpho Borrow](/smart-accounts/guides/typescript-viem/morpho-borrow-ts) and [Morpho Repay](/smart-accounts/guides/typescript-viem/morpho-repay-ts) guides.
Each step is idempotent, and skips work that has already been done on the chain.
:::

The full Morpho cycle lives in the [flare-viem-starter](https://github.com/flare-foundation/flare-viem-starter) repository under `src/morpho/`.

## Prerequisites

- An XRPL testnet wallet (`XRPL_SEED`) registered with the Flare smart-accounts operator and funded with testnet XRP.
- A Flare-side EOA (`PRIVATE_KEY`) used only to call permissionless mock-token `setBalance` — not to sign Morpho operations on behalf of the smart account.
- `XRPL_TESTNET_RPC_URL` pointing at an XRPL testnet node.
- Familiarity with [State Lookup](/smart-accounts/guides/typescript-viem/state-lookup-ts) and [Custom Instruction](/smart-accounts/guides/typescript-viem/custom-instruction-ts).

## Architecture

Morpho Blue markets are identified by a five-field [`MarketParams`](https://docs.morpho.org/get-started/resources/contracts/morpho#market-parameters) tuple (loan token, collateral token, oracle, IRM, LLTV).
Opening a position normally requires multiple Morpho calls (`supplyCollateral`, `borrow`, and so on).
Each call encoded in an XRPL memo must stay under the roughly 1024-byte memo cap.

The `MorphoMarketShim` contract pins the market parameters in immutable storage at deploy time.
That shrinks each memo payload so a bundled operation fits in one payment:

- `supplyAndBorrow` — used in the [Morpho Borrow](/smart-accounts/guides/typescript-viem/morpho-borrow-ts) guide.
- `repayAndWithdrawCollateral` — used in the [Morpho Repay](/smart-accounts/guides/typescript-viem/morpho-repay-ts) guide.

The smart account remains `onBehalf` for the position; borrowed assets are returned to the smart account, so the position remains self-contained.

### Coston2 Deployment Addresses

| Contract | Address |
| ----------------------- | ----------------------------------------------------------------------------------------------------------------------------------------- |
| Morpho Blue | [`0x8aE0b3CE90F16E88063516f2d88C8ac2ab552d95`](https://coston2-explorer.flare.network/address/0x8aE0b3CE90F16E88063516f2d88C8ac2ab552d95) |
| Loan token (mock) | [`0x4984B127c3065f4348858fAFdBa020f2c8633905`](https://coston2-explorer.flare.network/address/0x4984B127c3065f4348858fAFdBa020f2c8633905) |
| Collateral token (mock) | [`0x98bf2F2fF322d5eb61D6aE04Df50856525a85D16`](https://coston2-explorer.flare.network/address/0x98bf2F2fF322d5eb61D6aE04Df50856525a85D16) |
| Oracle (mock) | [`0x1e80830e9903c839Db803442c976DD2360D47FE0`](https://coston2-explorer.flare.network/address/0x1e80830e9903c839Db803442c976DD2360D47FE0) |
| IRM (mock) | [`0xDC275701300865D882D44ffe7cb1153535636d1a`](https://coston2-explorer.flare.network/address/0xDC275701300865D882D44ffe7cb1153535636d1a) |
| MorphoMarketShim | [`0x33d81a1d7986bB3AbAB4F67Ad6117233ADd6F87A`](https://coston2-explorer.flare.network/address/0x33d81a1d7986bB3AbAB4F67Ad6117233ADd6F87A) |

The market uses an LLTV of `86%` (`860000000000000000` in WAD).
The market ID is `keccak256(abi.encode(marketParams))`, matching Morpho Blue's `MarketParamsLib.id()`.

## Full Script

The script below is sets up the Morpho Blue position by funding the smart account with mock tokens, approving the shim smart contract, and authorizing the shim smart contract on Morpho Blue.

<CodeBlock language="typescript" title="src/morpho/setup.ts">
{MorphoSetupScript}
</CodeBlock>

## Code Breakdown

The numbered comments in the script above map to these steps.

**1., 2. Configure and connect.**
Set funding sizes in whole token units (`100` collateral, `1000` loan token), then open an XRPL client and wallet.
The XRPL wallet controls the personal account; the Flare EOA is only used for mock minting in step 6.

| Token | Units | Purpose |
| ---------- | ------ | ---------------------------------------------- |
| Collateral | `100` | Matches the supply size in the borrow script |
| Loan | `1000` | Buffer for interest across borrow/repay cycles |

**3., 4. Resolve addresses and log them.**
In parallel, the script looks up the personal account, the memo-only XRP fee, and market decimals.
It then prints the personal account, operator EOA, market ID, and shim address.

**5. Snapshot before setup.**
It logs the Morpho position and wallet balances.
On a first run, borrow shares and position collateral should be zero.

**6. Fund mock tokens on Flare.**
The `mintMock` function calls permissionless `setBalance` on the Coston2 mock ERC-20s, crediting the personal account.
This is a normal Flare transaction from the operator EOA without interacting with the smart account.

**7. Approve and authorize the shim.**
It sends up to 3 XRPL memos: unlimited `approve` for collateral and loan tokens, then `setAuthorization` for Morpho Blue.
Each action uses its own memo because two calls do not fit under the 1024-byte cap.

**8. Snapshot after setup.**
Wallet balances should reflect the mint; Morpho position fields stay zero until [Morpho Borrow](/smart-accounts/guides/typescript-viem/morpho-borrow-ts).

## Expected Output

When you run the script, you should see the following output.

```bash
Personal account: 0x...
Operator EOA: 0x...
Morpho market id: 0x...
Shim address: 0x33d81a1d7986bB3AbAB4F67Ad6117233ADd6F87A

=== Before setup ===
position supply (≈loan tokens): 0
position borrow (≈loan tokens): 0
position collateral: 0
...

Funded smart account with collateral and loan tokens.

[approve-collateral] XRPL transaction hash: ...
[approve-loan] XRPL transaction hash: ...
[set-authorization] XRPL transaction hash: ...

=== After setup ===
smart-account collateral balance: 100
smart-account loan-token balance: 1000
...
```

You can repeat borrow and repay without re-running the setup, as the loan-token buffer covers interest.
Re-run setup if allowances are revoked or the loan-token balance is exhausted.

:::tip[What's next]

After you have completed the setup, you can:

- Open a position by running the [Morpho Borrow](/smart-accounts/guides/typescript-viem/morpho-borrow-ts) guide.
- Close a position by running the [Morpho Repay](/smart-accounts/guides/typescript-viem/morpho-repay-ts) guide.

:::
112 changes: 112 additions & 0 deletions docs/smart-accounts/guides/typescript-viem/07-morpho-borrow.mdx
Original file line number Diff line number Diff line change
@@ -0,0 +1,112 @@
---
sidebar_position: 7
slug: morpho-borrow-ts
title: Morpho Borrow
authors: [nikerzetic]
description: Open a Morpho Blue borrow position from a Flare smart account via supplyAndBorrow.
tags: [intermediate, ethereum, flare-smart-accounts]
keywords:
[
ethereum,
flare-smart-accounts,
evm,
flare-network,
account-abstraction,
morpho,
defi,
]
unlisted: false
---

import CodeBlock from "@theme/CodeBlock";
import MorphoBorrowScript from "!!raw-loader!/examples/developer-hub-javascript/smart-accounts/morpho/borrow.ts";

This guide opens a [Morpho Blue](https://docs.morpho.org/) borrow position from a Flare smart account in a single XRPL memo.
It calls the `MorphoMarketShim` smart contract `supplyAndBorrow` function, which supplies `100` units of collateral and borrows up to roughly `99%` of the maximum healthy loan amount.

:::info Setup
Run the [Morpho Setup](/smart-accounts/guides/typescript-viem/morpho-setup-ts) guide first.
Without funded tokens, shim smart contract approvals, and Morpho authorization, the transaction reverts.
:::

To close the position follow the [Morpho Repay](/smart-accounts/guides/typescript-viem/morpho-repay-ts) guide.

The full Morpho cycle lives in the [flare-viem-starter](https://github.com/flare-foundation/flare-viem-starter).

## Full Script

To open a borrow position, explore the full script below.

<CodeBlock language="typescript" title="src/morpho/borrow.ts">
{MorphoBorrowScript}
</CodeBlock>

## Code Breakdown

**1. Connect to XRPL.**
Open an XRPL client and wallet.
The XRPL wallet controls the personal account.
Morpho operations are sent as memo-field custom instructions from the smart account, not as Flare EOA (External Owned Account) transactions.

**2. Resolve on-chain inputs in parallel.**
The script fetches the personal account address, the memo-only XRP fee, market token decimals, and the mock oracle price in parallel.

**3. Set collateral supply size.**
Collateral is fixed at `100` whole token units, scaled by `collateralDecimals`.
This matches the collateral funding amount from [Morpho Setup](/smart-accounts/guides/typescript-viem/morpho-setup-ts).

**4. Log addresses.**
It prints the personal account, operator EOA, Morpho market ID, and shim address for this run.

**5. Snapshot before borrowing.**
It logs the Morpho position and wallet balances before the borrow.
On a first borrow after setup, the borrowed shares and the position collateral should be zero while the smart account holds the funded tokens.

**6. Compute borrow size off-chain.**
The script reads the mock oracle price and applies Morpho Blue's health formula to derive the maximum borrowable amount:

```
maxBorrowAssets = collateral * oraclePrice * lltv / (oraclePriceScale * WAD)
```

It then borrows `99%` of that value to leave a small safety margin for interest accrued during the transaction.

**7. Send the supply-and-borrow memo.**
A single custom instruction executes the `MorphoMarketShim` smart contract `supplyAndBorrow` function.

Bundling supply and borrow inside the shim smart contract keeps the encoded user operation under the XRPL memo size limit.

**8. Snapshot after borrowing.**
Print the Morpho position and wallet balances after the borrow.
Expect position collateral to be near `100`, a non-zero borrow balance, and an increased loan-token wallet balance.

## Expected Output

When you run the script, you should see output similar to the following.

```bash
Personal account: 0x...
Operator EOA: 0x...
Morpho market id: 0x...
Shim address: 0x33d81a1d7986bB3AbAB4F67Ad6117233ADd6F87A

=== Before borrow ===
position borrow (≈loan tokens): 0
position collateral: 0
...

Oracle price: ...
Max borrowable: ... → borrowing: ...

[supply-and-borrow] XRPL transaction hash: ...
[supply-and-borrow] UserOperationExecuted event: ...

=== After borrow ===
position borrow (≈loan tokens): ...
position collateral: 100
...
```

:::tip[What's next]
After you have completed the borrow, you can explore how to [repay the borrow position](/smart-accounts/guides/typescript-viem/morpho-repay-ts).
:::
Loading
Loading