# Contract Interactions

Contract interactions let a business register approved EVM contracts or Solana programs, then expose a constrained execution surface to its backend. Use this when PayChain needs to help a business safely call smart contracts as part of a payment, treasury, or automation workflow.

{% hint style="info" %}
**Important note:** Contract interactions are not the same as normal invoice collection. Invoices track customer payments. Contract interactions are approved automation actions that may read from or write to a chain program or contract.
{% endhint %}

### When to use contract interactions

* A fintech app needs a controlled on-chain execution after a payment.
* A marketplace wants to trigger a settlement contract.
* A treasury operator wants approved backend actions without exposing wallet signer details.
* A product needs safe reads from EVM contracts or Solana programs.
* An internal backend needs repeatable execution with audit history.

### EVM contracts

For EVM contracts, operators register:

* Contract address.
* Chain and network.
* ABI.
* Allowed functions or published actions.
* Optional execution constraints.

Developer-facing usage should focus on the approved action, not private signing or sponsored-gas implementation details.

{% hint style="warning" %}
**Security note:** Do not document or expose private key, signer, network provider, or sponsored-gas internals. Developers should call PayChain’s approved action surface, not operate PayChain infrastructure directly.
{% endhint %}

### Solana programs

For Solana programs, operators register:

* Program ID.
* Network.
* Anchor IDL where available.
* Approved instructions or account reads.
* Account mappings required by published actions.

Solana actions should be documented with expected accounts, signer requirements, simulation behavior, and terminal execution status.

### Dashboard setup vs backend execution

| Step                             | Who does it           | Purpose                                                            |
| -------------------------------- | --------------------- | ------------------------------------------------------------------ |
| Register contract or program     | Dashboard operator    | Defines the on-chain surface PayChain can understand.              |
| Review functions or instructions | Dashboard operator    | Confirms what can be read or executed.                             |
| Publish approved action          | Dashboard operator    | Creates a constrained action for backend usage.                    |
| Quote or simulate                | Backend developer     | Checks cost, expected behavior, and failure risk before execution. |
| Execute action                   | Backend developer     | Runs only the approved action through PayChain.                    |
| Reconcile history                | Operator or developer | Tracks status, tx hash, errors, and business impact.               |

### Reads vs writes

* **Reads** query contract or program state and do not move funds by themselves.
* **Writes** broadcast transactions and can consume sponsored gas credits when PayChain sponsors the network cost.

{% hint style="info" %}
**Gas credit note:** Sponsored contract execution can reduce the business gas-credit balance. If credits are insufficient, eligible sponsored execution may pause until the business tops up.
{% endhint %}

### Recommended developer flow

1. Confirm the business has an approved contract integration.
2. Fetch the published actions available to the API key or backend service.
3. Validate your own product state before requesting execution.
4. Quote or simulate when the endpoint supports it.
5. Execute with an idempotency key.
6. Store the PayChain execution ID and request ID.
7. Wait for terminal execution status or webhook notification.
8. Reconcile the transaction hash and business object state.

### REST examples

Contract execution uses approved action IDs. The action must already be published by an operator from the dashboard and the API key must be scoped for contract execution.

#### Quote an approved action

```bash
curl -X POST "$PAYCHAIN_API_URL/contract-actions/$PAYCHAIN_CONTRACT_ACTION_ID/quote" \
  -H "x-api-key: $PAYCHAIN_CONTRACT_API_KEY" \
  -H "content-type: application/json" \
  -H "Idempotency-Key: order_123_contract_quote" \
  -d '{
    "params": {
      "amount": "25.00",
      "recipient": "0x0000000000000000000000000000000000000000"
    },
    "metadata": {
      "orderId": "order_123"
    }
  }'
```

#### Execute an approved action

```bash
curl -X POST "$PAYCHAIN_API_URL/contract-actions/$PAYCHAIN_CONTRACT_ACTION_ID/execute" \
  -H "x-api-key: $PAYCHAIN_CONTRACT_API_KEY" \
  -H "content-type: application/json" \
  -H "Idempotency-Key: order_123_contract_execute" \
  -d '{
    "params": {
      "amount": "25.00",
      "recipient": "0x0000000000000000000000000000000000000000"
    },
    "metadata": {
      "orderId": "order_123"
    }
  }'
```

#### Fetch execution status

```bash
curl "$PAYCHAIN_API_URL/contract-executions/exec_123" \
  -H "x-api-key: $PAYCHAIN_CONTRACT_API_KEY"
```

{% hint style="warning" %}
**Idempotency note:** Treat contract writes like financial actions. Use an idempotency key, store the execution ID, and fetch execution state before retrying after a timeout.
{% endhint %}

### Example use cases

#### Payment-triggered contract action

A merchant collects a fixed invoice, waits for `invoice.paid`, fetches the canonical invoice, then executes an approved contract action tied to the order.

Use this when:

* The payment and contract action are separate steps.
* Your backend must validate order state before execution.
* The contract action should only happen after confirmed settlement.

#### Treasury automation action

A treasury operator publishes a constrained action for a known token or settlement contract. The backend quotes and executes only that published action when internal approval rules pass.

Use this when:

* The business wants repeatable treasury movement.
* Operators need audit history.
* Developers should not manage private signing infrastructure.

#### Read-only contract view

A backend or dashboard can query approved read functions to display contract state without broadcasting a transaction.

Use this when:

* You need contract state for reconciliation.
* You need a pre-execution check.
* You need operator visibility without moving funds.

### What to document for each action

* Action name.
* Chain and network.
* Contract address or program ID.
* Function or instruction.
* Required parameters.
* Required accounts, where relevant.
* Whether it is read-only or writes to chain.
* Whether it can consume sponsored gas credits.
* Expected success state.
* Common failure states.
* Required API key or auth mode.

### Common mistakes

* Treating a contract execution as invoice payment confirmation.
* Exposing private signer, network provider, sponsored-gas, or treasury implementation details.
* Retrying a write action without an idempotency key.
* Letting client-side code choose unsafe contract parameters.
* Ignoring simulation or quote results before execution.
* Forgetting that sponsored execution can become gas-blocked.


---

# Agent Instructions: Querying This Documentation

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

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.paychainhq.io/paychainhq-documentation-page/developer-quickstart/contract-interactions.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
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.
