> For the complete documentation index, see [llms.txt](https://docs.kpk.io/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.kpk.io/funds/infrastructure/architecture/deployment/code-examples.md).

# Code examples

Look up, predict, and deploy KPK funds through the KpkOivFactory and the CCIP orchestrator, with viem, ethers.js, and Python.

Practical examples for looking up a fund's contract addresses, predicting them ahead of a deployment, and deploying a fund across chains through the [`KpkOivFactory`](https://docs.kpk.io/funds/infrastructure/architecture/deployment.md) and the [`CcipOivDeployer`](https://docs.kpk.io/funds/infrastructure/architecture/deployment/cross-chain-deployment.md) orchestrator.

**Source:** [`KpkOivFactory.sol`](https://github.com/karpatkey/onchain-investment-vehicles/blob/main/src/KpkOivFactory.sol) · [`CcipOivDeployer.sol`](https://github.com/karpatkey/onchain-investment-vehicles/blob/main/src/CcipOivDeployer.sol)

{% hint style="info" %}
The factory and orchestrator share the **same address on every chain**; take them from [Deployment addresses](https://docs.kpk.io/funds/infrastructure/architecture/deployment/deployment-addresses.md). The examples use the salt v4 addresses; owner, admin, and fee-receiver addresses are placeholders.
{% endhint %}

{% hint style="info" %}
In the returned `OivInstance`, the field named **`avatarSafe`** is the fund's **Portfolio Safe** (the Zodiac module's *avatar*, the Safe that holds the fund's assets); **`kpkSharesProxy`** is the ERC-20 shares token investors hold. `kpkSharesImpl` is the chain's shared `kpkShares` mastercopy. The two timelock fields are `address(0)` when the fund has no timelock.
{% endhint %}

## 1. Look up a registered fund

Funds in the factory's curated registry are returned by `getFund(registeredFundId)` as an `OivInstance`. Funds the factory deployed itself are logged in `instances(id)` with the same shape, for ids `0` to `instanceCount() - 1`. Stack-only chains log the fund in `stacks(id)` instead (`StackInstance`, ids `0` to `stackCount() - 1`).

{% hint style="info" %}
The salt v4 registry is empty until the factory owner (the Security Council Safe) registers funds. `getFund` reverts `FundNotRegistered` for any id that was never used or has since been unregistered, so iterate `0` to `registeredFundCount() - 1` and skip the ids that revert. Registry entries are owner-asserted and not verified onchain; for funds this factory deployed, read `instances(id)` instead.
{% endhint %}

```solidity
struct OivInstance {
    address avatarSafe;           // the fund's Portfolio Safe (holds assets)
    address managerSafe;
    address execRolesModifier;
    address subRolesModifier;
    address managerRolesModifier;
    address kpkSharesImpl;        // the chain's shared kpkShares mastercopy
    address kpkSharesProxy;       // the ERC-20 shares token
    address execTimelock;         // owns the exec Roles Modifier, or address(0)
    address sharesTimelock;       // holds DEFAULT_ADMIN_ROLE on the shares, or address(0)
}

function getFund(uint256 registeredFundId) external view returns (OivInstance memory);
```

{% tabs %}
{% tab title="viem" %}

```typescript
import { createPublicClient, http, parseAbi } from "viem";
import { mainnet } from "viem/chains";

const FACTORY = "0x73Bb12a05669748f3c9cbE8764271c69182f49E5"; // same on every chain

const ABI = parseAbi([
  "struct OivInstance { address avatarSafe; address managerSafe; address execRolesModifier; address subRolesModifier; address managerRolesModifier; address kpkSharesImpl; address kpkSharesProxy; address execTimelock; address sharesTimelock; }",
  "function getFund(uint256 registeredFundId) view returns (OivInstance)",
]);

const client = createPublicClient({ chain: mainnet, transport: http() });

const fund = await client.readContract({
  address: FACTORY, abi: ABI, functionName: "getFund", args: [0n],
});
console.log("Portfolio Safe:", fund.avatarSafe);
console.log("Shares token:  ", fund.kpkSharesProxy);
```

{% endtab %}

{% tab title="ethers.js" %}

```typescript
import { ethers } from "ethers";

const FACTORY = "0x73Bb12a05669748f3c9cbE8764271c69182f49E5";

const ABI = [
  `function getFund(uint256 registeredFundId) view returns (
     tuple(address avatarSafe, address managerSafe, address execRolesModifier,
           address subRolesModifier, address managerRolesModifier,
           address kpkSharesImpl, address kpkSharesProxy,
           address execTimelock, address sharesTimelock))`,
];

const provider = new ethers.JsonRpcProvider("https://eth.llamarpc.com");
const factory = new ethers.Contract(FACTORY, ABI, provider);

const fund = await factory.getFund(0);
console.log("Portfolio Safe:", fund.avatarSafe);
console.log("Shares token:  ", fund.kpkSharesProxy);
```

{% endtab %}

{% tab title="Python" %}

```python
from web3 import Web3

FACTORY = "0x73Bb12a05669748f3c9cbE8764271c69182f49E5"

OIV_INSTANCE = [{"name": n, "type": "address"} for n in
    ["avatarSafe", "managerSafe", "execRolesModifier", "subRolesModifier",
     "managerRolesModifier", "kpkSharesImpl", "kpkSharesProxy",
     "execTimelock", "sharesTimelock"]]
ABI = [{
    "name": "getFund", "type": "function", "stateMutability": "view",
    "inputs": [{"name": "registeredFundId", "type": "uint256"}],
    "outputs": [{"name": "", "type": "tuple", "components": OIV_INSTANCE}],
}]

w3 = Web3(Web3.HTTPProvider("https://eth.llamarpc.com"))
fund = w3.eth.contract(address=FACTORY, abi=ABI).functions.getFund(0).call()
print("Portfolio Safe:", fund[0])   # avatarSafe
print("Shares token:  ", fund[6])   # kpkSharesProxy
```

{% endtab %}
{% endtabs %}

{% hint style="info" %}
`predictOivAddresses(config, caller)` on the factory returns the same `OivInstance` for a set of inputs **without** sending a transaction, which is useful to look up a fund's Portfolio Safe before it is deployed. For CCIP-deployed funds, predict through the orchestrator instead (next section), which applies the config-and-topology-bound salt.
{% endhint %}

## 2. Deploy a fund across chains

A single call to `CcipOivDeployer.deployEverywhere` on any wired chain deploys the fund there and fans the operational stack out to every other reachable chain that is not a shares chain (see [Cross-chain deployment](https://docs.kpk.io/funds/infrastructure/architecture/deployment/cross-chain-deployment.md)). Build an `OivConfig` and the fund's `sharesChains` topology, **predict** the resulting addresses, **quote** the native CCIP fee, then **deploy** with that fee, plus a buffer, as `msg.value`.

The example deploys a fund whose shares live on Ethereum only, with both admin powers behind 2-day timelocks from birth.

```solidity
struct SharesChain { uint256 chainId; address asset; }
struct TimelockParams { uint256 minDelay; address[] proposers; address[] cancellers; }

function predictOiv(OivConfig config, SharesChain[] sharesChains) external view returns (OivInstance);
function quoteDeployEverywhere(OivConfig config, SharesChain[] sharesChains, uint256 gasLimit)
    external view returns (uint256 totalFee, uint256[] memory feePerDestination);
function deployEverywhere(OivConfig config, SharesChain[] sharesChains, uint256 gasLimit)
    external payable returns (OivInstance instance, bytes32[] memory messageIds);
```

{% hint style="warning" %}

* **Every field the salt binds is address-bearing**: everything except the per-chain base asset and the ignored fields noted on [Cross-chain deployment](https://docs.kpk.io/funds/infrastructure/architecture/deployment/cross-chain-deployment.md#entry-points). The salt binds the whole config and the topology, so predict with the exact `config` and `sharesChains` you will deploy, and keep both for the life of the fund, because `deployLocal`, `dispatchTo`, and `promoteShares` all need them again.
* **Sort every address list ascending by value**: `managerSafe.owners`, and each timelock's `proposers` and `cancellers`. A list in any other order reverts.
* **Gas limit.** Pass `3_000_000` for a timelocked fund; `2_000_000` is ample without an exec timelock.
  {% endhint %}

{% tabs %}
{% tab title="viem" %}

```typescript
import { createPublicClient, createWalletClient, http, parseAbi, zeroAddress } from "viem";
import { privateKeyToAccount } from "viem/accounts";
import { mainnet } from "viem/chains";

const CCIP = "0xD99e4B13fc50A6321f6A84f2D4F83d6e34AE699D"; // orchestrator, same on every chain
const USDC = "0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48";

// viem's parseAbi understands struct definitions: declare them once, reuse below.
const ABI = parseAbi([
  "struct SafeConfig { address[] owners; uint256 threshold; }",
  "struct AssetConfig { address asset; bool canDeposit; bool canRedeem; }",
  "struct TimelockParams { uint256 minDelay; address[] proposers; address[] cancellers; }",
  "struct ConstructorParams { address asset; address admin; string name; string symbol; address safe; uint64 subscriptionRequestTtl; uint64 redemptionRequestTtl; address feeReceiver; uint256 managementFeeRate; uint256 redemptionFeeRate; address performanceFeeModule; uint256 performanceFeeRate; }",
  "struct OivConfig { SafeConfig managerSafe; uint256 salt; address admin; ConstructorParams sharesParams; AssetConfig[] additionalAssets; TimelockParams execTimelock; TimelockParams sharesTimelock; }",
  "struct SharesChain { uint256 chainId; address asset; }",
  "struct OivInstance { address avatarSafe; address managerSafe; address execRolesModifier; address subRolesModifier; address managerRolesModifier; address kpkSharesImpl; address kpkSharesProxy; address execTimelock; address sharesTimelock; }",
  "function predictOiv(OivConfig config, SharesChain[] sharesChains) view returns (OivInstance)",
  "function quoteDeployEverywhere(OivConfig config, SharesChain[] sharesChains, uint256 gasLimit) view returns (uint256 totalFee, uint256[] feePerDestination)",
  "function deployEverywhere(OivConfig config, SharesChain[] sharesChains, uint256 gasLimit) payable returns (OivInstance instance, bytes32[] messageIds)",
]);

// Every address list must be strictly ascending by value.
const MANAGER_SAFE_OWNERS = ["0x1111...", "0x2222...", "0x3333..."];
const ADMIN = "0xAdminSafe...";           // fallback owner; each timelock below supersedes it
const TIMELOCK = {
  minDelay: 172800n,                      // 2 days (0 = no timelock; else 12 hours – 30 days)
  proposers: ["0xSecurityCouncilSafe..."], // proposers can also cancel
  cancellers: [],                         // extra veto-only members; never repeat a proposer
};

const config = {
  managerSafe: { owners: MANAGER_SAFE_OWNERS, threshold: 2n },
  salt: 1n,                              // any uint256; same inputs → same addresses
  admin: ADMIN,
  sharesParams: {
    asset: USDC,                         // this chain's base asset; must match sharesChains
    admin: zeroAddress,                  // ignored (overridden by config.admin)
    name: "KPK USD Alpha",
    symbol: "kUSD",
    safe: zeroAddress,                   // ignored (set to the deployed Portfolio Safe)
    subscriptionRequestTtl: 86400n,      // ≤ 7 days
    redemptionRequestTtl: 86400n,        // ≤ 7 days
    feeReceiver: "0xFeeReceiver...",
    managementFeeRate: 100n,             // 1.00% (bps, ≤ 2000)
    redemptionFeeRate: 0n,
    performanceFeeModule: zeroAddress,   // disabled
    performanceFeeRate: 0n,
  },
  additionalAssets: [],                  // e.g. [{ asset: DAI, canDeposit: true, canRedeem: true }]
  execTimelock: TIMELOCK,                // owns the exec Roles Modifier on every chain
  sharesTimelock: TIMELOCK,              // holds DEFAULT_ADMIN_ROLE on the shares token
} as const;

// Shares on Ethereum only; every other reachable wired chain gets the operational stack.
const SHARES_CHAINS = [{ chainId: 1n, asset: USDC }];
const GAS_LIMIT = 3_000_000n;            // timelocked fund

const client = createPublicClient({ chain: mainnet, transport: http() });

// 1) predict the deterministic addresses
const predicted = await client.readContract({
  address: CCIP, abi: ABI, functionName: "predictOiv", args: [config, SHARES_CHAINS],
});
console.log("Portfolio Safe will be:", predicted.avatarSafe);

// 2) quote the native CCIP fee
const [totalFee] = await client.readContract({
  address: CCIP, abi: ABI, functionName: "quoteDeployEverywhere", args: [config, SHARES_CHAINS, GAS_LIMIT],
});

// 3) deploy, paying the fee (plus a buffer) as msg.value
const wallet = createWalletClient({
  account: privateKeyToAccount("0x<PRIVATE_KEY>"), chain: mainnet, transport: http(),
});
const hash = await wallet.writeContract({
  address: CCIP, abi: ABI, functionName: "deployEverywhere", args: [config, SHARES_CHAINS, GAS_LIMIT],
  value: totalFee * 110n / 100n,        // 10% buffer; surplus is refunded
});
console.log("deployEverywhere tx:", hash);
```

{% endtab %}

{% tab title="ethers.js" %}

```typescript
import { ethers } from "ethers";

const CCIP = "0xD99e4B13fc50A6321f6A84f2D4F83d6e34AE699D";
const USDC = "0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48";

// Reused tuple shapes (ethers has no struct keyword, so inline tuples).
const TIMELOCK_PARAMS = "tuple(uint256 minDelay, address[] proposers, address[] cancellers)";
const OIV_CONFIG =
  "tuple(tuple(address[] owners, uint256 threshold) managerSafe, uint256 salt, address admin, " +
  "tuple(address asset, address admin, string name, string symbol, address safe, " +
  "uint64 subscriptionRequestTtl, uint64 redemptionRequestTtl, address feeReceiver, " +
  "uint256 managementFeeRate, uint256 redemptionFeeRate, address performanceFeeModule, " +
  "uint256 performanceFeeRate) sharesParams, tuple(address asset, bool canDeposit, bool canRedeem)[] additionalAssets, " +
  `${TIMELOCK_PARAMS} execTimelock, ${TIMELOCK_PARAMS} sharesTimelock)`;
const SHARES_CHAINS_T = "tuple(uint256 chainId, address asset)[]";
const OIV_INSTANCE =
  "tuple(address avatarSafe, address managerSafe, address execRolesModifier, address subRolesModifier, " +
  "address managerRolesModifier, address kpkSharesImpl, address kpkSharesProxy, " +
  "address execTimelock, address sharesTimelock)";

const ABI = [
  `function predictOiv(${OIV_CONFIG} config, ${SHARES_CHAINS_T} sharesChains) view returns (${OIV_INSTANCE})`,
  `function quoteDeployEverywhere(${OIV_CONFIG} config, ${SHARES_CHAINS_T} sharesChains, uint256 gasLimit) view returns (uint256 totalFee, uint256[] feePerDestination)`,
  `function deployEverywhere(${OIV_CONFIG} config, ${SHARES_CHAINS_T} sharesChains, uint256 gasLimit) payable returns (${OIV_INSTANCE} instance, bytes32[] messageIds)`,
];

// Every address list must be strictly ascending by value.
const timelock = {
  minDelay: 172800,                      // 2 days
  proposers: ["0xSecurityCouncilSafe..."],
  cancellers: [],
};

const config = {
  managerSafe: { owners: ["0x1111...", "0x2222...", "0x3333..."], threshold: 2 },
  salt: 1,
  admin: "0xAdminSafe...",
  sharesParams: {
    asset: USDC,
    admin: ethers.ZeroAddress,           // ignored
    name: "KPK USD Alpha",
    symbol: "kUSD",
    safe: ethers.ZeroAddress,            // ignored
    subscriptionRequestTtl: 86400,
    redemptionRequestTtl: 86400,
    feeReceiver: "0xFeeReceiver...",
    managementFeeRate: 100,              // 1.00%
    redemptionFeeRate: 0,
    performanceFeeModule: ethers.ZeroAddress,
    performanceFeeRate: 0,
  },
  additionalAssets: [],
  execTimelock: timelock,
  sharesTimelock: timelock,
};
const sharesChains = [{ chainId: 1, asset: USDC }];
const GAS_LIMIT = 3_000_000n;

const provider = new ethers.JsonRpcProvider("https://eth.llamarpc.com");
const orchestrator = new ethers.Contract(CCIP, ABI, provider);

const predicted = await orchestrator.predictOiv(config, sharesChains);
console.log("Portfolio Safe will be:", predicted.avatarSafe);

const [totalFee] = await orchestrator.quoteDeployEverywhere(config, sharesChains, GAS_LIMIT);

const signer = new ethers.Wallet("0x<PRIVATE_KEY>", provider);
const tx = await orchestrator.connect(signer).deployEverywhere(config, sharesChains, GAS_LIMIT, { value: totalFee * 110n / 100n }); // 10% buffer; surplus is refunded
console.log("deployEverywhere tx:", tx.hash);
```

{% endtab %}

{% tab title="Python" %}

```python
from web3 import Web3

CCIP = "0xD99e4B13fc50A6321f6A84f2D4F83d6e34AE699D"
USDC = "0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48"
ZERO = "0x" + "0" * 40

SAFE_CONFIG = [{"name": "owners", "type": "address[]"}, {"name": "threshold", "type": "uint256"}]
ASSET_CONFIG = [{"name": "asset", "type": "address"}, {"name": "canDeposit", "type": "bool"}, {"name": "canRedeem", "type": "bool"}]
TIMELOCK_PARAMS = [{"name": "minDelay", "type": "uint256"}, {"name": "proposers", "type": "address[]"},
                   {"name": "cancellers", "type": "address[]"}]
PARAMS = [
    {"name": "asset", "type": "address"}, {"name": "admin", "type": "address"},
    {"name": "name", "type": "string"}, {"name": "symbol", "type": "string"}, {"name": "safe", "type": "address"},
    {"name": "subscriptionRequestTtl", "type": "uint64"}, {"name": "redemptionRequestTtl", "type": "uint64"},
    {"name": "feeReceiver", "type": "address"}, {"name": "managementFeeRate", "type": "uint256"},
    {"name": "redemptionFeeRate", "type": "uint256"}, {"name": "performanceFeeModule", "type": "address"},
    {"name": "performanceFeeRate", "type": "uint256"},
]
OIV_CONFIG = {"name": "config", "type": "tuple", "components": [
    {"name": "managerSafe", "type": "tuple", "components": SAFE_CONFIG},
    {"name": "salt", "type": "uint256"}, {"name": "admin", "type": "address"},
    {"name": "sharesParams", "type": "tuple", "components": PARAMS},
    {"name": "additionalAssets", "type": "tuple[]", "components": ASSET_CONFIG},
    {"name": "execTimelock", "type": "tuple", "components": TIMELOCK_PARAMS},
    {"name": "sharesTimelock", "type": "tuple", "components": TIMELOCK_PARAMS},
]}
SHARES_CHAINS = {"name": "sharesChains", "type": "tuple[]", "components": [
    {"name": "chainId", "type": "uint256"}, {"name": "asset", "type": "address"},
]}
OIV_INSTANCE = [{"name": n, "type": "address"} for n in
    ["avatarSafe", "managerSafe", "execRolesModifier", "subRolesModifier",
     "managerRolesModifier", "kpkSharesImpl", "kpkSharesProxy",
     "execTimelock", "sharesTimelock"]]
GAS = {"name": "gasLimit", "type": "uint256"}

ABI = [
    {"name": "predictOiv", "type": "function", "stateMutability": "view",
     "inputs": [OIV_CONFIG, SHARES_CHAINS], "outputs": [{"name": "", "type": "tuple", "components": OIV_INSTANCE}]},
    {"name": "quoteDeployEverywhere", "type": "function", "stateMutability": "view",
     "inputs": [OIV_CONFIG, SHARES_CHAINS, GAS],
     "outputs": [{"name": "totalFee", "type": "uint256"}, {"name": "feePerDestination", "type": "uint256[]"}]},
    {"name": "deployEverywhere", "type": "function", "stateMutability": "payable",
     "inputs": [OIV_CONFIG, SHARES_CHAINS, GAS],
     "outputs": [{"name": "instance", "type": "tuple", "components": OIV_INSTANCE},
                 {"name": "messageIds", "type": "bytes32[]"}]},
]

# Every address list must be strictly ascending by value.
timelock = (172800, ["0xSecurityCouncilSafe..."], [])  # 2 days; sole proposer, no extra cancellers

config = (
    (["0x1111...", "0x2222...", "0x3333..."], 2),   # managerSafe (owners, threshold)
    1,                                              # salt
    "0xAdminSafe...",                               # admin
    (USDC, ZERO, "KPK USD Alpha", "kUSD", ZERO,
     86400, 86400, "0xFeeReceiver...", 100, 0, ZERO, 0),  # sharesParams
    [],                                             # additionalAssets
    timelock,                                       # execTimelock
    timelock,                                       # sharesTimelock
)
shares_chains = [(1, USDC)]                         # shares on Ethereum only
GAS_LIMIT = 3_000_000                               # timelocked fund

w3 = Web3(Web3.HTTPProvider("https://eth.llamarpc.com"))
orchestrator = w3.eth.contract(address=CCIP, abi=ABI)

predicted = orchestrator.functions.predictOiv(config, shares_chains).call()
print("Portfolio Safe will be:", predicted[0])   # avatarSafe

total_fee, _ = orchestrator.functions.quoteDeployEverywhere(config, shares_chains, GAS_LIMIT).call()

# Deploy: build, sign, and send with a 10% buffer over total_fee (surplus is refunded)
acct = w3.eth.account.from_key("0x<PRIVATE_KEY>")
tx = orchestrator.functions.deployEverywhere(config, shares_chains, GAS_LIMIT).build_transaction({
    "from": acct.address, "value": total_fee * 11 // 10, "nonce": w3.eth.get_transaction_count(acct.address),
})
signed = acct.sign_transaction(tx)
print("deployEverywhere tx:", w3.eth.send_raw_transaction(signed.raw_transaction).hex())
```

{% endtab %}
{% endtabs %}

{% hint style="info" %}
Deploy to a **subset** of chains with the `deployEverywhere(config, sharesChains, destChainIds[], gasLimit)` overload, and add a stack chain to an existing fund later, or retry a permanently-failed CCIP delivery, with `dispatchTo(config, sharesChains, destChainIds[], gasLimit)` using the **same** `config` and `sharesChains`. Fill a second declared shares chain with `deployLocal(config, sharesChains)` on that chain. See [Cross-chain deployment](https://docs.kpk.io/funds/infrastructure/architecture/deployment/cross-chain-deployment.md#operational-model).
{% endhint %}


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://docs.kpk.io/funds/infrastructure/architecture/deployment/code-examples.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
