bitpro가 원문에서 글자만 모은 내용이에요. 표·그림·수식은 빠지거나 깨질 수 있어요. 전체 75쪽 중 55쪽
na](https://github.com/crytic/echidna): fuzz testing
* [Slither](https://github.com/crytic/slither): static analysis for vulnerability detection
* [solidity-coverage](https://github.com/sc-forks/solidity-coverage/tree/master): code coverage for Solidity testing
## Smart contract archives
* [Smart contract sanctuary](https://github.com/tintinweb/smart-contract-sanctuary) - contracts verified on Etherscan
* [EVM function signature database](https://www.4byte.directory/)
# How to add swaps to your app using Kuru Flow
Source: https://docs.monad.xyz/guides/kuru-flow
Your application may need to allow users to swap between two assets. You want your users
to get the best price available across the ecosystem.
Aggregators check many liquidity sources and find the best price. Integrating an aggregator API
can thus be a convenient and efficient means of enabling swapping in your app.
In this guide, we will examine integrating one such aggregator,
[Kuru Flow](https://docs.kuru.io/kuru-flow/flow-overview). You'll learn how to integrate Kuru
Flow into a frontend application—from authentication to fetching quotes and executing swaps.
## Requirements
Before you begin, ensure you have the following:
* A frontend framework with wallet connection (React, Next.js, etc.)
* [wagmi](https://wagmi.sh) and [viem](https://viem.sh) for wallet interactions
* User wallet connected to Monad mainnet (chain ID `143`)
## 1. Configure Authentication
We first need to get credentials to access the Kuru Flow API.
Kuru Flow uses JWT tokens for API authentication.
```typescript lines title="lib/kuru-flow.ts" theme={null}
const KURU_FLOW_API = "https://ws.kuru.io";
async function generateToken(userAddress: string) {
const response = await fetch(`${KURU_FLOW_API}/api/generate-token`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ user_address: userAddress }),
});
return response.json();
// Returns: { token: string, expires_at: number, rate_limit: { rps: number, burst: number } }
}
```
## 2. Get a Swap Quote
The `/api/quote` endpoint calculates the best swap path and returns transaction data.
The following parameters are supported:
| Parameter | Required | Description |
| - | - | - |
| `userAddress` | Yes | User's wallet address |
| `tokenIn` | Yes | Token address (`0x0` for native MON) |
| `tokenOut` | Yes | Token address (`0x0` for native MON) |
| `amount` | Yes | Amount in smallest token units |
| `autoSlippage` | No\* | Set to `true` for automatic slippage calculation |
| `slippageTolerance` | No\* | Manual slippage in basis points (1-10000) |
| `referrerAddress` | No | Your address to receive referral fees |
| `referrerFeeBps` | No | Referral fee in basis points (0-10000) |
\*Either `autoSlippage: true` OR `slippageTolerance` must be provided.
We can write a small function to interact with the `quote` API:
```typescript lines title="lib/kuru-flow.ts" theme={null}
const KURU_FLOW_API = "https://ws.kuru.io";
// Your wallet address to receive referral fees
const REFERRER_ADDRESS = "0xYOUR_WALLET_ADDRESS_HERE";
const REFERRER_FEE_BPS = 50; // 0.5%
async function getQuote(
userAddress: string,
tokenIn: string,
tokenOut: string,
amount: string,
token: string
) {
const response = await fetch(`${KURU_FLOW_API}/api/quote`, {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${token}`,
},
body: JSON.stringify({
userAddress,
tokenIn,
tokenOut,
amount,
autoSlippage: true,
referrerAddress: REFERRER_ADDRESS,
referrerFeeBps: REFERRER_FEE_BPS,
}),
});
return response.json();
}
```
### Response Structure
```typescript lines title="lib/kuru-flow.ts" theme={null}
export interface QuoteResponse {
type: string;
status: "success" | "error";
output: string; // Expected output amount (in wei)
minOut: string; // Minimum output with slippage
transaction: {
to: string; // Router contract address
calldata: string; // Transaction calldata (WITHOUT 0x prefix!)
value: string; // Native MON amount (non-zero when swapping native MON)
};
gasPrices: {
slow: string;
standard: string;
fast: string;
rapid: string;
extreme: string;
};
message?: string; // Error message if status is "error"
}
```
<Note>
The `calldata` field does NOT include the `0x` prefix. You must add it before sending the transaction.
</Note>
## 3. Check Token Allowance (ERC20 Only)
Before executing a swap with ERC20 tokens, we should verify that the router has permission to
spend the user's tokens.
<Tip>
**Native MON does not require approval.** Skip this step when swapping native MON.
</Tip>
```typescript lines title="components/SwapCard.tsx" theme={null}
import { useState } from "react";
import { useAccount, useReadContract } from "wagmi";
import { parseUnits } from "viem";
import type { QuoteResponse } from "@/lib/kuru-flow";
// Token addresses
const NATIVE_MON = "0x0000000000000000000000000000000000000000" as const;
const USDC = "0x754704Bc059F8C67012fEd69BC8A327a5aafb603" as const;
const ERC20_ABI = [
{
name: "allowance",
type: "function",
stateMutability: "view",
inputs: [
{ name: "owner", type: "address" },
{ name: "spender", type: "address" },
],
outputs: [{ name: "", type: "uint256" }],
},
] as const;
// Inside your component:
const { address } = useAccount();
const [amount, setAmount] = useState("");
const [quote, setQuote] = useState<QuoteResponse | null>(null);
const tokenIn = USDC; // Example: swapping USDC
const isNativeToken = tokenIn === NATIVE_MON;
const amountWei = amount ? parseUnits(amount, 6) : BigInt(0);
// Check allowance against router address from quote (skip for native MON)
const { data: allowance } = useReadContract({
address: tokenIn,
abi: ERC20_ABI,
functionName: "allowance",
args: address && quote?.transaction?.to
? [address, quote.transaction.to as `0x${string}`]
: undefined,
query: {
enabled: !isNativeToken, // Don't check allowance for native token
},
});
// Native tokens don't need approval
const needsApproval = !isNativeToken && allowance !== undefined && amountWei > allowance;
```
## 4. Approve Token Spending (ERC20 Only)
If allowance is insufficient for an ERC20 token, we should request approval before swapping.
```typescript lines title="components/SwapCard.tsx" theme={null}
import { encodeFunctionData } from "viem";
import { useSendTransaction } from "wagmi";
const APPROVE_ABI = [
{
name: "approve",
type: "function",
stateMutability: "nonpayable",
inputs: [
{ name: "spender", type: "address" },
{ name: "amount", type: "uint256" },
],
outputs: [{ name: "", type: "bool" }],
},
] as const;
// Inside your component:
const { sendTransaction: sendApproveTx } = useSendTransaction();
const handleApprove = () => {
if (!quote?.transaction?.to) return;
const data = encodeFunctionData({
abi: APPROVE_ABI,
functionName: "approve",
args: [quote.transaction.to as `0x${string}`, amountWei],
});
sendApproveTx({
to: tokenIn,
data,
});
};
```
<Tip>
Use viem's `encodeFunctionData` instead of manual hex string manipulation for reliable ABI encoding.
</Tip>
## 5. Execute the Swap
To submit the swap, we should use the transaction data from the quote response:
```typescript lines title="components/SwapCard.tsx" theme={null}
// Inside your component:
const { sendTransaction: sendSwapTx } = useSendTransaction();
const handleSwap = () => {
if (!quote || quote.status !== "success") return;
// IMPORTANT: Add 0x prefix to calldata
const calldata = quote.transaction.calldata.startsWith("0x")
? quote.transaction.calldata
: `0x${quote.transaction.calldata}`;
sendSwapTx({
to: quote.transaction.to as `0x${string}`,
data: calldata as `0x${string}`,
value: BigInt(quote.transaction.value || "0"),
});
};
```
## Token Addresses and Decimals (Mainnet)
| Token | Address | Decimals | Notes |
| - | - | - | - |
| MON (native) | `0x0000000000000000000000000000000000000000` | 18 | No approval needed |
| USDC | `0x754704Bc059F8C67012fEd69BC8A327a5aafb603` | 6 | Requires approval |
<Warning>
Be careful with token decimals when formatting output. USDC uses 6 decimals, not 18.
```typescript theme={null}
import { formatEther, formatUnits } from "viem";
// WRONG - assumes 18 decimals
formatEther(BigInt(quote.output)) // Shows 0.000000002301622011
// CORRECT - use actual token decimals
formatUnits(BigInt(quote.output), 6) // Shows 2301.62
```
</Warning>
## Referral Fee System
Kuru features a referral system. As the referrer, we can earn fees on every swap by including your referrer details in quote requests.
```typescript lines title="lib/kuru-flow.ts" theme={null}
// Replace with YOUR wallet address to receive referral fees
export const REFERRER_ADDRESS = "0xYOUR_WALLET_ADDRESS_HERE";
// Fee in basis points (50 = 0.5%, 100 = 1%)
export const REFERRER_FEE_BPS = 50;
```
**Example fee calculations at 50 bps (0.5%):**
| Swap Output | Fee Amount |
| - | - |
| 100 USDC | 0.5 USDC |
| 500 USDC | 2.5 USDC |
| 1000 USDC | 5 USDC |
<Warning>
Replace `0xYOUR_WALLET_ADDRESS_HERE` with your actual wallet address before deploying. The `referrerAddress` must be a valid Ethereum address or transactions will fail.
</Warning>
## Error Handling
Along the way, we might run into errors. Here is how to interpret them:
| Status Code | Meaning |
| - | - |
| 400 | Bad request - check parameters |
| 401 | Unauthorized - invalid or expired token |
| 429 | Rate limited - wait before retrying |
| 500 | Server error - retry later |
## Common Mistakes
1. **Missing 0x prefix** - Add `0x` prefix to calldata before sending
2. **Invalid referrer address** - Must be a valid Ethereum address
3. **Skipping approval for ERC20** - ERC20 tokens require approval before swap (native MON does not)
4. **Wrong decimals** - USDC has 6 decimals, MON has 18
5. **Zero value for native MON swaps** - When swapping native MON, the transaction `value` must be set to the swap amount
## Next Steps
* Try the [Live Demo](https://kuru-flow-api-example-one.vercel.app/) to see Kuru Flow in action
* Clone the [Example Repository](https://github.com/monad-developers/kuru-flow-api-example) for a complete working implementation
* Read the [Kuru Flow Overview](https://docs.kuru.io/kuru-flow/flow-overview) for more details
* See [Monad Network Information](/developer-essentials/network-information) for RPC endpoints and chain configuration
# How to create passkey accounts with Mera
Source: https://docs.monad.xyz/guides/mera
Create and recover Monad accounts from a passkey, with no seed phrase.
[mera](https://mera.category.xyz/) derives EVM accounts from a passkey. Users create an account with Face ID, Touch ID, or a security key, and the same passkey reproduces the same accounts on every sign-in.
The accounts are regular EOAs. There is nothing to deploy, and no bundler or MPC service to run. Once you have an address, the rest is ordinary viem against a Monad RPC.
<Note>
**Try the demo first**
It is recommended to check that the [demo](https://mera.category.xyz/demo/) works with your passkey provider on the browsers and devices you plan to support. The [Authenticator support](https://mera.category.xyz/authenticator-support/) page lists the combinations that have been tested.
</Note>
<Tip>
Building a native mobile app? Follow [How to use Mera with React Native](/guides/mera/react-native) for platform association, native passkey APIs, and cross-device account reuse.
</Tip>
## Install
```bash theme={null}
npm install @category-labs/mera viem @scure/bip32 @scure/bip39
```
## Requirements
* HTTPS, or `localhost` in development.
* A passkey provider that supports the WebAuthn PRF extension, such as iCloud Keychain, 1Password, or Google Password Manager. The [Authenticator support](https://mera.category.xyz/authenticator-support/) page has the full list.
<Warning>
**Desktop Chrome**
On desktop Chrome, only passkeys saved to Google Password Manager return PRF. When Chrome saves to the local profile instead, the passkey is created but mera throws `PRF_UNAVAILABLE`. This is the most common setup failure.
</Warning>
## Create a passkey
`createPasskeyWithPrfOutput` prompts the user to create a passkey and returns 32 secret bytes.
```ts theme={null}
import { createPasskeyWithPrfOutput } from "@category-labs/mera";
const created = await createPasskeyWithPrfOutput({
rp: { id: location.hostname, name: "My Monad App" },
user: { name: "player@example.com", displayName: "Player One" },
});
// created.prfOutput — Uint8Array(32), the root of every account
localStorage.setItem(
"app.credential",
JSON.stringify({
credentialId: created.credentialId,
transports: created.transports,
}),
);
```
Every call creates a new passkey, and each passkey produces a different set of accounts. Run this once during onboarding and store the returned `credentialId`. Returning visits use `getPasskeyPrfOutput` with that credential, which is covered in [Signing in](#signing-in).
The credential metadata holds no key material, so `localStorage` is fine for it. Passing it back on the next sign-in lets the browser go straight to the same passkey rather than asking the user to pick one.
## Derive a key
The 32 bytes returned by the passkey, `prfOutput`, can be used to derive a standard BIP-44 account. Deriving it this way keeps the account portable, so an exported mnemonic imports into MetaMask or Rabby and produces the same address.
```ts theme={null}
import { HDKey } from "@scure/bip32";
import { entropyToMnemonic, mnemonicToSeedSync } from "@scure/bip39";
import { wordlist } from "@scure/bip39/wordlists/english";
function deriveEvmKey(prfOutput: Uint8Array, index = 0): Uint8Array {
const seed = mnemonicToSeedSync(entropyToMnemonic(prfOutput, wordlist));
const node = HDKey.fromMasterSeed(seed).derive(`m/44'/60'/0'/0/${index}`);
if (node.privateKey === null) throw new Error("derivation produced no key");
return node.privateKey;
}
```
Increment `index` for additional accounts from the same passkey.
## Send a transaction
A signing session holds the key, and `toViemAccount` wraps it as a viem `LocalAccount`. It behaves like any other viem account and supports the same signing methods.
```ts theme={null}
import { createSecp256k1SigningSession } from "@category-labs/mera";
import { toViemAccount } from "@category-labs/mera/viem";
import { createWalletClient, http, parseEther } from "viem";
import { monadTestnet } from "viem/chains";
const session = createSecp256k1SigningSession({
privateKey: deriveEvmKey(created.prfOutput),
});
const client = createWalletClient({
account: toViemAccount(session),
chain: monadTestnet,
transport: http(),
});
const hash = await client.sendTransaction({
to: "0x70997970C51812dc3A010C7d01b50e0d17dc79C8",
value: parseEther("0.01"),
gas: 21_000n,
});
session.end();
```
`end()` zeroes the key and cannot be undone, so the next transaction needs a new session. How long to keep one open is covered in [Putting it together](#putting-it-together).
Use `monad` instead of `monadTestnet` for mainnet. Both ship in `viem/chains`.
| Network | Chain ID | viem export |
| - | - | - |
| Monad | 143 | `monad` |
| Monad Testnet | 10143 | `monadTestnet` |
<Tip>
**Gas**
Monad charges the `gasLimit` you declare, not the gas used. Pass an explicit `gas` value, such as `21_000n` for a native transfer, instead of letting an estimate stand. See [Gas pricing](/developer-essentials/gas-pricing).
</Tip>
## Signing in
```ts theme={null}
import { getPasskeyPrfOutput } from "@category-labs/mera";
const stored = localStorage.getItem("app.credential");
const known = stored ? JSON.parse(stored) : undefined;
const { prfOutput, credentialId } = await getPasskeyPrfOutput({
rpId: location.hostname,
credential: known,
});
// Nothing stored? The browser may have used a different passkey, so record it.
localStorage.setItem(
"app.credential",
JSON.stringify(known?.credentialId === credentialId ? known : { credentialId }),
);
```
With a fresh device, `getPasskeyPrfOutput` will prompt the authenticator in a discoverable mode, and the user should be able to choose a previously saved passkey.
## Putting it together
There are two ways to arrange this, and the difference is how long the key stays in memory.
### Hold the session
Prompt the authenticator once, derive the key, and keep the session for as long as the user is signed in. This suits high-frequency workflows like trading, where a prompt per transaction is not workable. The key is in page memory for the whole session, and any script on the page can sign with it while it is live.
```ts theme={null}
// src/lib/wallet.ts
import {
createSecp256k1SigningSession,
getPasskeyPrfOutput,
type Secp256k1SigningSession,
} from "@category-labs/mera";
import { toViemAccount } from "@category-labs/mera/viem";
import { createWalletClient, http, parseEther, type Hex } from "viem";
import { monadTestnet } from "viem/chains";
let session: Secp256k1SigningSession | undefined;
export async function connect() {
const stored = localStorage.getItem("app.credential");
const { prfOutput } = await getPasskeyPrfOutput({
rpId: location.hostname,
credential: stored ? JSON.parse(stored) : undefined,
});
session = createSecp256k1SigningSession({
privateKey: deriveEvmKey(prfOutput),
});
return toViemAccount(session).address;
}
export function send(to: Hex, mon: string) {
if (!session) throw new Error("not connected");
const client = createWalletClient({
account: toViemAccount(session),
chain: monadTestnet,
transport: http(),
});
return client.sendTransaction({ to, value: parseEther(mon), gas: 21_000n });
}
export function disconnect() {
session?.end();
session = undefined;
}
```
Call `disconnect()` on sign-out, and consider calling it on an idle timeout as well.
### Prompt per transaction
Run the ceremony for each transaction and end the session as soon as it is sent. The key exists only for the duration of the send, at the cost of a passkey prompt every time.
```ts theme={null}
export async function send(to: Hex, mon: string) {
const stored = localStorage.getItem("app.credential");
const { prfOutput } = await getPasskeyPrfOutput({
rpId: location.hostname,
credential: stored ? JSON.parse(stored) : undefined,
});
using session = createSecp256k1SigningSession({
privateKey: deriveEvmKey(prfOutput),
});
const client = createWalletClient({
account: toViemAccount(session),
chain: monadTestnet,
transport: http(),
});
return client.sendTransaction({ to, value: parseEther(mon), gas: 21_000n });
}
```
`using` ends the session when the scope exits. If your build target does not support explicit resource management, call `session.end()` in a `finally` block instead.
## Errors
mera throws `MeraError` with a `code`. Use the code to identify the error, since message text can change between versions.
```ts theme={null}
import { isMeraError } from "@category-labs/mera";
if (isMeraError(error)) {
switch (error.code) {
case "PRF_UNAVAILABLE": // unsupported passkey provider
case "PASSKEY_OPERATION_FAILED": // prompt dismissed or failed; offer a retry
case "CRYPTO_UNAVAILABLE": // not a secure context
case "SESSION_ENDED": // signing call after end()
}
}
```
## Notes
* A passkey is tied to the `rpId` it was created for. If the app moves to a new domain, the accounts can no longer be derived, and users would need the 24-word mnemonic to recover them.
* Everything above derives the key from the passkey. When the key comes from somewhere else, such as a recovery phrase the user already has, [secret vaults](https://mera.category.xyz/concepts/secret-vaults/) encrypt it once and decrypt it with the passkey.
* `createEd25519SigningSession` and `getSolanaAddress` derive Solana accounts from the same passkey.
## Further resources
You can check out the [mera docs](https://mera.category.xyz/) for more details. The project is open source, so you can also [check out the code on GitHub](https:프로젝트로 돌아가기