bitpro가 원문에서 글자만 모은 내용이에요. 표·그림·수식은 빠지거나 깨질 수 있어요. 전체 52쪽 중 20쪽
rk.
```typescript
import { ethers } from "ethers";
// Set up on-chain variables, such as target address
const counter = "0x00172f67db60E5fA346e599cdE675f0ca213b47b";
const abi = ["function incrementContext() external"];
const apiKey = process.env.NEXT_PUBLIC_GELATO_RELAY_API_KEY;
if (!apiKey) {
throw new Error("Missing Gelato Relay API key");
}
const provider = new ethers.BrowserProvider(window.ethereum);
const signer = await provider.getSigner();
const user = await signer.getAddress();
// Generate the target payload
const contract = new ethers.Contract(counter, abi, signer);
const { data } = await contract.incrementContext.populateTransaction();
// Populate a relay request
const request: CallWithERC2771Request = {
chainId: (await provider.getNetwork()).chainId,
target: counter,
data,
user,
};
// Without a specific API key, the relay request will fail!
// Go to https://app.gelato.cloud to get an API key with 1Balance funding.
// Send a relay request using Gelato Relay!
const relayResponse = await relay.sponsoredCallERC2771(request, provider, apiKey);
```
#### Further Gelato resources
* [Gelato Relay Docs](https://docs.gelato.cloud/relay/erc2771-recommended/sponsoredcall-erc2771)
* [Gelato Supported Networks](https://docs.gelato.cloud/relay/additional-resources/supported-networks)
* [GitHub Repository](https://github.com/gelatodigital/how-tos-5-6-7-8-relay-intro-methods)
# Decentralized databases
Learn how to store the application data with a decentralized database on Filecoin.
### <mark style="color:blue;">Store data with Tableland</mark>
Tableland is a **decentralized database** built on the SQLite engine, which offers developers a web3-native, relational database that seamlessly integrates into their EVM-compatible stacks. Under the hood, Tableland records database tables as ERC721 tokens on-chain and enables the execution of SQL statements in a completely decentralized manner through on-chain smart contracts.
To learn more about what is tableland and how to use it, you can visit <https://tableland.xyz/>.
#### **Ingredients**
Ensure that you install and import the necessary dependencies in your projects.
* [Tableland](https://tableland.xyz/)
* [`@tableland/evm`](https://www.npmjs.com/package/@tableland/evm)
* [`@tableland/sdk`](https://www.npmjs.com/package/@tableland/sdk)
* [OpenZeppelin Contracts](https://docs.openzeppelin.com/contracts/5.x/)
#### **Instructions**
Let's take storage deal aggregation as an example to demonstrate how to integrate it with Tableland.
When uploading data via storage aggregation providers to the Filecoin network, you can choose to store its metadata in Tableland tables instead of storing it in the chain state. This metadata can then be easily accessed from the Tableland database and utilized directly within your application.
If you require sample datasets to use, you can use the [Filecoin Dataset Explorer](https://datasets.filecoin.io/).
As an example, let's design the deal aggregator table as follows. You can add more columns to this table to include additional aggregation metadata.
| column | data Type |
| --------- | ------------ |
| ID | int |
| CID | bytes/string |
| deal\_ID | int |
| miner\_ID | int |
| status | string |
1. **Create aggregator table**
To track all deal aggregation requests submitted to the smart contract, we need to create a database table. The following Solidity excerpt assumes the contract imports `SQLHelpers`, `TablelandDeployments`, and OpenZeppelin's `Strings` utility. It creates an aggregator table in the contract constructor so the deployed contract owns the table.
```solidity
import {Strings} from "@openzeppelin/contracts/utils/Strings.sol";
import {SQLHelpers} from "@tableland/evm/contracts/utils/SQLHelpers.sol";
import {TablelandDeployments} from "@tableland/evm/contracts/utils/TablelandDeployments.sol";
uint256 private _tableId;
string private constant _TABLE_PREFIX = "aggregator_table";
constructor() {
_tableId = TablelandDeployments.get().create(
address(this),
SQLHelpers.toCreateFromSchema(
"id integer primary key, cid text, deal_id integer, miner_id integer, status text",
_TABLE_PREFIX
)
);
}
```
2. We will create an `insert` function within the smart contract to add a record whenever an aggregation request is made.
```solidity
function insertRecord(uint256 id, string memory cid, string memory status) internal {
TablelandDeployments.get().mutate(
address(this), // Table owner, i.e., this contract
_tableId,
SQLHelpers.toInsert(
_TABLE_PREFIX,
_tableId,
"id,cid,status",
string.concat(
Strings.toString(id),
",",
SQLHelpers.quote(cid),
",",
SQLHelpers.quote(status)
)
)
);
}
```
Whenever the `submit` function is called, a record will be inserted into the aggregator table instead of being stored in the blockchain's state.
```solidity
function submit(string calldata cid) external returns (uint256) {
// Increment the transaction ID
transactionId++;
// Save the CID record to aggregator_table
insertRecord(transactionId, cid, "PROPOSED");
// Emit the event
emit SubmitAggregatorRequest(transactionId, cid);
return transactionId;
}
```
3. We create an `updateRecord` function to modify an aggregator record once the `complete` function is called after the storage deal has been made on the Filecoin network.
```solidity
function updateRecord(
uint256 id,
uint256 dealId,
uint256 minerId,
string memory status
) internal {
string memory setters = string.concat(
"deal_id=",
Strings.toString(dealId),
",miner_id=",
Strings.toString(minerId),
",status=",
SQLHelpers.quote(status)
);
string memory filters = string.concat("id=", Strings.toString(id));
TablelandDeployments.get().mutate(
address(this),
_tableId,
SQLHelpers.toUpdate(_TABLE_PREFIX, _tableId, setters, filters)
);
}
```
After SP finishes publishing the storage deal on-chain to include an aggregation request, a callback function `complete` will be called to notify the contract that a CID is packed into a storage deal. Then we can call `updateRecord` to update the details for this CID record in the Tableland database. This is an excerpt from the broader aggregator contract; keep your existing proof verification and return-data logic around the table update.
```solidity
function complete(
uint256 id,
uint64 dealId,
uint64 minerId,
InclusionProof memory proof,
InclusionVerifierData memory verifierData
) external returns (InclusionAuxData memory) {
// Verify proof and update the storage-deal state.
InclusionAuxData memory auxData;
updateRecord(id, dealId, minerId, "FINISHED");
// Return the verifier data required by the full aggregator contract.
return auxData;
}
```
4. **Query aggregation records**
By using the Tableland SDK, you can query the aggregation status of all data stored with the aggregator using SQL statements. For instance, you can retrieve all records associated with a specific CID by executing a SELECT statement.
```typescript
import { Database } from "@tableland/sdk";
const db = new Database();
const tableName = "aggregator_314159_123";
const cid = "bafy...";
const { results } = await db
.prepare(`SELECT * FROM ${tableName} WHERE cid = ?1`)
.bind(cid)
.all();
console.log(results);
```
To learn how to write different select statements using Tableland SDK, see the [Tableland prepared statements guide](https://docs.tableland.xyz/sdk/database/prepared-statements). For current Solidity helper signatures, use the [Tableland SQL helpers library](https://docs.tableland.xyz/smart-contracts/sql-helpers).
[Was this page helpful?](https://airtable.com/apppq4inOe4gmSSlk/pagoZHC2i1iqgphgl/form?prefill_Page+URL=https://docs.filecoin.io/build/advanced/decentralized-databases)
# Privacy & Access Control
Reference-only guide to official privacy and access-control resources for data stored on Filecoin.
{% hint style="info" %}
This page is reference-only.
We do not maintain step-by-step third-party privacy/access-control tutorials in Builder Cookbook. Use the official resources below for implementation details.
{% endhint %}
### <mark style="color:blue;">Encrypting data for storing on Filecoin</mark>
Use these official references for encryption workflows and secure upload patterns:
* [Lighthouse encryption docs](https://docs.lighthouse.storage/how-to/upload-encrypted-data)
* [Lighthouse access-control conditions](https://docs.lighthouse.storage/how-to/encryption-features/access-control-conditions)
* [Lighthouse SDK docs](https://docs.lighthouse.storage)
When building production flows, validate key management, signer auth, and recovery procedures in your own threat model.
### <mark style="color:blue;">Gated access to your dataset</mark>
For condition-based access control and policy design:
* [Lighthouse access-control docs](https://docs.lighthouse.storage/how-to/encryption-features/access-control-conditions)
* [Filecoin smart contracts best practices](/build-on-filecoin/developing-contracts/best-practices)
* [Built-in actors reference](/reference/built-in-actors)
[Was this page helpful?](https://airtable.com/apppq4inOe4gmSSlk/pagoZHC2i1iqgphgl/form?prefill_Page+URL=https://docs.filecoin.io/build/cookbook/data-storage/privacy-and-access-control)
# Cookbook
Task-focused guidance for building on Filecoin. Each page points you to the official, actively maintained tools and resources for a specific task, rather than duplicating third-party tutorials that drift out of date. The Filecoin Pin pages include full step-by-step walkthroughs.
## Table of contents
* [Store data](/build-on-filecoin/cookbook/store-data) — recipes for programmable storage of public or private data on Filecoin
* [Retrieve data](/build-on-filecoin/cookbook/retrieve-data) — recipes for fetching stored data from the network
* [Filecoin Pin](/build-on-filecoin/cookbook/filecoin-pin) — recipes for using Filecoin Pin to store and retrieve data on Filecoin Onchain Cloud
[Was this page helpful?](https://airtable.com/apppq4inOe4gmSSlk/pagoZHC2i1iqgphgl/form?prefill_Page+URL=https://docs.filecoin.io/build/cookbook)
# Store data
Reference-only guide to official storage onboarding resources for Filecoin data storage workflows.
{% hint style="info" %}
This page is reference-only.
We do not maintain step-by-step third-party storage tutorials in Builder Cookbook. Use the official resources below for implementation details.
{% endhint %}
### <mark style="color:blue;">Prepare data for Filecoin storage</mark>
Use these resources to prepare CAR artifacts and storage inputs:
* [Lighthouse documentation](https://docs.lighthouse.storage/)
* [go-car command-line tooling](https://github.com/ipld/go-car)
* [IPLD CAR specification and JavaScript libraries](https://github.com/ipld/js-car)
* [IPFS Desktop / Kubo docs](https://docs.ipfs.tech/)
Recommended outputs before proposing storage workflows:
* Piece CID / Payload CID
* CAR size and piece size
* A durable retrieval URL or CID
### <mark style="color:blue;">Store large data with Filecoin Onchain Cloud</mark>
Use the FOC stack for programmatic, verifiable storage at scale:
* [Filecoin Onchain Cloud overview](/build-on-filecoin/filecoin-onchain-cloud)
* [FOC quickstart and Synapse docs](/build-on-filecoin/filecoin-onchain-cloud/synapse-quickstart)
* [FOC developer guides](https://docs.filecoin.cloud/developer-guides)
* [PDP documentation](/provide-storage/pdp)
### <mark style="color:blue;">Store small data with storage onramps</mark>
For smaller datasets and managed ingestion paths:
* [Storage onramps overview](/getting-started/how-storage-works/storage-onramps)
* [Filecoin Pin getting started](/build-on-filecoin/cookbook/filecoin-pin/getting-started)
* [Lighthouse documentation](https://docs.lighthouse.storage/)
### <mark style="color:blue;">Monitor storage deal status from a smart contract</mark>
For actor-level deal status lookups and contract integration references:
* [Built-in actors overview](/reference/built-in-actors)
* [Protocol API reference](/reference/built-in-actors/protocol-api)
* [Filecoin.sol reference](/reference/built-in-actors/filecoin.sol)
### <mark style="color:blue;">Incentivized data storage</mark>
For incentive design and onboarding programs:
* [Filecoin Data Onboarding](https://dataonboarding.filecoin.io/)
* [Filecoin storage market basics](/getting-started/what-is-filecoin/storage-market)
[Was this page helpful?](https://airtable.com/apppq4inOe4gmSSlk/pagoZHC2i1iqgphgl/form?prefill_Page+URL=https://docs.filecoin.io/build/cookbook/store-data)
# Retrieve data
Reference-only guide to official retrieval resources for accessing data stored on Filecoin.
### <mark style="color:blue;">Retrieve data using retrieval clients</mark>
To retrieve data stored on the Filecoin network, the basic process involves making retrieval requests to storage providers or IPFS peers using the root Content ID (CID) for the data.
Filecoin retrieval clients handle provider discovery and transport selection behind the scenes. Provide the root CID, and the client returns the data through a command-line interface or a library integration.
#### **Ingredients**
With a given CID, you can use the following maintained retrieval tooling:
* [Lassie](https://github.com/filecoin-project/lassie): retrieves IPFS and Filecoin content over the best available protocols.
* [go-car](https://github.com/ipld/go-car): reads, lists, and extracts content-addressed archive (CAR) files.
#### **Instructions**
**Retrieving content with Lassie**
Install the current Lassie and go-car command-line tools. Make sure [Go](https://go.dev/doc/install) is installed and that your Go binary directory is on your `PATH`, or download the latest binaries from the [Lassie releases](https://github.com/filecoin-project/lassie/releases/latest) and [go-car releases](https://github.com/ipld/go-car/releases/latest):
```sh
go install github.com/filecoin-project/lassie/cmd/lassie@latest
go install github.com/ipld/go-car/cmd/car@latest
```
Lassie fetches content in CAR form. Stream the CAR to go-car when you want to extract the UnixFS files immediately:
```sh
lassie fetch -o - <CID> | car extract -
```
To save the CAR for later inspection or extraction:
```sh
lassie fetch -p -o <CID>.car <CID>
car ls -f <CID>.car
car extract -f <CID>.car
```
For example:
```sh
lassie fetch -o - bafybeic56z3yccnla3cutmvqsn5zy3g24muupcsjtoyp3pu5pm5amurjx4 | car extract -
```
For library integrations, use the current [Lassie Go library documentation](https://github.com/filecoin-project/lassie?tab=readme-ov-file#golang-library) instead of copying an example from this reference page.
For quick retrieval of existing datasets with the methods above, check out the [Filecoin Dataset Explorer](https://datasets.filecoin.io/).
* [Filecoin Dataset Explorer](https://datasets.filecoin.io/)
[Was this page helpful?](https://airtable.com/apppq4inOe4gmSSlk/pagoZHC2i1iqgphgl/form?prefill_Page+URL=https://docs.filecoin.io/build/cookbook/retrieve-data)
# Real World Assets (RWAs)
Verifiable data infrastructure for tokenized assets. Connect onchain assets to the offchain records they depend on using IPFS + Filecoin to make deeds, appraisals, certifications and other source data
Connect onchain assets to the offchain records they depend on. Use IPFS + Filecoin to make deeds, appraisals, certifications and other source data durable, content-addressed and independently verifiable.
* [Explore the working demo →](https://sgtpooki.github.io/Avalanche-IPFS-Filecoin-RWA-reference-Architecture/) (runs live on Avalanche Fuji and Filecoin Calibration; no wallet needed)
* [View implementation →](https://github.com/SgtPooki/Avalanche-IPFS-Filecoin-RWA-reference-Architecture)
## Your asset is onchain. Its source of truth usually isn't.
Tokenized assets rely on offchain records to establish what they represent. If those records live only in an issuer's database or cloud account, applications depend on that infrastructure to preserve the data unchanged.
IPFS + Filecoin give RWA applications a verifiable data layer: **IPFS identifies the exact content, Filecoin persistently stores it with cryptographic proofs, and your onchain application references the CID.**
## A hybrid architecture for real-world assets

| Component | What it does | Output |
| --------------------- | -------------------------------------------------------- | -------------------------------------------------- |
| **RWA source record** | Deed, title, appraisal, certification, disclosure | The document |
| **IPFS** | Content-addresses the record | A CID (content identifier) derived from the bytes |
| **Filecoin** | Persists the underlying data | Verifiable storage, backed by cryptographic proofs |
| **Avalanche** | References the CID from the onchain asset or application | Onchain state and transactions |
The result is a durable link between an onchain asset and the exact offchain data it represents.
## How it works
1. **Store the source record.** An issuer adds an offchain asset record such as a deed, appraisal or certification.
2. **Create a content-addressed reference.** IPFS generates a CID derived from the content itself. If the record changes, its CID changes too.
3. **Persist it on Filecoin.** The referenced data is stored on Filecoin, giving durable storage backed by cryptographic proofs.
4. **Reference it from Avalanche.** The application records the CID alongside the relevant asset or transaction on Avalanche.
5. **Verify independently.** A third party retrieves the record and checks that it matches the CID the application referenced.
## See it in action: property record
The [working example](https://sgtpooki.github.io/Avalanche-IPFS-Filecoin-RWA-reference-Architecture/) publishes a synthetic property record set for 123 Main Street: a deed, a survey, a parcel file and two tax assessments, issued by a county recorder. Each file is content-addressed with IPFS, stored on Filecoin, and listed in a manifest whose CID is anchored on Avalanche.
| Field | Value |
| -------------------- | --------------------------------------------------------------------------------------------------- |
| Property | 123 Main Street, Fairview |
| Record type | Property deed |
| Parcel | 07-14-226-0031 |
| Issuer | Fairview County Recorder |
| IPFS CID of the deed | `bafkreidh5qsi5z6uo2thzvynr27ioajoviafqiveunrielhugyj65l6rzu` |
| Filecoin status | Persisted, with a current storage proof |
| Avalanche reference | [Registry on Fuji](https://testnet.snowtrace.io/address/0x7fdfdb7F166A3dEE947A5533e20B8E5Ce8c80863) |
| Verification | Retrieved record matches the referenced CID |
Press **Verify now** in the demo, or run it from a terminal with no key:
```sh
git clone https://github.com/SgtPooki/Avalanche-IPFS-Filecoin-RWA-reference-Architecture.git
cd Avalanche-IPFS-Filecoin-RWA-reference-Architecture
npm ci
npm run verify
```
## What happens if the record changes?
Because the CID is derived from the content, changing the underlying record produces a different identifier. Applications can therefore verify that the retrieved document is the exact record originally referenced.
| Document | CID |
| ------------------------------------- | ------------------------------------------------------------- |
| `deed.pdf` (original) | `bafkreidh5qsi5z6uo2thzvynr27ioajoviafqiveunrielhugyj65l6rzu` |
| `deed-tampered.pdf` (one line edited) | `bafkreiausintabvl4n4hvgv2jdmazvy35bg26gku2ufu2bosxhrd7dzxqi` |
In the demo, open **Check a document** and drop in either file. The file is hashed in your browser and never uploaded; the edited cop프로젝트로 돌아가기