vault

package
v0.0.0-...-9fdd194 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Mar 28, 2024 License: Apache-2.0, MIT Imports: 28 Imported by: 0

Documentation

Index

Constants

View Source
const (
	VaultKey           = "swap_vault"
	VaultDeploymentKey = "swap_vault_transaction_deployment"
)

Variables

View Source
var (
	// ErrNoCheque is the error returned if there is no prior cheque for a vault or beneficiary.
	ErrNoCheque = errors.New("no cheque")
	// ErrNoChequeRecords is the error returned if there is no prior cheque record for a vault or beneficiary.
	ErrNoChequeRecords = errors.New("no cheque records")
	// ErrChequeNotIncreasing is the error returned if the cheque amount is the same or lower.
	ErrChequeNotIncreasing = errors.New("cheque cumulativePayout is not increasing")
	// ErrChequeInvalid is the error returned if the cheque itself is invalid.
	ErrChequeInvalid = errors.New("invalid cheque")
	// ErrWrongBeneficiary is the error returned if the cheque has the wrong beneficiary.
	ErrWrongBeneficiary = errors.New("wrong beneficiary")
	// ErrBouncingCheque is the error returned if the vault is demonstrably illiquid.
	ErrBouncingCheque = errors.New("bouncing cheque")
	ErrTokenCheque    = errors.New("wrong token cheque")
	// ErrChequeValueTooLow is the error returned if the after deduction value of a cheque did not cover 1 accounting credit
	ErrChequeValueTooLow = errors.New("cheque value lower than acceptable")
)
View Source
var (
	ErrInvalidFactory = errors.New(`not a valid factory contract;
	The correct way to upgrade:
		1.Make sure the current version is version 1.6.0 (or other 1.x versions)
		2.Refer to the official documentation to upgrade (https://docs.btfs.io/docs/tutorials-on-upgrading-btfs-v10-to-btfs-v20-mainnet) (Copy this link to open in your browser)`)
	ErrNotDeployedByFactory = errors.New("vault not deployed by factory")
)
View Source
var (
	// ErrOutOfFunds is the error when the vault has not enough free funds for a cheque
	ErrOutOfFunds = errors.New("vault out of funds")
	// ErrInsufficientFunds is the error when the vault has not enough free funds for a user action
	ErrInsufficientFunds = errors.New("insufficient token balance")
)
View Source
var ChequeTypes = eip712.Types{
	"EIP712Domain": eip712.EIP712DomainType,
	"Cheque": []eip712.Type{
		{
			Name: "vault",
			Type: "address",
		},
		{
			Name: "beneficiary",
			Type: "address",
		},
		{
			Name: "cumulativePayout",
			Type: "uint256",
		},
	},
}

ChequeTypes are the needed type descriptions for cheque signing

View Source
var (
	// ErrNoCashout is the error if there has not been any cashout action for the vault
	ErrNoCashout = errors.New("no prior cashout")
)
View Source
var MutiChequeTypes = eip712.Types{
	"EIP712Domain": eip712.EIP712DomainType,
	"MultiTokenCheque": []eip712.Type{
		{
			Name: "token",
			Type: "address",
		},
		{
			Name: "vault",
			Type: "address",
		},
		{
			Name: "beneficiary",
			Type: "address",
		},
		{
			Name: "cumulativePayout",
			Type: "uint256",
		},
	},
}
View Source
var RestartFixCashOutStatusLock bool = true
View Source
var RestartWaitCashOutOnlineTime time.Duration = 30 //seconds

Functions

func GetStoredVaultAddr

func GetStoredVaultAddr(stateStore storage.StateStorer) (vault common.Address, err error)

GetStoredVaultAddr returns vault address stored in stateStore. If you want exactly result, pls query the bttc chain.

func GetVaultImpl

func GetVaultImpl(ctx context.Context, vault common.Address, trxSvc transaction.Service) (vaultImpl common.Address, err error)

GetVaultImpl queries the vault implementation used for the proxy

func IsVaultImplCompatibleBetween

func IsVaultImplCompatibleBetween(ctx context.Context, vault1, vault2 common.Address, trxSvc transaction.Service) (isCompatible bool, err error)

IsVaultImplCompatibleBetween checks whether my vault's impl is compatible with peer's one.

func RecoverCheque

func RecoverCheque(cheque *SignedCheque, chaindID int64) (common.Address, error)

RecoverCheque recovers the issuer ethereum address from a signed cheque

Types

type CashChequeResult

type CashChequeResult struct {
	Beneficiary      common.Address // beneficiary of the cheque
	Recipient        common.Address // address which received the funds
	Caller           common.Address // caller of cashCheque
	TotalPayout      *big.Int       // total amount that was paid out in this call
	CumulativePayout *big.Int       // cumulative payout of the cheque that was cashed
	CallerPayout     *big.Int       // payout for the caller of cashCheque
	Bounced          bool           // indicates wether parts of the cheque bounced
}

CashChequeResult summarizes the result of a CashCheque or CashChequeBeneficiary call

func (*CashChequeResult) Equal

func (r *CashChequeResult) Equal(o *CashChequeResult) bool

Equal compares to CashChequeResults

type CashOutResult

type CashOutResult struct {
	TxHash   common.Hash
	Token    common.Address
	Vault    common.Address
	Amount   *big.Int
	CashTime int64
	Status   string
}

type CashOutStatusStoreInfo

type CashOutStatusStoreInfo struct {
	Token            common.Address
	Vault            common.Address
	Beneficiary      common.Address
	CumulativePayout *big.Int
	TxHash           string
}

type CashoutService

type CashoutService interface {
	// CashCheque sends a cashing transaction for the last cheque of the vault
	CashCheque(ctx context.Context, vault, recipient common.Address, token common.Address) (common.Hash, error)
	// CashoutStatus gets the status of the latest cashout transaction for the vault
	CashoutStatus(ctx context.Context, vaultAddress common.Address, token common.Address) (*CashoutStatus, error)
	AdjustCashCheque(ctx context.Context, vaultAddress, recipient common.Address, token common.Address) (totalCashOutAmount, newCashOutAmount *big.Int, err error)
	AdjustCashChequeTxHash(ctx context.Context, vaultAddress, recipient common.Address, token common.Address, txHash common.Hash, cumulativePayout *big.Int) (totalCashOutAmount, newCashOutAmount *big.Int, err error)
	HasCashoutAction(ctx context.Context, peer common.Address, token common.Address) (bool, error)
	CashoutResults() ([]CashOutResult, error)
	RestartFixChequeCashOut()
}

CashoutService is the service responsible for managing cashout actions

func NewCashoutService

func NewCashoutService(
	store storage.StateStorer,
	backend transaction.Backend,
	transactionService transaction.Service,
	chequeStore ChequeStore,
) CashoutService

NewCashoutService creates a new CashoutService

type CashoutStatus

type CashoutStatus struct {
	Last           *LastCashout // last cashout for a vault
	UncashedAmount *big.Int     // amount not yet cashed out
}

CashoutStatus is information about the last cashout and uncashed amounts

type Cheque

type Cheque struct {
	Token            common.Address
	Vault            common.Address
	Beneficiary      common.Address
	CumulativePayout *big.Int
}

Cheque represents a cheque for a SimpleSwap vault

func (*Cheque) Equal

func (cheque *Cheque) Equal(other *Cheque) bool

func (*Cheque) String

func (cheque *Cheque) String() string

type ChequeRecord

type ChequeRecord struct {
	Token       common.Address
	Vault       common.Address
	Beneficiary common.Address
	Amount      *big.Int
	ReceiveTime int64 //time.now().Unix()
}

type ChequeSigner

type ChequeSigner interface {
	// Sign signs a cheque
	Sign(cheque *Cheque) ([]byte, error)
}

ChequeSigner signs cheque

func NewChequeSigner

func NewChequeSigner(signer crypto.Signer, chainID int64) ChequeSigner

NewChequeSigner creates a new cheque signer for the given chainID.

type ChequeStore

type ChequeStore interface {
	// ReceiveCheque verifies and stores a cheque. It returns the total amount earned.
	ReceiveCheque(ctx context.Context, cheque *SignedCheque, amountCheck *big.Int, token common.Address) (*big.Int, error)
	// LastReceivedCheque returns the last cheque we received from a specific vault.
	LastReceivedCheque(vault common.Address, token common.Address) (*SignedCheque, error)
	// LastReceivedCheques return map[vault]cheque
	LastReceivedCheques(token common.Address) (map[common.Address]*SignedCheque, error)
	// ReceivedChequeRecordsByPeer returns the records we received from a specific vault.
	ReceivedChequeRecordsByPeer(vault common.Address) ([]ChequeRecord, error)
	// ListReceivedChequeRecords returns the records we received from a specific vault.
	ReceivedChequeRecordsAll() (map[common.Address][]ChequeRecord, error)
	ReceivedStatsHistory(days int, token common.Address) ([]DailyReceivedStats, error)
	SentStatsHistory(days int, token common.Address) ([]DailySentStats, error)

	// StoreSendChequeRecord store send cheque records.
	StoreSendChequeRecord(vault, beneficiary common.Address, amount *big.Int, token common.Address) error
	// SendChequeRecordsByPeer returns the records we send to a specific vault.
	SendChequeRecordsByPeer(beneficiary common.Address) ([]ChequeRecord, error)
	// SendChequeRecordsAll returns the records we send to a specific vault.
	SendChequeRecordsAll() (map[common.Address][]ChequeRecord, error)
}

ChequeStore handles the verification and storage of received cheques

func NewChequeStore

func NewChequeStore(
	store storage.StateStorer,
	factory Factory,
	chainID int64,
	beneficiary common.Address,
	transactionService transaction.Service,
	recoverChequeFunc RecoverChequeFunc) ChequeStore

NewChequeStore creates new ChequeStore

type DailyReceivedStats

type DailyReceivedStats struct {
	Amount *big.Int
	Count  int
	Date   int64 //time.now().Unix()
}

type DailySentStats

type DailySentStats struct {
	Amount *big.Int
	Count  int
	Date   int64 //time.now().Unix()
}

type Factory

type Factory interface {
	// ERC20Address returns the token for which this factory deploys vaults.
	ERC20Address(ctx context.Context) (common.Address, error)
	// Deploy return the existed one if already deployed, otherwise deploy one and return the trxHash
	Deploy(ctx context.Context, issuer common.Address, vaultLogic common.Address, peerId string, tokenAddress common.Address) (vault common.Address, trx common.Hash, err error)
	// WaitDeployed waits for the deployment transaction to confirm and returns the vault address
	WaitDeployed(ctx context.Context, txHash common.Hash) (common.Address, error)
	// VerifyBytecode checks that the factory is valid.
	VerifyBytecode(ctx context.Context) error
	// VerifyVault checks that the supplied vault has been deployed by this factory.
	VerifyVault(ctx context.Context, vault common.Address) error
	// GetPeerVault query peer's vault address deployed by this factory.
	GetPeerVault(ctx context.Context, peerID peer.ID) (vault common.Address, err error)
	// GetPeerVaultWithCache query peer's vault address deployed by this factory. Return cached if cache exists, otherwise query from BTTC.
	GetPeerVaultWithCache(ctx context.Context, peerID peer.ID) (vault common.Address, err error)
	// IsVaultCompatibleBetween checks whether my vault is compatible with the `peerID`'s one.
	IsVaultCompatibleBetween(ctx context.Context, peerID1, peerID2 peer.ID) (isCompatible bool, err error)
}

Factory is the main interface for interacting with the vault factory.

func NewFactory

func NewFactory(backend transaction.Backend, transactionService transaction.Service, address common.Address) Factory

NewFactory creates a new factory service for the provided factory contract.

type IndexRange

type IndexRange struct {
	MinIndex uint64
	MaxIndex uint64
}

the valid range is [MinIndex, MaxIndex)

type LastCashout

type LastCashout struct {
	TxHash   common.Hash
	Cheque   SignedCheque // the cheque that was used to cashout which may be different from the latest cheque
	Result   *CashChequeResult
	Reverted bool
}

LastCashout contains information about the last cashout

type RecoverChequeFunc

type RecoverChequeFunc func(cheque *SignedCheque, chainID int64) (common.Address, error)

type SendChequeFunc

type SendChequeFunc func(cheque *SignedCheque) error

SendChequeFunc is a function to send cheques.

type Service

type Service interface {
	// Deposit starts depositing erc20 token into the vault. This returns once the transactions has been broadcast.
	Deposit(ctx context.Context, amount *big.Int, token common.Address) (hash common.Hash, err error)
	// Withdraw starts withdrawing erc20 token from the vault. This returns once the transactions has been broadcast.
	Withdraw(ctx context.Context, amount *big.Int, token common.Address) (hash common.Hash, err error)
	// WaitForDeposit waits for the deposit transaction to confirm and verifies the result.
	WaitForDeposit(ctx context.Context, txHash common.Hash) error
	// TotalBalance returns the token balance of the vault.
	TotalBalance(ctx context.Context, token common.Address) (*big.Int, error)
	// TotalIssuedCount returns total issued count of the vault.
	TotalIssuedCount(token common.Address) (int, error)
	TotalIssued(token common.Address) (*big.Int, error)
	TotalReceivedCount(token common.Address) (int, error)
	TotalReceivedCashedCount(token common.Address) (int, error)
	TotalReceived(token common.Address) (*big.Int, error)
	TotalReceivedCashed(token common.Address) (*big.Int, error)
	TotalDailyReceived(token common.Address) (*big.Int, error)
	TotalDailyReceivedCashed(token common.Address) (*big.Int, error)
	// LiquidBalance returns the token balance of the vault sub stake amount. (not use)
	LiquidBalance(ctx context.Context) (*big.Int, error)
	// AvailableBalance returns the token balance of the vault which is not yet used for uncashed cheques.
	AvailableBalance(ctx context.Context, token common.Address) (*big.Int, error)
	// Address returns the address of the used vault contract.
	Address() common.Address
	// Issue a new cheque for the beneficiary with an cumulativePayout amount higher than the last.
	Issue(ctx context.Context, beneficiary common.Address, amount *big.Int, token common.Address, sendChequeFunc SendChequeFunc) (*big.Int, error)
	// LastCheque returns the last cheque we issued for the beneficiary.
	LastCheque(beneficiary common.Address, token common.Address) (*SignedCheque, error)
	// LastCheques returns the last cheques we issued for all beneficiaries.
	LastCheques(token common.Address) (map[common.Address]*SignedCheque, error)
	// WbttBalanceOf retrieve the addr balance
	WBTTBalanceOf(ctx context.Context, addr common.Address) (*big.Int, error)
	// TokenBalanceOf retrieve the addr balance
	TokenBalanceOf(ctx context.Context, addr common.Address, tokenStr string) (*big.Int, error)
	// BTTBalanceOf retrieve the btt balance of addr
	BTTBalanceOf(ctx context.Context, address common.Address, block *big.Int) (*big.Int, error)
	// TotalPaidOut return total pay out of the vault
	TotalPaidOut(ctx context.Context, token common.Address) (*big.Int, error)
	// CheckBalance
	CheckBalance(amount *big.Int) (err error)
	// UpgradeTo will upgrade vault implementation to `newVaultImpl`
	UpgradeTo(ctx context.Context, newVaultImpl common.Address) (old, new common.Address, err error)
}

Service is the main interface for interacting with the nodes vault.

func Init

func Init(
	ctx context.Context,
	vaultFactory Factory,
	stateStore storage.StateStorer,
	transactionService transaction.Service,
	swapBackend transaction.Backend,
	chainId int64,
	peerId string,
	vaultLogicAddress common.Address,
	overlayEthAddress common.Address,
	chequeSigner ChequeSigner,
	chequeStore ChequeStore,
	erc20Service erc20.Service,
	mpErc20Service map[string]erc20.Service,
) (vaultService Service, err error)

Init initialises the vault service.

func New

func New(transactionService transaction.Service, address, ownerAddress common.Address, store storage.StateStorer,
	chequeSigner ChequeSigner, erc20Service erc20.Service, mpErc20Service map[string]erc20.Service, chequeStore ChequeStore) (Service, error)

New creates a new vault service for the provided vault contract.

type SignedCheque

type SignedCheque struct {
	Cheque
	Signature []byte
}

SignedCheque represents a cheque together with its signature

func (*SignedCheque) Equal

func (cheque *SignedCheque) Equal(other *SignedCheque) bool

Directories

Path Synopsis

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL