Verified contractExactUNLICENSED
ZecSwap
Address0xeb3a00bcb6c9ff626fe57a5dbbdcf01730e7898f
- Balance
0 ETH
- Transactions
15
- Compiler
solc 0.8.28
- Same code
Only this contract
Details
- Compiler
- solc 0.8.28+commit.7893614a
- Language
- solidity
- Optimization
- Yes, 10,000 runs
- EVM version
- cancun
- License
- UNLICENSED
- Match
- Exactcreation code: yes, runtime code: yes
- Verified on Sourcify
- Created in block
- 26,250,774
- Creation transaction
- 0x9a1f10e785…8518bea7ee
4 files
- src/ZecSwap.solmain24.25 KB
- src/Pallas.sol3.68 KB
- src/ShieldVault.sol2.64 KB
- src/Token.sol1.6 KB
src/ZecSwap.sol
// SPDX-License-Identifier: UNLICENSED
pragma solidity 0.8.28;
import {Pallas} from "./Pallas.sol";
import {IRailgun, ShieldVault} from "./ShieldVault.sol";
import {Token} from "./Token.sol";
/// @title ZecSwap
/// @notice Settles atomic swaps of shielded ZEC for ERC-20 tokens held by makers.
/// @dev The ZEC sits in an Orchard address whose spend key is ±(e + z): the maker holds e,
/// the user holds z, and this contract stores E = [e]·G and Z = [z]·G. Revealing z pays the user
/// (and lets the maker sweep the ZEC); revealing e refunds the maker (and lets the user sweep it
/// back). A swap's time is cut into windows in which only one party may reveal, so no reveal is
/// ever raced, and one held up in the mempool still lands any time before its window closes:
///
/// - A forward swap: the maker may cancel it until `t0` unless it made it ready; the user may
/// claim once it is ready, or from `t0` without, until `t1`; from `t1` only the maker may refund,
/// for `LATE_WINDOW`, and after that only the user may claim, so neither is left waiting on
/// the other for good.
/// - A reverse escrow: the maker may claim once the user made it ready, until `t1`; the user may
/// refund it while it isn't ready, and from `t1`.
///
/// `ready` is given only before `t0`, and `open` refuses a `t0`, or a gap from `t0` to `t1`, under
/// `MIN_WINDOW`, so every window leaves its party time. Reveals make no token calls either: payouts
/// leave separately, so a paused or blacklisting token cannot revert a reveal.
///
/// A claim pays either the user's account, which withdraws it, or, where Railgun is deployed, the
/// user's Railgun balance: the maker commits at open to a note the user built, and `payout` can
/// only shield to it. Such a user has no account on this chain. Its `user` is a key of that swap
/// alone, which signs for the payout, and relayers send its transactions.
///
/// A swap's terms never change after open, so only their hash is stored: every call on a swap
/// supplies them again, and the call reverts unless they hash to what open stored. `Opened`
/// emits them for the parties to keep.
contract ZecSwap {
enum Stage {
None,
Open,
Ready,
Claimed,
Refunded
}
struct Terms {
address maker;
address token;
uint128 amount;
uint256[2] makerKey;
uint256[2] userKey;
address user;
/// After this the user may claim without the maker's `ready`.
uint64 t0;
/// After this the maker may refund a `Ready` swap.
uint64 t1;
/// The `noteCommitment` of the Railgun note a claim pays; zero pays `user`'s balance.
bytes32 payoutNote;
}
struct Swap {
/// `hashTerms` of the terms the swap opened with.
bytes32 termsHash;
Stage stage;
/// Whether a Railgun payout or reverse refund has left.
bool paidOut;
/// The share revealed at settlement: the user's once Claimed, the maker's once Refunded.
/// Kept in storage so the other party can read it without querying logs.
uint256 secret;
}
struct ReverseOpen {
address maker;
address user;
address token;
uint128 amount;
uint256[2] makerKey;
uint256[2] userKey;
uint64 t0;
uint64 t1;
bytes32 refundNote;
uint64 deadline;
}
struct ReverseFunding {
bytes32 refundNote;
uint64 blockNumber;
}
mapping(bytes32 id => ReverseFunding) public reverseFunding;
mapping(bytes32 id => uint64) public rescueNonces;
bytes32 private constant OPEN_REVERSE_TYPEHASH = keccak256(
"OpenReverse(address maker,address user,address token,uint128 amount,bytes32 makerKey,bytes32 userKey,uint64 t0,uint64 t1,bytes32 refundNote,uint64 deadline)"
);
bytes32 private constant READY_TYPEHASH = keccak256("Ready(bytes32 id,uint64 deadline)");
bytes32 private constant REFUND_PAYOUT_TYPEHASH =
keccak256("RefundPayout(bytes32 id,address relayer,uint128 fee)");
bytes32 private constant DOMAIN_TYPEHASH =
keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)");
bytes32 private constant PAYOUT_TYPEHASH = keccak256("Payout(bytes32 id,address relayer,uint128 fee)");
bytes32 private constant RESCUE_TYPEHASH =
keccak256("Rescue(bytes32 id,bytes32 note,address relayer,uint128 fee,uint64 nonce,uint64 deadline)");
/// secp256k1's n / 2. A signature with a larger `s` is the malleated twin of one without.
uint256 private constant HALF_N = 0x7fffffffffffffffffffffffffffffff5d576e7357a4501ddfe92f46681b20a0;
/// @notice The least time `open` leaves before `t0`, and from `t0` to `t1`.
uint256 public immutable MIN_WINDOW;
/// @notice How long from `t1` only the maker may refund a forward swap; then its user may claim.
uint256 public immutable LATE_WINDOW;
/// @notice Railgun's shield entry point; zero where claims can only pay accounts.
IRailgun public immutable RAILGUN;
/// @notice The code every swap's vault runs: each is an EIP-1167 proxy to this one.
ShieldVault public immutable VAULT_LOGIC;
bytes32 private immutable VAULT_CODE_HASH;
mapping(bytes32 id => Swap) private swaps;
/// @notice Keyed by `keccak256(abi.encode(maker, makerKey))`: a maker's share is single-use.
mapping(bytes32 makerKey => bool) public makerKeyUsed;
/// @notice What each account can withdraw: makers' inventory and users' claimed payouts.
mapping(address owner => mapping(address token => uint256)) public balanceOf;
event Deposited(address indexed owner, address indexed token, uint256 amount);
event Withdrawn(address indexed owner, address indexed token, uint256 amount, address to);
event Opened(
bytes32 indexed id,
address indexed maker,
address indexed user,
address token,
uint256 amount,
uint256[2] makerKey,
uint256[2] userKey,
uint64 t0,
uint64 t1,
bytes32 payoutNote
);
event MarkedReady(bytes32 indexed id);
event Claimed(bytes32 indexed id, uint256 userSecret);
event PaidOut(bytes32 indexed id, address relayer, uint256 fee);
event Rescued(bytes32 indexed id, address relayer, uint256 fee);
event Refunded(bytes32 indexed id, uint256 makerSecret);
error ZeroAmount();
error InvalidAmount();
error ZeroAddress();
error InsufficientBalance();
error InvalidKey();
error KeyReused();
error InvalidDeadlines();
error Unauthorized();
error WrongStage();
error NotNow();
error WrongSecret();
error NoShieldedPayouts();
error WrongNote();
error BadSignature();
error Expired();
error VaultNotDeployed();
error WrongTerms();
constructor(uint256 minWindow, uint256 lateWindow, IRailgun railgun) {
if (minWindow == 0 || lateWindow < minWindow || lateWindow > type(uint32).max) {
revert InvalidDeadlines();
}
MIN_WINDOW = minWindow;
LATE_WINDOW = lateWindow;
RAILGUN = railgun;
VAULT_LOGIC = new ShieldVault();
VAULT_CODE_HASH = keccak256(_vaultCode());
}
/// @notice Adds to the caller's inventory, from which it opens swaps.
function deposit(address token, uint256 amount) external {
if (amount == 0) revert ZeroAmount();
// Credited only for what arrived: a token that keeps a fee would otherwise hand the
// shortfall to everyone else holding it here.
uint256 before = Token.balanceOf(token, address(this));
Token.transferFrom(token, msg.sender, address(this), amount);
if (Token.balanceOf(token, address(this)) != before + amount) revert InsufficientBalance();
balanceOf[msg.sender][token] += amount;
emit Deposited(msg.sender, token, amount);
}
function withdraw(address token, uint256 amount, address to) external {
if (to == address(0)) revert ZeroAddress();
uint256 balance = balanceOf[msg.sender][token];
if (amount > balance) revert InsufficientBalance();
balanceOf[msg.sender][token] = balance - amount;
Token.transfer(token, to, amount);
emit Withdrawn(msg.sender, token, amount, to);
}
/// @notice Commits `amount` of the caller's inventory to a swap with the holder of `userKey`,
/// on the terms `Terms` describes, the caller as their `maker`. The user may claim from `t0`,
/// so an open mined less than `MIN_WINDOW` before it, leaving the maker no time to cancel, is
/// refused.
function open(
address token,
uint128 amount,
uint256[2] calldata makerKey,
uint256[2] calldata userKey,
address user,
uint64 t0,
uint64 t1,
bytes32 payoutNote
) external returns (bytes32 id) {
return _open(
Terms(msg.sender, token, amount, makerKey, userKey, user, t0, t1, payoutNote),
swapId(msg.sender, userKey)
);
}
function _open(Terms memory terms, bytes32 id) private returns (bytes32) {
if (terms.amount == 0) revert ZeroAmount();
if (terms.user == address(0)) revert ZeroAddress();
if (terms.payoutNote != 0 && address(RAILGUN) == address(0)) revert NoShieldedPayouts();
// Railgun notes hold at most uint120: more could never be paid out after the claim.
if (terms.payoutNote != 0 && terms.amount > type(uint120).max) revert InvalidAmount();
if (terms.t0 < block.timestamp + MIN_WINDOW || terms.t1 < terms.t0 + MIN_WINDOW) {
revert InvalidDeadlines();
}
uint256[2] memory makerKey = terms.makerKey;
uint256[2] memory userKey = terms.userKey;
if (
!Pallas.isOnCurve(makerKey[0], makerKey[1]) || !Pallas.isOnCurve(userKey[0], userKey[1])
|| makerKey[0] == userKey[0]
) revert InvalidKey();
_record(id, terms);
emit Opened(
id,
terms.maker,
terms.user,
terms.token,
terms.amount,
makerKey,
userKey,
terms.t0,
terms.t1,
terms.payoutNote
);
return id;
}
/// @dev Debits the inventory open locks, spends the maker's share and stores the swap.
function _record(bytes32 id, Terms memory terms) private {
bytes32 makerKeyHash = keccak256(abi.encode(terms.maker, terms.makerKey));
Swap storage swap = swaps[id];
if (swap.stage != Stage.None || makerKeyUsed[makerKeyHash]) revert KeyReused();
uint256 balance = balanceOf[terms.maker][terms.token];
if (terms.amount > balance) revert InsufficientBalance();
makerKeyUsed[makerKeyHash] = true;
balanceOf[terms.maker][terms.token] = balance - terms.amount;
// `hashTerms`, from memory: a static struct encodes the same wherever it is held, and
// hashing calldata in place keeps every later call's check cheaper.
swap.termsHash = keccak256(abi.encode(terms));
swap.stage = Stage.Open;
}
/// @notice Called by Relay Adapt after unshielding and approving the exact escrow amount.
/// The stored roles remain USDC side (`maker`) and ZEC side (`user`) in both directions. Ready
/// is given only before `t0`, so an open mined less than `MIN_WINDOW` before it is refused.
function openReverse(ReverseOpen calldata terms, bytes calldata signature)
external
returns (bytes32 id)
{
if (block.timestamp > terms.deadline) revert Expired();
if (terms.user == address(0) || terms.maker == address(0)) revert ZeroAddress();
if (terms.refundNote == 0) revert WrongNote();
if (terms.amount > type(uint120).max) revert InvalidAmount();
if (terms.deadline >= terms.t0) revert InvalidDeadlines();
if (address(RAILGUN) == address(0)) revert NoShieldedPayouts();
_checkSignature(
terms.user,
keccak256(
abi.encode(
OPEN_REVERSE_TYPEHASH,
terms.maker,
terms.user,
terms.token,
terms.amount,
keccak256(abi.encode(terms.makerKey)),
keccak256(abi.encode(terms.userKey)),
terms.t0,
terms.t1,
terms.refundNote,
terms.deadline
)
),
signature
);
// Record before the token call. A failed or short transfer rolls the entire open back.
balanceOf[terms.user][terms.token] += terms.amount;
id = _open(
Terms(
terms.user,
terms.token,
terms.amount,
terms.userKey,
terms.makerKey,
terms.maker,
terms.t0,
terms.t1,
0
),
reverseSwapId(terms.user, terms.makerKey)
);
reverseFunding[id] = ReverseFunding(terms.refundNote, uint64(block.number));
uint256 before = Token.balanceOf(terms.token, address(this));
Token.transferFrom(terms.token, msg.sender, address(this), terms.amount);
if (Token.balanceOf(terms.token, address(this)) != before + terms.amount) {
revert InsufficientBalance();
}
}
function readyWithSig(bytes32 id, Terms calldata terms, uint64 deadline, bytes calldata signature)
external
{
Swap storage swap = _load(id, terms);
if (block.timestamp > deadline) revert Expired();
if (reverseFunding[id].refundNote == 0) revert WrongStage();
_checkSignature(terms.maker, keccak256(abi.encode(READY_TYPEHASH, id, deadline)), signature);
_ready(id, swap, terms);
}
function refundPayout(
bytes32 id,
Terms calldata terms,
bytes32 npk,
IRailgun.ShieldCiphertext calldata ciphertext,
uint128 fee,
bytes calldata signature
) external {
Swap storage swap = _load(id, terms);
if (swap.stage != Stage.Refunded || swap.paidOut) revert WrongStage();
bytes32 note = reverseFunding[id].refundNote;
if (note == 0 || noteCommitment(npk, ciphertext) != note) revert WrongNote();
_checkSignature(
terms.maker, keccak256(abi.encode(REFUND_PAYOUT_TYPEHASH, id, msg.sender, fee)), signature
);
_shieldPayout(id, swap, terms, npk, ciphertext, fee);
}
/// @notice The maker attests that the ZEC deposit is confirmed, giving up its right to
/// cancel. Only before `t0`, from when an unready swap is the user's to claim anyway.
function ready(bytes32 id, Terms calldata terms) external {
Swap storage swap = _load(id, terms);
if (msg.sender != terms.maker) revert Unauthorized();
_ready(id, swap, terms);
}
function _ready(bytes32 id, Swap storage swap, Terms calldata terms) private {
if (block.timestamp >= terms.t0) revert Expired();
if (swap.stage != Stage.Open) revert WrongStage();
swap.stage = Stage.Ready;
emit MarkedReady(id);
}
/// @notice Reveals the user's share and credits the amount to the user to withdraw at will,
/// or holds it for `payout` into Railgun. Callable by anyone, in the claim's window.
function claim(bytes32 id, Terms calldata terms, uint256 userSecret) external {
Swap storage swap = _load(id, terms);
if (!_claimable(id, swap, terms)) revert NotNow();
if (!Pallas.isSpendAuthMul(userSecret, terms.userKey[0], terms.userKey[1])) revert WrongSecret();
swap.stage = Stage.Claimed;
swap.secret = userSecret;
if (terms.payoutNote == 0) balanceOf[terms.user][terms.token] += terms.amount;
emit Claimed(id, userSecret);
}
/// @notice Shields a claimed swap's amount into Railgun, to the note committed at open, less
/// the fee its user signed for the relayer that sends this. A step apart from `claim`, so
/// Railgun or the token failing can delay the payout but never the reveal.
function payout(
bytes32 id,
Terms calldata terms,
bytes32 npk,
IRailgun.ShieldCiphertext calldata ciphertext,
uint128 fee,
bytes calldata signature
) external {
Swap storage swap = _load(id, terms);
if (swap.stage != Stage.Claimed || terms.payoutNote == 0 || swap.paidOut) revert WrongStage();
if (noteCommitment(npk, ciphertext) != terms.payoutNote) revert WrongNote();
_checkSignature(terms.user, keccak256(abi.encode(PAYOUT_TYPEHASH, id, msg.sender, fee)), signature);
_shieldPayout(id, swap, terms, npk, ciphertext, fee);
}
function _shieldPayout(
bytes32 id,
Swap storage swap,
Terms calldata terms,
bytes32 npk,
IRailgun.ShieldCiphertext calldata ciphertext,
uint128 fee
) private {
swap.paidOut = true;
bytes memory code = _vaultCode();
address vault;
assembly ("memory-safe") {
vault := create2(0, add(code, 0x20), mload(code), id)
}
if (vault == address(0)) revert VaultNotDeployed();
Token.transfer(terms.token, vault, terms.amount);
ShieldVault(vault).shield(RAILGUN, terms.token, npk, ciphertext, fee, msg.sender);
emit PaidOut(id, msg.sender, fee);
}
/// @notice Shields whatever came back to a paid-out swap's vault again, to a note its user
/// signs for, less the fee it signs for the relayer that sends this.
function rescue(
bytes32 id,
Terms calldata terms,
bytes32 npk,
IRailgun.ShieldCiphertext calldata ciphertext,
uint128 fee,
uint64 nonce,
uint64 deadline,
bytes calldata signature
) external {
if (!_load(id, terms).paidOut) revert WrongStage();
if (block.timestamp > deadline) revert Expired();
if (nonce != rescueNonces[id]) revert BadSignature();
bytes32 note = noteCommitment(npk, ciphertext);
_checkSignature(
reverseFunding[id].refundNote == 0 ? terms.user : terms.maker,
keccak256(abi.encode(RESCUE_TYPEHASH, id, note, msg.sender, fee, nonce, deadline)),
signature
);
rescueNonces[id] = nonce + 1;
ShieldVault(vaultOf(id)).shield(RAILGUN, terms.token, npk, ciphertext, fee, msg.sender);
emit Rescued(id, msg.sender, fee);
}
/// @notice Reveals the maker's share and returns the amount to its inventory. Callable by
/// anyone, in the refund's window.
function refund(bytes32 id, Terms calldata terms, uint256 makerSecret) external {
Swap storage swap = _load(id, terms);
if (!_refundable(id, swap, terms)) revert NotNow();
if (!Pallas.isSpendAuthMul(makerSecret, terms.makerKey[0], terms.makerKey[1])) revert WrongSecret();
swap.stage = Stage.Refunded;
swap.secret = makerSecret;
if (reverseFunding[id].refundNote == 0) balanceOf[terms.maker][terms.token] += terms.amount;
emit Refunded(id, makerSecret);
}
/// @notice A swap's state. Its terms are only stored hashed; stage `None` means no swap.
function getSwap(bytes32 id) external view returns (Swap memory) {
return swaps[id];
}
/// @notice What a swap stores of the terms it opened with, and checks every later call's
/// against: their ABI encoding, hashed.
function hashTerms(Terms calldata terms) public pure returns (bytes32) {
return keccak256(abi.encode(terms));
}
/// @notice A swap is keyed by its maker and the user's public share, so a user finds its swap
/// from its own key, a share is never in two of one maker's swaps, and nobody can take a
/// swap's id by opening under someone else's share.
function swapId(address maker, uint256[2] memory userKey) public pure returns (bytes32) {
return keccak256(abi.encode(maker, userKey));
}
/// @notice A reverse escrow's id, from the escrowing user and the maker's share. It is never a
/// forward swap's id: a maker opening the forward swap a user had verified as a reverse
/// escrow, under the same terms, would take away that user's claim after `t0`.
function reverseSwapId(address user, uint256[2] memory makerKey) public pure returns (bytes32) {
return keccak256(abi.encode(user, makerKey, true));
}
/// @notice What a swap commits to as its payout note.
function noteCommitment(bytes32 npk, IRailgun.ShieldCiphertext calldata ciphertext)
public
pure
returns (bytes32)
{
return keccak256(abi.encode(npk, ciphertext));
}
/// @notice Where a swap's Railgun payout leaves from, and where Railgun sends it back.
function vaultOf(bytes32 id) public view returns (address) {
return address(
uint160(uint256(keccak256(abi.encodePacked(bytes1(0xff), address(this), id, VAULT_CODE_HASH))))
);
}
/// @dev EIP-1167 creation code of a minimal proxy to `VAULT_LOGIC`: a vault costs a fraction of
/// deploying the logic itself.
function _vaultCode() private view returns (bytes memory) {
return abi.encodePacked(
hex"3d602d80600a3d3981f3363d3d373d3d3d363d73",
address(VAULT_LOGIC),
hex"5af43d82803e903d91602b57fd5bf3"
);
}
/// @dev The swap `id` names, if `terms` are those it opened with. Every function that acts on
/// a swap reads its terms through here, from its caller; a swap that doesn't exist has none.
function _load(bytes32 id, Terms calldata terms) private view returns (Swap storage swap) {
swap = swaps[id];
if (swap.termsHash != hashTerms(terms)) revert WrongTerms();
}
/// @dev The claim's window: a ready swap until `t1`, and a forward one no one made ready from
/// `t0` until `t1`, the user's way out of a maker that neither readies nor cancels; and a
/// forward swap its maker didn't refund in `LATE_WINDOW` from `t1`.
function _claimable(bytes32 id, Swap storage swap, Terms calldata terms) private view returns (bool) {
Stage stage = swap.stage;
if (stage != Stage.Open && stage != Stage.Ready) return false;
bool forward = reverseFunding[id].refundNote == 0;
if (block.timestamp >= terms.t1) return forward && block.timestamp >= terms.t1 + LATE_WINDOW;
return stage == Stage.Ready || (forward && block.timestamp >= terms.t0);
}
/// @dev The refund's window, never open while the claim's is: before `t1` a swap no one made
/// ready, a forward one only until `t0`; from `t1` a reverse escrow for good, a forward swap for
/// `LATE_WINDOW`.
function _refundable(bytes32 id, Swap storage swap, Terms calldata terms) private view returns (bool) {
Stage stage = swap.stage;
if (stage != Stage.Open && stage != Stage.Ready) return false;
bool forward = reverseFunding[id].refundNote == 0;
if (block.timestamp >= terms.t1) return !forward || block.timestamp < terms.t1 + LATE_WINDOW;
return stage == Stage.Open && (!forward || block.timestamp < terms.t0);
}
/// @dev Checks an EIP-712 signature by `signer` over `structHash`, under this contract's
/// domain on this chain.
function _checkSignature(address signer, bytes32 structHash, bytes calldata signature) private view {
bytes32 domain = keccak256(
abi.encode(DOMAIN_TYPEHASH, keccak256("ZecSwap"), keccak256("1"), block.chainid, address(this))
);
bytes32 digest = keccak256(abi.encodePacked("\x19\x01", domain, structHash));
if (signature.length != 65 || uint256(bytes32(signature[32:64])) > HALF_N) revert BadSignature();
address recovered =
ecrecover(digest, uint8(signature[64]), bytes32(signature[:32]), bytes32(signature[32:64]));
if (recovered == address(0) || recovered != signer) revert BadSignature();
}
}
src/Pallas.sol
// SPDX-License-Identifier: UNLICENSED
pragma solidity 0.8.28;
/// @notice Pallas arithmetic for checking revealed Orchard spend-key shares.
/// @dev Pallas is y² = x³ + 5 over F_p with prime order q. The base is Orchard's
/// SpendAuthG = GroupHash("z.cash:Orchard", "G"), not the curve's standard generator.
library Pallas {
uint256 internal constant P = 0x40000000000000000000000000000000224698fc094cf91b992d30ed00000001;
uint256 internal constant Q = 0x40000000000000000000000000000000224698fc0994a8dd8c46eb2100000001;
uint256 internal constant GX = 0x375523b328f1d6063b8d187c3e5f445f0c7f0ce37b70a10c8d1a7284b875c963;
uint256 internal constant GY = 0x1ad0357fdf1a66db7b10bcfcfed624fbdfc914fec005bdd84ce33e817b0c3bc9;
/// @notice Whether (x, y) is a canonically encoded affine point. The identity has no
/// affine form and (0, 0) is not on the curve, so this also rejects it.
function isOnCurve(uint256 x, uint256 y) internal pure returns (bool) {
return x < P && y < P && mulmod(y, y, P) == addmod(mulmod(mulmod(x, x, P), x, P), 5, P);
}
/// @notice Whether (x, y) == [k]·SpendAuthG, for a scalar 0 < k < q.
function isSpendAuthMul(uint256 k, uint256 x, uint256 y) internal pure returns (bool) {
if (k == 0 || k >= Q || x >= P || y >= P) return false;
(uint256 jx, uint256 jy, uint256 jz) = mulSpendAuthG(k);
uint256 zz = mulmod(jz, jz, P);
return jx == mulmod(x, zz, P) && jy == mulmod(y, mulmod(zz, jz, P), P);
}
/// @dev Left-to-right double-and-add in Jacobian coordinates, starting from the top set
/// bit. The accumulator before an addition is [2m]·G with 2m + 1 <= k < q, so it is never
/// ±G and the incomplete mixed-addition formula is exact; Pallas has no 2-torsion, so
/// doubling is exact too. Formulas: dbl-2009-l and madd-2007-bl (a = 0).
function mulSpendAuthG(uint256 k) private pure returns (uint256 x, uint256 y, uint256 z) {
assembly ("memory-safe") {
let p := P
x := GX
y := GY
z := 1
let bit := 254
for {} iszero(shr(bit, k)) { bit := sub(bit, 1) } {}
for {} bit {} {
bit := sub(bit, 1)
let a := mulmod(x, x, p)
let b := mulmod(y, y, p)
let c := mulmod(b, b, p)
let t := addmod(x, b, p)
let d := addmod(mulmod(t, t, p), sub(p, addmod(a, c, p)), p)
d := addmod(d, d, p)
let e := mulmod(3, a, p)
z := mulmod(addmod(y, y, p), z, p)
x := addmod(mulmod(e, e, p), sub(p, addmod(d, d, p)), p)
y := addmod(mulmod(e, addmod(d, sub(p, x), p), p), sub(p, mulmod(8, c, p)), p)
if and(shr(bit, k), 1) {
let zz := mulmod(z, z, p)
let h := addmod(mulmod(GX, zz, p), sub(p, x), p)
let r := addmod(mulmod(GY, mulmod(z, zz, p), p), sub(p, y), p)
r := addmod(r, r, p)
let hh := mulmod(h, h, p)
let i := mulmod(4, hh, p)
let j := mulmod(h, i, p)
let v := mulmod(x, i, p)
let s := addmod(z, h, p)
z := addmod(mulmod(s, s, p), sub(p, addmod(zz, hh, p)), p)
let x3 := addmod(mulmod(r, r, p), sub(p, addmod(j, addmod(v, v, p), p)), p)
y :=
addmod(mulmod(r, addmod(v, sub(p, x3), p), p), sub(p, mulmod(2, mulmod(y, j, p), p)), p)
x := x3
}
}
}
}
}
src/ShieldVault.sol
// SPDX-License-Identifier: UNLICENSED
pragma solidity 0.8.28;
import {IERC20, Token} from "./Token.sol";
/// @notice The part of Railgun's `RailgunSmartWallet` a payout uses.
interface IRailgun {
struct TokenData {
uint8 tokenType; // 0: ERC-20
address tokenAddress;
uint256 tokenSubID;
}
struct CommitmentPreimage {
bytes32 npk;
TokenData token;
uint120 value;
}
/// @dev Encrypts only the note's `random`, to the receiver: the token and value it pays are
/// public and bound by the commitment, not the ciphertext.
struct ShieldCiphertext {
bytes32[3] encryptedBundle;
bytes32 shieldKey;
}
struct ShieldRequest {
CommitmentPreimage preimage;
ShieldCiphertext ciphertext;
}
/// @dev Pulls each request's value from the caller, the fee included.
function shield(ShieldRequest[] calldata requests) external;
}
/// @title ShieldVault
/// @notice Shields one swap's payout into Railgun. Every shielded payout leaves from its own vault
/// because Railgun's wallets let a note that its screening holds or rejects go only back to the
/// address it was shielded from: a note sent back lands here, tied to its swap, where the swap's
/// user can shield it again. The escrow deploys this once and each vault is a minimal proxy to it,
/// so `ESCROW` is the escrow in every vault.
contract ShieldVault {
error NotEscrow();
error ValueTooLarge();
address private immutable ESCROW = msg.sender;
/// @notice Pays `fee` of this vault's `token` to `feeTo` and shields the rest to the note
/// `npk`, which `ciphertext` lets its receiver find.
function shield(
IRailgun railgun,
address token,
bytes32 npk,
IRailgun.ShieldCiphertext calldata ciphertext,
uint256 fee,
address feeTo
) external {
if (msg.sender != ESCROW) revert NotEscrow();
uint256 value = IERC20(token).balanceOf(address(this)) - fee;
if (value > type(uint120).max) revert ValueTooLarge();
if (fee > 0) Token.transfer(token, feeTo, fee);
Token.approve(token, address(railgun), value);
IRailgun.ShieldRequest[] memory requests = new IRailgun.ShieldRequest[](1);
requests[0] = IRailgun.ShieldRequest({
preimage: IRailgun.CommitmentPreimage({
npk: npk,
token: IRailgun.TokenData({tokenType: 0, tokenAddress: token, tokenSubID: 0}),
value: uint120(value)
}),
ciphertext: ciphertext
});
railgun.shield(requests);
}
}
src/Token.sol
// SPDX-License-Identifier: UNLICENSED
pragma solidity 0.8.28;
interface IERC20 {
function balanceOf(address owner) external view returns (uint256);
function approve(address spender, uint256 amount) external returns (bool);
function transfer(address to, uint256 amount) external returns (bool);
function transferFrom(address from, address to, uint256 amount) external returns (bool);
}
/// @notice ERC-20 calls that accept tokens returning nothing, and fail on any other refusal.
library Token {
error TransferFailed();
function transfer(address token, address to, uint256 amount) internal {
call(token, abi.encodeCall(IERC20.transfer, (to, amount)));
}
function transferFrom(address token, address from, address to, uint256 amount) internal {
call(token, abi.encodeCall(IERC20.transferFrom, (from, to, amount)));
}
function approve(address token, address spender, uint256 amount) internal {
call(token, abi.encodeCall(IERC20.approve, (spender, amount)));
}
/// @dev What `owner` holds; an address without code fails as a transfer from it would.
function balanceOf(address token, address owner) internal view returns (uint256) {
if (token.code.length == 0) revert TransferFailed();
return IERC20(token).balanceOf(owner);
}
function call(address token, bytes memory data) private {
(bool ok, bytes memory result) = token.call(data);
if (!ok || (result.length == 0 ? token.code.length == 0 : !abi.decode(result, (bool)))) {
revert TransferFailed();
}
}
}
Compiler settingsShow
{
"viaIR": false,
"metadata": {
"appendCBOR": true,
"bytecodeHash": "ipfs",
"useLiteralContent": false
},
"optimizer": {
"runs": 10000,
"enabled": true
},
"evmVersion": "cancun",
"remappings": [
"forge-std/=lib/forge-std/src/"
]
}Source code and metadata: Sourcify.
The source code belongs to the authors of the contract.