概要
DealClientAxlコントラクト(ファイル名とコントラクト名が異なってるコントラクトになっています)は、Filecoinネットワーク上でストレージディールを作成・管理し、そのディールが成立したことの証明(アテステーション)を、Axelar General Message Passing (GMP) を介して他のブロックチェーンに送信する機能を持つスマートコントラクトです。 Filecoinのネイティブアクターと対話する機能を持ち、クロスチェーンでのデータ保存証明プロトコルのFilecoin側(宛先チェーン)における「証明者(Prover)」として機能します。
このコントラクトは、Filecoin Virtual Machine (FEVM) 上にデプロイされることを前提として設計されています。 主な役割は、他のブロックチェーン(ソースチェーン)からの要求に基づき、Filecoin上でデータのストレージディールを管理し、その結果をソースチェーンに報告することです。
まず、外部ユーザーやコントラクトはmakeDealProposalを呼び出して、Filecoinでのデータ保存に関する詳細な条件(CID、サイズ、価格など)を含むディール提案を作成します。
この提案はコントラクト内部に保存され、一意のIDで管理されます。
その後、Filecoinのストレージプロバイダーがこの提案を受け入れてディールを成立させると、Filecoinのネイティブアクターであるマーケットアクター(f05)が、このコントラクトのhandle_filecoin_methodを介してdealNotify関数をコールバックします。
これが、ディールが正式にオンチェーンで公開されたことの通知となります。
dealNotify関数は、通知を受け取ると、ディールIDや保存期間などの情報を含むデータアテステーションを作成します。
そして、このアテステーション情報をペイロードとして、Axelarのゲートウェイコントラクトを呼び出します。
Axelarネットワークは、このメッセージを指定されたソースチェーンのオラクルコントラクトへ安全に転送します。
このクロスチェーンメッセージングにかかるガス代は、gasServiceコントラクトを通じて支払われます。
このように、DealClientAxlはFilecoinのネイティブな仕組みとEVMのスマートコントラクト、そしてAxelarのクロスチェーンプロトコルを連携させることで、「Filecoinにデータが保存された」という事実を、他のブロックチェーン上で検証可能にするための重要な役割を担います。
機能
- Filecoinストレージディールの提案作成と管理
- Filecoinマーケットアクターからのディール成立通知の受信と処理
- ディール成立情報に基づくデータアテステーションの生成
- Axelar GMPを利用した、他チェーンへのアテステーション情報のクロスチェーン送信
- クロスチェーン通信のためのガス代管理
- DataCapの受信とイベント通知
- Filecoinネイティブアクター(マーケット、DataCap)からのコールバックを処理する汎用エントリポイントの提供
フロー
ディール成立通知とクロスチェーン証明
このシーケンス図は、Filecoinマーケットアクターからのディール成立通知を受け取り、Axelarを介して他のチェーンにその証明を送信するまでの流れを示しています。
sequenceDiagram
participant MarketActor as Filecoin Market Actor (f05)
participant DealClientAxl as DealClientAxl
participant AxelarGasService as Axelar Gas Service
participant AxelarGateway as Axelar Gateway
participant OtherChain as Other Chain Oracle
MarketActor->>DealClientAxl: handle_filecoin_method(MARKET_NOTIFY_DEAL_METHOD_NUM, params)
Note over DealClientAxl: ディール成立のコールバックを受信
DealClientAxl->>DealClientAxl: dealNotify(params)
Note over DealClientAxl: パラメータをデシリアライズし、<br>内部状態(pieceDeals, pieceStatus)を更新
Note over DealClientAxl: DataAttestationを作成
alt chainId is not current chain
DealClientAxl->>DealClientAxl: call_axelar(payload, ...)
DealClientAxl->>AxelarGasService: payNativeGasForContractCall{value: gasFunds}(...)
Note over AxelarGasService: クロスチェーン実行のガス代を支払う
DealClientAxl->>AxelarGateway: callContract(destinationChain, destinationAddress, payload)
Note over AxelarGateway: Axelarネットワークにメッセージ送信を依頼
AxelarGateway-->>OtherChain: (via Axelar Network)
else chainId is current chain
DealClientAxl->>OtherChain: _execute(...)
endコード
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.17;
import {MarketAPI} from "filecoin-solidity-api/contracts/v0.8/MarketAPI.sol";
import {CommonTypes} from "filecoin-solidity-api/contracts/v0.8/types/CommonTypes.sol";
import {MarketTypes} from "filecoin-solidity-api/contracts/v0.8/types/MarketTypes.sol";
import {AccountTypes} from "filecoin-solidity-api/contracts/v0.8/types/AccountTypes.sol";
import {CommonTypes} from "filecoin-solidity-api/contracts/v0.8/types/CommonTypes.sol";
import {AccountCBOR} from "filecoin-solidity-api/contracts/v0.8/cbor/AccountCbor.sol";
import {MarketCBOR} from "filecoin-solidity-api/contracts/v0.8/cbor/MarketCbor.sol";
import {BytesCBOR} from "filecoin-solidity-api/contracts/v0.8/cbor/BytesCbor.sol";
import {BigInts} from "filecoin-solidity-api/contracts/v0.8/utils/BigInts.sol";
import {CBOR} from "solidity-cborutils/contracts/CBOR.sol";
import {Misc} from "filecoin-solidity-api/contracts/v0.8/utils/Misc.sol";
import {FilAddresses} from "filecoin-solidity-api/contracts/v0.8/utils/FilAddresses.sol";
import {DataAttestation, IBridgeContract, StringsEqual} from "../sourceChain/Oracles.sol";
import {Strings} from "@openzeppelin/contracts/utils/Strings.sol";
import {AxelarExecutable} from "@axelar-network/axelar-gmp-sdk-solidity/contracts/executable/AxelarExecutable.sol";
import {IAxelarGateway} from "@axelar-network/axelar-gmp-sdk-solidity/contracts/interfaces/IAxelarGateway.sol";
import {IAxelarGasService} from "@axelar-network/axelar-gmp-sdk-solidity/contracts/interfaces/IAxelarGasService.sol";
using CBOR for CBOR.CBORBuffer;
contract DealClientAxl is AxelarExecutable {
using AccountCBOR for *;
using MarketCBOR for *;
IAxelarGasService public immutable gasService;
uint64 public constant AUTHENTICATE_MESSAGE_METHOD_NUM = 2643134072;
uint64 public constant DATACAP_RECEIVER_HOOK_METHOD_NUM = 3726118371;
uint64 public constant MARKET_NOTIFY_DEAL_METHOD_NUM = 4186741094;
address public constant MARKET_ACTOR_ETH_ADDRESS =
address(0xff00000000000000000000000000000000000005);
address public constant DATACAP_ACTOR_ETH_ADDRESS =
address(0xfF00000000000000000000000000000000000007);
uint256 public constant AXELAR_GAS_FEE = 100000000000000000; // Start with 0.1 FIL
struct SourceChain {
string chainName;
address sourceOracleAddress;
}
struct RequestId {
bytes32 requestId;
bool valid;
}
struct RequestIdx {
uint256 idx;
bool valid;
}
struct DealRequest {
bytes piece_cid;
uint64 piece_size;
bool verified_deal;
string label;
int64 start_epoch;
int64 end_epoch;
uint256 storage_price_per_epoch;
uint256 provider_collateral;
uint256 client_collateral;
uint64 extra_params_version;
ExtraParams extra_params;
}
struct ExtraParams {
string location_ref;
uint64 car_size;
bool skip_ipni_announce;
bool remove_unsealed_copy;
}
enum Status {
None,
DealPublished,
DealActivated,
DealTerminated
}
DealRequest[] public dealRequests;
mapping(bytes32 => RequestIdx) public dealIdToIndex;
mapping(bytes => uint64) public pieceDeals; // commP -> deal ID
mapping(bytes => RequestId) public pieceRequests; // commP -> deal request Id
mapping(bytes => Status) public pieceStatus;
mapping(bytes => uint256) public providerGasFunds; // Funds set aside for calling oracle by provider
mapping(uint256 => SourceChain) public chainIdToSourceChain;
event DealProposalCreate(
bytes32 indexed id,
uint64 size,
bool indexed verified,
uint256 price
);
event ReceivedDataCap(string received);
event DealNotify(
uint64 dealId,
bytes commP,
bytes chainId
);
event XChainProveDataStored(
string destinationChain,
string destinationAddress);
constructor(
address _gateway,
address _gasReceiver
) AxelarExecutable(_gateway) {
gasService = IAxelarGasService(_gasReceiver);
}
function setSourceChains(
uint[] calldata chainIds,
string[] calldata sourceChains,
address[] calldata sourceOracleAddresses
) external {
require(
chainIds.length == sourceChains.length &&
sourceChains.length == sourceOracleAddresses.length,
"Input arrays must have the same length"
);
for (uint i = 0; i < chainIds.length; i++) {
require(
chainIdToSourceChain[chainIds[i]].sourceOracleAddress !=
sourceOracleAddresses[i],
"Same source chain already configured in the Prover Contract"
);
chainIdToSourceChain[chainIds[i]] = SourceChain(
sourceChains[i],
sourceOracleAddresses[i]
);
}
}
function getSourceChain(uint256 chainId) public view returns (string memory, address) {
SourceChain memory source = chainIdToSourceChain[chainId];
require(source.sourceOracleAddress != address(0), "chainId Chain is not configured in Prover Contract");
return (source.chainName, source.sourceOracleAddress);
}
function addGasFunds(bytes calldata providerAddrData) external payable {
providerGasFunds[providerAddrData] += msg.value;
}
function makeDealProposal(DealRequest calldata deal) public returns (bytes32){
require(
pieceStatus[deal.piece_cid] != Status.DealActivated ||
pieceStatus[deal.piece_cid] != Status.DealPublished,
"this deal is already active or published"
);
uint256 idx = dealRequests.length;
dealRequests.push(deal);
bytes32 proposalId = keccak256(abi.encodePacked(msg.sender, block.timestamp, idx));
dealIdToIndex[proposalId] = RequestIdx(idx, true);
pieceRequests[deal.piece_cid] = RequestId(proposalId, true);
pieceStatus[deal.piece_cid] = Status.DealPublished;
emit DealProposalCreate(proposalId, deal.piece_size, deal.verified_deal, deal.storage_price_per_epoch);
return proposalId;
}
function getDealRequest(bytes32 proposalId) public view returns (DealRequest memory) {
require(dealIdToIndex[proposalId].valid, "Deal does not exist");
return dealRequests[dealIdToIndex[proposalId].idx];
}
function getDealProposal(bytes32 proposalId) public view returns (bytes memory) {
DealRequest memory deal = getDealRequest(proposalId);
MarketTypes.DealProposal memory proposal = MarketTypes.DealProposal(
CommonTypes.Cid(deal.piece_cid),
deal.piece_size,
deal.verified_deal,
FilAddresses.fromEthAddress(address(this)),
// Dummy provider address, should be replaced with the provider address who pickes the deal
FilAddresses.fromActorID(0),
CommonTypes.DealLabel(abi.encode(deal.label), true),
CommonTypes.ChainEpoch.wrap(deal.start_epoch),
CommonTypes.ChainEpoch.wrap(deal.end_epoch),
BigInts.fromUint256(deal.storage_price_per_epoch),
BigInts.fromUint256(deal.provider_collateral),
BigInts.fromUint256(deal.client_collateral)
);
return MarketCBOR.serializeDealProposal(proposal);
}
function serializeExtraParams(ExtraParams memory params) internal pure returns (bytes memory) {
CBOR.CBORBuffer memory buffer = CBOR.create(64);
buffer.startFixedArray(4);
buffer.writeString(params.location_ref);
buffer.writeUInt64(params.car_size);
buffer.writeBool(params.skip_ipni_announce);
buffer.writeBool(params.remove_unsealed_copy);
buffer.endSequence();
return buffer.data();
}
function getExtraParams(bytes32 proposalId) public view returns (bytes memory extra_params) {
DealRequest memory deal = getDealRequest(proposalId);
return serializeExtraParams(deal.extra_params);
}
function updateDealStatus(bytes memory pieceCid) public {
require(pieceDeals[pieceCid] > 0, "Deal does not exist for piece cid");
(int256 exit_code, MarketTypes.GetDealActivationReturn memory ret) = MarketAPI
.getDealActivation(pieceDeals[pieceCid]);
require(exit_code == 0, "Deal activation failed with non zero exit code");
if (CommonTypes.ChainEpoch.unwrap(ret.terminated) > 0) {
pieceStatus[pieceCid] = Status.DealTerminated;
} else if (CommonTypes.ChainEpoch.unwrap(ret.activated) > 0) {
pieceStatus[pieceCid] = Status.DealActivated;
}
}
// dealNotify is the callback from the market actor into the contract at the end
// of PublishStorageDeals. This message holds the previously approved deal proposal
// and the associated dealID. The dealID is stored as part of the contract state
// and the completion of this call marks the success of PublishStorageDeals
// @params - cbor byte array of MarketDealNotifyParams
function dealNotify(bytes memory params) internal {
require(
msg.sender == MARKET_ACTOR_ETH_ADDRESS,
"msg.sender needs to be market actor f05"
);
MarketTypes.MarketDealNotifyParams memory mdnp = MarketCBOR
.deserializeMarketDealNotifyParams(params);
MarketTypes.DealProposal memory proposal = MarketCBOR
.deserializeDealProposal(mdnp.dealProposal);
pieceDeals[proposal.piece_cid.data] = mdnp.dealId;
pieceStatus[proposal.piece_cid.data] = Status.DealPublished;
int64 duration = CommonTypes.ChainEpoch.unwrap(proposal.end_epoch) -
CommonTypes.ChainEpoch.unwrap(proposal.start_epoch);
// Expects deal label to be chainId encoded in bytes
uint256 chainId = asciiBytesToUint(proposal.label.data);
DataAttestation memory attest = DataAttestation(
proposal.piece_cid.data,
duration,
mdnp.dealId,
uint256(Status.DealPublished)
);
bytes memory payload = abi.encode(attest);
emit DealNotify(mdnp.dealId,
proposal.piece_cid.data,
proposal.label.data
);
if (chainId == block.chainid) {
IBridgeContract(
chainIdToSourceChain[chainId].sourceOracleAddress
)._execute(
chainIdToSourceChain[chainId].chainName,
addressToHexString(address(this)),
payload
);
} else {
// If the chainId is not the current chain, we need to call the gateway
// to forward the message to the correct chain
call_axelar(
payload,
proposal.provider.data,
AXELAR_GAS_FEE,
chainId
);
}
}
function call_axelar(
bytes memory payload,
bytes memory providerAddrData,
uint256 gasTarget,
uint256 chainId
) internal {
uint256 gasFunds = gasTarget;
//TODO Need to rethink who should pay for the crosschain tx gas fee
// if (providerGasFunds[providerAddrData] >= gasTarget) {
// providerGasFunds[providerAddrData] -= gasTarget;
// } else {
// gasFunds = providerGasFunds[providerAddrData];
// providerGasFunds[providerAddrData] = 0;
// }
string memory sourceChain = chainIdToSourceChain[chainId]
.chainName;
string memory sourceOracleAddress = addressToHexString(
chainIdToSourceChain[chainId].sourceOracleAddress
);
gasService.payNativeGasForContractCall{value: gasFunds}(
address(this),
sourceChain,
sourceOracleAddress,
payload,
msg.sender
);
emit XChainProveDataStored(sourceChain, sourceOracleAddress);
gateway().callContract(sourceChain, sourceOracleAddress, payload);
}
function _execute(
bytes32 commandId,
string calldata sourceChain,
string calldata sourceAddress,
bytes calldata payload) internal override{
//Do Nothing
}
function debug_call(
bytes calldata commp,
bytes calldata providerAddrData,
uint256 gasFunds,
uint256 chainId
) public {
DataAttestation memory attest = DataAttestation(
commp,
0,
42,
uint256(Status.DealPublished)
);
bytes memory payload = abi.encode(attest);
if (chainId == block.chainid) {
IBridgeContract(
chainIdToSourceChain[chainId].sourceOracleAddress
)._execute(
chainIdToSourceChain[chainId].chainName,
addressToHexString(address(this)),
payload
);
} else {
// If the chainId is not the current chain, we need to call the gateway
// to forward the message to the correct chain
call_axelar(payload, providerAddrData, gasFunds, chainId);
}
}
// handle_filecoin_method is the universal entry point for any evm based
// actor for a call coming from a builtin filecoin actor
// @method - FRC42 method number for the specific method hook
// @params - CBOR encoded byte array params
function handle_filecoin_method(
uint64 method,
uint64,
bytes memory params
) public returns (uint32, uint64, bytes memory) {
bytes memory ret;
uint64 codec;
// dispatch methods
if (method == AUTHENTICATE_MESSAGE_METHOD_NUM) {
// If we haven't reverted, we should return a CBOR true to indicate that verification passed.
// Always authenticate message
CBOR.CBORBuffer memory buf = CBOR.create(1);
buf.writeBool(true);
ret = buf.data();
codec = Misc.CBOR_CODEC;
} else if (method == MARKET_NOTIFY_DEAL_METHOD_NUM) {
dealNotify(params);
} else if (method == DATACAP_RECEIVER_HOOK_METHOD_NUM) {
receiveDataCap(params);
} else {
revert("the filecoin method that was called is not handled");
}
return (0, codec, ret);
}
function receiveDataCap(bytes memory params) internal {
require(
msg.sender == DATACAP_ACTOR_ETH_ADDRESS,
"msg.sender needs to be datacap actor f07"
);
emit ReceivedDataCap("DataCap Received!");
//TODO:Add get datacap balance api and store datacap amount
}
function addressToHexString(
address _addr
) internal pure returns (string memory) {
return Strings.toHexString(uint256(uint160(_addr)), 20);
}
function asciiBytesToUint(
bytes memory asciiBytes
) public pure returns (uint256) {
uint256 result = 0;
for (uint256 i = 0; i < asciiBytes.length; i++) {
uint256 digit = uint256(uint8(asciiBytes[i])) - 48; // Convert ASCII to digit
require(digit <= 9, "Invalid ASCII byte");
result = result * 10 + digit;
}
return result;
}
}構造体
SourceChain
struct SourceChain {
string chainName;
address sourceOracleAddress;
}クロスチェーン通信の宛先となるソースチェーンの情報を保持する構造体。
chainNameAxelarネットワークで認識されるチェーン名(例: "Avalanche")。sourceOracleAddressソースチェーン上にデプロイされている、アテステーションを受信するオラクルコントラクトのアドレス。
RequestId
struct RequestId {
bytes32 requestId;
bool valid;
}ディール提案リクエストの一意のIDとその有効性を保持する構造体。
requestIdkeccak256で生成されたリクエストID。validこのIDが有効であるかを示すフラグ。
RequestIdx
struct RequestIdx {
uint256 idx;
bool valid;
}dealRequests配列内でのディールリクエストのインデックスとその有効性を保持する構造体。
idxdealRequests配列のインデックス。validこのインデックスが有効であるかを示すフラグ。
DealRequest
struct DealRequest {
bytes piece_cid;
uint64 piece_size;
bool verified_deal;
string label;
int64 start_epoch;
int64 end_epoch;
uint256 storage_price_per_epoch;
uint256 provider_collateral;
uint256 client_collateral;
uint64 extra_params_version;
ExtraParams extra_params;
}Filecoinのストレージディール提案に必要な全てのパラメータを定義する構造体。
piece_cid保存するデータのコンテンツID(Piece CID)。piece_sizeピースのサイズ。verified_dealFilecoin Plusの検証済みディールであるか。labelディールに付与するラベル。 クロスチェーン通信では宛先チェーンIDの識別に利用されます。start_epochディール開始エポック。end_epochディール終了エポック。storage_price_per_epoch1エポックあたりのストレージ価格。provider_collateralプロバイダーが提供する担保。client_collateralクライアントが提供する担保。extra_params_versionextra_paramsのバージョン。extra_paramsExtraParams構造体で定義される追加パラメータ。
ExtraParams
struct ExtraParams {
string location_ref;
uint64 car_size;
bool skip_ipni_announce;
bool remove_unsealed_copy;
}ディール提案の追加パラメータを定義する構造体。
location_refデータの取得元URLなど。car_sizeCARファイルのサイズ。skip_ipni_announceIPNIへの広告をスキップするか。remove_unsealed_copy未封印コピーを削除するか。
変数
gasService
IAxelarGasService public immutable gasService;Axelarのガスサービスコントラクトのインスタンスです。 クロスチェーンメッセージの実行にかかるガス代を宛先チェーンで支払うために使用されます。 コンストラクタで初期化され、変更不可能です。
dealRequests
DealRequest[] public dealRequests;makeDealProposal関数によって作成された全てのDealRequest構造体を格納する動的な配列です。
dealIdToIndex
mapping(bytes32 => RequestIdx) public dealIdToIndex;ディール提案ID(bytes32)から、その提案データがdealRequests配列のどこに格納されているかを示すRequestIdx構造体へのマッピングです。
pieceDeals
mapping(bytes => uint64) public pieceDeals; // commP -> deal IDデータのピースCIDから、Filecoinマーケットアクターによって割り当てられた正式なディールID(uint64)へのマッピングです。
dealNotify関数で設定されます。
pieceRequests
mapping(bytes => RequestId) public pieceRequests; // commP -> deal request IdピースCIDから、このコントラクトが生成したディール提案リクエストID(RequestId)へのマッピングです。
pieceStatus
mapping(bytes => Status) public pieceStatus;ピースCIDをキーとして、そのディールの現在の状態(Status enum)を追跡するマッピングです。
providerGasFunds
mapping(bytes => uint256) public providerGasFunds; // Funds set aside for calling oracle by providerストレージプロバイダーがクロスチェーン証明のガス代として事前に預け入れた資金を管理するマッピングです。 キーはプロバイダーのアドレス(バイト形式)です。
chainIdToSourceChain
mapping(uint256 => SourceChain) public chainIdToSourceChain;チェーンIDから、そのチェーンの名前とオラクルコントラクトのアドレスを格納したSourceChain構造体へのマッピングです。
setSourceChains関数で設定されます。
イベント
DealProposalCreate
event DealProposalCreate(
bytes32 indexed id,
uint64 size,
bool indexed verified,
uint256 price
);makeDealProposal関数が正常に実行され、新しいディール提案が作成されたときに発行されるイベント。
ReceivedDataCap
event ReceivedDataCap(string received);FilecoinのDataCapアクターからDataCapを受け取った時に、receiveDataCap関数内で発行されるイベント。
DealNotify
event DealNotify(
uint64 dealId,
bytes commP,
bytes chainId
);マーケットアクターからのdealNotifyコールバックが処理されたときに発行され、成立したディールID、ピースCID、および宛先チェーンIDを記録するイベント。
XChainProveDataStored
event XChainProveDataStored(
string destinationChain,
string destinationAddress
);Axelarゲートウェイを介して他のチェーンにデータ保存証明を送信する時に発行されるイベント。
関数
constructor
constructor(
address _gateway,
address _gasReceiver
) AxelarExecutable(_gateway) {
gasService = IAxelarGasService(_gasReceiver);
}コントラクトを初期化するコンストラクタ。
コントラクトがデプロイされる際に一度だけ実行されます。
AxelarExecutableのconstructorを呼び出してAxelarネットワークのゲートウェイアドレスを設定します。
また、クロスチェーンメッセージのガス代を支払うためのAxelarガスサービスコントラクトのアドレスを受け取り、gasService状態変数に設定します。
gasServiceはimmutableとして宣言されているため、このコンストラクタで設定された後、変更することはできません。
引数
_gateway- Axelarネットワークのゲートウェイコントラクトのアドレス。
_gasReceiver- Axelarのガスサービスコントラクトのアドレス。
setSourceChains
function setSourceChains(
uint[] calldata chainIds,
string[] calldata sourceChains,
address[] calldata sourceOracleAddresses
) external {
require(
chainIds.length == sourceChains.length &&
sourceChains.length == sourceOracleAddresses.length,
"Input arrays must have the same length"
);
for (uint i = 0; i < chainIds.length; i++) {
require(
chainIdToSourceChain[chainIds[i]].sourceOracleAddress !=
sourceOracleAddresses[i],
"Same source chain already configured in the Prover Contract"
);
chainIdToSourceChain[chainIds[i]] = SourceChain(
sourceChains[i],
sourceOracleAddresses[i]
);
}
}クロスチェーン通信の宛先となるソースチェーンの情報を設定する関数。
複数のソースチェーン(データ保存証明の送信先)の情報を一括で登録します。
入力として、チェーンID、チェーン名(Axelarで認識される名前)、各チェーン上のオラクルコントラクトのアドレスを配列で受け取ります。
まず、すべての入力配列の長さが同じであることを検証します。
その後、ループ内で各チェーンIDに対して、同じ設定が既に存在しないことを確認した上で、chainIdToSourceChainマッピングにSourceChain構造体として情報を保存します。
引数
chainIds- 設定するチェーンのIDの配列。
sourceChains- 設定するチェーンの名前の配列。
sourceOracleAddresses- 設定するチェーン上のオラクルコントラクトのアドレスの配列。
getSourceChain
function getSourceChain(uint256 chainId) public view returns (string memory, address) {
SourceChain memory source = chainIdToSourceChain[chainId];
require(source.sourceOracleAddress != address(0), "chainId Chain is not configured in Prover Contract");
return (source.chainName, source.sourceOracleAddress);
}指定されたチェーンIDに対応するソースチェーンの情報を取得する関数。
chainIdToSourceChainマッピングから指定されたchainIdの情報を検索します。
もし該当する設定が存在しない場合(オラクルアドレスがゼロアドレスの場合)、エラーを返します。
設定が見つかった場合は、そのチェーンの名前とオラクルコントラクトのアドレスを返します。
引数
chainId- 情報を取得したいチェーンのID。
戻り値
string memory- ソースチェーンの名前。
address- ソースチェーン上のオラクルコントラクトのアドレス。
addGasFunds
function addGasFunds(bytes calldata providerAddrData) external payable {
providerGasFunds[providerAddrData] += msg.value;
}ストレージプロバイダーがクロスチェーン実行のためのガス代を事前に入金する関数。
ストレージプロバイダーがAxelarを介したクロスチェーンメッセージの実行手数料を支払うために使用されます。
関数が呼び出される際に送信されたFIL(msg.value)は、providerGasFundsマッピングに、送信者(プロバイダー)のアドレスのバイト表現をキーとして加算・保存されます。
引数
providerAddrData- ガス代を入金するストレージプロバイダーのFilecoinアドレス(バイト配列形式)。
makeDealProposal
function makeDealProposal(DealRequest calldata deal) public returns (bytes32){
require(
pieceStatus[deal.piece_cid] != Status.DealActivated ||
pieceStatus[deal.piece_cid] != Status.DealPublished,
"this deal is already active or published"
);
uint256 idx = dealRequests.length;
dealRequests.push(deal);
bytes32 proposalId = keccak256(abi.encodePacked(msg.sender, block.timestamp, idx));
dealIdToIndex[proposalId] = RequestIdx(idx, true);
pieceRequests[deal.piece_cid] = RequestId(proposalId, true);
pieceStatus[deal.piece_cid] = Status.DealPublished;
emit DealProposalCreate(proposalId, deal.piece_size, deal.verified_deal, deal.storage_price_per_epoch);
return proposalId;
}新しいFilecoinストレージディールの提案を作成する関数。
クライアントがFilecoinでのデータ保存を提案するために呼び出します。
入力としてディールの詳細を含むDealRequest構造体を受け取ります。
まず、同じデータ(piece_cid)に対するディールが既に有効化または公開されていないかを確認します。
問題なければ、提案をdealRequests配列の末尾に追加し、送信者アドレス、タイムスタンプ、配列インデックスからkeccak256ハッシュを計算して一意のproposalIdを生成します。
このIDと関連情報を各種マッピング(dealIdToIndex, pieceRequests, pieceStatus)に保存し、データをDealPublishedに更新します。
最後にDealProposalCreateイベントを発行し、生成されたproposalIdを返します。
引数
deal- ディールの詳細を含む
DealRequest構造体。
- ディールの詳細を含む
戻り値
bytes32- 生成された一意のディール提案ID。
getDealRequest
function getDealRequest(bytes32 proposalId) public view returns (DealRequest memory) {
require(dealIdToIndex[proposalId].valid, "Deal does not exist");
return dealRequests[dealIdToIndex[proposalId].idx];
}提案IDに基づいて、保存されているDealRequestの完全な詳細を取得する関数。
proposalIdを引数に取り、dealIdToIndexマッピングを検索して対応するRequestIdxを取得します。
提案IDが無効な場合はエラーを返します。
IDが有効であれば、RequestIdxに含まれるインデックスを使用してdealRequests配列からDealRequest構造体を取得し、その内容を返します。
引数
proposalId- 詳細を取得したいディールの提案ID。
戻り値
DealRequest memory- ディール提案の詳細情報。
getDealProposal
function getDealProposal(bytes32 proposalId) public view returns (bytes memory) {
DealRequest memory deal = getDealRequest(proposalId);
MarketTypes.DealProposal memory proposal = MarketTypes.DealProposal(
CommonTypes.Cid(deal.piece_cid),
deal.piece_size,
deal.verified_deal,
FilAddresses.fromEthAddress(address(this)),
// Dummy provider address, should be replaced with the provider address who pickes the deal
FilAddresses.fromActorID(0),
CommonTypes.DealLabel(abi.encode(deal.label), true),
CommonTypes.ChainEpoch.wrap(deal.start_epoch),
CommonTypes.ChainEpoch.wrap(deal.end_epoch),
BigInts.fromUint256(deal.storage_price_per_epoch),
BigInts.fromUint256(deal.provider_collateral),
BigInts.fromUint256(deal.client_collateral)
);
return MarketCBOR.serializeDealProposal(proposal);
}Filecoinのマーケットアクターが解釈可能なCBOR形式にシリアライズされたディール提案データを生成する関数。
まずgetDealRequestを呼び出してディールの詳細を取得します。
次に、その情報をfilecoin-solidity-apiライブラリで定義されているMarketTypes.DealProposal構造体の形式に変換します。
この時、クライアントアドレスはこのコントラクト自身のアドレスに設定され、プロバイダーアドレスは後で実際のプロバイダーによって置き換えられるため、一時的にダミーの値(Actor ID 0)が設定されます。
最後に、MarketCBOR.serializeDealProposalを使用してこの構造体をCBOR形式のバイト配列にシリアライズして返します。
引数
proposalId- シリアライズしたいディールの提案ID。
戻り値
bytes memory- CBOR形式にシリアライズされたディール提案データ。
serializeExtraParams
function serializeExtraParams(ExtraParams memory params) internal pure returns (bytes memory) {
CBOR.CBORBuffer memory buffer = CBOR.create(64);
buffer.startFixedArray(4);
buffer.writeString(params.location_ref);
buffer.writeUInt64(params.car_size);
buffer.writeBool(params.skip_ipni_announce);
buffer.writeBool(params.remove_unsealed_copy);
buffer.endSequence();
return buffer.data();
}ディール提案の追加パラメータ(ExtraParams構造体)をCBOR形式にシリアライズするヘルパー関数。
ExtraParams構造体を受け取り、その各フィールドをsolidity-cborutilsライブラリを使用してCBORの固定長配列としてエンコードします。
エンコードされたデータはバイト配列として返されます。
引数
params- シリアライズする
ExtraParams構造体。
- シリアライズする
戻り値
bytes memory- CBOR形式にシリアライズされた追加パラメータデータ。
getExtraParams
function getExtraParams(bytes32 proposalId) public view returns (bytes memory extra_params) {
DealRequest memory deal = getDealRequest(proposalId);
return serializeExtraParams(deal.extra_params);
}提案IDに基づいて、ディールの追加パラメータをCBOR形式で取得する関数。
指定されたproposalIdに対応するディールリクエストを取得し、その中のextra_paramsフィールドをserializeExtraParams関数に渡してCBOR形式に変換します。
結果として得られるバイト配列を返します。
引数
proposalId- 追加パラメータを取得したいディールの提案ID。
戻り値
bytes memory- CBOR形式にシリアライズされた追加パラメータデータ。
updateDealStatus
function updateDealStatus(bytes memory pieceCid) public {
require(pieceDeals[pieceCid] > 0, "Deal does not exist for piece cid");
(int256 exit_code, MarketTypes.GetDealActivationReturn memory ret) = MarketAPI
.getDealActivation(pieceDeals[pieceCid]);
require(exit_code == 0, "Deal activation failed with non zero exit code");
if (CommonTypes.ChainEpoch.unwrap(ret.terminated) > 0) {
pieceStatus[pieceCid] = Status.DealTerminated;
} else if (CommonTypes.ChainEpoch.unwrap(ret.activated) > 0) {
pieceStatus[pieceCid] = Status.DealActivated;
}
}Filecoinオンチェーンのディール状態を照会し、コントラクト内のステートを更新する関数。
特定のデータ(pieceCid)に対応するディールの現在の状態をFilecoinネットワークに問い合わせます。
まず、pieceDealsマッピングにディールIDが存在することを確認します。
次にMarketAPI.getDealActivationを呼び出し、Filecoinネイティブアクターにディールの状態を照会します。
API呼び出しが成功した場合、戻り値(有効化されたエポックまたは終了したエポック)を評価し、コントラクト内のpieceStatusマッピングをDealActivatedまたはDealTerminatedに更新します。
引数
pieceCid- ステートを更新したいディールのピースCID。
dealNotify
function dealNotify(bytes memory params) internal {
require(
msg.sender == MARKET_ACTOR_ETH_ADDRESS,
"msg.sender needs to be market actor f05"
);
// ... (rest of the function logic)
}Filecoinのマーケットアクターからディールが正式に成立したことを通知されるコールバック関数。
Filecoinのネイティブアクターからのみ呼び出されることを想定しています(handle_filecoin_method経由)。
まず、呼び出し元がマーケットアクター(f05)のアドレスであることを確認します。
次に、CBOR形式で渡されたparamsをMarketDealNotifyParams構造体にデシリアライズし、ディールIDやプロバイダー情報などを取得します。
pieceDealsとpieceStatusマッピングを更新し、ディールが公開されたことを記録します。
その後、クロスチェーン送信用のDataAttestation(データ証明)オブジェクトを作成します。
ディールラベルに含まれるチェーンIDを評価し、もしそれが現在のチェーン(Filecoin自身)であれば、直接同じチェーンのオラクルコントラクトを呼び出します。
そうでなければ、call_axelar関数を呼び出して、Axelarネットワーク経由で他のチェーンにデータ証明を送信します。
引数
params- マーケットアクターから渡される、ディールの詳細を含むCBOR形式のバイト配列。
call_axelar
function call_axelar(
bytes memory payload,
bytes memory providerAddrData,
uint256 gasTarget,
uint256 chainId
) internal {
// ... (rest of the function logic)
}Axelarネットワークを利用して他のブロックチェーンにメッセージ(データ証明)を送信する関数。
クロスチェーン通信の実行を担当します。
宛先チェーンの名前とオラクルアドレスをchainIdToSourceChainマッピングから取得します。
次に、gasService.payNativeGasForContractCallを呼び出し、宛先チェーンでメッセージを実行するためのガス代をFILで支払います。
最後に、gateway().callContractを呼び出して、Axelarゲートウェイにペイロードの送信を依頼します。
XChainProveDataStoredイベントを発行して、クロスチェーン送信が開始されたことを記録します。
引数
payload- 宛先チェーンに送信するデータ(ABIエンコードされた
DataAttestation)。
- 宛先チェーンに送信するデータ(ABIエンコードされた
providerAddrData- ガス代の支払元を特定するためのプロバイダーアドレス(バイト配列)。
gasTarget- 支払うガス代の目標額。
chainId- 宛先チェーンのID。
_execute
function _execute(
bytes32 commandId,
string calldata sourceChain,
string calldata sourceAddress,
bytes calldata payload) internal override{
//Do Nothing
}Axelar GMPからクロスチェーンメッセージを受信するためのエントリポイント。
この関数はAxelarExecutableインターフェースを実装するために定義されています。
このコントラクトはメッセージを送信する側(Prover)であり、他のチェーンからメッセージを受信することは想定されていないため、関数の実装は空になっています。
引数
commandId,sourceChain,sourceAddress,payload- Axelarネットワークから渡されるパラメータ。
debug_call
function debug_call(
bytes calldata commp,
bytes calldata providerAddrData,
uint256 gasFunds,
uint256 chainId
) public {
// ... (rest of the function logic)
}デバッグやテスト目的で、dealNotifyのクロスチェーン送信部分を擬似的に実行する関数。
開発者が手動でクロスチェーン通信のロジックをテストするために使用します。
ダミーのDataAttestationを作成し、dealNotifyと同様に、宛先チェーンIDに応じて直接実行するか、call_axelarを呼び出すかの条件分岐を実行します。
引数
commp- テスト用のピースコミットメント。
providerAddrData- テスト用のプロバイダーアドレス。
gasFunds- テスト用のガス代。
chainId- テスト用の宛先チェーンID。
handle_filecoin_method
function handle_filecoin_method(
uint64 method,
uint64,
bytes memory params
) public returns (uint32, uint64, bytes memory) {
bytes memory ret;
uint64 codec;
// dispatch methods
if (method == AUTHENTICATE_MESSAGE_METHOD_NUM) {
// If we haven't reverted, we should return a CBOR true to indicate that verification passed.
// Always authenticate message
CBOR.CBORBuffer memory buf = CBOR.create(1);
buf.writeBool(true);
ret = buf.data();
codec = Misc.CBOR_CODEC;
} else if (method == MARKET_NOTIFY_DEAL_METHOD_NUM) {
dealNotify(params);
} else if (method == DATACAP_RECEIVER_HOOK_METHOD_NUM) {
receiveDataCap(params);
} else {
revert("the filecoin method that was called is not handled");
}
return (0, codec, ret);
}Filecoinのネイティブアクターからの呼び出しを受け付けるための汎用的なエントリポイント関数。
FRC-0042標準に準拠しており、EVMベースのアクターがFilecoinのネイティブアクターと対話するための標準的なインターフェースです。
method番号に基づいて処理を振り分けるディスパッチャとして機能します。
AUTHENTICATE_MESSAGE_METHOD_NUM常に認証成功(CBOR形式のtrue)を返します。MARKET_NOTIFY_DEAL_METHOD_NUMdealNotify関数を呼び出します。DATACAP_RECEIVER_HOOK_METHOD_NUMreceiveDataCap関数を呼び出します。- 上記以外 エラーを返します。
引数
method- 呼び出されたメソッドの番号。
uint64- 未使用のパラメータ。
params- ネイティブアクターから渡されるCBOR形式のパラメータ。
戻り値
uint32- 実行の終了コード(0は成功)。
uint64- 戻り値のデータのコーデックタイプ。
bytes memory- CBOR形式でエンコードされた戻り値。
receiveDataCap
function receiveDataCap(bytes memory params) internal {
require(
msg.sender == DATACAP_ACTOR_ETH_ADDRESS,
"msg.sender needs to be datacap actor f07"
);
emit ReceivedDataCap("DataCap Received!");
//TODO:Add get datacap balance api and store datacap amount
}FilecoinのDataCapアクターからのDataCap受信を処理する関数。
handle_filecoin_methodから呼び出されます。
まず、呼び出し元がDataCapアクター(f07)のアドレスであることを検証します。
検証に成功すると、ReceivedDataCapイベントを発行して、DataCapを受信したことを記録します。
コード内のTODOコメントは、将来的に受信したDataCapの量を保存・管理する機能が追加される可能性を示唆しています。
引数
params- DataCapアクターから渡されるCBOR形式のパラメータ(現在は未使用)。
addressToHexString
function addressToHexString(
address _addr
) internal pure returns (string memory) {
return Strings.toHexString(uint256(uint160(_addr)), 20);
}address型を16進数文字列に変換するヘルパー関数。
OpenZeppelinのStringsライブラリのtoHexStringメソッドを利用して、Solidityのaddress型を0xから始まる16進数文字列に変換します。
クロスチェーンメッセージでアドレスを文字列として扱う必要がある場合などに使用されます。
引数
_addr- 変換する
address。
- 変換する
戻り値
string memory- 変換後の16進数文字列。
asciiBytesToUint
function asciiBytesToUint(
bytes memory asciiBytes
) public pure returns (uint256) {
uint256 result = 0;
for (uint256 i = 0; i < asciiBytes.length; i++) {
uint256 digit = uint256(uint8(asciiBytes[i])) - 48; // Convert ASCII to digit
require(digit <= 9, "Invalid ASCII byte");
result = result * 10 + digit;
}
return result;
}ASCII数字で構成されるバイト配列をuint256型の数値に変換するヘルパー関数。
例えば"314159"のような文字列をバイト配列で受け取り、それを数値の314159に変換します。
ループ処理で各バイトのASCIIコードから48を引くことで数値に変換し、10進数の位取りを考慮して最終的な数値を組み立てます。
ディールラベルにエンコードされたチェーンIDを読み取るために使用されます。
引数
asciiBytes- 変換するASCII数字のバイト配列。
戻り値
uint256- 変換後の数値。