---
updatedAt: 2026-11-10T01:00:11.000Z
agentTools:
  projectIndex: https://docs.dinari.com/llms.txt
---

# Placing dShare Orders with Safe Vaults

This guide shows how to place a dShare order where a safe vault funds the order, signs the permit, and submits the transaction.

## How it works

1. Approve Permit2 from the Safe (once per payment token, per chain).
2. Create an order request with `createPermit` and receive the EIP-712 permit.
3. Sign the permit with the Safe (**ERC-1271** signature).
4. Build the transaction with `createPermitTransaction`.
5. Execute the transaction from the Safe.
6. Poll the order request until it reaches a terminal state.

<Callout icon="🚧" theme="warn">
  ### Permit2 approval is required

  Dinari issues an ERC-2612 permit to any wallet without a Permit2 allowance, and a Safe cannot sign ERC-2612. See [Step 3](#step-3--approve-permit2-one-time-per-token).
</Callout>

```mermaid
sequenceDiagram
    autonumber
    participant S as Safe
    participant P as Partner
    participant D as Dinari
    participant C as Chain

    S->>C: approve(Permit2) on payment token (one-time)
    P->>D: createPermit
    D-->>P: order_request_id, permit
    P->>S: Sign permit (owners)
    S-->>P: ERC-1271 signature
    P->>D: createPermitTransaction
    D-->>P: contract_address, data, value
    P->>S: execTransaction
    S->>C: Submit order
    P->>D: orderRequests.retrieve
    D-->>P: Status
```

## Prerequisites

To place an order, an Entity needs:

* A valid **KYC** on the Entity.
* A valid **Account** under the Entity.
* Enough **payment-token balance** in the Safe to cover the order plus fees.

For this integration you also need:

* #### A **Dinari API Key ID and API Secret Key** from `partners.dinari.com`. Start in **sandbox**.
* A **deployed Safe** (v1.3.0+) using the default `CompatibilityFallbackHandler`.
* Private keys for at least `threshold` Safe owners, stored server-side.
* Native gas in the owner EOA that executes Safe transactions.

### Step 1: Initialize the clients

```typescript TypeScript
import { DinariClient, DinariEnvironment } from "@dinari/api-sdk";
import Safe from "@safe-global/protocol-kit";

const dinariCredentials = await loadDinariCredentialsFromSecretManager();
const walletSecrets = await loadWalletSecretsFromSecretManager();
const config = await loadChainConfig();

const dinari = new DinariClient({
  apiKeyId: dinariCredentials.apiKeyID,
  apiSecretKey: dinariCredentials.apiSecretKey,
  environment: DinariEnvironment.Sandbox, // defaults to DinariEnvironment.Production
});

const safe = await Safe.init({
  provider: config.rpcUrl,
  signer: walletSecrets.ownerPrivateKey, // a Safe owner
  safeAddress: config.safeAddress,
});

if (!(await safe.isSafeDeployed())) {
  throw new Error("Deploy the Safe before signing permits");
}

const safeAddress = await safe.getAddress();
```
```python Python
import os

from dinari_api_sdk import DinariClient
from dinari_api_sdk.environment import DinariClientEnvironment

client = DinariClient(
    api_key_id=os.environ["DINARI_API_KEY_ID"],
    api_secret_key=os.environ["DINARI_API_SECRET_KEY"],
    environment=DinariClientEnvironment.SANDBOX,  # defaults to DinariClientEnvironment.PRODUCTION
)
```
```go Go
package main

import (
	"context"
	"os"

	dinari "github.com/dinaricrypto/dinari-api-sdk-go"
	client "github.com/dinaricrypto/dinari-api-sdk-go/client"
	option "github.com/dinaricrypto/dinari-api-sdk-go/option"
)

var (
	c = client.NewDinariClient(
		option.WithBaseURL(dinari.Environments.Sandbox), // Defaults to production when omitted
		option.WithAPIKeyID(os.Getenv("DINARI_API_KEY_ID")),
		option.WithAPISecretKey(os.Getenv("DINARI_API_SECRET_KEY")),
	)
	ctx = context.Background()
)
```
```java Java
import com.dinari.api.DinariClient;
import com.dinari.api.core.Environment;

public class Main {
    static final DinariClient client = DinariClient.builder()
            .environment(Environment.SANDBOX) // defaults to Environment.PRODUCTION
            .apiKeyId(System.getenv("DINARI_API_KEY_ID"))
            .apiSecretKey(System.getenv("DINARI_API_SECRET_KEY"))
            .build();
}
```

> The Safe interactions in this guide use the Safe TypeScript SDK. The Python, Go and Java tabs show the Dinari API calls that stand on their own (client setup, stock lookup, permit creation and order status), with the same variable names.

### Step 2: Complete KYC and link the Safe (one-time)

KYC requires the user to complete a hosted flow, so it cannot be fully automated server-side.

```typescript TypeScript
const entity = await dinari.entities.createEntities({ name: "Jane Doe" });
const kyc = await dinari.kyc.createManagedEntityKycEmbed({ entityId: entity.id });
console.log("Send the user to:", kyc.embedUrl);

const account = await dinari.accounts.createEntityAccounts({ entityId: entity.id });
const accountId = account.id;

const nonceResp = await dinari.wallets.getAccountWalletConnectionNonce({
  accountId,
  walletAddress: safeAddress,
  chainId: "eip155:421614",
});

const linkMessage = await safe.signMessage(safe.createMessage(nonceResp.message));

await dinari.wallets.createAccountWalletConnection({
  accountId,
  chainId: "eip155:421614",
  nonce: nonceResp.nonce,
  signature: linkMessage.encodedSignatures(),
  walletAddress: safeAddress,
});
```

<Callout icon="📘" theme="info">
  ### Link the Safe, not an owner

  `walletAddress` must be the Safe address. Linking an owner EOA attributes orders to a wallet with no funds.
</Callout>

### Step 3: Approve Permit2 (one-time, per token)

`createpermit` picks the permit type from the wallet's on-chain ERC-20 allowance to Permit2, not from the wallet type:

| Safe's allowance to Permit2 | Permit returned              | Safe can sign? |
| --------------------------- | ---------------------------- | -------------- |
| None                        | ERC-2612 `Permit`            | No             |
| Present                     | Permit2 `PermitTransferFrom` | Yes            |

Send the approval as a Safe transaction so the allowance belongs to the Safe:

```typescript TypeScript
import { encodeFunctionData, erc20Abi, maxUint256 } from "viem";

const PERMIT2 = "0x000000000022D473030F116dDEE9F6B43aC78BA3";

const approveTx = await safe.createTransaction({
  transactions: [
    {
      to: config.paymentTokenAddress,
      value: "0",
      data: encodeFunctionData({
        abi: erc20Abi,
        functionName: "approve",
        args: [PERMIT2, maxUint256],
      }),
    },
  ],
});

await safe.executeTransaction(await safe.signTransaction(approveTx));
```

<Callout icon="🚧" theme="warn">
  ### Per token, per chain

  Each payment token on each chain needs its own approval. If the allowance is revoked or used up, `createPermit` goes back to returning ERC-2612 permits.
</Callout>

### Step 4: Select the stock and order parameters

```typescript TypeScript
const stocks = await dinari.marketData.getStocks({ symbols: "AAPL", limit: 20 });
const stock = (Array.isArray(stocks) ? stocks : stocks.data).find((s) => s.symbol === "AAPL");
if (!stock) throw new Error("Stock not found");
const stockId = stock.id;
```
```python Python
stocks = client.market_data.get_stocks(symbols="AAPL", limit=20)
stock = next((s for s in (stocks if isinstance(stocks, list) else stocks.data) if s.symbol == "AAPL"), None)
if stock is None:
    raise RuntimeError("Stock not found")
stock_id = stock.id
```
```go Go
stocks, err := c.MarketData.GetStocks(ctx, &dinari.GetStocksRequest{
	Symbols: []*string{dinari.String("AAPL")},
	Limit:   dinari.Int(20),
})
if err != nil {
	log.Fatalf("Failed to list stocks: %v", err)
}

var stockID string
for _, s := range stocks.GetPaginatedStockResponse().Data {
	if s.Symbol == "AAPL" {
		stockID = s.ID
	}
}
if stockID == "" {
	log.Fatal("Stock not found")
}
```
```java Java
var stocks = client.marketData().getStocks(
        GetStocksRequest.builder().symbols("AAPL").limit(20).build());
String stockId = ((PaginatedStockResponse) stocks.get()).getData().stream()
        .filter(s -> s.getSymbol().equals("AAPL"))
        .findFirst()
        .orElseThrow(() -> new RuntimeException("Stock not found"))
        .getId();
```

| Field                    | Meaning                                                              |
| ------------------------ | -------------------------------------------------------------------- |
| `stock_id`               | Dinari UUID of the dShare (from `marketData.getStocks()`).           |
| `order_side`             | `"BUY"` or `"SELL"`.                                                 |
| `order_type`             | `"MARKET"` or `"LIMIT"`.                                             |
| `order_tif`              | Time-in-force, e.g. `"DAY"`.                                         |
| `payment_token`          | Payment-token address. Must be the token approved in Step 3.         |
| `payment_token_quantity` | For a market **buy**, the notional amount of payment token to spend. |
| `chain_id`               | CAIP-2 chain id, e.g. `"eip155:421614"`.                             |

Market sells and limit orders use `asset_quantity` instead; limit orders also take `limit_price`. Fees are added on top of the notional.

### Step 5: Create the order permit

```typescript TypeScript
const permitResponse = await dinari.orderRequests.createEip155OrderRequestPermit({
  accountId,
  chainId: "eip155:421614",
  orderSide: "BUY",
  orderType: "MARKET",
  orderTif: "DAY",
  stockId,
  paymentToken: config.paymentTokenAddress,
  paymentTokenQuantity: 10.0,
});

const orderRequestId = permitResponse.orderRequestId;
const permit = permitResponse.permit as Record<string, any>; // { domain, types, primaryType, message }

if (permit.primaryType === "Permit") {
  throw new Error("Got an ERC-2612 permit. Approve Permit2 from the Safe (Step 3).");
}
```
```python Python
permit_response = client.order_requests.create_eip155order_request_permit(
    account_id=account_id,
    chain_id="eip155:421614",
    order_side="BUY",
    order_type="MARKET",
    order_tif="DAY",
    stock_id=stock_id,
    payment_token=payment_token_address,
    payment_token_quantity=10.0,
)

order_request_id = permit_response.order_request_id
permit = permit_response.permit  # { domain, types, primaryType, message }

if permit["primaryType"] == "Permit":
    raise RuntimeError("Got an ERC-2612 permit. Approve Permit2 from the Safe (Step 3).")
```
```go Go
permitResponse, err := c.OrderRequests.CreateEip155OrderRequestPermit(ctx, &dinari.Eip155OrderRequestPermitInput{
	AccountID:            accountID,
	ChainID:              dinari.ChainIDEip155421614,
	OrderSide:            dinari.OrderSideBuy,
	OrderType:            dinari.OrderTypeMarket,
	OrderTif:             dinari.OrderTifDay,
	StockID:              dinari.String(stockID),
	PaymentToken:         paymentTokenAddress,
	PaymentTokenQuantity: dinari.Float64(10.0),
})
if err != nil {
	log.Fatalf("Failed to create permit: %v", err)
}

orderRequestID := permitResponse.OrderRequestID
permit := permitResponse.Permit // { domain, types, primaryType, message }

if permit["primaryType"] == "Permit" {
	log.Fatal("Got an ERC-2612 permit. Approve Permit2 from the Safe (Step 3).")
}
```
```java Java
var permitResponse = client.orderRequests().createEip155OrderRequestPermit(
        accountId,
        Eip155OrderRequestPermitInput.builder()
                .chainId(ChainId.EIP155421614)
                .orderTif(OrderTif.DAY)
                .orderSide(OrderSide.BUY)
                .orderType(OrderType.MARKET)
                .paymentToken(paymentTokenAddress)
                .stockId(stockId)
                .paymentTokenQuantity(10.0)
                .build());

String orderRequestId = permitResponse.getOrderRequestId();
Map<String, Object> permit = permitResponse.getPermit(); // { domain, types, primaryType, message }

if ("Permit".equals(permit.get("primaryType"))) {
    throw new IllegalStateException("Got an ERC-2612 permit. Approve Permit2 from the Safe (Step 3).");
}
```

Check `primaryType` before signing. `Permit` means ERC-2612 and will fail; `PermitTransferFrom` or `PermitWitnessTransferFrom` means Permit2.

### Step 6: Sign the permit with the Safe

```typescript TypeScript
let signedPermit = await safe.signMessage(
  safe.createMessage({
    domain: permit.domain,
    types: permit.types,
    primaryType: permit.primaryType,
    message: permit.message,
  }),
);

// For threshold > 1, add each remaining owner's signature:
for (const ownerKey of walletSecrets.additionalOwnerKeys) {
  const ownerSafe = await safe.connect({ signer: ownerKey });
  signedPermit = await ownerSafe.signMessage(signedPermit);
}

const permitSignature = signedPermit.encodedSignatures();
```

<Callout icon="🚧" theme="warn">
  ### Use `encodedSignatures()`

  Pass the Safe's encoded signature, not an owner's raw 65-byte signature. The Safe's `isValidSignature` rejects raw owner signatures.
</Callout>

Permits have a short deadline. If owner approvals take time, create a new permit (Step 5) once signers are ready.

### Step 7: Build and send the transaction

```typescript TypeScript
const tx = await dinari.orderRequests.createEip155PermitTransaction({
  accountId,
  body: { orderRequestId, permitSignature },
});

const orderTx = await safe.createTransaction({
  transactions: [
    { to: tx.contractAddress, data: tx.data, value: tx.value ?? "0" },
  ],
});

const result = await safe.executeTransaction(await safe.signTransaction(orderTx));
console.log("Tx hash:", result.hash);
```

The owner EOA pays gas; the Safe is `msg.sender`. Do not send `tx.data` directly from an owner EOA.

### Step 8: Poll order status

```typescript TypeScript
const orderRequest = await dinari.orderRequests.getOrderRequestById({
  accountId,
  orderRequestId,
});
console.log("Status:", orderRequest.status);
```
```python Python
order_request = client.order_requests.get_order_request_by_id(
    account_id=account_id,
    order_request_id=order_request_id,
)
print("Status:", order_request.status)
```
```go Go
orderRequest, err := c.OrderRequests.GetOrderRequestByID(ctx, &dinari.GetOrderRequestByIDRequest{
	AccountID:      accountID,
	OrderRequestID: orderRequestID,
})
if err != nil {
	log.Fatalf("Failed to get order request: %v", err)
}
fmt.Println("Status:", orderRequest.Status)
```
```java Java
var orderRequest = client.orderRequests().getOrderRequestById(accountId, orderRequestId);
System.out.println("Status: " + orderRequest.getStatus());
```

Two status concepts exist:

* `OrderRequestStatus` — the request status (pre-brokerage), on the `OrderRequest`.
* `BrokerageOrderStatus` — the resulting `Order`, via `dinari.orders.getOrderById({ accountId, orderId })`.

### Permit2 and smart contract wallets

ERC-2612 `permit()` verifies signatures with `ecrecover`, which only works for EOAs. Permit2 checks whether the signer has code and, if so, calls `isValidSignature` on it (ERC-1271). A Safe can only pass the second check.

`createPermit` returns an ERC-2612 permit whenever the wallet has no Permit2 allowance for the payment token. A new Safe has none, so its first order fails. The API accepts the signature either way, because verification happens on-chain:

| Flow             | What you see                                 |
| ---------------- | -------------------------------------------- |
| User Sponsored   | Safe transaction reverts, usually `GS013`    |
| Dinari Sponsored | No error returned; the order request expires |

<br />

<Callout icon="🔨" theme="warn">
  **Fix:** approve Permit2 from the Safe ([Step 3](#step-3--approve-permit2-one-time-per-token)) and check `primaryType` before signing ([Step 5](#step-5--create-the-order-permit)).
</Callout>

## Common errors

| Symptom                                         | Likely Cause                                       | Fix                                                                  |
| ----------------------------------------------- | -------------------------------------------------- | -------------------------------------------------------------------- |
| `primaryType` is `Permit`                       | No Permit2 allowance for this token/chain          | Approve Permit2 from the Safe (Step 3)                               |
| `GS013` on order submission                     | ERC-2612 permit was signed                         | Approve Permit2, create and sign a new permit                        |
| Order request expires (Dinari Sponsored)        | ERC-2612 permit was signed                         | Approve Permit2, create and sign a new permit                        |
| `isValidSignature` reverts                      | Safe not deployed, or non-default fallback handler | Deploy the Safe; use `CompatibilityFallbackHandler`                  |
| Signature rejected with a Permit2 permit        | Raw owner signature sent                           | Send `encodedSignatures()`                                           |
| Transaction reverts as expired                  | Permit deadline passed during signing              | Create a new permit                                                  |
| Wallet linking fails                            | Safe not deployed, or owner EOA linked             | Deploy, then link the Safe address                                   |
| Order reverts or attributed to the wrong wallet | `tx.data` sent from an owner EOA                   | Execute through the Safe (Step 7)                                    |
| Insufficient funds                              | Safe balance below notional + fees                 | Fund the Safe; see [Partner Fees](https://docs.dinari.com/docs/fees) |