Railgun 백서

Railgun

원문

bitpro가 원문에서 글자만 모은 내용이에요. 표·그림·수식은 빠지거나 깨질 수 있어요. 전체 6쪽 중 3쪽

. The nullification computation occurs in such a way that only the user can determine which UTXO has been spent, and an outside observer cannot link a Nullifier and note. The `[nInputs]` value is the number of inputs. * `commitmentsOut [noutputs]` * Any new inputs being created requires new notes and this parameter is the hashed note of the balance changes from the spend transaction. # Gasless Interactions Another major innovation deployed by the RAILGUN system is the ability to send interactions without needing to spend the underlying blockchain’s gas currency. Through the power of Broadcasters and complex ZK circuits, users can interact with RAILGUN entirely in their currency of choice. For example, a user would not need to hold a small balance of ETH to submit gas for interactions on the Ethereum network and could instead choose to only hold and spend a stablecoin like DAI, with all associated gas being submitted in DAI. This is achieved through something called a “Meta Transaction”, a special form of Ethereum/blockchain transaction that is nested within another transaction. The gas fee can be paid in whatever asset the user specifies with the Broadcaster and nested transaction performing any conversion frictionlessly for the user. Like any other spend transactions, a Meta Transaction in RAILGUN calls the transact() function. # Unshielding Tokens Unshielding is the process where funds are withdrawn from the RAILGUN privacy system to a public 0x address. Users can withdraw tokens out of RAILGUN by initiating an unshield interaction and inputting any 0x address. Under the hood, withdrawals are identical to a regular private send interaction in that they call the transact() function. The only difference is that the zk-SNARK circuit outputs for withdrawals are unencrypted, and they contain a check to establish whether the interaction is flagged as a withdrawal or not. The check is contained in the unshield parameter. If unshield is non-zero, the transaction is confirmed as an unshield interaction, and the smart contract will check whether the hashed note matches the transaction hash output. If all the inputs pass the ZK proof, the tokens are then sent to the unshield address, which is a public 0x address selected by the user. # Integrating RAILGUN How developers add RAILGUN privacy to existing dApps via Adapt Modules and RAILGUN Connect. RAILGUN’s largest advancement in privacy technology is the ability to interact with smart contracts native to chains where RAILGUN is deployed. Through ZK proofs and the cryptography described above, as well as additional smart contracts (called Adapt Modules), privacy can be added to any on-chain dApp. Adapt Modules form the core of the RAILGUN SDK. For developers, the fact that RAILGUN lives directly on-chain means that they do not have to refactor their existing code and deploy contracts on unproven networks with no liquidity. They can integrate RAILGUN with confidence that their dApps will be just as secure as before, as the system is as secure as the main blockchain, with no security tradeoffs. For developers, the theoretical maximum user base for integrating the RAILGUN SDK is all of their existing users plus any additional privacy-conscious users. Users do not have to wait for new dApps to be built or redeployed on an off-chain solution nor do they have to wait for liquidity to arrive as it already is present in the underlying dApp. RAILGUN and its SDK thus has the best product market fit out of any privacy solution. Adapt Modules are separate smart contracts to the main RAILGUN privacy smart contracts, this architecture has 2 key advantages: 1. Increased security and protection of privacy as the external integrations of RAILGUN cannot contaminate the main codebase. 2. Ease of implementation with existing smart contracts and dApps due to less unnecessary bloat. Adapt Modules form the core of the RAILGUN SDK which is the flexible and powerful toolkit that allows developers to bring privacy to their applications. For developers, the fact that RAILGUN lives directly on-chain means that they do not have to refactor their existing code and deploy contracts on unproven networks with no liquidity. They can integrate RAILGUN with confidence that their dApps will be just as secure as before as the system is as secure as the main blockchain with no security tradeoffs. ## RAILGUN Connect RAILGUN Connect is a WalletConnect-style plugin for RAILGUN wallets, currently in development. It lets existing dApps accept privacy-preserving interactions without a RAILGUN-specific integration, the same way WalletConnect lets a wallet present an account to any dApp. It is not a bridge. It does not move assets between chains. RAILGUN itself never uses a bridge or L2 for anything. Privacy is provided directly by smart contracts on each supported chain. # RAILGUN SDKs The RAILGUN SDKs are written in TypeScript and come in 2 forms depending on the needs of any integrating dApps: * [RAILGUN Cookbook](https://docs.railgun.org/developer-guide/cookbook/cookbook-overview) - Easily integrate RAILGUN into any existing dApp to enable private features such as private lending, private trading, private minting, etc. * ​[Wallet SDK](https://docs.railgun.org/developer-guide/wallet/wallet-overview) – Toolkit to integrate RAILGUN as a private mode for wallets. [RAILGUN Cookbook](https://docs.railgun.org/developer-guide/cookbook/cookbook-overview) is suitable for most dApp developers integrating RAILGUN. It enables users to call your public smart contract from a private 0zk address. Calls can also be linked together in "Recipes" such that users can combine multiple DeFi actions together in a single transaction. For example, a user might be able to go from stablecoins in a 0zk address to providing liquidity in a DEX and depositing that liquidity into a yield optimizer such as Beefy Finance, all in the same Cookbook Recipe. With Wallet SDK, developers can quickly and simply add RAILGUN privacy to their wallets to perform the following RAILGUN actions: * Generate private keys and 0zk addresses * Generate deposits into private balances * Scan interaction history and sync balances * Generate ZK proofs for withdrawals, to send interactions, and to initiate cross-contract calls The `generateDeposit()` and `transact()` functions are contained within the Wallet SDK and are callable by dApps once integrated. **Links:**&#x20; Developer Guide - <https://docs.railgun.org/developer-guide> \ RAILGUN Cookbook GitHub: <https://github.com/Railgun-Community/cookbook>\ Wallet SDK GitHub - <https://github.com/Railgun-Community/quickstart> # Adapt Modules Adapt Modules are smart contract extensions separate from the main RAILGUN privacy system. They allow for extended functionality without impacting the main privacy system’s code. Adapt Modules require 2 fields, a contract address, and parameters to execute the contract. Note that Adapt Modules, while flexible and work for most DeFi applications, are quickly being succeeded by the [EIP-7702](/wiki/learn/integrating-railgun/eip-7702-integration) flow, which is currently an experimental feature. Developers may want to integrate the 7702 flow instead of Adapt Modules for their use cases. The parameters in Adapt Modules are not validated by the core RAILGUN code, which allows for them to be implemented with any custom logic, and arbitrarily across any smart contract. Any relevant proofs are only submittable from the specified contract, and they are only valid if they pass both the RAILGUN core protocol rules and the Adapt Module’s validation rules. Execution parameters are bound into the SNARK proof itself, such that the interaction is only valid if the parameters are met. <figure><img src="https://4189133001-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MgpI5FGDnzf3cR6tzx7%2Fuploads%2FbY728eKZ8dImEs9cA6Ee%2Fimage.png?alt=media&amp;token=600b7c24-8e53-4a2d-8906-e9529da7b4c3" alt=""><figcaption></figcaption></figure> # Example - DEX Swaps Independent RAILGUN-integrated wallets, [Railway Wallet](https://www.railway.xyz/), [Terminal Wallet](https://terminal-wallet.com/), and others have a built-in swap integration with the [0x API ](https://www.0x.org/)(the same tech as Matcha.xyz) to enable private DEX trading. Once the best trade route is found, the wallet generates a proof to extract the token that is being sold from the user’s private balance, then swaps them using the 0x API, and shields the resulting tokens back into the private balance. A swap of DAI into WETH through a private swap takes the following steps: 1. User starts the swap interaction on the RAILGUN integrated wallet and specifies the amount of WETH to swap. 2. [Adapt Module](https://docs.railgun.org/wiki/learn/integrating-railgun/adapt-modules) performs a contract multicall which executes the following actions: * a) Calls `transact()` to unshield DAI from the private balance. As previously stated, the `transact()` will verify that the UTXO has not been nullified and that the user has sufficient funds to execute the swap. * b) Swap from DAI into WETH is executed using the 0x API and Adapt Module, calling the 0x smart contract address and passing parameters to the contract. * c) Calls `shield()`to shield the WETH back into the private balance. If the price of WETH has gone down since the start of the interaction, then both WETH and any DAI leftover will be shielded into the private balance. 3. The contract Merkle Tree is updated with the new notes from `shield()`. As swaps performed through the Railway DEX call the `transact()`and `shield()` functions, the swap transaction also updates the events emitted by the respective functions: * `Transact` * `Shield` * `Nullifiers` As with all other interaction types on RAILGUN, to an outside observer, the interaction appears to originate from a Broadcaster address. As Step 2b has an external touchpoint outside of the RAILGUN system, the number of tokens swapped and the token type will be visible but as it does not interact with the user’s 0x address in any way, the user remains private, and no interactions are linked. This process gives RAILGUN users full privacy and executes an immediate swap against their RAILGUN balance without a rollup delay. The encrypted 0x API call is also much harder to front-run as it’s passed as a cross-contract call to the RAILGUN Relay-Adapt contract. Whilst it is still possible to front-run Railway DEX interactions through simulating the contract, it is markedly more difficult than reading the data fields in a standard DEX interaction. # EIP-7702 Integration ## EIP-7702 Integration > **Status: Released.** The 7702-capable SDK modules are on npm under the `latest` tag. The delegate contract is deployed and listed in the on-chain registry on each supported network (see "Registry" below). EIP-7702 lets an externally owned account (EOA) delegate its execution to a smart contract, for the duration of one signed Type 4 authorization. Railgun uses this to replace Adapt Relay. Adapt Relay is the shared, communal contract that Railgun transactions have used for external DeFi and swap calls (cross-contract calls). In its place, each user's own EOA points to a single whitelisted delegate contract. This page describes what changes for a wallet that integrates Railgun. It covers why the change exists and what to implement. #### Why this exists Adapt Relay is a shared contract. Every wallet's swap and DeFi transactions execute as the same communal contract instance. This works for a simple swap-and-shield: the output is an ordinary, transferable ERC-20 that Railgun can route back to the user. It does not work for protocols that return a position or receipt token that is non-transferable, or otherwise bound to the depositing address. Aave is the clearest case. Its obligation tokens (aTokens) are non-transferable. A position opened by a shared relay contract has no way to be attributed, or moved back out, to the individual user who funded it. This puts an entire category of DeFi out of reach of the old shared-contract model: lending and borrowing positions, and non-transferable or account-bound receipt tokens generally. With EIP-7702, each user delegates their own EOA to the delegate contract instead of routing through a shared one. The DeFi call executes as the user's own account. Whatever position comes back, transferable or not, is already in the address that opened it. It was never held by a shared intermediary. This is what makes protocols like Aave integrable at all, not just safer to integrate. #### Reference implementation Terminal Wallet has a working 7702 integration on the `feat/7702-integration-base` branch: [github.com/Terminal-Wallet/terminal-wallet-cli/compare/master...feat/7702-integration-base](https://github.com/Terminal-Wallet/terminal-wallet-cli/compare/master...feat/7702-integration-base). It is a full, working reference for everything below: package upgrade, base-token shield and unshield, private swaps, gas plumbing, broadcaster wiring, and an ephemeral-account admin and recovery UI. Wallet devs who integrate 7702 should expect to make substantially the same changes. This doc walks through what they are. That branch uses the release-candidate packages, so use the stable versions below. The underlying on-chain mechanics live in `@railgun-community/engine` (stable release `9.8.0`). The public GitHub `release` branch is older: [github.com/Railgun-Community/engine/compare/main...release](https://github.com/Railgun-Community/engine/compare/main...release) (engine `9.7.0-rc.0`). Wallet devs who use the SDK (`@railgun-community/wallet`, which wraps this engine) will not call most of this directly. It is the source of truth for what the SDK does under the hood. This doc references it below, where it clarifies or corrects something Terminal Wallet's app-level code does not show. #### What changes for a wallet integration **Upgrade to 7702-capable SDK versions.** The 7702 code paths exist from these versions forward: `@railgun-community/wallet` ≥11.2.0, `@railgun-community/cookbook` ≥3.0.2, `@railgun-community/shared-models` ≥8.2.1, `@railgun-community/waku-broadcaster-client-node` ≥10.0.1, `ethers` 6.14.3. These are on npm under the `latest` dist-tag, so a plain `npm install @railgun-community/wallet` installs them. Do not use the earlier `-rc` versions or the `@dev` tag. They use the earlier development delegate addresses. These are major-version upgrades, so check the release notes of each package for other breaking changes. `@railgun-community/waku-broadcaster-client-node` 10.0.1 declares a peer dependency of `@railgun-community/wallet` `~11.1.0`, so you can see a peer-dependency warning with wallet 11.2.0. **Base-token (ETH) shield.** Derive the wallet's current `EphemeralAccount` (via the SDK's `getCurrentEphemeralWallet`), and pass it into `gasEstimateForShieldBaseToken` and `populateShieldBaseToken`. The SDK takes the 7702 path only when it receives an `EphemeralAccount` signer. The delegate contract wraps ETH to WETH atomically as part of the shield, so there is no separate manual wrap step. Before you derive the account, realign the wallet's local ephemeral index with on-chain history once per session (`EphemeralKeyManager.scanHistoryForEphemeralIndex`). This protects an imported or restored wallet whose local index counter reset to 0 while indices were already spent on-chain. **Base-token (ETH) unshield also routes through 7702** in the Terminal Wallet reference implementation. `getUnshieldBaseTokenGasEstimate` flags it explicitly as a 7702 (type-4) relay-adapt transaction, so the same Type4 gas handling below applies. Private ERC-20 transfers and unshields that do not touch the base token are not affected. **DeFi and swap (cross-contract call) flows.** Switch from `gasEstimateForUnprovenCrossContractCalls` and `generateCrossContractCallsProof` to the 7702 variants: `gasEstimateForUnprovenCrossContractCalls7702` and `generateCrossContractCallsProof7702`. If you use a cookbook swap recipe (for example the 0x recipe), watch for this gotcha: the stock recipe defaults its quote's taker and recipient to the network's `relayAdaptContract` address. Under 7702, the delegate code executes as the user's own ephemeral EOA, not as a separate contract instance. A quote built against the old relay-adapt address routes the bought tokens to a non-executing address, and the downstream shield then operates on the wrong account. Override the quote's taker and recipient to the ephemeral EOA's own address instead. Also use the recipe's own `minGasLimit` (its floor, for example around 2.7M for swap-and-shield) rather than a hardcoded value. A swap's variable external call under-estimates gas and needs a real floor, or it reverts out of gas. Deterministic operations (shield, unshield, recovery, with no variable external call) can safely use `0` instead. **Gas typing, common to all 7702 flows.** A 7702 (type-4) transaction must keep its EIP-1559 fee fields (`maxFeePerGas` and `maxPriorityFeePerGas`) through the whole pipeline. Tag these flows explicitly, with an `is7702Transaction` flag through your gas-details plumbing, so a broadcaster-routing branch does not downgrade them to Type1 or legacy pricing. That downgrade would zero out the priority fee on the populated transaction. Separately, pin `overallBatchMinGasPrice` to `0` for 7702 batches. That field is a legacy gas-price commitment check on the Railgun smart contract. A non-zero value reverts as "Gas price too low" once pricing is governed by the type-4 `maxFeePerGas` instead. **Broadcaster wiring.** 7702 flows need a 7702-capable broadcaster. Filter broadcaster discovery to broadcasters that advertise 7702 support, using the `use7702Only` flag on the find-broadcaster calls. When you submit, pass the signed authorization tuple and explicit type-4 fee overrides (`gasLimit`, `maxFeePerGas`, `maxPriorityFeePerGas`) through to the broadcaster call. Without them, the broadcaster silently falls back to a legacy submission and drops the authorization, so the bundle can never broadcast. Pass your own already-computed gas limit rather than relying on the broadcaster's own `estimateGas` on the type-4 transaction. That estimate under-counts 7702 execution and can submit below the delegate contract's minimum-gas check, which fails with "Not enough gas supplied". **7702-delegated (ephemeral) EOA management.** A delegated EOA is a real on-chain account, not a disposable signer. It can end up holding a balance the wallet needs to know about. If a DeFi or swap call fails partway through (a slippage revert, or an out-of-gas failure before the re-shield step), the leftover value lands in that EOA rather than in a shared contract. It sits there until the wallet notices and acts. This applies beyond DeFi and swap flows too. Any delegated EOA, including one touched only by a shield or base-token unshield flow, can end up holding native gas token or leftover balances the user did not intend to leave there. These delegated EOAs are ephemeral. A wallet derives them from a sequential local index per wallet and chain, rather than reusing the user's single long-lived address, for privacy. Use the current index for a given operation, so the gas estimate, proof, and submission all agree on the same address. Only advance, or "ratchet," to the next index after that operation has actually broadcast. Never ratchet speculatively. Keep a durable local record of the index, not just an in-memory value. Realign it against on-chain history on session start and on demand: check which addresses show up as unshield recipients in the wallet's local transaction history. A restored or imported wallet's local counter will not know what has already been used on-chain. Ship tooling for this. Do not leave it to the user to notice a stray balance. Build an admin view that shows the
프로젝트로 돌아가기