> For the complete documentation index, see [llms.txt](https://docs.sodex.com/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.sodex.com/for-developers/developers/wealth/recurring-buys.md).

# Recurring Buys

Prefund a shared USDC balance, then create a plan that buys one allowlisted target on a schedule. Both steps run on ValueChain. Contract addresses are on [Wealth Contracts](https://docs.sodex.com/for-developers/developers/wealth/contracts.md).

`AutomaticInvestmentDeposit` holds the USDC and mints 18-decimal shares to the owner. `AutomaticInvestment` stores the plan. Creating a plan records the schedule. An operator spends `amount` from the shared balance when the plan is due. The same balance funds every plan of that wallet.

Each owner has one active or paused plan per target. Cancel that plan before creating another for the same target. The cancelled plan index stays assigned.

Read the resulting plans with [Recurring Buy Plans API](https://docs.sodex.com/for-developers/api-reference/wealth-api/recurring-buys.md). `availableAssets` there is this shared balance.

## Schedule

`amount` is raw USDC units, the same unit as `asset()` on the deposit contract. `planType` and `dayOfPeriod` are integers.

| `planType`  | Value | `dayOfPeriod`                 | When it is due                                                   |
| ----------- | ----- | ----------------------------- | ---------------------------------------------------------------- |
| `DAILY`     | `0`   | `0`                           | Every local day.                                                 |
| `WEEKLY`    | `1`   | `1` Monday through `7` Sunday | That local weekday.                                              |
| `BI_WEEKLY` | `2`   | `1` Monday through `7` Sunday | That weekday in the creation week, then every second local week. |
| `MONTHLY`   | `3`   | `1`–`31`                      | That day of the local month. A shorter month has no execution.   |

The operator can execute from local midnight until 09:30 local time. A China vault (`vaultType` `0`) uses UTC+8. A US book target (`vaultType` `1`) uses UTC-4, with no daylight-saving change. The user does not send the execution transaction.

If the shared balance is below `amount` when the operator runs, that execution reverts and the plan stays active.

## 1. Select a target

`getTargetConfig(vault)` returns `minInvestAmount`. A zero minimum means the address is not allowlisted. `amount` must be at least that minimum. List allowlisted targets with `getNumVaults()` and `getVaultByRange(start, end)`.

For a China vault, `vault` is the fund vault from [Fund Information](https://docs.sodex.com/for-developers/api-reference/wealth-api/funds.md#get-fund-information). The USDC must already be on ValueChain. If it is still on another network, move it with [Mirror Protocol](https://docs.sodex.com/for-developers/developers/mirror-protocol.md) first.

## 2. Prefund

Call `deposit` from the owner's wallet. The wallet pays SOSO gas. Approve the deposit contract to spend the USDC first.

`depositOnBehalf` is the relayed form. The owner signs an ERC-2612 permit that names the deposit contract as spender. The permit signature is 65 bytes, and the contract submits it on every `depositOnBehalf` call. Read the token `name()` and `nonces(owner)` for that permit. The permit domain version used by vUSDC is `"1"`.

Install `viem` and `tsx`. Set `PRIVATE_KEY` and `PREFUNDED_USDC` (raw USDC units). Save as `recurring-buy.mts` and run `npx tsx recurring-buy.mts`.

```typescript
import {
  createPublicClient, createWalletClient, defineChain, http, parseAbi,
  type Address, type Hex,
} from "viem";
import { privateKeyToAccount } from "viem/accounts";

const valuechain = defineChain({
  id: 286623, name: "ValueChain",
  nativeCurrency: { name: "SOSO", symbol: "SOSO", decimals: 18 },
  rpcUrls: { default: { http: ["https://mainnet.valuechain.xyz"] } },
});
const investment = "0x76f8064b1B0f091D8f86D2EB203631D44B685146" as Address;
const deposit = "0x355Be5eEE2965050Bd056f7cb0dFAAeD3cB11964" as Address;
const account = privateKeyToAccount(process.env.PRIVATE_KEY as Hex);
const publicClient = createPublicClient({ chain: valuechain, transport: http() });
const walletClient = createWalletClient({ account, chain: valuechain, transport: http() });
const prefund = BigInt(process.env.PREFUNDED_USDC!);

const erc20Abi = parseAbi([
  "function approve(address spender, uint256 amount) returns (bool)",
  "function allowance(address owner, address spender) view returns (uint256)",
]);
const depositAbi = parseAbi([
  "function asset() view returns (address)",
  "function balanceOfAssets(address account) view returns (uint256)",
  "function balanceOfShares(address account) view returns (uint256)",
  "function deposit(uint256 assets) returns (uint256 shares)",
  "function redeem(uint256 shares) returns (uint256 assets)",
]);

const asset = await publicClient.readContract({
  address: deposit, abi: depositAbi, functionName: "asset",
});
const allowance = await publicClient.readContract({
  address: asset, abi: erc20Abi, functionName: "allowance", args: [account.address, deposit],
});
if (allowance < prefund) {
  const approveHash = await walletClient.writeContract({
    address: asset, abi: erc20Abi, functionName: "approve", args: [deposit, prefund],
  });
  const approveReceipt = await publicClient.waitForTransactionReceipt({ hash: approveHash });
  if (approveReceipt.status !== "success") throw new Error("Approval reverted");
}

const hash = await walletClient.writeContract({
  address: deposit, abi: depositAbi, functionName: "deposit", args: [prefund],
});
const receipt = await publicClient.waitForTransactionReceipt({ hash });
if (receipt.status !== "success") throw new Error("deposit reverted");

const available = await publicClient.readContract({
  address: deposit, abi: depositAbi, functionName: "balanceOfAssets", args: [account.address],
});
console.log({ depositTxHash: hash, availableAssets: available.toString() });
```

`balanceOfAssets` is the USDC value of the position. `balanceOfShares` is the 18-decimal share balance. `decimals()` on the deposit contract returns `18`. A deposit that converts to zero shares reverts.

Shares are an internal ledger. They are not a transferable ERC-20. Deposit rounds shares down. A later debit rounds shares up so the recipient can redeem at least the USDC amount.

### Withdraw unused USDC

`redeem(shares)` burns the owner's shares and sends USDC to that owner. `redeemOnBehalf(owner, shares, deadline, signature)` is the relayed form. Its EIP-712 domain name is `AutomaticInvestmentDeposit`, version `"1"`, and `verifyingContract` is the deposit contract. The nonce is `nonces(owner)` on the deposit contract, which is separate from the plan-contract nonce.

```solidity
RedeemOnBehalf(address owner, uint256 shares, uint256 nonce, uint256 deadline)
```

USDC is sent to `owner`. The relayer does not receive it.

## 3. Create a plan

Call `createInvestmentPlan` from the owner's wallet.

```solidity
createInvestmentPlan(address vault, uint256 amount, uint8 planType, uint8 dayOfPeriod)
```

Append this to the client above. Set `VAULT_ADDRESS`, `PLAN_AMOUNT` (raw USDC units per execution), `PLAN_TYPE`, and `DAY_OF_PERIOD`.

```typescript
const investmentAbi = parseAbi([
  "function getTargetConfig(address vault) view returns (uint8, uint256)",
  "function createInvestmentPlan(address vault, uint256 amount, uint8 planType, uint8 dayOfPeriod)",
  "function getUserPlanIndex(address user, address vault) view returns (uint256)",
]);
const vault = process.env.VAULT_ADDRESS as Address;
const amount = BigInt(process.env.PLAN_AMOUNT!);
const planType = Number(process.env.PLAN_TYPE ?? "0");
const dayOfPeriod = Number(process.env.DAY_OF_PERIOD ?? "0");

const [, minInvestAmount] = await publicClient.readContract({
  address: investment, abi: investmentAbi, functionName: "getTargetConfig", args: [vault],
});
if (minInvestAmount === 0n) throw new Error("Target is not allowlisted");
if (amount < minInvestAmount) throw new Error(`Amount below minimum: ${minInvestAmount}`);

const createHash = await walletClient.writeContract({
  address: investment, abi: investmentAbi, functionName: "createInvestmentPlan",
  args: [vault, amount, planType, dayOfPeriod],
});
const createReceipt = await publicClient.waitForTransactionReceipt({ hash: createHash });
if (createReceipt.status !== "success") throw new Error("createInvestmentPlan reverted");

const planIndex = await publicClient.readContract({
  address: investment, abi: investmentAbi, functionName: "getUserPlanIndex",
  args: [account.address, vault],
});
console.log({ createTxHash: createHash, planIndex: planIndex.toString() });
```

`getUserPlanIndex` reverts when that owner has no active or paused plan for the vault. After a successful create it returns the plan index. The same index is the third topic of `InvestmentPlanCreated`.

### Signed create

Use this path instead of the direct `createInvestmentPlan` call when another wallet pays gas. Keep the client, `vault`, `amount`, `planType`, and `dayOfPeriod` from the sections above. The owner signs EIP-712 `CreateInvestmentPlan`. The domain name is `AutomaticInvestment`, version `"1"`, and `verifyingContract` is the plan contract. Read `nonces(owner)` on the plan contract and sign that value. The transaction consumes it.

```solidity
CreateInvestmentPlan(address owner, address vault, uint256 amount, uint8 planType, uint8 dayOfPeriod, uint256 nonce, uint256 deadline)
```

```solidity
createInvestmentPlanOnBehalf((address owner, address vault, uint256 amount, uint8 planType, uint8 dayOfPeriod) params, uint256 deadline, bytes signature)
```

Set `USER_PK` for the plan owner and `RELAYER_PK` for the gas payer. To have SoDEX broadcast the call, use the [Transaction Relayer](https://docs.sodex.com/for-developers/developers/valuechain-evm/relayer.md). The relayer is `msg.sender`, so the owner must be inside the signed `CreateParams`.

```typescript
const user = privateKeyToAccount(process.env.USER_PK as Hex);
const relayer = privateKeyToAccount(process.env.RELAYER_PK as Hex);
const userClient = createWalletClient({ account: user, chain: valuechain, transport: http() });
const relayerClient = createWalletClient({ account: relayer, chain: valuechain, transport: http() });
const onBehalfAbi = parseAbi([
  "function nonces(address owner) view returns (uint256)",
  "function createInvestmentPlanOnBehalf((address owner, address vault, uint256 amount, uint8 planType, uint8 dayOfPeriod) params, uint256 deadline, bytes signature)",
]);

const deadline = BigInt(Math.floor(Date.now() / 1000) + 3600);
const nonce = await publicClient.readContract({
  address: investment, abi: onBehalfAbi, functionName: "nonces", args: [user.address],
});
const signature = await userClient.signTypedData({
  domain: { name: "AutomaticInvestment", version: "1", chainId: valuechain.id, verifyingContract: investment },
  types: {
    CreateInvestmentPlan: [
      { name: "owner", type: "address" },
      { name: "vault", type: "address" },
      { name: "amount", type: "uint256" },
      { name: "planType", type: "uint8" },
      { name: "dayOfPeriod", type: "uint8" },
      { name: "nonce", type: "uint256" },
      { name: "deadline", type: "uint256" },
    ],
  },
  primaryType: "CreateInvestmentPlan",
  message: { owner: user.address, vault, amount, planType, dayOfPeriod, nonce, deadline },
});
const signedHash = await relayerClient.writeContract({
  address: investment,
  abi: onBehalfAbi,
  functionName: "createInvestmentPlanOnBehalf",
  args: [{ owner: user.address, vault, amount, planType, dayOfPeriod }, deadline, signature],
});
console.log({ signedCreateTxHash: signedHash });
```

A signed prefund uses the same relayer pattern against the deposit contract:

```solidity
depositOnBehalf(address owner, uint256 assets, uint256 deadline, bytes permitSignature)
```

The permit `spender` is the deposit contract, and `value` is the USDC amount. Sign it with the USDC nonce, then pass the 65-byte signature as `permitSignature`.

## 4. Pause, resume, and cancel

The owner calls these with the vault address. The `OnBehalf` forms take `owner`, `vault`, `deadline`, and an EIP-712 signature. They use the same `AutomaticInvestment` domain and the plan-contract nonce.

| Action | Direct call                   | Typed data                                                                         |
| ------ | ----------------------------- | ---------------------------------------------------------------------------------- |
| Pause  | `pauseInvestmentPlan(vault)`  | `PauseInvestmentPlan(address owner,address vault,uint256 nonce,uint256 deadline)`  |
| Resume | `resumeInvestmentPlan(vault)` | `ResumeInvestmentPlan(address owner,address vault,uint256 nonce,uint256 deadline)` |
| Cancel | `cancelInvestmentPlan(vault)` | `CancelInvestmentPlan(address owner,address vault,uint256 nonce,uint256 deadline)` |

Pause requires an active plan. Resume requires a paused plan. Cancel removes the vault from the owner's plan map and leaves the prefund in the deposit contract. Withdraw that USDC with `redeem`. The plan index remains queryable through the API with `status=history`.
