25f68c1e4c
* [marketplace] get active slots from chain # Conflicts: # codex/contracts/market.nim * [marketplace] make on chain event callbacks async # Conflicts: # tests/codex/helpers/mockmarket.nim * [marketplace] make availability optional for node restart # Conflicts: # tests/codex/testsales.nim * [marketplace] add async state machine Allows for `enterAsync` to be cancelled. * [marketplace] move sale process to async state machine * [marketplace] sales state machine tests * bump dagger-contracts * [marketplace] fix ci issue with chronicles output * PR comments - add slotIndex to `SalesAgent` constructor - remove `SalesAgent.init` - rename `SalesAgent.init` to `start` and `SalesAgent.deinit` to `stop`. - rename `SalesAgent. populateRequest` to `SalesAgent.retreiveRequest`. - move availability removal to the downloading state. once availability is persisted to disk, it should survive node restarts. - * [marketplace] handle slot filled by other host Handle the case when in the downloading, proving, or filling states, that another host fills the slot. * [marketplace] use requestId for mySlots * [marketplace] infer slot index from slotid prevents reassigning a random slot index when restoring state from chain * [marketplace] update to work with latest contracts * [marketplace] clean up * [marketplace] align with contract changes - getState / state > requestState - getSlot > getRequestFromSlotId - support MarketplaceConfig - support slotState, remove unneeded Slot type - collateral > config.collateral.initialAmount - remove proofPeriod contract call - Revert reason “Slot empty” > “Slot is free” - getProofEnd > read SlotState Tests for changes * [marketplace] add missing file * [marketplace] bump codex-contracts-eth * [config] remove unused imports * [sales] cleanup * [sales] fix: do not crash when fetching state fails * [sales] make slotIndex non-optional * Rebase and update NBS commit Rebase on top of main and update NBS commit to the CI fix. * [marketplace] use async subscription event handlers * [marketplace] support slotIndex no longer optional Previously, SalesAgent.slotIndex had been moved to not optional. However, there were still many places where optionality was assumed. This commit removes those assumuptions. * [marketplace] sales state machine: use slotState Use `slotState` instead of `requestState` for sales state machine. * [marketplace] clean up * [statemachine] adds a statemachine for async workflows Allows events to be scheduled synchronously. See https://github.com/status-im/nim-codex/pull/344 Co-Authored-By: Ben Bierens <thatbenbierens@gmail.com> Co-Authored-By: Eric Mastro <eric.mastro@gmail.com> * [market] make market callbacks synchronous * [statemachine] export Event * [statemachine] ensure that no errors are raised * [statemachine] add machine parameter to run method * [statemachine] initialize queue on start * [statemachine] check futures before cancelling them * [sales] use new async state machine - states use new run() method and event mechanism - StartState starts subscriptions and loads request * [statemachine] fix unsusbscribe before subscribe * [sales] replace old state transition tests * [sales] separate state machine from sales data * [sales] remove reference from SalesData to Sales * [sales] separate sales context from sales * [sales] move decoupled types into their own modules * [sales] move retrieveRequest to SalesData * [sales] move subscription logic into SalesAgent * [sales] unsubscribe when finished or errored * [build] revert back to released version of nim-ethers * [sales] remove SaleStart state * [sales] add missing base method * [sales] move asyncSpawn helper to utils * [sales] fix imports * [sales] remove unused variables * [sales statemachine] add async state machine error handling (#349) * [statemachine] add error handling to asyncstatemachine - add error handling to catch errors during state.run - Sales: add ErrorState to identify which state to transition to during an error. This had to be added to SalesAgent constructor due to circular dependency issues, otherwise it would have been added directly to SalesAgent. - Sales: when an error during run is encountered, the SaleErrorState is constructed with the error, and by default (base impl) will return the error state, so the machine can transition to it. This can be overridden by individual states if needed. * [sales] rename onSaleFailed to onSaleErrored Because there is already a state named SaleFailed which is meant to react to an onchain RequestFailed event and also because this callback is called from SaleErrored, renaming to onSaleErrored prevents ambiguity and confusion as to what has happened at the callback callsite. * [statemachine] forward error to state directly without going through a machine method first * [statemachine] remove unnecessary error handling AsyncQueueFullError is already handled in schedule() * [statemachine] test that cancellation ignores onError * [sales] simplify error handling in states Rely on the state machine error handling instead of catching errors in the state run method --------- Co-authored-by: Mark Spanbroek <mark@spanbroek.net> * [statemachine] prevent memory leaks prevent memory leaks and nil access defects by: - allowing multiple subscribe/unsubscribes of salesagent - disallowing individual salesagent subscription calls to be made externally (requires the .subscribed check) - allowing mutiple start/stops of asyncstatemachine - disregard asyncstatemachine schedules if machine not yet started * [salesagent] add salesagent-specific tests 1. test multiple subscribe/unsubscribes 2. test scheduling machine without being started 3. test subscriptions are working correctly with external events 4. test errors can be overridden at the state level for ErrorHandlingStates. --------- Co-authored-by: Eric Mastro <eric.mastro@gmail.com> Co-authored-by: Mark Spanbroek <mark@spanbroek.net> Co-authored-by: Ben Bierens <thatbenbierens@gmail.com> |
||
---|---|---|
.. | ||
Readme.md | ||
clock.nim | ||
config.nim | ||
deployment.nim | ||
interactions.nim | ||
market.nim | ||
marketplace.nim | ||
proofs.nim | ||
requests.nim | ||
testtoken.nim |
Readme.md
Codex Contracts in Nim
Nim API for the Codex smart contracts.
Usage
For a global overview of the steps involved in starting and fulfilling a storage contract, see Codex Contracts.
Smart contract
Connecting to the smart contract on an Ethereum node:
import codex/contracts
import ethers
let address = # fill in address where the contract was deployed
let provider = JsonRpcProvider.new("ws://localhost:8545")
let marketplace = Marketplace.new(address, provider)
Setup client and host so that they can sign transactions; here we use the first two accounts on the Ethereum node:
let accounts = await provider.listAccounts()
let client = provider.getSigner(accounts[0])
let host = provider.getSigner(accounts[1])
Collateral
Hosts need to put up collateral before participating in storage contracts.
A host can learn about the amount of collateral that is required:
let config = await marketplace.config()
let collateral = config.collateral.initialAmount
The host then needs to prepare a payment to the smart contract by calling the
approve
method on the ERC20 token. Note that interaction with ERC20
contracts is not part of this library.
After preparing the payment, the host can deposit collateral:
await storage
.connect(host)
.deposit(collateral)
When a host is not participating in storage offers or contracts, it can withdraw its collateral:
await storage
.connect(host)
.withdraw()
Storage requests
Creating a request for storage:
let request : StorageRequest = (
client: # address of the client requesting storage
duration: # duration of the contract in seconds
size: # size in bytes
contentHash: # SHA256 hash of the content that's going to be stored
proofProbability: # require a storage proof roughly once every N periods
maxPrice: # maximum price the client is willing to pay
expiry: # expiration time of the request (in unix time)
nonce: # random nonce to differentiate between similar requests
)
When a client wants to submit this request to the network, it needs to pay the
maximum price to the smart contract in advance. The difference between the
maximum price and the offered price will be reimbursed later. To prepare, the
client needs to call the approve
method on the ERC20 token. Note that
interaction with ERC20 contracts is not part of this library.
Once the payment has been prepared, the client can submit the request to the network:
await storage
.connect(client)
.requestStorage(request)
Storage offers
Creating a storage offer:
let offer: StorageOffer = (
host: # address of the host that is offering storage
requestId: request.id,
price: # offered price (in number of tokens)
expiry: # expiration time of the offer (in unix time)
)
Hosts submits an offer:
await storage
.connect(host)
.offerStorage(offer)
Client selects an offer:
await storage
.connect(client)
.selectOffer(offer.id)
Starting and finishing a storage contract
The host whose offer got selected can start the storage contract once it received the data that needs to be stored:
await storage
.connect(host)
.startContract(offer.id)
Once the storage contract is finished, the host can release payment:
await storage
.connect(host)
.finishContract(id)
Storage proofs
Time is divided into periods, and each period a storage proof may be required from the host. The odds of requiring a storage proof are negotiated through the storage request. For more details about the timing of storage proofs, please refer to the design document.
At the start of each period of time, the host can check whether a storage proof is required:
let isProofRequired = await storage.isProofRequired(offer.id)
If a proof is required, the host can submit it before the end of the period:
await storage
.connect(host)
.submitProof(id, proof)
If a proof is not submitted, then a validator can mark a proof as missing:
await storage
.connect(validator)
.markProofAsMissing(id, period)