Verified contractPartialUNLICENSED
SpokeOptimisticFinalityLogic
Address0xe29578c5aef73b045d0baabee52b223d5cf02443
- Balance
0 ETH
- Transactions
45
- Compiler
solc 0.8.20
- Same code
Only this contract
Details
- Compiler
- solc 0.8.20+commit.a1b79de6
- Language
- solidity
- Optimization
- Yes, 2,000 runs
- EVM version
- paris
- License
- UNLICENSED
- Match
- Partialcreation code: yes, runtime code: yes
- Verified on Sourcify
- Created in block
- 22,445,641
- Creation transaction
- 0xd58f40d1ab…081a894a6b
- Libraries
- src/libraries/logic/accounting/SpokeAccountingLogic.sol:SpokeAccountingLogic0xf933…76c764src/libraries/logic/accounting/CommonAccountingLogic.sol:CommonAccountingLogic0x6e0e…cf4d04src/libraries/logic/optimisticFinality/CommonOptimisticFinalityLogic.sol:CommonOptimisticFinalityLogic0xffe5…6a01f3
28 files
- src/libraries/logic/optimisticFinality/SpokeOptimisticFinalityLogic.solmain28.64 KB
- @chainlink/contracts/src/v0.8/interfaces/AggregatorV3Interface.sol592 B
- @openzeppelin/contracts/token/ERC20/IERC20.sol2.78 KB
- @openzeppelin/contracts/token/ERC20/extensions/IERC20Permit.sol3.8 KB
- @openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol5.77 KB
- @openzeppelin/contracts/utils/Address.sol6.26 KB
- @pythnetwork/pyth-sdk-solidity/IPyth.sol9.49 KB
- @pythnetwork/pyth-sdk-solidity/IPythEvents.sol1.01 KB
- @pythnetwork/pyth-sdk-solidity/PythStructs.sol1.18 KB
- @wormhole/Utils.sol459 B
- @wormhole/interfaces/IERC20.sol2.74 KB
- @wormhole/interfaces/IWETH.sol230 B
- @wormhole/interfaces/IWormholeRelayer.sol36.66 KB
- src/contracts/HubSpokeEvents.sol2.96 KB
- src/contracts/HubSpokeStructs.sol12.37 KB
- src/interfaces/IAssetRegistry.sol3.88 KB
- src/interfaces/IHub.sol3.75 KB
- src/interfaces/IHubPriceUtilities.sol1.93 KB
- src/interfaces/ILegacyAssetRegistry.sol1.77 KB
- src/interfaces/ILiquidationCalculator.sol1.32 KB
- src/interfaces/ISpoke.sol1.45 KB
- src/interfaces/ISynonymPriceOracle.sol857 B
- src/interfaces/ISynonymPriceSource.sol521 B
- src/interfaces/IWormholeTunnel.sol6.12 KB
- src/interfaces/rewards/IMoneyMarketRewardsDistributor.sol472 B
- src/libraries/logic/accounting/CommonAccountingLogic.sol2.32 KB
- src/libraries/logic/accounting/SpokeAccountingLogic.sol3.75 KB
- src/libraries/logic/optimisticFinality/CommonOptimisticFinalityLogic.sol1.06 KB
src/libraries/logic/optimisticFinality/SpokeOptimisticFinalityLogic.sol
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.0;
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {IWormholeTunnel} from "../../../interfaces/IWormholeTunnel.sol";
import {ISpoke} from "../../../interfaces/ISpoke.sol";
import {IHub} from "../../../interfaces/IHub.sol";
import {IWETH} from "@wormhole/interfaces/IWETH.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {HubSpokeStructs} from "../../../contracts/HubSpokeStructs.sol";
import {HubSpokeEvents} from "../../../contracts/HubSpokeEvents.sol";
import "@wormhole/Utils.sol";
import {CommonAccountingLogic} from "../accounting/CommonAccountingLogic.sol";
import {SpokeAccountingLogic} from "../accounting/SpokeAccountingLogic.sol";
import {CommonOptimisticFinalityLogic} from "./CommonOptimisticFinalityLogic.sol";
library SpokeOptimisticFinalityLogic {
using SafeERC20 for IERC20;
// events need to be in both library and contract to be picked up
// see: https://ethereum.stackexchange.com/questions/11137/watching-events-defined-in-libraries
event SpokeCreditCreated(address indexed user, address indexed asset, uint256 amount, uint256 nonce);
event SpokeCreditLost(address indexed user, address indexed asset, uint256 amount, uint256 nonce);
event SpokeCreditRefundable(address indexed user, address indexed asset, uint256 amount, uint256 nonce);
event SpokeCreditConfirmed(uint256 nonce);
event SpokeCreditFinalized(uint256 nonce);
event SpokeCreditRefunded(address indexed user, address indexed asset, uint256 amount, uint256 nonce);
event SpokeLimitsChanged(address indexed asset, uint256 creditLimit, uint256 custodyLimit, uint256 transactionLimit);
event SpokeFeesChanged(uint256 inboundTokenFee, uint256 outboundTokenFee);
event SpokeFundsReleased(address indexed user, address indexed asset, uint256 amount, uint256 nonce);
event SpokeTopUpReceived(address indexed asset, uint256 amount);
event PossibleHubMisconfiguration(address assetSentAsWeth, address realWeth);
// end events from HubSpokeEvents
error CreditAlreadyFinalized();
error CreditLimitExceeded();
error CustodyLimitExceeded();
error FundsAlreadyReleased();
error InsufficientFunds();
error InsufficientMsgValue();
error InsufficientSpokeBalance();
error InvalidAction();
error InvalidAmount();
error InvalidCostForReturnDeliveryLength();
error InvalidReleaseFundsPayload();
error TransactionLimitExceeded();
error TransferFailed();
error UnexpectedTokenReceived();
function SPOKE_TOP_UP_GAS_LIMIT() public pure returns (uint256) {
return 500_000;
}
function INSTANT_MESSAGE_FEE_PRECISION() public pure returns (uint256) {
return 1e18;
}
function HUB_FINALIZE_CREDIT_GAS_LIMIT() public pure returns (uint256) {
return 600_000;
}
function HUB_CONFIRM_TOP_UP_GAS_LIMIT() public pure returns (uint256) {
return 100_000;
}
function setLimits(
HubSpokeStructs.SpokeOptimisticFinalityState storage ofState,
address _token,
uint256 _creditLimit,
uint256 _custodyLimit,
uint256 _transactionLimit
) public {
HubSpokeStructs.SpokeBalances storage balance = ofState.tokenBalances[toWormholeFormat(_token)];
balance.creditLimit = _creditLimit;
balance.custodyLimit = _custodyLimit;
balance.transactionLimit = _transactionLimit;
balance.lastUpdated = block.timestamp;
emit SpokeLimitsChanged(_token, _creditLimit, _custodyLimit, _transactionLimit);
}
function setInstantMessageFees(
HubSpokeStructs.SpokeOptimisticFinalityState storage ofState,
uint256 _inboundTokenInstantMessageFee,
uint256 _outboundTokenInstantMessageFee
) public {
uint256 precision = INSTANT_MESSAGE_FEE_PRECISION();
if (_inboundTokenInstantMessageFee > precision || _outboundTokenInstantMessageFee > precision) {
revert InvalidAmount();
}
ofState.inboundTokenInstantMessageFee = _inboundTokenInstantMessageFee;
ofState.outboundTokenInstantMessageFee = _outboundTokenInstantMessageFee;
emit SpokeFeesChanged(_inboundTokenInstantMessageFee, _outboundTokenInstantMessageFee);
}
function handleInstantAction(
HubSpokeStructs.SpokeOptimisticFinalityState storage ofState,
HubSpokeStructs.SpokeCommunicationState storage commState,
IWETH weth,
HubSpokeStructs.Action action,
address asset,
uint256 amount,
uint256[] calldata costForReturnDelivery
) public {
uint256[] memory costs;
uint256 valueToSend = msg.value;
{
uint256 totalCost;
(totalCost, costs) = getInstantActionDeliveryCosts(commState, costForReturnDelivery);
if (msg.value < totalCost) {
revert InsufficientMsgValue();
}
(action, asset, amount, valueToSend) = CommonAccountingLogic.handleInboundTokensAndAdjustAction(action, asset, amount, weth, totalCost);
}
if (amount == 0 || address(asset) == address(0)) {
revert InvalidAction();
}
ofState.lastInstantActionNonces[msg.sender]++; // increment the nonce for this action
if (CommonOptimisticFinalityLogic.getActionDirection(action) == HubSpokeStructs.ActionDirection.Inbound) {
// validation checks for instant deposits and repays
if (amount > ofState.tokenBalances[toWormholeFormat(address(asset))].transactionLimit) {
revert TransactionLimitExceeded();
}
// instant token sends are sent with two messages
if (costs.length != 2) {
revert InvalidCostForReturnDeliveryLength();
}
// check credit limit
HubSpokeStructs.SpokeBalances storage balance = ofState.tokenBalances[toWormholeFormat(address(asset))];
amount -= amount * ofState.inboundTokenInstantMessageFee / INSTANT_MESSAGE_FEE_PRECISION();
HubSpokeStructs.Credit storage storedCredit = ofState.storedCredits[msg.sender][ofState.lastInstantActionNonces[msg.sender]];
if (
storedCredit.createdAt != 0 &&
(
storedCredit.token != toWormholeFormat(address(asset)) ||
storedCredit.creditedAmount != amount
)
) {
// there already exists a credit under that nonce and the token or amount conflicts
// this does not happen in a non-malicious flow
// it means the user sent a deposit that got reorg'd and it was registered on the Hub
// the user later replaced that deposit, because it was not re-executed with the same parameters
// take the tokens and the ETH to recover at least some of the value the attacker was already credited with
// these are added to the reserves on the Spoke since state is not updated
// creditGiven was already updated when the reorg'd credit was confirmed by the Hub
storedCredit.status = HubSpokeStructs.CreditStatus.LOST;
storedCredit.updatedAt = block.timestamp;
emit SpokeCreditLost(msg.sender, asset, amount, ofState.lastInstantActionNonces[msg.sender]);
return;
}
// when the credit finalizes, the entire amount should be made available for new credit
balance.unlocksPending += amount;
balance.lastUpdated = block.timestamp;
// balance.deposits is not updated here, because credit is given
// credit is moved to deposits in finalizeCredit
// only add credit if there was no reorg (credit was not created by the Hub confirmation)
if (storedCredit.createdAt == 0) {
balance.creditGiven += amount;
// this check is skipped if the credit already exists, because this credit has already been processed in the Hub
// in rare cases this can lead to credit limit being temporarily exceeded
if (balance.creditGiven + balance.creditLost > balance.creditLimit) {
revert CreditLimitExceeded();
}
// check if the currently finalized amount plus the pending amount is under the custody limit
if (balance.deposits + balance.unlocksPending > balance.custodyLimit) {
revert CustodyLimitExceeded();
}
storedCredit.user = toWormholeFormat(msg.sender);
storedCredit.token = toWormholeFormat(address(asset));
storedCredit.creditedAmount = amount;
storedCredit.nonce = ofState.lastInstantActionNonces[msg.sender];
storedCredit.createdAt = block.timestamp;
emit SpokeCreditCreated(msg.sender, address(asset), amount, storedCredit.nonce);
_sendInstantActionTunnelMessage(
ofState,
commState,
action,
storedCredit.token, // same as b32(a(asset)), but already as b32
amount,
costs[0],
costForReturnDelivery[0]
);
} else {
// the credit has been created through Hub confirmation.
// when it was created the amount of credit has been accounted as lost
// this tx restores the lost tokens
balance.creditLost -= amount;
balance.creditGiven += amount;
}
// the finalize credit message is sent regardless if the credit existed before or not
// if it did then it must have gotten reorg'd. checks for credit being identical have been made earlier.
// when this message finalizes the credit no protocol loss will be incurred and the credit
// will be finalized correctly in spite of the reorg
_sendFinalizeCreditTunnelMessage(
commState,
storedCredit,
costs[1],
costForReturnDelivery[1]
);
} else {
// borrow and withdraw flow
// instant token sends are sent with one message
if (costForReturnDelivery.length != 1) {
revert InvalidCostForReturnDeliveryLength();
}
if (ofState.tokenBalances[toWormholeFormat(address(asset))].deposits < amount) {
revert InsufficientFunds();
}
_sendInstantActionTunnelMessage(
ofState,
commState,
action,
toWormholeFormat(asset),
amount,
costs[0],
costForReturnDelivery[0]
);
}
}
function handleReleaseFunds(
HubSpokeStructs.SpokeOptimisticFinalityState storage ofState,
IWETH weth,
bytes calldata payload
) public {
HubSpokeStructs.ReleaseFundsPayload memory rfp = abi.decode(payload, (HubSpokeStructs.ReleaseFundsPayload));
if (rfp.token == bytes32(0) || rfp.amount == 0) {
revert InvalidReleaseFundsPayload();
}
address user = fromWormholeFormat(rfp.user);
if (ofState.fundReleases[user][rfp.nonce].amount != 0) {
// there already exists a release of funds under that nonce
// this should never happen, because SpokeFundRelease is only created in this function.
// revert to prevent the duplicate release
revert FundsAlreadyReleased();
}
if (ofState.tokenBalances[rfp.token].deposits < rfp.amount) {
revert InsufficientFunds();
}
// full amount is subtracted from deposits
// as a result, the fee is accounted towards reserves
ofState.tokenBalances[rfp.token].deposits -= rfp.amount;
ofState.tokenBalances[rfp.token].lastUpdated = block.timestamp;
ofState.fundReleases[user][rfp.nonce] = HubSpokeStructs.SpokeFundRelease({
nonce: rfp.nonce,
user: rfp.user,
token: rfp.token,
amount: rfp.amount,
releasedAt: block.timestamp
});
if (rfp.unwrapWeth && rfp.token == toWormholeFormat(address(weth))) {
weth.withdraw(rfp.amount);
(bool success,) = fromWormholeFormat(rfp.user).call{value: rfp.amount}("");
if (!success) {
revert TransferFailed();
}
} else {
address token = fromWormholeFormat(rfp.token);
if (rfp.unwrapWeth) {
emit PossibleHubMisconfiguration(token, address(weth));
}
// we default to just transferring the token if the Hub somehow messed up and requested to unwrap something other than WETH.
// reverting here would be problematic. we can't replay this, because it's simply invalid and will not become valid later.
// it's probably best not to revert instants on non-critical issues.
// this should never happen anyway, because rfp.token is passed around in payloads from Spoke to Hub and back to Spoke without being changed.
IERC20(token).safeTransfer(fromWormholeFormat(rfp.user), rfp.amount);
}
emit SpokeFundsReleased(fromWormholeFormat(rfp.user), fromWormholeFormat(rfp.token), rfp.amount, rfp.nonce);
}
function handleTopUp(
HubSpokeStructs.SpokeOptimisticFinalityState storage ofState,
HubSpokeStructs.SpokeCommunicationState storage commState,
IWormholeTunnel.MessageSource calldata source,
IERC20 token,
uint256 amount
) public {
token.safeTransferFrom(msg.sender, address(this), amount);
HubSpokeStructs.SpokeBalances storage balance = ofState.tokenBalances[toWormholeFormat(address(token))];
balance.deposits += amount;
balance.lastUpdated = block.timestamp;
emit SpokeTopUpReceived(address(token), amount);
IWormholeTunnel.TunnelMessage memory message;
message.source.refundRecipient = source.refundRecipient;
message.source.sender = toWormholeFormat(address(this));
message.target.chainId = commState.hubChainId;
message.target.recipient = commState.hubContractAddress;
message.target.selector = IHub.confirmTopUpMessage.selector;
message.target.payload = abi.encode(HubSpokeStructs.ConfirmTopUpPayload({
token: toWormholeFormat(address(token)),
amount: amount
}));
message.finality = IWormholeTunnel.MessageFinality.INSTANT;
uint256 cost = commState.wormholeTunnel.getMessageCost(commState.hubChainId, HUB_CONFIRM_TOP_UP_GAS_LIMIT(), 0, false);
commState.wormholeTunnel.sendEvmMessage{value: cost}(message, HUB_CONFIRM_TOP_UP_GAS_LIMIT());
}
function handleConfirmCredit(
HubSpokeStructs.SpokeOptimisticFinalityState storage ofState,
bytes calldata payload
) public {
HubSpokeStructs.ConfirmCreditPayload memory ccp = abi.decode(payload, (HubSpokeStructs.ConfirmCreditPayload));
address user = fromWormholeFormat(ccp.credit.user);
HubSpokeStructs.Credit storage storedCredit = ofState.storedCredits[user][ccp.credit.nonce];
if (CommonOptimisticFinalityLogic.creditMissingOrConflicting(ccp.credit, storedCredit)) {
address token = fromWormholeFormat(ccp.credit.token);
HubSpokeStructs.SpokeBalances storage balance = ofState.tokenBalances[ccp.credit.token];
if (storedCredit.createdAt != 0) {
// credit already exists with different user, token or amount
// this means that the credit being confirmed got reorg'd out of the spoke
// also, before the current confirmation arrived, a new credit has been given
// the credit in the Spoke is a new credit that replaced the one that got confirmed
// the Spoke credit got reverted when it reached the Hub (same user nonce) and is invalid
// only the credit confirmed by the Hub actually got accounted for
// the credit coming from the Hub is lost, but the stored credit can still finalize
// if it finalizes, its amount will be added to reserves
// the incoming credit will never finalize, but it's not accounted for in the Spoke
// signal that the stored credit is Lost
ccp.credit.status = HubSpokeStructs.CreditStatus.LOST;
emit SpokeCreditLost(user, token, ccp.credit.creditedAmount, ccp.credit.nonce);
} else {
// - we don't update SpokeBalances unlocksPending or deposits
// if the action is non-malicious these values will be updated
// when the action is re-executed
// - we don't increase the users nonce in anticipation that this was a non-malicious reorg
// in this case the users deposit will be re-added under the same nonce
// if the deposit is not re-added then the users action must have been malicious
// the next user action will revert on the Hub, because the Spoke will send it with
// a nonce that already exists on the Hub
ccp.credit.status = HubSpokeStructs.CreditStatus.CONFIRMED;
emit SpokeCreditCreated(user, token, ccp.credit.creditedAmount, ccp.credit.nonce);
}
// re-create the credit
// regardless if the Spoke Credit is missing or conflicting, we overwrite it with what came from the Hub
// because that's what was accounted for
// Solidity quirk: can't use the storedCredit storage pointer for this assignment
ccp.credit.createdAt = block.timestamp;
ofState.storedCredits[user][ccp.credit.nonce] = ccp.credit;
// add the amount as credit that is lost
// credit that is conflicting is lost for sure
// credit that is missing might still return to correct state if the same tx is re-added into a later block
balance.creditLost += ccp.credit.creditedAmount;
// creditGiven and unlocksPending are not updated here.
// if there was a credit conflict then the later post-reorg credit that modified the balances
// can still finalize. in that case, finalizeCredit() will reduce creditGiven and unlocksPending
balance.lastUpdated = block.timestamp;
} else {
storedCredit.status = HubSpokeStructs.CreditStatus.CONFIRMED;
}
// this confirms the credit. the stored credit here always matches the incoming credit
storedCredit.updatedAt = block.timestamp;
emit SpokeCreditConfirmed(ccp.credit.nonce);
}
function handleFinalizeCredit(
HubSpokeStructs.SpokeOptimisticFinalityState storage ofState,
bytes calldata payload
) public {
HubSpokeStructs.FinalizeCreditPayload memory fcp = abi.decode(payload, (HubSpokeStructs.FinalizeCreditPayload));
address user = fromWormholeFormat(fcp.credit.user);
HubSpokeStructs.SpokeBalances storage balance = ofState.tokenBalances[fcp.credit.token];
HubSpokeStructs.Credit storage storedCredit = ofState.storedCredits[user][fcp.credit.nonce];
if (storedCredit.status == HubSpokeStructs.CreditStatus.CONFIRMED) {
storedCredit.status = HubSpokeStructs.CreditStatus.FINALIZED;
storedCredit.updatedAt = block.timestamp;
emit SpokeCreditFinalized(fcp.credit.nonce);
} else if (storedCredit.createdAt > 0 && storedCredit.status == HubSpokeStructs.CreditStatus.PENDING) {
// the credit has been created, but hasn't been confirmed by the Hub and hasn't been marked as LOST
// one of two things could have happened here:
// - this was a failed malicious attempt where the original TX was a borrow
// which got replaced with a deposit or repay
// - this was a deposit or repay that failed for non-malicious reasons
// such as a crossed deposit limit or invalid repay amount
// in both cases a manual resolution is needed
storedCredit.status = HubSpokeStructs.CreditStatus.REFUNDABLE;
storedCredit.updatedAt = block.timestamp;
emit SpokeCreditRefundable(user, fromWormholeFormat(storedCredit.token), storedCredit.creditedAmount, storedCredit.nonce);
}
// confirmed and pending credit cases are handled above
// if credit was lost, one of two things could have happened:
// - if replaced before confirmation then a new Credit was created and creditGiven was increased
// - if replaced after confirmation then no finalization message was sent so this function will not be called
// this should never underflow, because we only add this when creating credit
balance.creditGiven -= fcp.credit.creditedAmount;
balance.lastUpdated = block.timestamp;
balance.unlocksPending -= fcp.credit.creditedAmount;
if (ofState.storedCredits[user][fcp.credit.nonce].status == HubSpokeStructs.CreditStatus.FINALIZED) {
// move the amount from credit to finalized deposit
// only account towards deposits if this is a happy path with confirmed credit
// if the credit was missing or conflicting then the credit being finalized has not been confirmed by the Hub
// this means that the amount should be acounted towards protocol reserves
// in that case we have two possible scenarios. the finalized amount (now stored as reserve) can be:
// - refunded in case of a non-malicious Hub revert (ex. deposit bounced due to limits)
// - taken over to cover the loss in case of a malicious attempt
balance.deposits += fcp.credit.creditedAmount;
}
}
function handleFixLostCredit(
HubSpokeStructs.SpokeOptimisticFinalityState storage ofState,
HubSpokeStructs.SpokeCommunicationState storage commState,
IERC20 token,
uint256 amount,
bool fromReserves
) public {
HubSpokeStructs.SpokeBalances storage balance = ofState.tokenBalances[toWormholeFormat(address(token))];
if (balance.creditLost < amount) {
revert InvalidAmount();
}
uint256 cost = commState.wormholeTunnel.getMessageCost(commState.hubChainId, HUB_CONFIRM_TOP_UP_GAS_LIMIT(), 0, false);
// the cost can be covered either by passing it as msg.value or from reserves
// either way the balance needs to exceed the cost
if (address(this).balance < cost) {
revert InsufficientMsgValue();
}
if (!fromReserves) {
token.safeTransferFrom(msg.sender, address(this), amount);
} else if (SpokeAccountingLogic.getReserveAmount(ofState, address(token)) < amount) {
revert InsufficientFunds();
}
balance.creditLost -= amount;
balance.deposits += amount;
// this flow is the same as a top up confirmation
// it just increases the Hub accounted Spoke finalized deposit balance
// sent as an instant, because owner is assumed to not be malicious
bytes32 spokeAddressWhFormat = toWormholeFormat(address(this));
IWormholeTunnel.TunnelMessage memory message;
message.source.refundRecipient = spokeAddressWhFormat;
message.source.sender = spokeAddressWhFormat;
message.target.chainId = commState.hubChainId;
message.target.recipient = commState.hubContractAddress;
message.target.selector = IHub.confirmFixLostCreditMessage.selector;
message.target.payload = abi.encode(HubSpokeStructs.ConfirmFixLostCreditPayload({
token: toWormholeFormat(address(token)),
amount: amount
}));
message.finality = IWormholeTunnel.MessageFinality.INSTANT;
commState.wormholeTunnel.sendEvmMessage{value: cost}(message, HUB_CONFIRM_TOP_UP_GAS_LIMIT());
}
function handleRefundCredit(
HubSpokeStructs.SpokeOptimisticFinalityState storage ofState,
address _user,
uint256 _nonce
) public {
HubSpokeStructs.Credit storage credit = ofState.storedCredits[_user][_nonce];
if (credit.status != HubSpokeStructs.CreditStatus.REFUNDABLE) {
// the credit has been confirmed by the Hub
// there can be no refund
// the user should make a withdrawal instead
revert InvalidAction();
}
IERC20 token = IERC20(fromWormholeFormat(credit.token));
if (SpokeAccountingLogic.getReserveAmount(ofState, address(token)) < credit.creditedAmount) {
revert InsufficientFunds();
}
credit.status = HubSpokeStructs.CreditStatus.REFUNDED;
token.safeTransfer(_user, credit.creditedAmount);
emit SpokeCreditRefunded(_user, address(token), credit.creditedAmount, _nonce);
}
function _sendFinalizeCreditTunnelMessage(
HubSpokeStructs.SpokeCommunicationState storage commState,
HubSpokeStructs.Credit storage credit,
uint256 actionCost,
uint256 returnDeliveryCost
) internal {
IWormholeTunnel.TunnelMessage memory message;
message.source.refundRecipient = message.source.refundRecipient;
message.source.sender = message.source.refundRecipient;
message.source.chainId = commState.wormholeTunnel.chainId();
message.target.chainId = commState.hubChainId;
message.target.recipient = commState.hubContractAddress;
message.target.selector = IHub.finalizeCreditMessage.selector;
message.target.payload = abi.encode(HubSpokeStructs.FinalizeCreditPayload({
credit: credit
}));
message.receiverValue = returnDeliveryCost;
commState.wormholeTunnel.sendEvmMessage{value: actionCost}(
message,
HUB_FINALIZE_CREDIT_GAS_LIMIT()
);
}
function _sendInstantActionTunnelMessage(
HubSpokeStructs.SpokeOptimisticFinalityState storage ofState,
HubSpokeStructs.SpokeCommunicationState storage commState,
HubSpokeStructs.Action action,
bytes32 asset,
uint256 amount,
uint256 actionCost,
uint256 returnDeliveryCost
) internal {
IWormholeTunnel.TunnelMessage memory message;
message.source.refundRecipient = toWormholeFormat(msg.sender);
message.source.sender = toWormholeFormat(address(this));
message.target.chainId = commState.hubChainId;
message.target.recipient = commState.hubContractAddress;
message.target.selector = IHub.instantActionMessage.selector;
message.target.payload = abi.encode(HubSpokeStructs.UserActionPayload({
user: message.source.refundRecipient,
action: action,
token: asset,
amount: amount,
nonce: ofState.lastInstantActionNonces[msg.sender]
}));
message.finality = IWormholeTunnel.MessageFinality.INSTANT;
message.receiverValue = returnDeliveryCost;
commState.wormholeTunnel.sendEvmMessage{value: actionCost}(
message,
commState.defaultGasLimitRoundtrip
);
}
function getInstantActionDeliveryCosts(
HubSpokeStructs.SpokeCommunicationState storage commState,
uint256[] calldata returnCosts
) public view returns (uint256 total, uint256[] memory costs) {
// for deposit/repay flow there should be two returnCosts. the first one to send an accounting confirmation, the second one to send the finalization confirmation
// for withdraw/borrow flow there should only be a single return cost
costs = new uint256[](returnCosts.length);
for (uint256 i = 0; i < returnCosts.length; i++) {
costs[i] = commState.wormholeTunnel.getMessageCost(
commState.hubChainId,
commState.defaultGasLimitRoundtrip,
returnCosts[i],
false
);
total += costs[i];
}
}
}@chainlink/contracts/src/v0.8/interfaces/AggregatorV3Interface.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
interface AggregatorV3Interface {
function decimals() external view returns (uint8);
function description() external view returns (string memory);
function version() external view returns (uint256);
function getRoundData(
uint80 _roundId
) external view returns (uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound);
function latestRoundData()
external
view
returns (uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound);
}
@openzeppelin/contracts/token/ERC20/IERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/IERC20.sol)
pragma solidity ^0.8.20;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
/**
* @dev Returns the value of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the value of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves a `value` amount of tokens from the caller's account to `to`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address to, uint256 value) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets a `value` amount of tokens as the allowance of `spender` over the
* caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 value) external returns (bool);
/**
* @dev Moves a `value` amount of tokens from `from` to `to` using the
* allowance mechanism. `value` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address from, address to, uint256 value) external returns (bool);
}
@openzeppelin/contracts/token/ERC20/extensions/IERC20Permit.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/extensions/IERC20Permit.sol)
pragma solidity ^0.8.20;
/**
* @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in
* https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].
*
* Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by
* presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't
* need to send a transaction, and thus is not required to hold Ether at all.
*
* ==== Security Considerations
*
* There are two important considerations concerning the use of `permit`. The first is that a valid permit signature
* expresses an allowance, and it should not be assumed to convey additional meaning. In particular, it should not be
* considered as an intention to spend the allowance in any specific way. The second is that because permits have
* built-in replay protection and can be submitted by anyone, they can be frontrun. A protocol that uses permits should
* take this into consideration and allow a `permit` call to fail. Combining these two aspects, a pattern that may be
* generally recommended is:
*
* ```solidity
* function doThingWithPermit(..., uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) public {
* try token.permit(msg.sender, address(this), value, deadline, v, r, s) {} catch {}
* doThing(..., value);
* }
*
* function doThing(..., uint256 value) public {
* token.safeTransferFrom(msg.sender, address(this), value);
* ...
* }
* ```
*
* Observe that: 1) `msg.sender` is used as the owner, leaving no ambiguity as to the signer intent, and 2) the use of
* `try/catch` allows the permit to fail and makes the code tolerant to frontrunning. (See also
* {SafeERC20-safeTransferFrom}).
*
* Additionally, note that smart contract wallets (such as Argent or Safe) are not able to produce permit signatures, so
* contracts should have entry points that don't rely on permit.
*/
interface IERC20Permit {
/**
* @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens,
* given ``owner``'s signed approval.
*
* IMPORTANT: The same issues {IERC20-approve} has related to transaction
* ordering also apply here.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `deadline` must be a timestamp in the future.
* - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner`
* over the EIP712-formatted function arguments.
* - the signature must use ``owner``'s current nonce (see {nonces}).
*
* For more information on the signature format, see the
* https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP
* section].
*
* CAUTION: See Security Considerations above.
*/
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external;
/**
* @dev Returns the current nonce for `owner`. This value must be
* included whenever a signature is generated for {permit}.
*
* Every successful call to {permit} increases ``owner``'s nonce by one. This
* prevents a signature from being used multiple times.
*/
function nonces(address owner) external view returns (uint256);
/**
* @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}.
*/
// solhint-disable-next-line func-name-mixedcase
function DOMAIN_SEPARATOR() external view returns (bytes32);
}
@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/utils/SafeERC20.sol)
pragma solidity ^0.8.20;
import {IERC20} from "../IERC20.sol";
import {IERC20Permit} from "../extensions/IERC20Permit.sol";
import {Address} from "../../../utils/Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using Address for address;
/**
* @dev An operation with an ERC20 token failed.
*/
error SafeERC20FailedOperation(address token);
/**
* @dev Indicates a failed `decreaseAllowance` request.
*/
error SafeERC20FailedDecreaseAllowance(address spender, uint256 currentAllowance, uint256 requestedDecrease);
/**
* @dev Transfer `value` amount of `token` from the calling contract to `to`. If `token` returns no value,
* non-reverting calls are assumed to be successful.
*/
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeCall(token.transfer, (to, value)));
}
/**
* @dev Transfer `value` amount of `token` from `from` to `to`, spending the approval given by `from` to the
* calling contract. If `token` returns no value, non-reverting calls are assumed to be successful.
*/
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeCall(token.transferFrom, (from, to, value)));
}
/**
* @dev Increase the calling contract's allowance toward `spender` by `value`. If `token` returns no value,
* non-reverting calls are assumed to be successful.
*/
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 oldAllowance = token.allowance(address(this), spender);
forceApprove(token, spender, oldAllowance + value);
}
/**
* @dev Decrease the calling contract's allowance toward `spender` by `requestedDecrease`. If `token` returns no
* value, non-reverting calls are assumed to be successful.
*/
function safeDecreaseAllowance(IERC20 token, address spender, uint256 requestedDecrease) internal {
unchecked {
uint256 currentAllowance = token.allowance(address(this), spender);
if (currentAllowance < requestedDecrease) {
revert SafeERC20FailedDecreaseAllowance(spender, currentAllowance, requestedDecrease);
}
forceApprove(token, spender, currentAllowance - requestedDecrease);
}
}
/**
* @dev Set the calling contract's allowance toward `spender` to `value`. If `token` returns no value,
* non-reverting calls are assumed to be successful. Meant to be used with tokens that require the approval
* to be set to zero before setting it to a non-zero value, such as USDT.
*/
function forceApprove(IERC20 token, address spender, uint256 value) internal {
bytes memory approvalCall = abi.encodeCall(token.approve, (spender, value));
if (!_callOptionalReturnBool(token, approvalCall)) {
_callOptionalReturn(token, abi.encodeCall(token.approve, (spender, 0)));
_callOptionalReturn(token, approvalCall);
}
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address-functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data);
if (returndata.length != 0 && !abi.decode(returndata, (bool))) {
revert SafeERC20FailedOperation(address(token));
}
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*
* This is a variant of {_callOptionalReturn} that silents catches all reverts and returns a bool instead.
*/
function _callOptionalReturnBool(IERC20 token, bytes memory data) private returns (bool) {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We cannot use {Address-functionCall} here since this should return false
// and not revert is the subcall reverts.
(bool success, bytes memory returndata) = address(token).call(data);
return success && (returndata.length == 0 || abi.decode(returndata, (bool))) && address(token).code.length > 0;
}
}
@openzeppelin/contracts/utils/Address.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/Address.sol)
pragma solidity ^0.8.20;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev The ETH balance of the account is not enough to perform the operation.
*/
error AddressInsufficientBalance(address account);
/**
* @dev There's no code at `target` (it is not a contract).
*/
error AddressEmptyCode(address target);
/**
* @dev A call to an address target failed. The target may have reverted.
*/
error FailedInnerCall();
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://consensys.net/diligence/blog/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.8.20/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
if (address(this).balance < amount) {
revert AddressInsufficientBalance(address(this));
}
(bool success, ) = recipient.call{value: amount}("");
if (!success) {
revert FailedInnerCall();
}
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason or custom error, it is bubbled
* up by this function (like regular Solidity function calls). However, if
* the call reverted with no returned reason, this function reverts with a
* {FailedInnerCall} error.
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
if (address(this).balance < value) {
revert AddressInsufficientBalance(address(this));
}
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResultFromTarget(target, success, returndata);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResultFromTarget(target, success, returndata);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResultFromTarget(target, success, returndata);
}
/**
* @dev Tool to verify that a low level call to smart-contract was successful, and reverts if the target
* was not a contract or bubbling up the revert reason (falling back to {FailedInnerCall}) in case of an
* unsuccessful call.
*/
function verifyCallResultFromTarget(
address target,
bool success,
bytes memory returndata
) internal view returns (bytes memory) {
if (!success) {
_revert(returndata);
} else {
// only check if target is a contract if the call was successful and the return data is empty
// otherwise we already know that it was a contract
if (returndata.length == 0 && target.code.length == 0) {
revert AddressEmptyCode(target);
}
return returndata;
}
}
/**
* @dev Tool to verify that a low level call was successful, and reverts if it wasn't, either by bubbling the
* revert reason or with a default {FailedInnerCall} error.
*/
function verifyCallResult(bool success, bytes memory returndata) internal pure returns (bytes memory) {
if (!success) {
_revert(returndata);
} else {
return returndata;
}
}
/**
* @dev Reverts with returndata if present. Otherwise reverts with {FailedInnerCall}.
*/
function _revert(bytes memory returndata) private pure {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
/// @solidity memory-safe-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert FailedInnerCall();
}
}
}
@pythnetwork/pyth-sdk-solidity/IPyth.sol
// SPDX-License-Identifier: Apache-2.0
pragma solidity ^0.8.0;
import "./PythStructs.sol";
import "./IPythEvents.sol";
/// @title Consume prices from the Pyth Network (https://pyth.network/).
/// @dev Please refer to the guidance at https://docs.pyth.network/documentation/pythnet-price-feeds/best-practices for how to consume prices safely.
/// @author Pyth Data Association
interface IPyth is IPythEvents {
/// @notice Returns the period (in seconds) that a price feed is considered valid since its publish time
function getValidTimePeriod() external view returns (uint validTimePeriod);
/// @notice Returns the price and confidence interval.
/// @dev Reverts if the price has not been updated within the last `getValidTimePeriod()` seconds.
/// @param id The Pyth Price Feed ID of which to fetch the price and confidence interval.
/// @return price - please read the documentation of PythStructs.Price to understand how to use this safely.
function getPrice(
bytes32 id
) external view returns (PythStructs.Price memory price);
/// @notice Returns the exponentially-weighted moving average price and confidence interval.
/// @dev Reverts if the EMA price is not available.
/// @param id The Pyth Price Feed ID of which to fetch the EMA price and confidence interval.
/// @return price - please read the documentation of PythStructs.Price to understand how to use this safely.
function getEmaPrice(
bytes32 id
) external view returns (PythStructs.Price memory price);
/// @notice Returns the price of a price feed without any sanity checks.
/// @dev This function returns the most recent price update in this contract without any recency checks.
/// This function is unsafe as the returned price update may be arbitrarily far in the past.
///
/// Users of this function should check the `publishTime` in the price to ensure that the returned price is
/// sufficiently recent for their application. If you are considering using this function, it may be
/// safer / easier to use either `getPrice` or `getPriceNoOlderThan`.
/// @return price - please read the documentation of PythStructs.Price to understand how to use this safely.
function getPriceUnsafe(
bytes32 id
) external view returns (PythStructs.Price memory price);
/// @notice Returns the price that is no older than `age` seconds of the current time.
/// @dev This function is a sanity-checked version of `getPriceUnsafe` which is useful in
/// applications that require a sufficiently-recent price. Reverts if the price wasn't updated sufficiently
/// recently.
/// @return price - please read the documentation of PythStructs.Price to understand how to use this safely.
function getPriceNoOlderThan(
bytes32 id,
uint age
) external view returns (PythStructs.Price memory price);
/// @notice Returns the exponentially-weighted moving average price of a price feed without any sanity checks.
/// @dev This function returns the same price as `getEmaPrice` in the case where the price is available.
/// However, if the price is not recent this function returns the latest available price.
///
/// The returned price can be from arbitrarily far in the past; this function makes no guarantees that
/// the returned price is recent or useful for any particular application.
///
/// Users of this function should check the `publishTime` in the price to ensure that the returned price is
/// sufficiently recent for their application. If you are considering using this function, it may be
/// safer / easier to use either `getEmaPrice` or `getEmaPriceNoOlderThan`.
/// @return price - please read the documentation of PythStructs.Price to understand how to use this safely.
function getEmaPriceUnsafe(
bytes32 id
) external view returns (PythStructs.Price memory price);
/// @notice Returns the exponentially-weighted moving average price that is no older than `age` seconds
/// of the current time.
/// @dev This function is a sanity-checked version of `getEmaPriceUnsafe` which is useful in
/// applications that require a sufficiently-recent price. Reverts if the price wasn't updated sufficiently
/// recently.
/// @return price - please read the documentation of PythStructs.Price to understand how to use this safely.
function getEmaPriceNoOlderThan(
bytes32 id,
uint age
) external view returns (PythStructs.Price memory price);
/// @notice Update price feeds with given update messages.
/// This method requires the caller to pay a fee in wei; the required fee can be computed by calling
/// `getUpdateFee` with the length of the `updateData` array.
/// Prices will be updated if they are more recent than the current stored prices.
/// The call will succeed even if the update is not the most recent.
/// @dev Reverts if the transferred fee is not sufficient or the updateData is invalid.
/// @param updateData Array of price update data.
function updatePriceFeeds(bytes[] calldata updateData) external payable;
/// @notice Wrapper around updatePriceFeeds that rejects fast if a price update is not necessary. A price update is
/// necessary if the current on-chain publishTime is older than the given publishTime. It relies solely on the
/// given `publishTimes` for the price feeds and does not read the actual price update publish time within `updateData`.
///
/// This method requires the caller to pay a fee in wei; the required fee can be computed by calling
/// `getUpdateFee` with the length of the `updateData` array.
///
/// `priceIds` and `publishTimes` are two arrays with the same size that correspond to senders known publishTime
/// of each priceId when calling this method. If all of price feeds within `priceIds` have updated and have
/// a newer or equal publish time than the given publish time, it will reject the transaction to save gas.
/// Otherwise, it calls updatePriceFeeds method to update the prices.
///
/// @dev Reverts if update is not needed or the transferred fee is not sufficient or the updateData is invalid.
/// @param updateData Array of price update data.
/// @param priceIds Array of price ids.
/// @param publishTimes Array of publishTimes. `publishTimes[i]` corresponds to known `publishTime` of `priceIds[i]`
function updatePriceFeedsIfNecessary(
bytes[] calldata updateData,
bytes32[] calldata priceIds,
uint64[] calldata publishTimes
) external payable;
/// @notice Returns the required fee to update an array of price updates.
/// @param updateData Array of price update data.
/// @return feeAmount The required fee in Wei.
function getUpdateFee(
bytes[] calldata updateData
) external view returns (uint feeAmount);
/// @notice Parse `updateData` and return price feeds of the given `priceIds` if they are all published
/// within `minPublishTime` and `maxPublishTime`.
///
/// You can use this method if you want to use a Pyth price at a fixed time and not the most recent price;
/// otherwise, please consider using `updatePriceFeeds`. This method does not store the price updates on-chain.
///
/// This method requires the caller to pay a fee in wei; the required fee can be computed by calling
/// `getUpdateFee` with the length of the `updateData` array.
///
///
/// @dev Reverts if the transferred fee is not sufficient or the updateData is invalid or there is
/// no update for any of the given `priceIds` within the given time range.
/// @param updateData Array of price update data.
/// @param priceIds Array of price ids.
/// @param minPublishTime minimum acceptable publishTime for the given `priceIds`.
/// @param maxPublishTime maximum acceptable publishTime for the given `priceIds`.
/// @return priceFeeds Array of the price feeds corresponding to the given `priceIds` (with the same order).
function parsePriceFeedUpdates(
bytes[] calldata updateData,
bytes32[] calldata priceIds,
uint64 minPublishTime,
uint64 maxPublishTime
) external payable returns (PythStructs.PriceFeed[] memory priceFeeds);
/// @notice Similar to `parsePriceFeedUpdates` but ensures the updates returned are
/// the first updates published in minPublishTime. That is, if there are multiple updates for a given timestamp,
/// this method will return the first update.
///
///
/// @dev Reverts if the transferred fee is not sufficient or the updateData is invalid or there is
/// no update for any of the given `priceIds` within the given time range and uniqueness condition.
/// @param updateData Array of price update data.
/// @param priceIds Array of price ids.
/// @param minPublishTime minimum acceptable publishTime for the given `priceIds`.
/// @param maxPublishTime maximum acceptable publishTime for the given `priceIds`.
/// @return priceFeeds Array of the price feeds corresponding to the given `priceIds` (with the same order).
function parsePriceFeedUpdatesUnique(
bytes[] calldata updateData,
bytes32[] calldata priceIds,
uint64 minPublishTime,
uint64 maxPublishTime
) external payable returns (PythStructs.PriceFeed[] memory priceFeeds);
}
@pythnetwork/pyth-sdk-solidity/IPythEvents.sol
// SPDX-License-Identifier: Apache-2.0
pragma solidity ^0.8.0;
/// @title IPythEvents contains the events that Pyth contract emits.
/// @dev This interface can be used for listening to the updates for off-chain and testing purposes.
interface IPythEvents {
/// @dev Emitted when the price feed with `id` has received a fresh update.
/// @param id The Pyth Price Feed ID.
/// @param publishTime Publish time of the given price update.
/// @param price Price of the given price update.
/// @param conf Confidence interval of the given price update.
event PriceFeedUpdate(
bytes32 indexed id,
uint64 publishTime,
int64 price,
uint64 conf
);
/// @dev Emitted when a batch price update is processed successfully.
/// @param chainId ID of the source chain that the batch price update comes from.
/// @param sequenceNumber Sequence number of the batch price update.
event BatchPriceFeedUpdate(uint16 chainId, uint64 sequenceNumber);
}
@pythnetwork/pyth-sdk-solidity/PythStructs.sol
// SPDX-License-Identifier: Apache-2.0
pragma solidity ^0.8.0;
contract PythStructs {
// A price with a degree of uncertainty, represented as a price +- a confidence interval.
//
// The confidence interval roughly corresponds to the standard error of a normal distribution.
// Both the price and confidence are stored in a fixed-point numeric representation,
// `x * (10^expo)`, where `expo` is the exponent.
//
// Please refer to the documentation at https://docs.pyth.network/documentation/pythnet-price-feeds/best-practices for how
// to how this price safely.
struct Price {
// Price
int64 price;
// Confidence interval around the price
uint64 conf;
// Price exponent
int32 expo;
// Unix timestamp describing when the price was published
uint publishTime;
}
// PriceFeed represents a current aggregate price from pyth publisher feeds.
struct PriceFeed {
// The price ID.
bytes32 id;
// Latest available price
Price price;
// Latest available exponentially-weighted moving average price
Price emaPrice;
}
}
@wormhole/Utils.sol
// SPDX-License-Identifier: Apache 2
pragma solidity ^0.8.13;
import "./interfaces/IWormholeRelayer.sol";
function toWormholeFormat(address addr) pure returns (bytes32) {
return bytes32(uint256(uint160(addr)));
}
function fromWormholeFormat(bytes32 whFormatAddress) pure returns (address) {
if (uint256(whFormatAddress) >> 160 != 0) {
revert NotAnEvmAddress(whFormatAddress);
}
return address(uint160(uint256(whFormatAddress)));
}
@wormhole/interfaces/IERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.6.0) (token/ERC20/IERC20.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `to`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address to, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `from` to `to` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address from, address to, uint256 amount) external returns (bool);
}
@wormhole/interfaces/IWETH.sol
// contracts/Bridge.sol
// SPDX-License-Identifier: Apache 2
pragma solidity ^0.8.0;
import "./IERC20.sol";
interface IWETH is IERC20 {
function deposit() external payable;
function withdraw(uint256 amount) external;
}
@wormhole/interfaces/IWormholeRelayer.sol
// SPDX-License-Identifier: Apache 2
pragma solidity ^0.8.0;
/**
* @title WormholeRelayer
* @author
* @notice This project allows developers to build cross-chain applications powered by Wormhole without needing to
* write and run their own relaying infrastructure
*
* We implement the IWormholeRelayer interface that allows users to request a delivery provider to relay a payload (and/or additional messages)
* to a chain and address of their choice.
*/
/**
* @notice VaaKey identifies a wormhole message
*
* @custom:member chainId Wormhole chain ID of the chain where this VAA was emitted from
* @custom:member emitterAddress Address of the emitter of the VAA, in Wormhole bytes32 format
* @custom:member sequence Sequence number of the VAA
*/
struct VaaKey {
uint16 chainId;
bytes32 emitterAddress;
uint64 sequence;
}
// 0-127 are reserved for standardized KeyTypes, 128-255 are for custom use
uint8 constant VAA_KEY_TYPE = 1;
struct MessageKey {
uint8 keyType; // 0-127 are reserved for standardized KeyTypes, 128-255 are for custom use
bytes encodedKey;
}
interface IWormholeRelayerBase {
event SendEvent(
uint64 indexed sequence,
uint256 deliveryQuote,
uint256 paymentForExtraReceiverValue
);
function getRegisteredWormholeRelayerContract(
uint16 chainId
) external view returns (bytes32);
/**
* @notice Returns true if a delivery has been attempted for the given deliveryHash
* Note: invalid deliveries where the tx reverts are not considered attempted
*/
function deliveryAttempted(
bytes32 deliveryHash
) external view returns (bool attempted);
/**
* @notice block number at which a delivery was successfully executed
*/
function deliverySuccessBlock(
bytes32 deliveryHash
) external view returns (uint256 blockNumber);
/**
* @notice block number of the latest attempt to execute a delivery that failed
*/
function deliveryFailureBlock(
bytes32 deliveryHash
) external view returns (uint256 blockNumber);
}
/**
* @title IWormholeRelayerSend
* @notice The interface to request deliveries
*/
interface IWormholeRelayerSend is IWormholeRelayerBase {
/**
* @notice Publishes an instruction for the default delivery provider
* to relay a payload to the address `targetAddress` on chain `targetChain`
* with gas limit `gasLimit` and `msg.value` equal to `receiverValue`
*
* `targetAddress` must implement the IWormholeReceiver interface
*
* This function must be called with `msg.value` equal to `quoteEVMDeliveryPrice(targetChain, receiverValue, gasLimit)`
*
* Any refunds (from leftover gas) will be paid to the delivery provider. In order to receive the refunds, use the `sendPayloadToEvm` function
* with `refundChain` and `refundAddress` as parameters
*
* @param targetChain in Wormhole Chain ID format
* @param targetAddress address to call on targetChain (that implements IWormholeReceiver)
* @param payload arbitrary bytes to pass in as parameter in call to `targetAddress`
* @param receiverValue msg.value that delivery provider should pass in for call to `targetAddress` (in targetChain currency units)
* @param gasLimit gas limit with which to call `targetAddress`.
* @return sequence sequence number of published VAA containing delivery instructions
*/
function sendPayloadToEvm(
uint16 targetChain,
address targetAddress,
bytes memory payload,
uint256 receiverValue,
uint256 gasLimit
) external payable returns (uint64 sequence);
/**
* @notice Publishes an instruction for the default delivery provider
* to relay a payload to the address `targetAddress` on chain `targetChain`
* with gas limit `gasLimit` and `msg.value` equal to `receiverValue`
*
* Any refunds (from leftover gas) will be sent to `refundAddress` on chain `refundChain`
* `targetAddress` must implement the IWormholeReceiver interface
*
* This function must be called with `msg.value` equal to `quoteEVMDeliveryPrice(targetChain, receiverValue, gasLimit)`
*
* @param targetChain in Wormhole Chain ID format
* @param targetAddress address to call on targetChain (that implements IWormholeReceiver)
* @param payload arbitrary bytes to pass in as parameter in call to `targetAddress`
* @param receiverValue msg.value that delivery provider should pass in for call to `targetAddress` (in targetChain currency units)
* @param gasLimit gas limit with which to call `targetAddress`. Any units of gas unused will be refunded according to the
* `targetChainRefundPerGasUnused` rate quoted by the delivery provider
* @param refundChain The chain to deliver any refund to, in Wormhole Chain ID format
* @param refundAddress The address on `refundChain` to deliver any refund to
* @return sequence sequence number of published VAA containing delivery instructions
*/
function sendPayloadToEvm(
uint16 targetChain,
address targetAddress,
bytes memory payload,
uint256 receiverValue,
uint256 gasLimit,
uint16 refundChain,
address refundAddress
) external payable returns (uint64 sequence);
/**
* @notice Publishes an instruction for the default delivery provider
* to relay a payload and VAAs specified by `vaaKeys` to the address `targetAddress` on chain `targetChain`
* with gas limit `gasLimit` and `msg.value` equal to `receiverValue`
*
* `targetAddress` must implement the IWormholeReceiver interface
*
* This function must be called with `msg.value` equal to `quoteEVMDeliveryPrice(targetChain, receiverValue, gasLimit)`
*
* Any refunds (from leftover gas) will be paid to the delivery provider. In order to receive the refunds, use the `sendVaasToEvm` function
* with `refundChain` and `refundAddress` as parameters
*
* @param targetChain in Wormhole Chain ID format
* @param targetAddress address to call on targetChain (that implements IWormholeReceiver)
* @param payload arbitrary bytes to pass in as parameter in call to `targetAddress`
* @param receiverValue msg.value that delivery provider should pass in for call to `targetAddress` (in targetChain currency units)
* @param gasLimit gas limit with which to call `targetAddress`.
* @param vaaKeys Additional VAAs to pass in as parameter in call to `targetAddress`
* @return sequence sequence number of published VAA containing delivery instructions
*/
function sendVaasToEvm(
uint16 targetChain,
address targetAddress,
bytes memory payload,
uint256 receiverValue,
uint256 gasLimit,
VaaKey[] memory vaaKeys
) external payable returns (uint64 sequence);
/**
* @notice Publishes an instruction for the default delivery provider
* to relay a payload and VAAs specified by `vaaKeys` to the address `targetAddress` on chain `targetChain`
* with gas limit `gasLimit` and `msg.value` equal to `receiverValue`
*
* Any refunds (from leftover gas) will be sent to `refundAddress` on chain `refundChain`
* `targetAddress` must implement the IWormholeReceiver interface
*
* This function must be called with `msg.value` equal to `quoteEVMDeliveryPrice(targetChain, receiverValue, gasLimit)`
*
* @param targetChain in Wormhole Chain ID format
* @param targetAddress address to call on targetChain (that implements IWormholeReceiver)
* @param payload arbitrary bytes to pass in as parameter in call to `targetAddress`
* @param receiverValue msg.value that delivery provider should pass in for call to `targetAddress` (in targetChain currency units)
* @param gasLimit gas limit with which to call `targetAddress`. Any units of gas unused will be refunded according to the
* `targetChainRefundPerGasUnused` rate quoted by the delivery provider
* @param vaaKeys Additional VAAs to pass in as parameter in call to `targetAddress`
* @param refundChain The chain to deliver any refund to, in Wormhole Chain ID format
* @param refundAddress The address on `refundChain` to deliver any refund to
* @return sequence sequence number of published VAA containing delivery instructions
*/
function sendVaasToEvm(
uint16 targetChain,
address targetAddress,
bytes memory payload,
uint256 receiverValue,
uint256 gasLimit,
VaaKey[] memory vaaKeys,
uint16 refundChain,
address refundAddress
) external payable returns (uint64 sequence);
/**
* @notice Publishes an instruction for the delivery provider at `deliveryProviderAddress`
* to relay a payload and VAAs specified by `vaaKeys` to the address `targetAddress` on chain `targetChain`
* with gas limit `gasLimit` and `msg.value` equal to
* receiverValue + (arbitrary amount that is paid for by paymentForExtraReceiverValue of this chain's wei) in targetChain wei.
*
* Any refunds (from leftover gas) will be sent to `refundAddress` on chain `refundChain`
* `targetAddress` must implement the IWormholeReceiver interface
*
* This function must be called with `msg.value` equal to
* quoteEVMDeliveryPrice(targetChain, receiverValue, gasLimit, deliveryProviderAddress) + paymentForExtraReceiverValue
*
* @param targetChain in Wormhole Chain ID format
* @param targetAddress address to call on targetChain (that implements IWormholeReceiver)
* @param payload arbitrary bytes to pass in as parameter in call to `targetAddress`
* @param receiverValue msg.value that delivery provider should pass in for call to `targetAddress` (in targetChain currency units)
* @param paymentForExtraReceiverValue amount (in current chain currency units) to spend on extra receiverValue
* (in addition to the `receiverValue` specified)
* @param gasLimit gas limit with which to call `targetAddress`. Any units of gas unused will be refunded according to the
* `targetChainRefundPerGasUnused` rate quoted by the delivery provider
* @param refundChain The chain to deliver any refund to, in Wormhole Chain ID format
* @param refundAddress The address on `refundChain` to deliver any refund to
* @param deliveryProviderAddress The address of the desired delivery provider's implementation of IDeliveryProvider
* @param vaaKeys Additional VAAs to pass in as parameter in call to `targetAddress`
* @param consistencyLevel Consistency level with which to publish the delivery instructions - see
* https://book.wormhole.com/wormhole/3_coreLayerContracts.html?highlight=consistency#consistency-levels
* @return sequence sequence number of published VAA containing delivery instructions
*/
function sendToEvm(
uint16 targetChain,
address targetAddress,
bytes memory payload,
uint256 receiverValue,
uint256 paymentForExtraReceiverValue,
uint256 gasLimit,
uint16 refundChain,
address refundAddress,
address deliveryProviderAddress,
VaaKey[] memory vaaKeys,
uint8 consistencyLevel
) external payable returns (uint64 sequence);
/**
* @notice Publishes an instruction for the delivery provider at `deliveryProviderAddress`
* to relay a payload and external messages specified by `messageKeys` to the address `targetAddress` on chain `targetChain`
* with gas limit `gasLimit` and `msg.value` equal to
* receiverValue + (arbitrary amount that is paid for by paymentForExtraReceiverValue of this chain's wei) in targetChain wei.
*
* Any refunds (from leftover gas) will be sent to `refundAddress` on chain `refundChain`
* `targetAddress` must implement the IWormholeReceiver interface
*
* This function must be called with `msg.value` equal to
* quoteEVMDeliveryPrice(targetChain, receiverValue, gasLimit, deliveryProviderAddress) + paymentForExtraReceiverValue
*
* Note: MessageKeys can specify wormhole messages (VaaKeys) or other types of messages (ex. USDC CCTP attestations). Ensure the selected
* DeliveryProvider supports all the MessageKey.keyType values specified or it will not be delivered!
*
* @param targetChain in Wormhole Chain ID format
* @param targetAddress address to call on targetChain (that implements IWormholeReceiver)
* @param payload arbitrary bytes to pass in as parameter in call to `targetAddress`
* @param receiverValue msg.value that delivery provider should pass in for call to `targetAddress` (in targetChain currency units)
* @param paymentForExtraReceiverValue amount (in current chain currency units) to spend on extra receiverValue
* (in addition to the `receiverValue` specified)
* @param gasLimit gas limit with which to call `targetAddress`. Any units of gas unused will be refunded according to the
* `targetChainRefundPerGasUnused` rate quoted by the delivery provider
* @param refundChain The chain to deliver any refund to, in Wormhole Chain ID format
* @param refundAddress The address on `refundChain` to deliver any refund to
* @param deliveryProviderAddress The address of the desired delivery provider's implementation of IDeliveryProvider
* @param messageKeys Additional messagess to pass in as parameter in call to `targetAddress`
* @param consistencyLevel Consistency level with which to publish the delivery instructions - see
* https://book.wormhole.com/wormhole/3_coreLayerContracts.html?highlight=consistency#consistency-levels
* @return sequence sequence number of published VAA containing delivery instructions
*/
function sendToEvm(
uint16 targetChain,
address targetAddress,
bytes memory payload,
uint256 receiverValue,
uint256 paymentForExtraReceiverValue,
uint256 gasLimit,
uint16 refundChain,
address refundAddress,
address deliveryProviderAddress,
MessageKey[] memory messageKeys,
uint8 consistencyLevel
) external payable returns (uint64 sequence);
/**
* @notice Publishes an instruction for the delivery provider at `deliveryProviderAddress`
* to relay a payload and VAAs specified by `vaaKeys` to the address `targetAddress` on chain `targetChain`
* with `msg.value` equal to
* receiverValue + (arbitrary amount that is paid for by paymentForExtraReceiverValue of this chain's wei) in targetChain wei.
*
* Any refunds (from leftover gas) will be sent to `refundAddress` on chain `refundChain`
* `targetAddress` must implement the IWormholeReceiver interface
*
* This function must be called with `msg.value` equal to
* quoteDeliveryPrice(targetChain, receiverValue, encodedExecutionParameters, deliveryProviderAddress) + paymentForExtraReceiverValue
*
* @param targetChain in Wormhole Chain ID format
* @param targetAddress address to call on targetChain (that implements IWormholeReceiver), in Wormhole bytes32 format
* @param payload arbitrary bytes to pass in as parameter in call to `targetAddress`
* @param receiverValue msg.value that delivery provider should pass in for call to `targetAddress` (in targetChain currency units)
* @param paymentForExtraReceiverValue amount (in current chain currency units) to spend on extra receiverValue
* (in addition to the `receiverValue` specified)
* @param encodedExecutionParameters encoded information on how to execute delivery that may impact pricing
* e.g. for version EVM_V1, this is a struct that encodes the `gasLimit` with which to call `targetAddress`
* @param refundChain The chain to deliver any refund to, in Wormhole Chain ID format
* @param refundAddress The address on `refundChain` to deliver any refund to, in Wormhole bytes32 format
* @param deliveryProviderAddress The address of the desired delivery provider's implementation of IDeliveryProvider
* @param vaaKeys Additional VAAs to pass in as parameter in call to `targetAddress`
* @param consistencyLevel Consistency level with which to publish the delivery instructions - see
* https://book.wormhole.com/wormhole/3_coreLayerContracts.html?highlight=consistency#consistency-levels
* @return sequence sequence number of published VAA containing delivery instructions
*/
function send(
uint16 targetChain,
bytes32 targetAddress,
bytes memory payload,
uint256 receiverValue,
uint256 paymentForExtraReceiverValue,
bytes memory encodedExecutionParameters,
uint16 refundChain,
bytes32 refundAddress,
address deliveryProviderAddress,
VaaKey[] memory vaaKeys,
uint8 consistencyLevel
) external payable returns (uint64 sequence);
/**
* @notice Publishes an instruction for the delivery provider at `deliveryProviderAddress`
* to relay a payload and VAAs specified by `vaaKeys` to the address `targetAddress` on chain `targetChain`
* with `msg.value` equal to
* receiverValue + (arbitrary amount that is paid for by paymentForExtraReceiverValue of this chain's wei) in targetChain wei.
*
* Any refunds (from leftover gas) will be sent to `refundAddress` on chain `refundChain`
* `targetAddress` must implement the IWormholeReceiver interface
*
* This function must be called with `msg.value` equal to
* quoteDeliveryPrice(targetChain, receiverValue, encodedExecutionParameters, deliveryProviderAddress) + paymentForExtraReceiverValue
*
* Note: MessageKeys can specify wormhole messages (VaaKeys) or other types of messages (ex. USDC CCTP attestations). Ensure the selected
* DeliveryProvider supports all the MessageKey.keyType values specified or it will not be delivered!
*
* @param targetChain in Wormhole Chain ID format
* @param targetAddress address to call on targetChain (that implements IWormholeReceiver), in Wormhole bytes32 format
* @param payload arbitrary bytes to pass in as parameter in call to `targetAddress`
* @param receiverValue msg.value that delivery provider should pass in for call to `targetAddress` (in targetChain currency units)
* @param paymentForExtraReceiverValue amount (in current chain currency units) to spend on extra receiverValue
* (in addition to the `receiverValue` specified)
* @param encodedExecutionParameters encoded information on how to execute delivery that may impact pricing
* e.g. for version EVM_V1, this is a struct that encodes the `gasLimit` with which to call `targetAddress`
* @param refundChain The chain to deliver any refund to, in Wormhole Chain ID format
* @param refundAddress The address on `refundChain` to deliver any refund to, in Wormhole bytes32 format
* @param deliveryProviderAddress The address of the desired delivery provider's implementation of IDeliveryProvider
* @param messageKeys Additional messagess to pass in as parameter in call to `targetAddress`
* @param consistencyLevel Consistency level with which to publish the delivery instructions - see
* https://book.wormhole.com/wormhole/3_coreLayerContracts.html?highlight=consistency#consistency-levels
* @return sequence sequence number of published VAA containing delivery instructions
*/
function send(
uint16 targetChain,
bytes32 targetAddress,
bytes memory payload,
uint256 receiverValue,
uint256 paymentForExtraReceiverValue,
bytes memory encodedExecutionParameters,
uint16 refundChain,
bytes32 refundAddress,
address deliveryProviderAddress,
MessageKey[] memory messageKeys,
uint8 consistencyLevel
) external payable returns (uint64 sequence);
/**
* @notice Requests a previously published delivery instruction to be redelivered
* (e.g. with a different delivery provider)
*
* This function must be called with `msg.value` equal to
* quoteEVMDeliveryPrice(targetChain, newReceiverValue, newGasLimit, newDeliveryProviderAddress)
*
* @notice *** This will only be able to succeed if the following is true **
* - newGasLimit >= gas limit of the old instruction
* - newReceiverValue >= receiver value of the old instruction
* - newDeliveryProvider's `targetChainRefundPerGasUnused` >= old relay provider's `targetChainRefundPerGasUnused`
*
* @param deliveryVaaKey VaaKey identifying the wormhole message containing the
* previously published delivery instructions
* @param targetChain The target chain that the original delivery targeted. Must match targetChain from original delivery instructions
* @param newReceiverValue new msg.value that delivery provider should pass in for call to `targetAddress` (in targetChain currency units)
* @param newGasLimit gas limit with which to call `targetAddress`. Any units of gas unused will be refunded according to the
* `targetChainRefundPerGasUnused` rate quoted by the delivery provider, to the refund chain and address specified in the original request
* @param newDeliveryProviderAddress The address of the desired delivery provider's implementation of IDeliveryProvider
* @return sequence sequence number of published VAA containing redelivery instructions
*
* @notice *** This will only be able to succeed if the following is true **
* - newGasLimit >= gas limit of the old instruction
* - newReceiverValue >= receiver value of the old instruction
*/
function resendToEvm(
VaaKey memory deliveryVaaKey,
uint16 targetChain,
uint256 newReceiverValue,
uint256 newGasLimit,
address newDeliveryProviderAddress
) external payable returns (uint64 sequence);
/**
* @notice Requests a previously published delivery instruction to be redelivered
*
*
* This function must be called with `msg.value` equal to
* quoteDeliveryPrice(targetChain, newReceiverValue, newEncodedExecutionParameters, newDeliveryProviderAddress)
*
* @param deliveryVaaKey VaaKey identifying the wormhole message containing the
* previously published delivery instructions
* @param targetChain The target chain that the original delivery targeted. Must match targetChain from original delivery instructions
* @param newReceiverValue new msg.value that delivery provider should pass in for call to `targetAddress` (in targetChain currency units)
* @param newEncodedExecutionParameters new encoded information on how to execute delivery that may impact pricing
* e.g. for version EVM_V1, this is a struct that encodes the `gasLimit` with which to call `targetAddress`
* @param newDeliveryProviderAddress The address of the desired delivery provider's implementation of IDeliveryProvider
* @return sequence sequence number of published VAA containing redelivery instructions
*
* @notice *** This will only be able to succeed if the following is true **
* - (For EVM_V1) newGasLimit >= gas limit of the old instruction
* - newReceiverValue >= receiver value of the old instruction
* - (For EVM_V1) newDeliveryProvider's `targetChainRefundPerGasUnused` >= old relay provider's `targetChainRefundPerGasUnused`
*/
function resend(
VaaKey memory deliveryVaaKey,
uint16 targetChain,
uint256 newReceiverValue,
bytes memory newEncodedExecutionParameters,
address newDeliveryProviderAddress
) external payable returns (uint64 sequence);
/**
* @notice Returns the price to request a relay to chain `targetChain`, using the default delivery provider
*
* @param targetChain in Wormhole Chain ID format
* @param receiverValue msg.value that delivery provider should pass in for call to `targetAddress` (in targetChain currency units)
* @param gasLimit gas limit with which to call `targetAddress`.
* @return nativePriceQuote Price, in units of current chain currency, that the delivery provider charges to perform the relay
* @return targetChainRefundPerGasUnused amount of target chain currency that will be refunded per unit of gas unused,
* if a refundAddress is specified.
* Note: This value can be overridden by the delivery provider on the target chain. The returned value here should be considered to be a
* promise by the delivery provider of the amount of refund per gas unused that will be returned to the refundAddress at the target chain.
* If a delivery provider decides to override, this will be visible as part of the emitted Delivery event on the target chain.
*/
function quoteEVMDeliveryPrice(
uint16 targetChain,
uint256 receiverValue,
uint256 gasLimit
)
external
view
returns (
uint256 nativePriceQuote,
uint256 targetChainRefundPerGasUnused
);
/**
* @notice Returns the price to request a relay to chain `targetChain`, using delivery provider `deliveryProviderAddress`
*
* @param targetChain in Wormhole Chain ID format
* @param receiverValue msg.value that delivery provider should pass in for call to `targetAddress` (in targetChain currency units)
* @param gasLimit gas limit with which to call `targetAddress`.
* @param deliveryProviderAddress The address of the desired delivery provider's implementation of IDeliveryProvider
* @return nativePriceQuote Price, in units of current chain currency, that the delivery provider charges to perform the relay
* @return targetChainRefundPerGasUnused amount of target chain currency that will be refunded per unit of gas unused,
* if a refundAddress is specified
* Note: This value can be overridden by the delivery provider on the target chain. The returned value here should be considered to be a
* promise by the delivery provider of the amount of refund per gas unused that will be returned to the refundAddress at the target chain.
* If a delivery provider decides to override, this will be visible as part of the emitted Delivery event on the target chain.
*/
function quoteEVMDeliveryPrice(
uint16 targetChain,
uint256 receiverValue,
uint256 gasLimit,
address deliveryProviderAddress
)
external
view
returns (
uint256 nativePriceQuote,
uint256 targetChainRefundPerGasUnused
);
/**
* @notice Returns the price to request a relay to chain `targetChain`, using delivery provider `deliveryProviderAddress`
*
* @param targetChain in Wormhole Chain ID format
* @param receiverValue msg.value that delivery provider should pass in for call to `targetAddress` (in targetChain currency units)
* @param encodedExecutionParameters encoded information on how to execute delivery that may impact pricing
* e.g. for version EVM_V1, this is a struct that encodes the `gasLimit` with which to call `targetAddress`
* @param deliveryProviderAddress The address of the desired delivery provider's implementation of IDeliveryProvider
* @return nativePriceQuote Price, in units of current chain currency, that the delivery provider charges to perform the relay
* @return encodedExecutionInfo encoded information on how the delivery will be executed
* e.g. for version EVM_V1, this is a struct that encodes the `gasLimit` and `targetChainRefundPerGasUnused`
* (which is the amount of target chain currency that will be refunded per unit of gas unused,
* if a refundAddress is specified)
*/
function quoteDeliveryPrice(
uint16 targetChain,
uint256 receiverValue,
bytes memory encodedExecutionParameters,
address deliveryProviderAddress
)
external
view
returns (uint256 nativePriceQuote, bytes memory encodedExecutionInfo);
/**
* @notice Returns the (extra) amount of target chain currency that `targetAddress`
* will be called with, if the `paymentForExtraReceiverValue` field is set to `currentChainAmount`
*
* @param targetChain in Wormhole Chain ID format
* @param currentChainAmount The value that `paymentForExtraReceiverValue` will be set to
* @param deliveryProviderAddress The address of the desired delivery provider's implementation of IDeliveryProvider
* @return targetChainAmount The amount such that if `targetAddress` will be called with `msg.value` equal to
* receiverValue + targetChainAmount
*/
function quoteNativeForChain(
uint16 targetChain,
uint256 currentChainAmount,
address deliveryProviderAddress
) external view returns (uint256 targetChainAmount);
/**
* @notice Returns the address of the current default delivery provider
* @return deliveryProvider The address of (the default delivery provider)'s contract on this source
* chain. This must be a contract that implements IDeliveryProvider.
*/
function getDefaultDeliveryProvider()
external
view
returns (address deliveryProvider);
}
/**
* @title IWormholeRelayerDelivery
* @notice The interface to execute deliveries. Only relevant for Delivery Providers
*/
interface IWormholeRelayerDelivery is IWormholeRelayerBase {
enum DeliveryStatus {
SUCCESS,
RECEIVER_FAILURE
}
enum RefundStatus {
REFUND_SENT,
REFUND_FAIL,
CROSS_CHAIN_REFUND_SENT,
CROSS_CHAIN_REFUND_FAIL_PROVIDER_NOT_SUPPORTED,
CROSS_CHAIN_REFUND_FAIL_NOT_ENOUGH,
NO_REFUND_REQUESTED
}
/**
* @custom:member recipientContract - The target contract address
* @custom:member sourceChain - The chain which this delivery was requested from (in wormhole
* ChainID format)
* @custom:member sequence - The wormhole sequence number of the delivery VAA on the source chain
* corresponding to this delivery request
* @custom:member deliveryVaaHash - The hash of the delivery VAA corresponding to this delivery
* request
* @custom:member gasUsed - The amount of gas that was used to call your target contract
* @custom:member status:
* - RECEIVER_FAILURE, if the target contract reverts
* - SUCCESS, if the target contract doesn't revert
* @custom:member additionalStatusInfo:
* - If status is SUCCESS, then this is empty.
* - If status is RECEIVER_FAILURE, this is `RETURNDATA_TRUNCATION_THRESHOLD` bytes of the
* return data (i.e. potentially truncated revert reason information).
* @custom:member refundStatus - Result of the refund. REFUND_SUCCESS or REFUND_FAIL are for
* refunds where targetChain=refundChain; the others are for targetChain!=refundChain,
* where a cross chain refund is necessary, or if the default code path is used where no refund is requested (NO_REFUND_REQUESTED)
* @custom:member overridesInfo:
* - If not an override: empty bytes array
* - Otherwise: An encoded `DeliveryOverride`
*/
event Delivery(
address indexed recipientContract,
uint16 indexed sourceChain,
uint64 indexed sequence,
bytes32 deliveryVaaHash,
DeliveryStatus status,
uint256 gasUsed,
RefundStatus refundStatus,
bytes additionalStatusInfo,
bytes overridesInfo
);
/**
* @notice The delivery provider calls `deliver` to relay messages as described by one delivery instruction
*
* The delivery provider must pass in the specified (by VaaKeys[]) signed wormhole messages (VAAs) from the source chain
* as well as the signed wormhole message with the delivery instructions (the delivery VAA)
*
* The messages will be relayed to the target address (with the specified gas limit and receiver value) iff the following checks are met:
* - the delivery VAA has a valid signature
* - the delivery VAA's emitter is one of these WormholeRelayer contracts
* - the delivery provider passed in at least enough of this chain's currency as msg.value (enough meaning the maximum possible refund)
* - the instruction's target chain is this chain
* - the relayed signed VAAs match the descriptions in container.messages (the VAA hashes match, or the emitter address, sequence number pair matches, depending on the description given)
*
* @param encodedVMs - An array of signed wormhole messages (all from the same source chain
* transaction)
* @param encodedDeliveryVAA - Signed wormhole message from the source chain's WormholeRelayer
* contract with payload being the encoded delivery instruction container
* @param relayerRefundAddress - The address to which any refunds to the delivery provider
* should be sent
* @param deliveryOverrides - Optional overrides field which must be either an empty bytes array or
* an encoded DeliveryOverride struct
*/
function deliver(
bytes[] memory encodedVMs,
bytes memory encodedDeliveryVAA,
address payable relayerRefundAddress,
bytes memory deliveryOverrides
) external payable;
}
interface IWormholeRelayer is IWormholeRelayerDelivery, IWormholeRelayerSend {}
/*
* Errors thrown by IWormholeRelayer contract
*/
// Bound chosen by the following formula: `memoryWord * 4 + selectorSize`.
// This means that an error identifier plus four fixed size arguments should be available to developers.
// In the case of a `require` revert with error message, this should provide 2 memory word's worth of data.
uint256 constant RETURNDATA_TRUNCATION_THRESHOLD = 132;
//When msg.value was not equal to `delivery provider's quoted delivery price` + `paymentForExtraReceiverValue`
error InvalidMsgValue(uint256 msgValue, uint256 totalFee);
error RequestedGasLimitTooLow();
error DeliveryProviderDoesNotSupportTargetChain(
address relayer,
uint16 chainId
);
error DeliveryProviderCannotReceivePayment();
error DeliveryProviderDoesNotSupportMessageKeyType(uint8 keyType);
//When calling `delivery()` a second time even though a delivery is already in progress
error ReentrantDelivery(address msgSender, address lockedBy);
error InvalidPayloadId(uint8 parsed, uint8 expected);
error InvalidPayloadLength(uint256 received, uint256 expected);
error InvalidVaaKeyType(uint8 parsed);
error TooManyMessageKeys(uint256 numMessageKeys);
error InvalidDeliveryVaa(string reason);
//When the delivery VAA (signed wormhole message with delivery instructions) was not emitted by the
// registered WormholeRelayer contract
error InvalidEmitter(bytes32 emitter, bytes32 registered, uint16 chainId);
error MessageKeysLengthDoesNotMatchMessagesLength(uint256 keys, uint256 vaas);
error VaaKeysDoNotMatchVaas(uint8 index);
//When someone tries to call an external function of the WormholeRelayer that is only intended to be
// called by the WormholeRelayer itself (to allow retroactive reverts for atomicity)
error RequesterNotWormholeRelayer();
//When trying to relay a `DeliveryInstruction` to any other chain but the one it was specified for
error TargetChainIsNotThisChain(uint16 targetChain);
//When a `DeliveryOverride` contains a gas limit that's less than the original
error InvalidOverrideGasLimit();
//When a `DeliveryOverride` contains a receiver value that's less than the original
error InvalidOverrideReceiverValue();
//When a `DeliveryOverride` contains a 'refund per unit of gas unused' that's less than the original
error InvalidOverrideRefundPerGasUnused();
//When the delivery provider doesn't pass in sufficient funds (i.e. msg.value does not cover the
// maximum possible refund to the user)
error InsufficientRelayerFunds(uint256 msgValue, uint256 minimum);
//When a bytes32 field can't be converted into a 20 byte EVM address, because the 12 padding bytes
// are non-zero (duplicated from Utils.sol)
error NotAnEvmAddress(bytes32);
src/contracts/HubSpokeEvents.sol
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.0;
import "../interfaces/ILiquidationCalculator.sol";
/**
* @title HubSpokeEvents
* @notice Events emitted by the Hub and Spoke contracts
*/
contract HubSpokeEvents {
event Liquidation(address indexed liquidator, address indexed vault, ILiquidationCalculator.DenormalizedLiquidationAsset[] liquidationAssets);
event AccrualIndexUpdated(bytes32 indexed asset, uint256 deposit, uint256 borrow, uint256 timestamp);
event Deposit(address indexed vault, bytes32 indexed asset, uint256 amount, uint256 vaultTotalDeposited);
event Withdraw(address indexed vault, bytes32 indexed asset, uint256 amount, uint256 vaultTotalDeposited);
event Borrow(address indexed vault, bytes32 indexed asset, uint256 amount, uint256 vaultTotalBorrowed);
event Repay(address indexed vault, bytes32 indexed asset, uint256 amount, uint256 vaultTotalBorrowed);
event ReservesWithdrawn(bytes32 indexed asset, uint256 amount, uint16 destinationChain, bytes32 destinationAddress);
event SpokeRegistered(uint16 chainId, bytes32 spoke);
event GlobalStateMigrated();
event UserMigrated(address indexed user);
event SetLiquidationFee(uint256 value, uint256 precision);
event SpokeCreditCreated(address indexed user, address indexed asset, uint256 amount, uint256 nonce);
event SpokeCreditLost(address indexed user, address indexed asset, uint256 amount, uint256 nonce);
event SpokeCreditRefundable(address indexed user, address indexed asset, uint256 amount, uint256 nonce);
event SpokeCreditConfirmed(uint256 nonce);
event SpokeCreditFinalized(uint256 nonce);
event SpokeCreditRefunded(address indexed user, address indexed asset, uint256 amount, uint256 nonce);
event SpokeLimitsChanged(address indexed asset, uint256 creditLimit, uint256 custodyLimit, uint256 transactionLimit);
event SpokeFeesChanged(uint256 inboundTokenFee, uint256 outboundTokenFee);
event SpokeFundsReleased(address indexed user, address indexed asset, uint256 amount, uint256 nonce);
event SpokeTopUpReceived(address indexed asset, uint256 amount);
event SpokeRefundSent(address user, address token, uint256 amount);
event HubCreditCreated(uint16 indexed chainId, bytes32 indexed user, bytes32 indexed asset, uint256 amount, uint256 nonce);
event HubCreditLost(uint16 indexed chainId, bytes32 indexed user, bytes32 indexed asset, uint256 amount, uint256 nonce);
event HubCreditRefundable(uint16 indexed chainId, bytes32 indexed user, bytes32 indexed asset, uint256 amount, uint256 nonce);
event HubCreditFinalized(uint16 indexed chainId, uint256 nonce);
event PossibleHubMisconfiguration(address assetSentAsWeth, address realWeth);
event AccountPaired(uint16 indexed chainId, bytes32 indexed account, bytes32 indexed userId);
event AccountPairingRequestReceived(uint16 indexed chainId, bytes32 indexed account, bytes32 indexed userId);
}
src/contracts/HubSpokeStructs.sol
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.0;
import {ILiquidationCalculator} from "../interfaces/ILiquidationCalculator.sol";
import {IHubPriceUtilities} from "../interfaces/IHubPriceUtilities.sol";
import {IAssetRegistry} from "../interfaces/IAssetRegistry.sol";
import {ILegacyAssetRegistry} from "../interfaces/ILegacyAssetRegistry.sol";
import {IWormholeTunnel} from "../interfaces/IWormholeTunnel.sol";
import {IMoneyMarketRewardsDistributor} from "../interfaces/rewards/IMoneyMarketRewardsDistributor.sol";
/**
* @title HubSpokeStructs
* @notice A set of structs and enums used in the Hub and Spoke contracts
*/
library HubSpokeStructs {
/**
* @param wormhole: Address of the Wormhole contract
* @param tokenBridge: Address of the TokenBridge contract
* @param wormholeRelayer: Address of the WormholeRelayer contract
* @param consistencyLevel: Desired level of finality the Wormhole guardians will reach before signing the messages
* NOTE: consistencyLevel = 200 will result in an instant message, while all other values will wait for finality
* Recommended finality levels can be found here: https://book.wormhole.com/reference/contracts.html
* @param pythAddress: Address of the Pyth oracle on the Hub chain
* @param priceStandardDeviations: priceStandardDeviations = (psd * priceStandardDeviationsPrecision), where psd is
* the number of standard deviations that we use for our price intervals in calculations relating to allowing
* withdraws, borrows, or liquidations
* @param priceStandardDeviationsPrecision: A precision number that allows us to represent our desired noninteger
* price standard deviation as an integer (psd = priceStandardDeviations/priceStandardDeviationsPrecision)
* @param maxLiquidationPortionPrecision: A precision number that allows us to represent our desired noninteger
* max liquidation portion mlp as an integer (mlp = maxLiquidationPortion/maxLiquidationPortionPrecision)
* @param interestAccrualIndexPrecision: A precision number that allows us to represent our noninteger interest
* accrual indices as integers; we store each index as its true value multiplied by interestAccrualIndexPrecision
* @param collateralizationRatioPrecision: A precision number that allows us to represent our noninteger
* collateralization ratios as integers; we store each ratio as its true value multiplied by
* collateralizationRatioPrecision
* @param liquidationFee: The fee taken by the protocol on liquidation
* @param _circleMessageTransmitter: Cicle Message Transmitter contract (cctp)
* @param _circleTokenMessenger: Cicle Token Messenger contract (cctp)
* @param _USDC: USDC token contract (cctp)
*/
struct ConstructorArgs {
/* Liquidation Information */
uint256 interestAccrualIndexPrecision;
uint256 liquidationFee;
uint256 liquidationFeePrecision;
/* WormholeTunnel */
IWormholeTunnel wormholeTunnel;
}
struct StoredVaultAmount {
DenormalizedVaultAmount amounts;
AccrualIndices accrualIndices;
}
struct DenormalizedVaultAmount {
uint256 deposited;
uint256 borrowed;
}
struct NotionalVaultAmount {
uint256 deposited;
uint256 borrowed;
}
struct AccrualIndices {
uint256 deposited;
uint256 borrowed;
}
struct UserActionPayload {
bytes32 user;
Action action;
bytes32 token;
uint256 amount;
uint256 nonce;
}
struct ConfirmCreditPayload {
Credit credit;
}
struct ReleaseFundsPayload {
bytes32 user;
bytes32 token;
uint256 amount;
uint256 nonce;
bool unwrapWeth;
}
struct ConfirmTopUpPayload {
bytes32 token;
uint256 amount;
}
struct ConfirmFixLostCreditPayload {
bytes32 token;
uint256 amount;
}
struct FinalizeCreditPayload {
Credit credit;
}
struct RequestPairingPayload {
bytes32 newAccount;
bytes32 userId;
}
enum Action { // mapping to use in Laika so that I don't have to count each time
Deposit, // 0
Borrow, // 1
Withdraw, // 2
Repay, // 3
DepositNative, // 4
RepayNative, // 5
WithdrawNative,// 6
BorrowNative // 7
}
enum ActionDirection {
Inbound, // receiving tokens from user: Deposit (+native), Repay (+native)
Outbound // sending tokens to user: Withdraw (+native), Borrow (+native)
}
enum CreditStatus {
PENDING, // before confirmation arrives
CONFIRMED, // after Hub confirms it
REFUNDABLE, // if it gets finalized, but hasn't been confirmed earlier
FINALIZED, // after it gets finalized. terminal status.
REFUNDED, // after a refund is processed. terminal status.
LOST // after a credit conflict is found. this means that the deposit/repay was accounted for, but the Credit got reorg'd and there now is a deficit. terminal status.
}
struct Credit {
bytes32 user;
bytes32 token;
uint256 creditedAmount;
uint256 _deprecated_forwardedAmount;
uint256 nonce;
uint256 createdAt;
uint256 updatedAt;
CreditStatus status;
}
struct SpokeBalances {
uint256 creditGiven; // amount of tokens sent by the user to the Spoke, but not yet finalized
uint256 creditLost; // amount of credit that got reorg'd and then stolen
uint256 unlocksPending; // amount of non-finalized Spoke-side deposits
uint256 creditLimit; // the limit of tokens that can be sent in flight
uint256 custodyLimit; // the limit of tokens that can be held in custody
uint256 transactionLimit; // the limit of tokens that can be transferred in a single TX
uint256 deposits; // the amount of finalized tokens that are user deposits (as opposed to credit or protocol reserves. deposits = balance - reserve - credit)
uint256 lastUpdated; // the last block timestamp the balances were updated
}
struct SpokeFundRelease {
uint256 nonce; // the user nonce of the release
bytes32 user; // the user receiving the released tokens
bytes32 token; // the token being released
uint256 amount; // the amount being released
uint256 releasedAt;// the timestamp of the release
}
struct HubSpokeBalances {
uint256 finalized;
uint256 unfinalized;
}
struct SpokeState {
bytes32 spoke; // the address of the Spoke
bytes32 wrappedNativeAsset; // the address of the wrapped native asset on the Spoke chain
// assetId => SpokeBalances
mapping(bytes32 => HubSpokeBalances) balances;
// user as bytes32 => nonce => Credit struct
mapping(bytes32 => mapping(uint256 => Credit)) credits;
// user as bytes32 => nonce
mapping(bytes32 => uint256) maxNonces;
uint256[50] __gap; // gap for additional params
}
struct HubState {
// number of confirmations for wormhole messages
uint8 _deprecated_consistencyLevel;
// vault for lending. user => token => amounts
mapping(address => mapping(address => HubSpokeStructs.StoredVaultAmount)) _deprecated_vault;
// total asset amounts (tokenAddress => (uint256, uint256))
mapping(address => HubSpokeStructs.StoredVaultAmount) _deprecated_totalAssets;
// interest accrual indices
mapping(address => HubSpokeStructs.AccrualIndices) _deprecated_indices;
// last timestamp for update
mapping(address => uint256) _deprecated_lastActivityBlockTimestamps;
// interest accrual rate precision level
uint256 _deprecated_interestAccrualIndexPrecision;
// calculator for liquidation amounts
ILiquidationCalculator _deprecated_liquidationCalculator;
// price utilities for getting prices
IHubPriceUtilities _deprecated_priceUtilities;
// asset registry for getting asset info
ILegacyAssetRegistry _deprecated_assetRegistry;
// protocol fee taken on liquidation
uint256 _deprecated_liquidationFee;
// for wormhole relay quotes
uint256 _deprecated_defaultGasLimit;
// for refunding of returnCost amount
uint256 _deprecated_refundGasLimit;
// toggle for using CCTP for asset => USDC
bool _deprecated_isUsingCCTP;
// the precision of the liquidation fee
uint256 _deprecated_liquidationFeePrecision;
// chainId => SpokeParams
mapping(uint16 => SpokeState) _deprecated_spokeStates;
IWormholeTunnel _deprecated_wormholeTunnel;
// this mirrors the spokeBalances but as wrapped addresses
// this is done so that reserves can be computed without knowing the Spoke address of the token
// this will be deprecated once we move to full Spoke custody of funds
mapping(address => HubSpokeBalances) _deprecated_wrappedTokenSpokeBalances;
IMoneyMarketRewardsDistributor _deprecated_rewardDistributor;
}
struct AssetState {
StoredVaultAmount totals;
AccrualIndices indices;
uint256 lastActivityBlockTimestamp;
mapping(address => HubSpokeStructs.StoredVaultAmount) userVaults;
}
struct UserIdState {
// address remapping for non-EVM chains and multisig support
// the core idea is that the accounts are indexed by Hub chain account address (userId)
// additional addresses can be paired with the userId (one per spoke chain)
// hub account address as b32 (userId) => chainId => spoke address
mapping(bytes32 => mapping(uint16 => bytes32)) spokeChainAddresses;
// chainId => spoke address => hub account address as b32 (userId)
// the addressing is incompatible with spokeChainAddresses to prevent errors
mapping(uint16 => mapping(bytes32 => bytes32)) userIds;
// chainId => requesting address => userId
mapping(uint16 => mapping(bytes32 => bytes32)) pairingRequests;
}
struct FeesLimitsAndPrecisionsState {
// interest accrual rate precision level
uint256 interestAccrualIndexPrecision;
// protocol fee taken on liquidation
uint256 liquidationFee;
// for wormhole relay quotes
uint256 defaultGasLimit;
// for refunding of returnCost amount
uint256 refundGasLimit;
// the precision of the liquidation fee
uint256 liquidationFeePrecision;
}
struct AuxilaryContracts {
// calculator for liquidation amounts
ILiquidationCalculator liquidationCalculator;
// price utilities for getting prices
IHubPriceUtilities priceUtilities;
// asset registry for getting asset info
IAssetRegistry assetRegistry;
// the tunnel through which Hub and Spokes communicate
IWormholeTunnel wormholeTunnel;
// the reward distribution contract
IMoneyMarketRewardsDistributor rewardDistributor;
}
struct SpokeCommunicationState {
IWormholeTunnel wormholeTunnel;
uint16 hubChainId;
bytes32 hubContractAddress;
uint256 defaultGasLimitRoundtrip;
uint256[50] __gap;
}
struct SpokeOptimisticFinalityState {
uint256 inboundTokenInstantMessageFee; // the percentage fee for instant messages accepting tokens. INSTANT_MESSAGE_FEE_PRECISION = 100%
uint256 outboundTokenInstantMessageFee; // the percentage fee for instant messages sending tokens. INSTANT_MESSAGE_FEE_PRECISION = 100%
mapping(bytes32 => HubSpokeStructs.SpokeBalances) tokenBalances; // bytes32 (wormhole format) address of the token => SpokeBalances
mapping(address => mapping(uint256 => HubSpokeStructs.Credit)) storedCredits; // user => nonce => Credit
mapping(address => mapping(uint256 => HubSpokeStructs.SpokeFundRelease)) fundReleases; // user => nonce => SpokeFundRelease
mapping(address => uint256) lastInstantActionNonces; // user => nonce
uint256 avgTransactionsPerTopUp;
uint256[50] __gap;
}
}
src/interfaces/IAssetRegistry.sol
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {IWETH} from "@wormhole/interfaces/IWETH.sol";
import "../contracts/HubSpokeStructs.sol";
interface IAssetRegistry {
struct AssetInfo {
uint256 collateralizationRatioDeposit;
uint256 collateralizationRatioBorrow;
uint8 decimals;
address interestRateCalculator;
bool exists;
uint256 borrowLimit;
uint256 supplyLimit;
uint256 maxLiquidationBonus; // 1e6 precision; 130e4 = 130% = 1.3; the liquidator gets 30% over what he repays
uint256[50] __gap;
}
function registerAsset(
string memory assetName,
uint8 decimals,
uint256 collateralizationRatioDeposit,
uint256 collateralizationRatioBorrow,
address interestRateCalculator,
uint256 maxLiquidationBonus,
uint256 supplyLimit,
uint256 borrowLimit
) external;
function PROTOCOL_MAX_DECIMALS() external pure returns (uint8);
function COLLATERALIZATION_RATIO_PRECISION() external pure returns (uint256);
function LIQUIDATION_BONUS_PRECISION() external pure returns (uint256);
function deregisterAsset(string memory _name) external;
function getAssetId(string memory _name) external pure returns (bytes32);
function getAssetId(uint16 _chainId, bytes32 _address) external view returns (bytes32);
function getAssetName(bytes32 _assetId) external view returns (string memory);
function getAssetName(uint16 _chainId, bytes32 _address) external view returns (string memory);
function assetExists(string memory _name) external view returns (bool);
function assetExists(bytes32 _id) external view returns (bool);
function getAssetInfo(string memory _name) external view returns (AssetInfo memory);
function getAssetInfo(bytes32 _id) external view returns (AssetInfo memory);
function getAssetAddress(string memory _name, uint16 _chainId) external view returns (bytes32);
function getAssetAddress(bytes32 _id, uint16 _chainId) external view returns (bytes32);
function requireAssetAddress(bytes32 _id, uint16 _chainId) external view returns (bytes32);
function getRegisteredAssets() external view returns (bytes32[] memory);
function getSupportedChains() external view returns (uint16[] memory);
function WETH() external view returns (IWETH);
function setCollateralizationRatios(string memory _name, uint256 _deposit, uint256 _borrow) external;
function setCollateralizationRatios(bytes32 _id, uint256 _deposit, uint256 _borrow) external;
function setLimits(string memory _name, uint256 _deposit, uint256 _borrow) external;
function setLimits(bytes32 _id, uint256 _deposit, uint256 _borrow) external;
function setMaxLiquidationBonus(string memory _name, uint256 _bonus) external;
function setMaxLiquidationBonus(bytes32 _id, uint256 _bonus) external;
function setInterestRateCalculator(string memory _name, address _calculator) external;
function setInterestRateCalculator(bytes32 _id, address _calculator) external;
// binds a Spoke chain asset address to the asset identifier
function bindAsset(string memory _name, uint16 _chainId, bytes32 _address) external;
function bindAsset(bytes32 _id, uint16 _chainId, bytes32 _address) external;
function bindAssets(string memory _name, uint16[] calldata _chains, bytes32[] calldata _addresses) external;
function bindAssets(bytes32 _id, uint16[] calldata _chains, bytes32[] calldata _addresses) external;
// removes Spoke chain asset binding from the asset identifier
function unbindAsset(string memory _name, uint16 _chainId) external;
function unbindAsset(bytes32 _id, uint16 _chainId) external;
function unbindAsset(uint16 _chainId, bytes32 _address) external;
}
src/interfaces/IHub.sol
// SPDX-License-Identifier: Apache 2
pragma solidity ^0.8.0;
import "../contracts/HubSpokeStructs.sol";
import "./ILiquidationCalculator.sol";
import "./IHubPriceUtilities.sol";
import "./IAssetRegistry.sol";
import {IWormholeTunnel} from "./IWormholeTunnel.sol";
/**
* @notice interface for external contracts that need to access Hub state
*/
interface IHub {
function checkVaultHasAssets(address vault, bytes32 assetId, uint256 normalizedAmount)
external
view;
function checkProtocolGloballyHasAssets(
bytes32 assetId,
uint256 normalizedAmount
) external view;
function checkProtocolGloballyHasAssets(
bytes32 assetId,
uint256 normalizedAmount,
uint256 borrowLimit
) external view;
function getInterestAccrualIndices(bytes32 assetId)
external
view
returns (HubSpokeStructs.AccrualIndices memory);
function getInterestAccrualIndexPrecision() external view returns (uint256);
function getVaultAmounts(address vaultOwner, bytes32 assetId)
external
view
returns (HubSpokeStructs.DenormalizedVaultAmount memory);
function getCurrentAccrualIndices(bytes32 assetId)
external
view
returns (HubSpokeStructs.AccrualIndices memory);
function updateAccrualIndices(bytes32 assetId) external;
function getLastActivityBlockTimestamp(bytes32 assetId) external view returns (uint256);
function getGlobalAmounts(bytes32 assetId) external view returns (HubSpokeStructs.DenormalizedVaultAmount memory);
function getReserveAmount(bytes32 assetId) external view returns (uint256);
function getSpokeBalances(uint16 chainId, bytes32 homeAddress) external view returns (HubSpokeStructs.HubSpokeBalances memory);
function getSpokeBalances(bytes32 assetId) external view returns (HubSpokeStructs.HubSpokeBalances memory);
function getLiquidationCalculator() external view returns (ILiquidationCalculator);
function getPriceUtilities() external view returns (IHubPriceUtilities);
function getAssetRegistry() external view returns (IAssetRegistry);
function getWormholeTunnel() external view returns (IWormholeTunnel);
function getLiquidationFeeAndPrecision() external view returns (uint256, uint256);
function liquidation(ILiquidationCalculator.LiquidationInput memory input) external;
function userActions(HubSpokeStructs.Action action, bytes32 asset, uint256 amount) external payable;
function confirmPairingRequest(uint16 _chainId, bytes32 _account) external;
// ----- cross chain message handlers ---
function userActionMessage(
IWormholeTunnel.MessageSource calldata source,
IERC20 token,
uint256 amount,
bytes calldata payload
) external payable;
function instantActionMessage(
IWormholeTunnel.MessageSource calldata source,
IERC20 token,
uint256 amount,
bytes calldata payload
) external;
function finalizeCreditMessage(
IWormholeTunnel.MessageSource calldata source,
IERC20 token,
uint256 amount,
bytes calldata payload
) external;
function confirmTopUpMessage(
IWormholeTunnel.MessageSource calldata source,
IERC20 token,
uint256 amount,
bytes calldata payload
) external;
function confirmFixLostCreditMessage(
IWormholeTunnel.MessageSource calldata source,
IERC20 token,
uint256 amount,
bytes calldata payload
) external;
function pairingRequestMessage(
IWormholeTunnel.MessageSource calldata source,
IERC20 token,
uint256 amount,
bytes calldata payload
) external;
}
src/interfaces/IHubPriceUtilities.sol
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.0;
import "@pythnetwork/pyth-sdk-solidity/IPyth.sol";
import "./IHub.sol";
import "./IAssetRegistry.sol";
import "./ISynonymPriceOracle.sol";
import "../contracts/HubSpokeStructs.sol";
interface IHubPriceUtilities {
function getAssetRegistry() external view returns (IAssetRegistry);
function getPrices(bytes32 asset) external view returns (uint256, uint256, uint256, uint256);
function getVaultEffectiveNotionals(address vaultOwner, bool collateralizationRatios) external view returns (HubSpokeStructs.NotionalVaultAmount memory);
function calculateNotionals(bytes32 asset, HubSpokeStructs.DenormalizedVaultAmount memory vaultAmount) external view returns (HubSpokeStructs.NotionalVaultAmount memory);
function calculateEffectiveNotionals(bytes32 asset, HubSpokeStructs.DenormalizedVaultAmount memory vaultAmount) external view returns (HubSpokeStructs.NotionalVaultAmount memory);
function invertNotionals(bytes32 asset, HubSpokeStructs.NotionalVaultAmount memory realValues) external view returns (HubSpokeStructs.DenormalizedVaultAmount memory);
function applyCollateralizationRatios(bytes32 asset, HubSpokeStructs.NotionalVaultAmount memory vaultAmount) external view returns (HubSpokeStructs.NotionalVaultAmount memory);
function removeCollateralizationRatios(bytes32 asset, HubSpokeStructs.NotionalVaultAmount memory vaultAmount) external view returns (HubSpokeStructs.NotionalVaultAmount memory);
function getHub() external view returns (IHub);
function setHub(IHub _hub) external;
function getPriceOracle() external view returns (ISynonymPriceOracle);
function setPriceOracle(ISynonymPriceOracle _priceOracle) external;
function getPriceStandardDeviations() external view returns (uint256, uint256);
function setPriceStandardDeviations(uint256 _priceStandardDeviations, uint256 _precision) external;
}
src/interfaces/ILegacyAssetRegistry.sol
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {IWETH} from "@wormhole/interfaces/IWETH.sol";
import "../contracts/HubSpokeStructs.sol";
interface ILegacyAssetRegistry {
struct AssetInfo {
uint256 collateralizationRatioDeposit;
uint256 collateralizationRatioBorrow;
uint8 decimals;
address interestRateCalculator;
bool exists;
uint256 borrowLimit;
uint256 supplyLimit;
uint256 maxLiquidationPortion;
uint256 maxLiquidationBonus; // 1e6 precision; 130e4 = 130% = 1.3; the liquidator gets 30% over what he repays
}
function registerAsset(
address assetAddress,
uint256 collateralizationRatioDeposit,
uint256 collateralizationRatioBorrow,
address interestRateCalculator,
uint256 maxLiquidationPortion,
uint256 maxLiquidationBonus
) external;
function getAssetInfo(address assetAddress) external view returns (AssetInfo memory);
function setAssetParams(
address assetAddress,
uint256 borrowLimit,
uint256 supplyLimit,
uint256 maxLiquidationPortion,
uint256 maxLiquidationBonus,
address interestRateCalculatorAddress
) external;
function setCollateralizationRatios(address _asset, uint256 _deposit, uint256 _borrow) external;
function getRegisteredAssets() external view returns (address[] memory);
function getCollateralizationRatioPrecision() external view returns (uint256);
function getMaxLiquidationPortionPrecision() external view returns (uint256);
function WETH() external view returns (IWETH);
function getMaxDecimals() external view returns (uint8);
}
src/interfaces/ILiquidationCalculator.sol
// SPDX-License-Identifier: Apache 2
pragma solidity ^0.8.0;
import "../contracts/HubSpokeStructs.sol";
interface ILiquidationCalculator {
enum RepaymentMethod {
TOKEN_TRANSFER,
FROM_DEPOSIT,
DEBT_TAKEOVER
}
enum PaymentMethod {
TOKEN_TRANSFER,
DEPOSIT_TAKEOVER
}
/**
* @param assetId - The ID of the repaid/received asset
* @param repaidAmount - The amount of the asset that is being repaid (can be zero)
* @param receivedAmount - The amount of the asset that is being received (can be zero)
* @param depositTakeover - A flag if the liquidator will take the deposit of the debtor instead of collateral tokens
* @param repayFromDeposit - A flag if the liquidator will repay from their existing deposit instead of providing tokens
*/
struct DenormalizedLiquidationAsset {
bytes32 assetId;
uint256 repaidAmount;
uint256 receivedAmount;
RepaymentMethod repaymentMethod;
PaymentMethod paymentMethod;
}
/**
* @param vault - the address of the vault that is being liquidated
*/
struct LiquidationInput {
address vault;
DenormalizedLiquidationAsset[] assets;
}
function getMaxHealthFactor() external view returns (uint256, uint256);
}
src/interfaces/ISpoke.sol
// SPDX-License-Identifier: Apache 2
pragma solidity ^0.8.0;
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {IWormholeTunnel} from "./IWormholeTunnel.sol";
interface ISpoke {
error CreditLimitExceeded();
error CustodyLimitExceeded();
error FundsAlreadyReleased();
error InsufficientMsgValue();
error InsufficientFunds();
error InvalidAction();
error InvalidAmount();
error InvalidCostForReturnDeliveryLength();
error InvalidDeliveryCost();
error InvalidReleaseFundsPayload();
error OnlyHubSender();
error OnlyWormholeTunnel();
error TransactionLimitExceeded();
error TransferFailed();
error UnusedParameterMustBeZero();
function releaseFunds(
IWormholeTunnel.MessageSource calldata source,
IERC20 token,
uint256 amount,
bytes calldata payload
) external payable;
function topUp(
IWormholeTunnel.MessageSource calldata source,
IERC20 token,
uint256 amount,
bytes calldata payload
) external payable;
function confirmCredit(
IWormholeTunnel.MessageSource calldata source,
IERC20 token,
uint256 amount,
bytes calldata payload
) external payable;
function finalizeCredit(
IWormholeTunnel.MessageSource calldata source,
IERC20 token,
uint256 amount,
bytes calldata payload
) external payable;
}
src/interfaces/ISynonymPriceOracle.sol
// SPDX-License-Identifier: Unlicense
pragma solidity ^0.8.0;
import {AggregatorV3Interface} from "@chainlink/contracts/src/v0.8/interfaces/AggregatorV3Interface.sol";
import {ISynonymPriceSource} from "./ISynonymPriceSource.sol";
interface ISynonymPriceOracle is ISynonymPriceSource {
struct PriceSource {
ISynonymPriceSource priceSource;
uint256 maxPriceAge;
}
function sequencerUptimeFeed() external view returns (AggregatorV3Interface);
function sequencerGracePeriod() external view returns (uint256);
function getPrice(bytes32 _asset) external view returns (Price memory price);
function setPriceSource(bytes32 _asset, PriceSource memory _priceSource) external;
function removePriceSource(bytes32 _asset) external;
function getPriceSource(bytes32 _asset) external view returns (PriceSource memory);
}
src/interfaces/ISynonymPriceSource.sol
// SPDX-License-Identifier: Unlicense
pragma solidity ^0.8.0;
interface ISynonymPriceSource {
error NoPriceForAsset();
error StalePrice();
struct Price {
uint256 price;
uint256 confidence;
uint256 precision;
uint256 updatedAt;
}
function getPrice(bytes32 _asset, uint256 _maxAge) external view returns (Price memory price);
function priceAvailable(bytes32 _asset) external view returns (bool);
function outputAsset() external view returns (string memory);
}
src/interfaces/IWormholeTunnel.sol
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.0;
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {IWormholeRelayer} from "@wormhole/interfaces/IWormholeRelayer.sol";
interface IWormholeTunnel {
error InsufficientMsgValue();
error InvalidCCTPConfig();
error InvalidTunnelMessage();
error InvalidVaa();
error OnlyWormholeRelayer();
error ReplayProtection();
error SameChainCallsNotSupported();
error TransferFailed();
error TunnelEndNotRegistered();
event CCTPConfigChanged(address indexed messageTransmitter, address indexed tokenMessenger, address indexed usdc);
event TunnelEndRegistered(uint16 indexed chainId, bytes32 indexed sender, bool supportsCCTP);
event CustomRelayerSet(uint16 indexed chainId, IWormholeRelayer relayerAddress);
event TargetReverted(bytes ret);
enum MessageFinality {
FINALIZED,
SAFE,
INSTANT
}
struct TunnelMessage {
MessageSource source; // defines the sender of the message and the chain it's coming from
MessageTarget target; // defines the recipient of the message and the chain it's going to
bytes32 token; // the address of the token sent along with the message (optional)
uint256 amount; // the amount of the token sent along with the message (optional)
uint256 receiverValue; // the value that the message recipient is supposed to receive in target chain native currency (optional)
MessageFinality finality; // the finality of the message
}
struct MessageSource {
uint16 chainId; // the chain id of the sender
bytes32 sender; // the address of the sender
// the address that should receive any WH cost refunds on target chain.
// in case the message recipient reverts and tokens were sent, the tokens will be returned to this address on source chain
bytes32 refundRecipient;
}
struct MessageTarget {
uint16 chainId; // the chain id of the recipient
bytes32 recipient; // the address of the recipient of the message on the target chain
bytes4 selector; // if the recipient is a contract, the selector of the function to call (optional)
bytes payload; // if the recipient is a contract, the data to send to the function call (optional)
}
/**
* @dev sends a message assuming the target chain is EVM
* @param _message the message to send
* @param _gasLimit the gas limit for the message
*/
function sendEvmMessage(
TunnelMessage calldata _message,
uint256 _gasLimit
) external payable;
/**
* @dev sends a message providing no additional execution parameters (for gasless chains or custom relayers)
* @param _message the message to send
*/
function sendMessage(
TunnelMessage calldata _message
) external payable;
/**
* @dev sends a message providing additional encoded execution parameters
* @param _message the message to send
* @param encodedExecutionParams the encoded execution parameters
*/
function sendMessage(
TunnelMessage calldata _message,
bytes calldata encodedExecutionParams
) external payable;
function USDC() external view returns (IERC20);
/**
* @dev whether this tunnel supports Circle's CCTP
*/
function supportsCCTP() external view returns (bool);
/**
* @dev whether the tunnel end on a given chain supports Circle's CCTP
*/
function tunnelEndSupportsCCTP(uint16 _chainId) external view returns (bool);
/**
* @dev the chain id of the tunnel
*/
function chainId() external view returns (uint16);
/**
* @dev returns whether a given _chainId is EVM compatible
*/
function isEvm(uint16 _chainId) external view returns (bool);
/**
* @dev the gas required for the tunnel to send a message with a token transfer
* this is on top of any gas required with cross chain contract calls and only covers what the tunnel uses
*/
function GAS_USAGE_WITH_TOKEN() external view returns (uint256);
/**
* @dev the gas required for the tunnel to send a message without a token transfer
* same as above, but without the token transfer
*/
function GAS_USAGE_WITHOUT_TOKEN() external view returns (uint256);
/**
* @dev gets the address of a token on the current chain
* handles both CCTP USDC translation and TokenBridge wrapped tokens (native addr -> wrapped addr)
* can't handle "unbridging" tokens (getting the original token asset from a bridged asset address)
* @param tokenHomeChain the chain id of the token
* @param tokenHomeAddress the address of the token on the home chain
*/
function getTokenAddressOnThisChain(uint16 tokenHomeChain, bytes32 tokenHomeAddress) external view returns (address);
/**
* @dev gets the cost of sending a message
* @param _targetChain the chain id of the target chain
* @param _gasLimitOnTarget the gas limit for parsing and executing the message
* @param _receiverValue the value that the message recipient is supposed to receive in target chain native currency
* @param _withTokenTransfer whether the message includes a token transfer
*/
function getMessageCost(uint16 _targetChain, uint256 _gasLimitOnTarget, uint256 _receiverValue, bool _withTokenTransfer) external view returns (uint256 cost);
/**
* @dev checks if an amount is valid for a token transfer. WH TokenBridge limits amounts to 8 decimals. USDC through CCTP is assumed ok.
* @param token the address of the token
* @param amount the amount to transfer
*/
function isValidAmount(IERC20 token, uint256 amount) external view returns (bool);
/**
* @dev returns the address of the relayer that handles messages to and from chainId
* @param chainId the WH chainId
* @return IWormholeRelayer the relayer contract
*/
function getRelayer(uint16 chainId) external view returns (IWormholeRelayer);
}
src/interfaces/rewards/IMoneyMarketRewardsDistributor.sol
// SPDX-License-Identifier: Apache 2
pragma solidity ^0.8.0;
import {IHub} from "../IHub.sol";
interface IMoneyMarketRewardsDistributor {
event MarketSupportAdded(bytes32 indexed token);
event MarketSupportRemoved(bytes32 indexed token);
event UserSharesMigrated(address indexed user, bytes32 indexed pool);
function handleBalanceChange(address _user, bytes32 _assetId) external;
function migrateShares(address _user, bytes32 _assetId) external;
}
src/libraries/logic/accounting/CommonAccountingLogic.sol
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.0;
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {IWETH} from "@wormhole/interfaces/IWETH.sol";
import {HubSpokeStructs} from "../../../contracts/HubSpokeStructs.sol";
library CommonAccountingLogic {
using SafeERC20 for IERC20;
error InsufficientMsgValue();
error UnusedParameterMustBeZero();
function handleInboundTokensAndAdjustAction(
HubSpokeStructs.Action _action,
address _asset,
uint256 _amount,
IWETH _weth
) public returns (
HubSpokeStructs.Action action,
address asset,
uint256 amount
) {
(action, asset, amount, ) = handleInboundTokensAndAdjustAction(_action, _asset, _amount, _weth, 0);
}
function handleInboundTokensAndAdjustAction(
HubSpokeStructs.Action _action,
address _asset,
uint256 _amount,
IWETH _weth,
uint256 _cost
) public returns (
HubSpokeStructs.Action action,
address asset,
uint256 amount,
uint256 remainingMsgValue
) {
action = _action;
asset = _asset;
amount = _amount;
remainingMsgValue = msg.value;
if (action == HubSpokeStructs.Action.RepayNative || action == HubSpokeStructs.Action.DepositNative) {
if (asset != address(0) || amount != 0) revert UnusedParameterMustBeZero();
if (msg.value <= _cost) {
revert InsufficientMsgValue();
}
asset = address(_weth);
amount = msg.value - _cost;
_weth.deposit{value: amount}();
action = action == HubSpokeStructs.Action.RepayNative ? HubSpokeStructs.Action.Repay : HubSpokeStructs.Action.Deposit;
remainingMsgValue = _cost;
} else if (action == HubSpokeStructs.Action.Deposit || action == HubSpokeStructs.Action.Repay) {
IERC20(asset).safeTransferFrom(msg.sender, address(this), amount);
}
// the else case here is that the action was a Withdraw (+native) or a Borrow, which have no inbound tokens
// or asset address to adjust, in such case, this function is a no-op pass-through
}
}src/libraries/logic/accounting/SpokeAccountingLogic.sol
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.0;
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "@wormhole/Utils.sol";
import {IWormholeTunnel} from "../../../interfaces/IWormholeTunnel.sol";
import {IHub} from "../../../interfaces/IHub.sol";
import {HubSpokeStructs} from "../../../contracts/HubSpokeStructs.sol";
library SpokeAccountingLogic {
using SafeERC20 for IERC20;
uint256 public constant REQUEST_PAIRING_GAS_LIMIT = 100_000;
error InsufficientFunds();
error InsufficientMsgValue();
error TransferFailed();
error ZeroAddress();
// events need to be in both library and contract to be picked up
// see: https://ethereum.stackexchange.com/questions/11137/watching-events-defined-in-libraries
event ReservesWithdrawn(address indexed asset, uint256 amount, address destination);
// end events from HubSpokeEvents
function getReserveAmount(
HubSpokeStructs.SpokeOptimisticFinalityState storage ofState,
address asset
) public view returns (uint256) {
HubSpokeStructs.SpokeBalances storage balance = ofState.tokenBalances[toWormholeFormat(address(asset))];
return IERC20(asset).balanceOf(address(this)) - balance.deposits - balance.creditGiven;
}
function withdrawReserves(
HubSpokeStructs.SpokeOptimisticFinalityState storage ofState,
address asset,
uint256 amount,
address recipient
) public {
if (recipient == address(0)) {
revert ZeroAddress();
}
if (asset == address(0)) {
if (address(this).balance < amount) {
revert InsufficientFunds();
}
(bool success,) = payable(recipient).call{value: amount}("");
if (!success) {
revert TransferFailed();
}
} else {
if (amount > getReserveAmount(ofState, asset)) {
revert InsufficientFunds();
}
IERC20(asset).safeTransfer(recipient, amount);
}
emit ReservesWithdrawn(asset, amount, recipient);
}
function getPairingCost(
HubSpokeStructs.SpokeCommunicationState storage commState
) public view returns (uint256) {
return commState.wormholeTunnel.getMessageCost(
commState.hubChainId,
REQUEST_PAIRING_GAS_LIMIT,
0, // no return message, so no ETH sent to the Hub
false // no token transfer
);
}
function handlePairingRequest(
HubSpokeStructs.SpokeCommunicationState storage commState,
bytes32 userId
) public {
uint256 cost = getPairingCost(commState);
if (msg.value < cost) {
revert InsufficientMsgValue();
}
bytes32 senderWhFormat = toWormholeFormat(msg.sender);
IWormholeTunnel.TunnelMessage memory message;
message.source.refundRecipient = senderWhFormat;
message.source.sender = toWormholeFormat(address(this));
message.source.chainId = commState.wormholeTunnel.chainId();
message.target.chainId = commState.hubChainId;
message.target.recipient = commState.hubContractAddress;
message.target.selector = IHub.pairingRequestMessage.selector;
message.target.payload = abi.encode(HubSpokeStructs.RequestPairingPayload({
newAccount: senderWhFormat,
userId: userId
}));
message.finality = IWormholeTunnel.MessageFinality.INSTANT;
commState.wormholeTunnel.sendEvmMessage{value: cost}(
message,
REQUEST_PAIRING_GAS_LIMIT
);
}
}src/libraries/logic/optimisticFinality/CommonOptimisticFinalityLogic.sol
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.0;
import {HubSpokeStructs} from "../../../contracts/HubSpokeStructs.sol";
library CommonOptimisticFinalityLogic {
function creditMissingOrConflicting(HubSpokeStructs.Credit memory credit, HubSpokeStructs.Credit storage storedCredit) public view returns (bool) {
return storedCredit.createdAt == 0 ||
storedCredit.user != credit.user ||
storedCredit.token != credit.token ||
storedCredit.creditedAmount != credit.creditedAmount;
}
function getActionDirection(HubSpokeStructs.Action _action) public pure returns (HubSpokeStructs.ActionDirection) {
if (
_action == HubSpokeStructs.Action.Withdraw ||
_action == HubSpokeStructs.Action.WithdrawNative ||
_action == HubSpokeStructs.Action.Borrow ||
_action == HubSpokeStructs.Action.BorrowNative
) {
return HubSpokeStructs.ActionDirection.Outbound;
}
return HubSpokeStructs.ActionDirection.Inbound;
}
}Compiler settingsShow
{
"viaIR": false,
"metadata": {
"useLiteralContent": true
},
"libraries": {
"src/libraries/logic/accounting/SpokeAccountingLogic.sol": {
"SpokeAccountingLogic": "0xf93353f929b19b82a7f01b61b02844cabf76c764"
},
"src/libraries/logic/accounting/CommonAccountingLogic.sol": {
"CommonAccountingLogic": "0x6e0e8c78d7b894beff66ade8b27b089a53cf4d04"
},
"src/libraries/logic/optimisticFinality/CommonOptimisticFinalityLogic.sol": {
"CommonOptimisticFinalityLogic": "0xffe52f091e6c51f264694f7c173222bac06a01f3"
}
},
"optimizer": {
"runs": 2000,
"enabled": true
},
"evmVersion": "paris"
}Source code and metadata: Sourcify.
The source code belongs to the authors of the contract.